@operad-io/engine 0.0.0-stage → 0.1.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 (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/config.schema.json +188 -0
  4. package/keys.schema.json +12 -0
  5. package/package.json +22 -4
  6. package/src/config/config.ts +627 -0
  7. package/src/config/index.ts +1 -0
  8. package/src/flow/define-flow.ts +57 -0
  9. package/src/flow/index.ts +5 -0
  10. package/src/flow/load.ts +41 -0
  11. package/src/flow/types.ts +107 -0
  12. package/src/flow/validate.ts +296 -0
  13. package/src/http/address.ts +142 -0
  14. package/src/http/index.ts +25 -0
  15. package/src/http/link.ts +20 -0
  16. package/src/http/server.ts +920 -0
  17. package/src/http/token.ts +90 -0
  18. package/src/index.ts +18 -0
  19. package/src/kernel/decide.ts +689 -0
  20. package/src/kernel/index.ts +3 -0
  21. package/src/kernel/state.ts +275 -0
  22. package/src/kernel/types.ts +366 -0
  23. package/src/log/errors.ts +77 -0
  24. package/src/log/facts.ts +50 -0
  25. package/src/log/index.ts +6 -0
  26. package/src/log/json-value.ts +67 -0
  27. package/src/log/open-log.ts +17 -0
  28. package/src/log/schema.ts +5 -0
  29. package/src/log/secret.ts +30 -0
  30. package/src/log/sqlite.ts +1011 -0
  31. package/src/log/types.ts +230 -0
  32. package/src/loop/code-watch.ts +486 -0
  33. package/src/loop/index.ts +3 -0
  34. package/src/loop/older-code.ts +58 -0
  35. package/src/loop/serve.ts +483 -0
  36. package/src/markdown.ts +451 -0
  37. package/src/notify/index.ts +10 -0
  38. package/src/notify/notify.ts +256 -0
  39. package/src/platform/file-lock.ts +385 -0
  40. package/src/platform/index.ts +13 -0
  41. package/src/platform/load.ts +18 -0
  42. package/src/platform/process-group.ts +675 -0
  43. package/src/platform/process-watch.ts +152 -0
  44. package/src/platform/sqlite-open.ts +104 -0
  45. package/src/platform/step-reap.ts +668 -0
  46. package/src/platform/watch.ts +158 -0
  47. package/src/platform/worker-reports.ts +34 -0
  48. package/src/plugin/action-schema.ts +550 -0
  49. package/src/plugin/declared-flows.ts +74 -0
  50. package/src/plugin/define-plugin.ts +12 -0
  51. package/src/plugin/errors.ts +73 -0
  52. package/src/plugin/filters.ts +46 -0
  53. package/src/plugin/harness.ts +50 -0
  54. package/src/plugin/home.ts +13 -0
  55. package/src/plugin/index.ts +65 -0
  56. package/src/plugin/install.ts +268 -0
  57. package/src/plugin/keys.ts +63 -0
  58. package/src/plugin/load.ts +256 -0
  59. package/src/plugin/logger.ts +30 -0
  60. package/src/plugin/object-facts.ts +132 -0
  61. package/src/plugin/open-store.ts +32 -0
  62. package/src/plugin/paging.ts +133 -0
  63. package/src/plugin/registry.ts +1786 -0
  64. package/src/plugin/secrets.ts +141 -0
  65. package/src/plugin/semver.ts +110 -0
  66. package/src/plugin/settings.ts +64 -0
  67. package/src/plugin/sqlite-store.ts +756 -0
  68. package/src/plugin/store.ts +318 -0
  69. package/src/plugin/types.ts +1243 -0
  70. package/src/plugin/usage.ts +157 -0
  71. package/src/plugin/validate.ts +1028 -0
  72. package/src/runner/answer.ts +156 -0
  73. package/src/runner/ask.ts +483 -0
  74. package/src/runner/cancel.ts +51 -0
  75. package/src/runner/errors.ts +20 -0
  76. package/src/runner/grants.ts +92 -0
  77. package/src/runner/index.ts +33 -0
  78. package/src/runner/limits.ts +403 -0
  79. package/src/runner/lock.ts +140 -0
  80. package/src/runner/runner.ts +1175 -0
  81. package/src/runner/service.ts +184 -0
  82. package/src/runner/step-worker.ts +303 -0
  83. package/src/testing/clock.ts +67 -0
  84. package/src/testing/index.ts +90 -0
  85. package/src/testing/types.ts +116 -0
  86. package/src/testing/world.ts +369 -0
  87. package/src/trigger/cron.ts +193 -0
  88. package/src/trigger/index.ts +32 -0
  89. package/src/trigger/kernel.ts +1221 -0
  90. package/src/trigger/rules.ts +300 -0
  91. package/src/trigger/store.ts +233 -0
  92. package/src/trigger/types.ts +156 -0
  93. package/src/util.ts +50 -0
  94. package/src/views/history.ts +634 -0
  95. package/src/views/index.ts +7 -0
  96. package/src/views/pending.ts +209 -0
  97. package/src/views/presentation.ts +2609 -0
  98. package/src/views/running.ts +255 -0
  99. package/src/views/settings.ts +452 -0
  100. package/src/views/types.ts +72 -0
  101. package/src/views/uploads.ts +228 -0
  102. package/triggers.schema.json +48 -0
@@ -0,0 +1,300 @@
1
+ /** Reading and checking `$OPERAD_HOME/triggers.json`. */
2
+
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import type { JsonValue } from "../log/types.ts";
6
+ import type { PluginRegistry } from "../plugin/registry.ts";
7
+ import { CronError, parseCron } from "./cron.ts";
8
+ import type { TriggerMode, TriggerRule } from "./types.ts";
9
+ import { isRecord } from "../util.ts";
10
+
11
+ /** `triggers.json` is not usable; the message names the rule and field. */
12
+ export class TriggerError extends Error {
13
+ constructor(message: string, options?: ErrorOptions) {
14
+ super(message, options);
15
+ this.name = "TriggerError";
16
+ }
17
+ }
18
+
19
+ export const TRIGGERS_FILE = "triggers.json";
20
+
21
+ export function triggersPath(home: string): string {
22
+ return join(home, TRIGGERS_FILE);
23
+ }
24
+
25
+ const RULE_KEYS = new Set(["source", "type", "start", "object", "mode", "schedule"]);
26
+ const START_KEYS = new Set(["flow", "params"]);
27
+ const MODES: readonly TriggerMode[] = ["observe", "candidate", "auto"];
28
+
29
+ function requireText(
30
+ value: unknown,
31
+ at: string,
32
+ field: string,
33
+ ): string {
34
+ if (typeof value !== "string" || value.trim().length === 0) {
35
+ throw new TriggerError(`${at}: ${field}: must be a non-empty string`);
36
+ }
37
+ return value;
38
+ }
39
+
40
+ function checkKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>, at: string): void {
41
+ for (const key of Object.keys(value)) {
42
+ if (!allowed.has(key)) {
43
+ throw new TriggerError(`${at}: ${key}: not a rule field`);
44
+ }
45
+ }
46
+ }
47
+
48
+ function readMode(value: unknown, at: string): TriggerMode {
49
+ if (value === "observe" || value === "candidate" || value === "auto") {
50
+ return value;
51
+ }
52
+ throw new TriggerError(
53
+ `${at}: mode: must be ${MODES.map((mode) => `"${mode}"`).join(", ")}`,
54
+ );
55
+ }
56
+
57
+ /**
58
+ * A plain JSON copy of a rule's params. Each property is read once while the
59
+ * copy is built, so a getter cannot pass the check with one value and hand
60
+ * back another, and the rule keeps the snapshot rather than a live object.
61
+ */
62
+ function snapshotJsonValue(value: unknown, path: string): JsonValue {
63
+ const seen = new WeakSet<object>();
64
+
65
+ function walk(current: unknown, at: string): JsonValue {
66
+ if (current === null) return null;
67
+ switch (typeof current) {
68
+ case "string":
69
+ case "boolean":
70
+ return current;
71
+ case "number":
72
+ if (!Number.isFinite(current)) {
73
+ throw new Error(`${at} is not a finite JSON number`);
74
+ }
75
+ return current;
76
+ case "object":
77
+ break;
78
+ default:
79
+ throw new Error(`${at} is not JSON (${typeof current})`);
80
+ }
81
+
82
+ if (seen.has(current)) {
83
+ throw new Error(`${at} contains a cycle`);
84
+ }
85
+ seen.add(current);
86
+
87
+ // `JSON.stringify` calls `toJSON` even when it is not enumerable, so the
88
+ // value it would store differs from the value inspected here.
89
+ if (typeof (current as { toJSON?: unknown }).toJSON === "function") {
90
+ throw new Error(
91
+ `${at} has a toJSON method, so its JSON form is not the value inspected`,
92
+ );
93
+ }
94
+
95
+ let copy: JsonValue;
96
+ if (Array.isArray(current)) {
97
+ const items: JsonValue[] = [];
98
+ for (let index = 0; index < current.length; index += 1) {
99
+ if (!(index in current)) {
100
+ throw new Error(`${at}[${index}] is a hole, not a JSON value`);
101
+ }
102
+ items.push(walk(current[index], `${at}[${index}]`));
103
+ }
104
+ copy = items;
105
+ } else {
106
+ const prototype = Object.getPrototypeOf(current);
107
+ if (prototype !== Object.prototype && prototype !== null) {
108
+ throw new Error(`${at} is not a plain JSON object`);
109
+ }
110
+ const record: { [key: string]: JsonValue } = {};
111
+ for (const [key, item] of Object.entries(current)) {
112
+ Object.defineProperty(record, key, {
113
+ value: walk(item, `${at}.${key}`),
114
+ enumerable: true,
115
+ writable: true,
116
+ configurable: true,
117
+ });
118
+ }
119
+ copy = record;
120
+ }
121
+
122
+ seen.delete(current);
123
+ return copy;
124
+ }
125
+
126
+ return walk(value, path);
127
+ }
128
+
129
+ function readStart(value: unknown, at: string): TriggerRule["start"] {
130
+ if (!isRecord(value)) {
131
+ throw new TriggerError(`${at}: start: must be an object`);
132
+ }
133
+ checkKeys(value, START_KEYS, `${at}: start`);
134
+ const flow = requireText(value.flow, `${at}: start.flow`, "flow");
135
+ // An absent key means "no params"; a present key must be JSON even when its
136
+ // value is `undefined`. The snapshot freezes every nested value at load.
137
+ if (!Object.hasOwn(value, "params")) return { flow };
138
+ try {
139
+ return { flow, params: snapshotJsonValue(value.params, "start.params") };
140
+ } catch (error) {
141
+ const detail = error instanceof Error ? error.message : String(error);
142
+ throw new TriggerError(`${at}: ${detail}`, { cause: error });
143
+ }
144
+ }
145
+
146
+ function readRule(value: unknown, index: number, file: string): TriggerRule {
147
+ const at = `${file}: rule ${index}`;
148
+ if (!isRecord(value)) {
149
+ throw new TriggerError(`${at}: must be an object`);
150
+ }
151
+ checkKeys(value, RULE_KEYS, at);
152
+
153
+ const source = requireText(value.source, at, "source");
154
+ const type = requireText(value.type, at, "type");
155
+ const start = readStart(value.start, at);
156
+ const object = requireText(value.object, at, "object");
157
+ const mode = readMode(value.mode, at);
158
+
159
+ let schedule: string | undefined;
160
+ if (value.schedule !== undefined) {
161
+ schedule = requireText(value.schedule, at, "schedule");
162
+ try {
163
+ parseCron(schedule);
164
+ } catch (error) {
165
+ const detail = error instanceof CronError ? error.message : String(error);
166
+ throw new TriggerError(`${at}: schedule: ${detail}`, { cause: error });
167
+ }
168
+ }
169
+
170
+ return schedule === undefined
171
+ ? { source, type, start, object, mode }
172
+ : { source, type, start, object, mode, schedule };
173
+ }
174
+
175
+ /**
176
+ * Checks a parsed `triggers.json` value. `registry` is optional so a caller can
177
+ * check the file before any plugin loads; when it is given, a rule whose flow
178
+ * does not exist is refused at load.
179
+ */
180
+ export function parseTriggerRules(
181
+ raw: unknown,
182
+ file: string,
183
+ registry?: PluginRegistry,
184
+ ): readonly TriggerRule[] {
185
+ if (!Array.isArray(raw)) {
186
+ throw new TriggerError(`${file}: must be a JSON array of rules`);
187
+ }
188
+ const rules = raw.map((entry, index) => readRule(entry, index, file));
189
+ for (const [index, rule] of rules.entries()) {
190
+ if (
191
+ registry !== undefined &&
192
+ registry.flow(rule.start.flow) === undefined
193
+ ) {
194
+ throw new TriggerError(
195
+ `${file}: rule ${index}: start.flow: unknown flow "${rule.start.flow}"`,
196
+ );
197
+ }
198
+ }
199
+ return rules;
200
+ }
201
+
202
+ /** One rule and where it came from: `user`, or the plugin that shipped it. */
203
+ export interface SourcedTriggerRule {
204
+ readonly rule: TriggerRule;
205
+ readonly from: string;
206
+ }
207
+
208
+ export interface LoadTriggerRulesOptions {
209
+ readonly home: string;
210
+ readonly registry?: PluginRegistry | undefined;
211
+ /** Where a skipped duplicate plugin rule is reported. Defaults to stderr. */
212
+ readonly onLog?: ((message: string) => void) | undefined;
213
+ }
214
+
215
+ function ruleKey(rule: TriggerRule): string {
216
+ return JSON.stringify([rule.source, rule.type]);
217
+ }
218
+
219
+ /**
220
+ * Merges the rules plugins ship with the user's rules. A user rule with the
221
+ * same source and type removes every plugin rule for that pair. When two
222
+ * plugins ship a rule for the same pair, the later one is skipped and named
223
+ * in one log line.
224
+ */
225
+ export function mergeTriggerRules(
226
+ userRules: readonly TriggerRule[],
227
+ pluginRules: readonly { readonly plugin: string; readonly rule: TriggerRule }[],
228
+ onLog: (message: string) => void = (message) => console.error(message),
229
+ ): readonly SourcedTriggerRule[] {
230
+ const userPairs = new Set(userRules.map(ruleKey));
231
+ const owner = new Map<string, string>();
232
+ const merged: SourcedTriggerRule[] = [];
233
+
234
+ for (const entry of pluginRules) {
235
+ const key = ruleKey(entry.rule);
236
+ if (userPairs.has(key)) continue;
237
+ const first = owner.get(key);
238
+ if (first !== undefined) {
239
+ if (first !== entry.plugin) {
240
+ onLog(
241
+ `trigger rule ${entry.rule.source}/${entry.rule.type}: plugin "${entry.plugin}" is skipped; plugin "${first}" already declares it`,
242
+ );
243
+ }
244
+ continue;
245
+ }
246
+ owner.set(key, entry.plugin);
247
+ merged.push({ rule: entry.rule, from: entry.plugin });
248
+ }
249
+
250
+ for (const rule of userRules) merged.push({ rule, from: "user" });
251
+ return merged;
252
+ }
253
+
254
+ /** Reads the user's file; a missing file is an empty rule list, not an error. */
255
+ async function readUserRules(
256
+ options: LoadTriggerRulesOptions,
257
+ ): Promise<readonly TriggerRule[]> {
258
+ const file = triggersPath(options.home);
259
+ let text: string;
260
+ try {
261
+ text = await readFile(file, "utf8");
262
+ } catch (error) {
263
+ if (
264
+ typeof error === "object" &&
265
+ error !== null &&
266
+ "code" in error &&
267
+ error.code === "ENOENT"
268
+ ) {
269
+ return [];
270
+ }
271
+ throw new TriggerError(`${file}: ${String(error)}`, { cause: error });
272
+ }
273
+
274
+ let raw: unknown;
275
+ try {
276
+ raw = JSON.parse(text);
277
+ } catch (error) {
278
+ throw new TriggerError(`${file}: invalid JSON: ${String(error)}`, {
279
+ cause: error,
280
+ });
281
+ }
282
+ return parseTriggerRules(raw, file, options.registry);
283
+ }
284
+
285
+ /** The rules in force, with where each came from. */
286
+ export async function loadSourcedTriggerRules(
287
+ options: LoadTriggerRulesOptions,
288
+ ): Promise<readonly SourcedTriggerRule[]> {
289
+ const userRules = await readUserRules(options);
290
+ const pluginRules = options.registry?.triggerRules() ?? [];
291
+ return mergeTriggerRules(userRules, pluginRules, options.onLog);
292
+ }
293
+
294
+ /** The merged rules in force: plugin defaults, then the user's rules. */
295
+ export async function loadTriggerRules(
296
+ options: LoadTriggerRulesOptions,
297
+ ): Promise<readonly TriggerRule[]> {
298
+ const sourced = await loadSourcedTriggerRules(options);
299
+ return sourced.map((entry) => entry.rule);
300
+ }
@@ -0,0 +1,233 @@
1
+ /** The trigger metadata a run needs: its event files and its pending start. */
2
+
3
+ import { randomUUID } from "node:crypto";
4
+ import {
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ readdirSync,
9
+ rmSync,
10
+ writeFileSync,
11
+ } from "node:fs";
12
+ import { join } from "node:path";
13
+ import type { StartInput } from "../kernel/types.ts";
14
+ import type { TriggerEvent, TriggerView } from "./types.ts";
15
+ import { isRecord } from "../util.ts";
16
+
17
+ /**
18
+ * A start whose run metadata may not be written yet. It is written before the
19
+ * run exists, so a process that dies between `startRun` and the run's own
20
+ * start files loses nothing: whoever finds the idle run adopts this record.
21
+ */
22
+ export interface PendingStart {
23
+ readonly id: string;
24
+ readonly flow: string;
25
+ readonly object: string;
26
+ readonly at: number;
27
+ readonly inputId?: string;
28
+ readonly start: StartInput;
29
+ readonly view?: TriggerView;
30
+ }
31
+
32
+ /** Reads a run's start metadata without opening a store. */
33
+ export function readStoredStart(
34
+ storeRoot: string,
35
+ runId: string,
36
+ ): StartInput | undefined {
37
+ const path = join(storeRoot, "triggers", "runs", runId, "start.json");
38
+ try {
39
+ const value = JSON.parse(readFileSync(path, "utf8")) as unknown;
40
+ if (!isRecord(value) || value.kind !== "start") return undefined;
41
+ return value as unknown as StartInput;
42
+ } catch {
43
+ return undefined;
44
+ }
45
+ }
46
+
47
+ /** Reads a run's trigger view without opening a store. */
48
+ export function readStoredTrigger(
49
+ storeRoot: string,
50
+ runId: string,
51
+ ): TriggerView | undefined {
52
+ const path = join(storeRoot, "triggers", "runs", runId, "trigger.json");
53
+ try {
54
+ const value = JSON.parse(readFileSync(path, "utf8")) as unknown;
55
+ if (!isRecord(value)) return undefined;
56
+ if (
57
+ typeof value.source !== "string" ||
58
+ typeof value.key !== "string" ||
59
+ typeof value.type !== "string" ||
60
+ typeof value.hops !== "number"
61
+ ) {
62
+ return undefined;
63
+ }
64
+ return value as unknown as TriggerView;
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ export interface TriggerStoreOptions {
71
+ readonly root: string;
72
+ readonly clock?: (() => number) | undefined;
73
+ }
74
+
75
+ /** The paths an event's summary and data files use inside the store. */
76
+ export interface EventFilePaths {
77
+ readonly summary: string;
78
+ readonly data: string;
79
+ }
80
+
81
+ /**
82
+ * The files a run or a step reads. The log holds the event itself; this store
83
+ * holds only material that cannot live in a JSON log: summary and data files,
84
+ * a run's start metadata and the pending start of a run being created.
85
+ */
86
+ export class TriggerStore {
87
+ readonly root: string;
88
+ private readonly clock: () => number;
89
+
90
+ constructor(options: TriggerStoreOptions) {
91
+ this.root = options.root;
92
+ this.clock = options.clock ?? (() => Date.now());
93
+ mkdirSync(options.root, { recursive: true });
94
+ }
95
+
96
+ eventPaths(inputId: string): EventFilePaths {
97
+ const directory = join(this.root, "events", inputId);
98
+ return {
99
+ summary: join(directory, "summary.txt"),
100
+ data: join(directory, "data.json"),
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Writes the summary and data files of an event and returns the step-visible
106
+ * view. An existing file is kept: the first event for an input wins, exactly
107
+ * as the log's `recordInput` keeps the first payload.
108
+ */
109
+ writeEventFiles(inputId: string, event: TriggerEvent): TriggerView {
110
+ const paths = this.eventPaths(inputId);
111
+ if (event.summary !== undefined && !existsSync(paths.summary)) {
112
+ mkdirSync(join(this.root, "events", inputId), { recursive: true });
113
+ writeFileSync(paths.summary, event.summary, "utf8");
114
+ }
115
+ if (event.data !== undefined && !existsSync(paths.data)) {
116
+ mkdirSync(join(this.root, "events", inputId), { recursive: true });
117
+ writeFileSync(paths.data, `${JSON.stringify(event.data, null, 2)}\n`, "utf8");
118
+ }
119
+ return {
120
+ source: event.source,
121
+ key: event.key,
122
+ type: event.type,
123
+ ...(event.link === undefined ? {} : { link: event.link }),
124
+ hops: event.hops,
125
+ ...(event.summary === undefined ? {} : { summary: paths.summary }),
126
+ ...(event.data === undefined ? {} : { data: paths.data }),
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Writes a start before the run exists and returns its id. The caller drops
132
+ * it once the run's own `start.json` and `trigger.json` are written.
133
+ */
134
+ writePendingStart(
135
+ record: Omit<PendingStart, "id" | "at">,
136
+ ): string {
137
+ const id = randomUUID();
138
+ const pending: PendingStart = { ...record, id, at: this.clock() };
139
+ const directory = join(this.root, "pending");
140
+ mkdirSync(directory, { recursive: true });
141
+ writeFileSync(
142
+ join(directory, `${id}.json`),
143
+ `${JSON.stringify(pending)}\n`,
144
+ "utf8",
145
+ );
146
+ return id;
147
+ }
148
+
149
+ /**
150
+ * The pending start for a flow and object. A record written no later than
151
+ * `notAfter`, the run's own start time, wins, so an attempt that never made
152
+ * a run cannot be mistaken for the one that did. Under a clock skew between
153
+ * the store and the log the newest record is still the best answer.
154
+ */
155
+ pendingStart(
156
+ flow: string,
157
+ object: string,
158
+ notAfter?: number,
159
+ ): PendingStart | undefined {
160
+ const directory = join(this.root, "pending");
161
+ let names: string[];
162
+ try {
163
+ names = readdirSync(directory).filter((name) => name.endsWith(".json"));
164
+ } catch {
165
+ return undefined;
166
+ }
167
+ let before: PendingStart | undefined;
168
+ let latest: PendingStart | undefined;
169
+ for (const name of names.sort()) {
170
+ let value: unknown;
171
+ try {
172
+ value = JSON.parse(readFileSync(join(directory, name), "utf8"));
173
+ } catch {
174
+ continue;
175
+ }
176
+ if (!isRecord(value)) continue;
177
+ if (typeof value.id !== "string") continue;
178
+ if (value.flow !== flow || value.object !== object) continue;
179
+ if (typeof value.at !== "number") continue;
180
+ if (!isRecord(value.start) || value.start.kind !== "start") continue;
181
+ const pending = value as unknown as PendingStart;
182
+ if (latest === undefined || pending.at >= latest.at) latest = pending;
183
+ if (notAfter !== undefined && pending.at > notAfter) continue;
184
+ if (before === undefined || pending.at >= before.at) before = pending;
185
+ }
186
+ return before ?? latest;
187
+ }
188
+
189
+ dropPendingStart(id: string): void {
190
+ rmSync(join(this.root, "pending", `${id}.json`), { force: true });
191
+ }
192
+
193
+ /** Persist a run's trigger view so a recovered step sees the same files. */
194
+ writeRunTrigger(runId: string, view: TriggerView): void {
195
+ const directory = join(this.root, "runs", runId);
196
+ mkdirSync(directory, { recursive: true });
197
+ writeFileSync(join(directory, "trigger.json"), `${JSON.stringify(view)}\n`, "utf8");
198
+ }
199
+
200
+ readRunTrigger(runId: string): TriggerView | undefined {
201
+ const path = join(this.root, "runs", runId, "trigger.json");
202
+ try {
203
+ const value = JSON.parse(readFileSync(path, "utf8")) as unknown;
204
+ if (!isRecord(value)) return undefined;
205
+ if (
206
+ typeof value.source !== "string" ||
207
+ typeof value.key !== "string" ||
208
+ typeof value.type !== "string" ||
209
+ typeof value.hops !== "number"
210
+ ) {
211
+ return undefined;
212
+ }
213
+ return value as unknown as TriggerView;
214
+ } catch {
215
+ return undefined;
216
+ }
217
+ }
218
+
219
+ writeRunStart(runId: string, start: unknown): void {
220
+ const directory = join(this.root, "runs", runId);
221
+ mkdirSync(directory, { recursive: true });
222
+ writeFileSync(join(directory, "start.json"), `${JSON.stringify(start)}\n`, "utf8");
223
+ }
224
+
225
+ readRunStart(runId: string): unknown {
226
+ const path = join(this.root, "runs", runId, "start.json");
227
+ try {
228
+ return JSON.parse(readFileSync(path, "utf8")) as unknown;
229
+ } catch {
230
+ return undefined;
231
+ }
232
+ }
233
+ }
@@ -0,0 +1,156 @@
1
+ /** The words a source sends, and the words a step sees. */
2
+
3
+ import type { JsonValue } from "../log/types.ts";
4
+
5
+ /** An event deeper than this is recorded and starts nothing. */
6
+ export const MAX_TRIGGER_HOPS = 8;
7
+
8
+ export type TriggerMode = "observe" | "candidate" | "auto";
9
+
10
+ /** What a source, the CLI or a step sends. */
11
+ export interface TriggerEvent {
12
+ readonly source: string;
13
+ readonly key: string;
14
+ readonly type: string;
15
+ readonly object?: string;
16
+ readonly summary?: string;
17
+ /** External material: written to a file, never put into a prompt. */
18
+ readonly data?: JsonValue;
19
+ readonly link?: string;
20
+ /** Outside events are 0; an event a run emits is the starting event's + 1. */
21
+ readonly hops: number;
22
+ }
23
+
24
+ /** One routing rule from `triggers.json`. */
25
+ export interface TriggerRule {
26
+ readonly source: string;
27
+ readonly type: string;
28
+ readonly start: {
29
+ readonly flow: string;
30
+ readonly params?: JsonValue;
31
+ };
32
+ /** A fixed object key, or `"$event.object"`. */
33
+ readonly object: string;
34
+ readonly mode: TriggerMode;
35
+ readonly schedule?: string;
36
+ }
37
+
38
+ /** What a step sees as `ctx.trigger`; read-only, and file paths only. */
39
+ export interface TriggerView {
40
+ readonly source: string;
41
+ readonly key: string;
42
+ readonly type: string;
43
+ readonly link?: string;
44
+ readonly hops: number;
45
+ readonly summary?: string;
46
+ readonly data?: string;
47
+ }
48
+
49
+ export interface StartRequest {
50
+ readonly flow: string;
51
+ readonly params?: JsonValue;
52
+ /** The run's object key, such as `task:42` or `flow:dev/run`. */
53
+ readonly object: string;
54
+ readonly trigger?: TriggerEvent;
55
+ /** Internal: an event already recorded through the log's input store. */
56
+ readonly inputId?: string;
57
+ /** The access profile the run starts with, opaque to the kernel. */
58
+ readonly access?: JsonValue;
59
+ }
60
+
61
+ /** What starting one run did. */
62
+ export type StartResult =
63
+ | {
64
+ readonly kind: "started";
65
+ readonly runId: string;
66
+ readonly duplicate: boolean;
67
+ }
68
+ | {
69
+ readonly kind: "active";
70
+ readonly runId: string;
71
+ readonly duplicate: boolean;
72
+ }
73
+ | {
74
+ readonly kind: "recorded";
75
+ readonly duplicate: boolean;
76
+ }
77
+ | {
78
+ readonly kind: "observed";
79
+ readonly duplicate: boolean;
80
+ }
81
+ | {
82
+ readonly kind: "candidate";
83
+ readonly pendingId: string;
84
+ readonly duplicate: boolean;
85
+ }
86
+ | {
87
+ readonly kind: "skipped";
88
+ readonly reason: string;
89
+ readonly duplicate: boolean;
90
+ };
91
+
92
+ /** What handling one event did. */
93
+ export interface TriggerResult {
94
+ readonly kind:
95
+ | "started"
96
+ | "active"
97
+ | "recorded"
98
+ | "observed"
99
+ | "candidate"
100
+ | "skipped";
101
+ readonly inputId: string;
102
+ readonly duplicate: boolean;
103
+ readonly runId?: string;
104
+ readonly pendingId?: string;
105
+ readonly flow?: string;
106
+ readonly object?: string;
107
+ readonly reason?: string;
108
+ }
109
+
110
+ /** A candidate the pending view offers to start or dismiss. */
111
+ export interface TriggerCandidate {
112
+ readonly pendingId: string;
113
+ readonly inputId: string;
114
+ readonly flow: string;
115
+ readonly params?: JsonValue;
116
+ readonly object: string;
117
+ readonly event: TriggerEvent;
118
+ readonly status: "pending" | "started" | "dismissed";
119
+ readonly runId?: string;
120
+ readonly at: number;
121
+ }
122
+
123
+ /** An event routed to a flow that cannot start yet, and why. */
124
+ export interface RefusedStart {
125
+ readonly inputId: string;
126
+ readonly flow: string;
127
+ readonly object: string;
128
+ readonly reason: string;
129
+ }
130
+
131
+ /** An event a step sends; the kernel adds the source, run scope and hops. */
132
+ export interface StepEvent {
133
+ readonly type: string;
134
+ readonly key: string;
135
+ readonly object?: string;
136
+ readonly summary?: string;
137
+ readonly data?: JsonValue;
138
+ }
139
+
140
+ /** An event a source plugin sends; the kernel adds nothing but validation. */
141
+ export interface SourceEvent {
142
+ readonly source?: string;
143
+ readonly key: string;
144
+ readonly type: string;
145
+ readonly object?: string;
146
+ readonly summary?: string;
147
+ readonly data?: JsonValue;
148
+ readonly link?: string;
149
+ }
150
+
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
+ }