@operad-io/engine 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,12 @@
1
+ # @operad-io/engine
2
+
3
+ **The core of operad: flows, plugins and their records.** The kernel: flows, what waits for a person (pending), and history. Plugins are built on it with `definePlugin`.
4
+
5
+ This package is part of [operad](https://github.com/operad-io/operad). Most people install only [`@operad-io/cli`](https://www.npmjs.com/package/@operad-io/cli).
6
+
7
+ ## Documentation
8
+
9
+ - User guide: [docs/user/index.md](https://github.com/operad-io/operad/blob/main/docs/user/index.md)
10
+ - Website: <https://operad.io>
11
+
12
+ MIT licensed.
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@operad-io/engine",
3
- "version": "0.0.1",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts",
7
7
  "./platform": "./src/platform/index.ts",
8
8
  "./testing": "./src/testing/index.ts"
9
9
  },
10
- "description": "operad: the graph engine for flows, facts and plugins (in development)",
10
+ "description": "operad: the graph engine for flows, facts and plugins",
11
11
  "repository": {
12
12
  "type": "git",
13
13
  "url": "git+https://github.com/operad-io/operad.git",
package/src/http/token.ts CHANGED
@@ -13,6 +13,11 @@ const LABEL = "label";
13
13
  /** The actor id used when a token has no label of its own. */
14
14
  export const DEFAULT_HTTP_TOKEN_LABEL = "operad app";
15
15
 
16
+ /** The label a token acts as: an empty one would be refused as an actor, so it falls back. */
17
+ function labelOf(label: string | undefined): string {
18
+ return label === undefined || label.length === 0 ? DEFAULT_HTTP_TOKEN_LABEL : label;
19
+ }
20
+
16
21
  /** The token and the name an action records it by. */
17
22
  export interface HttpToken {
18
23
  readonly token: string;
@@ -38,7 +43,7 @@ export async function readHttpToken(
38
43
  const label = await store.get(LABEL);
39
44
  return {
40
45
  token: token.reveal(),
41
- label: label?.reveal() ?? DEFAULT_HTTP_TOKEN_LABEL,
46
+ label: labelOf(label?.reveal()),
42
47
  };
43
48
  }
44
49
 
@@ -58,7 +63,7 @@ export async function ensureHttpToken(home: string): Promise<HttpToken> {
58
63
  await store.set(LABEL, DEFAULT_HTTP_TOKEN_LABEL);
59
64
  label = await store.get(LABEL);
60
65
  }
61
- return { token, label: label?.reveal() ?? DEFAULT_HTTP_TOKEN_LABEL };
66
+ return { token, label: labelOf(label?.reveal()) };
62
67
  }
63
68
 
64
69
  /**
@@ -74,7 +79,7 @@ export async function rotateHttpToken(home: string): Promise<HttpToken> {
74
79
  await store.set(LABEL, DEFAULT_HTTP_TOKEN_LABEL);
75
80
  label = await store.get(LABEL);
76
81
  }
77
- return { token, label: label?.reveal() ?? DEFAULT_HTTP_TOKEN_LABEL };
82
+ return { token, label: labelOf(label?.reveal()) };
78
83
  }
79
84
 
80
85
  /** Compares two tokens without an early exit. */
package/src/index.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import pkg from "../package.json" with { type: "json" };
2
+
1
3
  /** The operad graph engine. */
2
- export const ENGINE_VERSION = "0.0.1";
4
+ export const ENGINE_VERSION: string = pkg.version;
3
5
 
4
6
  export * from "./flow/index.ts";
5
7
  export * from "./kernel/index.ts";
@@ -87,6 +87,8 @@ export interface LineRunOptions {
87
87
  readonly cwd: string;
88
88
  readonly env?: Readonly<Record<string, string>> | undefined;
89
89
  readonly timeoutMs?: number | undefined;
90
+ /** How long the line may write no output before its group is stopped. */
91
+ readonly stallMs?: number | undefined;
90
92
  readonly signal: AbortSignal;
91
93
  readonly logger?: PluginLogger | undefined;
92
94
  readonly clock?: Clock | undefined;
@@ -106,10 +108,13 @@ export interface LineOutcome {
106
108
  readonly exitCode: number | null;
107
109
  readonly signal: string | null;
108
110
  readonly timedOut: boolean;
111
+ readonly stalled: boolean;
109
112
  readonly cancelled: boolean;
110
113
  readonly spawnError: string | undefined;
111
114
  readonly log: string | undefined;
112
115
  readonly tail: readonly string[];
116
+ /** More of the end of the output, for the reason a stall gives. */
117
+ readonly stallTail: readonly string[];
113
118
  }
114
119
 
115
120
  /** The last `count` lines of a chunk of output, with no trailing blank line. */
@@ -130,14 +135,17 @@ class Output {
130
135
  private wrote = false;
131
136
  private chain: Promise<void> = Promise.resolve();
132
137
  private readonly logger: PluginLogger | undefined;
138
+ private readonly onOutput: (() => void) | undefined;
133
139
 
134
- constructor(logger: PluginLogger | undefined) {
140
+ constructor(logger: PluginLogger | undefined, onOutput?: () => void) {
135
141
  this.logger = logger;
142
+ this.onOutput = onOutput;
136
143
  }
137
144
 
138
145
  push(text: string): void {
139
146
  if (text.length === 0) return;
140
147
  this.tail = (this.tail + text).slice(-TAIL_LIMIT);
148
+ this.onOutput?.();
141
149
  if (this.logger === undefined) return;
142
150
 
143
151
  this.buffer += text;
@@ -432,15 +440,18 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
432
440
  exitCode: null,
433
441
  signal: null,
434
442
  timedOut: false,
443
+ stalled: false,
435
444
  cancelled: true,
436
445
  spawnError: undefined,
437
446
  log: options.logger?.path,
438
447
  tail: [],
448
+ stallTail: [],
439
449
  };
440
450
  }
441
451
 
442
452
  const clock = options.clock ?? systemClock;
443
- const output = new Output(options.logger);
453
+ let resetStallForOutput = (): void => {};
454
+ const output = new Output(options.logger, () => resetStallForOutput());
444
455
  let child: ChildProcess;
445
456
  try {
446
457
  child = spawn(
@@ -466,10 +477,12 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
466
477
  exitCode: null,
467
478
  signal: null,
468
479
  timedOut: false,
480
+ stalled: false,
469
481
  cancelled: false,
470
482
  spawnError,
471
483
  log: options.logger?.path,
472
484
  tail: output.tailLines(20),
485
+ stallTail: output.tailLines(200),
473
486
  };
474
487
  }
475
488
 
@@ -511,6 +524,7 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
511
524
 
512
525
  let finished = false;
513
526
  let timedOut = false;
527
+ let stalled = false;
514
528
  let cancelled = false;
515
529
  let timer: unknown;
516
530
  if (options.timeoutMs !== undefined) {
@@ -520,6 +534,22 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
520
534
  void stop();
521
535
  }, options.timeoutMs);
522
536
  }
537
+ let stallTimer: unknown;
538
+ const clearStall = (): void => {
539
+ if (stallTimer === undefined) return;
540
+ clock.clearTimeout(stallTimer);
541
+ stallTimer = undefined;
542
+ };
543
+ const resetStall = (): void => {
544
+ if (finished || options.stallMs === undefined || options.stallMs <= 0) return;
545
+ clearStall();
546
+ stallTimer = clock.setTimeout(() => {
547
+ if (finished) return;
548
+ stalled = true;
549
+ void stop();
550
+ }, options.stallMs);
551
+ };
552
+ resetStallForOutput = resetStall;
523
553
  const onAbort = (): void => {
524
554
  if (finished) return;
525
555
  cancelled = true;
@@ -536,7 +566,10 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
536
566
  exited.then((exit): Startup => ({ kind: "exit", exit })),
537
567
  ]);
538
568
 
539
- const finish = async (): Promise<readonly string[]> => {
569
+ const finish = async (): Promise<{
570
+ readonly tail: readonly string[];
571
+ readonly stallTail: readonly string[];
572
+ }> => {
540
573
  const drainedOutput = Promise.all(drained).then(() => undefined);
541
574
  let drainTimer: unknown;
542
575
  const drainLimit = new Promise<void>((resolve) => {
@@ -548,16 +581,17 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
548
581
  control?.destroy();
549
582
  await drainedOutput;
550
583
  await output.end();
551
- return output.tailLines(20);
584
+ return { tail: output.tailLines(20), stallTail: output.tailLines(200) };
552
585
  };
553
586
 
554
587
  if (startup.kind !== "ready") {
555
588
  finished = true;
556
589
  if (timer !== undefined) clock.clearTimeout(timer);
590
+ clearStall();
557
591
  options.signal.removeEventListener("abort", onAbort);
558
592
  await stop();
559
593
  await Promise.race([exited, failed]);
560
- const tail = await finish();
594
+ const { tail, stallTail } = await finish();
561
595
  const spawnError =
562
596
  cancelled || timedOut
563
597
  ? undefined
@@ -568,15 +602,18 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
568
602
  exitCode: startup.kind === "exit" ? startup.exit.code : null,
569
603
  signal: startup.kind === "exit" ? startup.exit.signal : null,
570
604
  timedOut,
605
+ stalled: false,
571
606
  cancelled,
572
607
  spawnError,
573
608
  log: options.logger?.path,
574
609
  tail,
610
+ stallTail,
575
611
  };
576
612
  }
577
613
 
578
614
  readySeen = true;
579
615
  openGate();
616
+ resetStall();
580
617
 
581
618
  // One read serves the race and, if the shell's exit wins it, the look for
582
619
  // the record afterwards: a second read would queue behind this one and miss
@@ -594,6 +631,7 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
594
631
 
595
632
  finished = true;
596
633
  if (timer !== undefined) clock.clearTimeout(timer);
634
+ clearStall();
597
635
  options.signal.removeEventListener("abort", onAbort);
598
636
 
599
637
  let exit: Exit;
@@ -614,22 +652,24 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
614
652
  // A line that reported its own status has already ended, so there is nothing
615
653
  // left to give SIGTERM time for; waiting the grace here made every successful
616
654
  // line pay 500 ms. A cancellation or timeout still takes the TERM path.
617
- if (ended.kind === "end" && !cancelled && !timedOut) {
655
+ if (ended.kind === "end" && !cancelled && !timedOut && !stalled) {
618
656
  const pid = child.pid;
619
657
  if (pid !== undefined) (options.killGroup ?? killProcessGroup)(pid, "SIGKILL");
620
658
  } else {
621
659
  await stop();
622
660
  }
623
661
  await Promise.race([exited, failed]);
624
- const tail = await finish();
662
+ const { tail, stallTail } = await finish();
625
663
 
626
664
  return {
627
665
  exitCode: exit.code,
628
666
  signal: exit.signal,
629
667
  timedOut,
668
+ stalled,
630
669
  cancelled,
631
670
  spawnError: undefined,
632
671
  log: options.logger?.path,
633
672
  tail,
673
+ stallTail,
634
674
  };
635
675
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Packages that are not part of the CLI's own dependencies are installed into
3
3
  * one Bun project under the operad home when the person enables them
4
- * (docs/backlog/operad-plugins.md decision 11). The project keeps its own
4
+ * (ADR 0012 D4). The project keeps its own
5
5
  * `package.json` and lockfile; nothing is installed into the CLI's tree.
6
6
  *
7
7
  * The claude harness needs `@anthropic-ai/claude-agent-sdk`, whose optional
@@ -58,7 +58,7 @@ async function importPluginFile(file: string): Promise<Record<string, unknown>>
58
58
  * named in every import error. A path gets a fresh module instance so a later
59
59
  * reload does not reuse the old value.
60
60
  *
61
- * `installed` is the package's file in the home's Bun project (decision 11).
61
+ * `installed` is the package's file in the home's Bun project (ADR 0012 D4).
62
62
  * The workspace link is tried first, so a checkout keeps loading its own code;
63
63
  * when there is no such link, the home package is imported by path.
64
64
  */
@@ -1,3 +1,4 @@
1
+ import type { ClientApi } from "../views/presentation.ts";
1
2
  import { join } from "node:path";
2
3
  import type { FlowDefinition, StepType } from "../flow/types.ts";
3
4
  import { loadFlow as loadFlowFile } from "../flow/load.ts";
@@ -1572,6 +1573,7 @@ export class PluginRegistry {
1572
1573
  readonly rules: readonly TriggerRule[];
1573
1574
  readonly clock: () => number;
1574
1575
  readonly emit: (event: TriggerEvent) => MaybePromise<void>;
1576
+ readonly client: ClientApi;
1575
1577
  readonly signal?: AbortSignal | undefined;
1576
1578
  }): Promise<readonly { readonly plugin: string; readonly handle: SourceHandle }[]> {
1577
1579
  const running: { plugin: string; handle: SourceHandle }[] = [];
@@ -1609,6 +1611,7 @@ export class PluginRegistry {
1609
1611
  settings: this.settingsFor(plugin.name),
1610
1612
  secrets: this.secretsFor(plugin.name),
1611
1613
  emit,
1614
+ client: options.client,
1612
1615
  };
1613
1616
  try {
1614
1617
  const handle = await plugin.start(ctx);
@@ -1,3 +1,4 @@
1
+ import type { ClientApi } from "../views/presentation.ts";
1
2
  import type { FlowDefinition } from "../flow/types.ts";
2
3
  import type { KernelState } from "../kernel/types.ts";
3
4
  import type { Secret } from "../log/secret.ts";
@@ -202,7 +203,7 @@ export interface ViewContext extends PluginBaseContext {
202
203
 
203
204
  /**
204
205
  * An access profile: opaque JSON the kernel hands to steps. Its shape belongs
205
- * to `operad-sandbox.md`, not to the kernel.
206
+ * to ADR 0025, not to the kernel.
206
207
  */
207
208
  export type AccessProfile = Readonly<Record<string, JsonValue>>;
208
209
 
@@ -1112,6 +1113,12 @@ export interface SourceContext extends PluginBaseContext {
1112
1113
  readonly clock: () => number;
1113
1114
  /** Sends one event through the kernel's rules. */
1114
1115
  emit(event: SourceEvent): Promise<void>;
1116
+ /**
1117
+ * The client API HTTP and the TUI use, the same object: `list`, `get`,
1118
+ * `section`, `events`, `act`, `pending` and `answer`. `act` and `answer`
1119
+ * need an actor.
1120
+ */
1121
+ readonly client: ClientApi;
1115
1122
  }
1116
1123
 
1117
1124
  /** The shape `definePlugin` accepts. The version is added by the helper. */
@@ -1,5 +1,6 @@
1
1
  /** The one entry point that starts runs, and the rules that point events at it. */
2
2
 
3
+ import type { ClientApi } from "../views/presentation.ts";
3
4
  import { readFileSync } from "node:fs";
4
5
  import type { KernelState, StartInput } from "../kernel/types.ts";
5
6
  import { inputIdFor } from "../log/facts.ts";
@@ -44,6 +45,8 @@ export interface KernelOptions {
44
45
  readonly rules?: readonly TriggerRule[] | undefined;
45
46
  readonly clock?: (() => number) | undefined;
46
47
  readonly onLog?: ((message: string) => void) | undefined;
48
+ /** The client API source plugins get; needed to start sources. */
49
+ readonly client?: ClientApi | undefined;
47
50
  }
48
51
 
49
52
  function objectOf(event: TriggerEvent): string | undefined {
@@ -163,6 +166,7 @@ export class Kernel {
163
166
  readonly store: TriggerStore;
164
167
  readonly rules: readonly TriggerRule[];
165
168
  readonly clock: () => number;
169
+ private readonly client: ClientApi | undefined;
166
170
  private readonly onLog: (message: string) => void;
167
171
  private readonly runningSources: {
168
172
  readonly plugin: string;
@@ -184,6 +188,7 @@ export class Kernel {
184
188
  this.storeRoot = options.storeRoot;
185
189
  this.rules = options.rules ?? [];
186
190
  this.clock = options.clock ?? (() => Date.now());
191
+ this.client = options.client;
187
192
  this.onLog = options.onLog ?? ((message) => console.error(message));
188
193
  this.store = new TriggerStore({
189
194
  root: `${options.storeRoot}/triggers`,
@@ -833,9 +838,13 @@ export class Kernel {
833
838
 
834
839
  /** Starts every loaded source; a broken one is logged and skipped. */
835
840
  async startSources(): Promise<void> {
841
+ if (this.client === undefined) {
842
+ throw new Error("the kernel has no client API to give its sources");
843
+ }
836
844
  const running = await this.registry.startSources({
837
845
  rules: this.rules,
838
846
  clock: this.clock,
847
+ client: this.client,
839
848
  emit: async (event) => {
840
849
  await this.receive(event);
841
850
  },
@@ -54,7 +54,7 @@ import {
54
54
  import { readState } from "../runner/service.ts";
55
55
  import { recordAnswer } from "../runner/answer.ts";
56
56
  import { StateError } from "../runner/errors.ts";
57
- import { listPending } from "./pending.ts";
57
+ import { listPending, type CandidateSource, type PendingItem } from "./pending.ts";
58
58
  import {
59
59
  listSettings,
60
60
  setSetting,
@@ -243,6 +243,16 @@ export interface ActOptions {
243
243
  readonly actor: Actor;
244
244
  }
245
245
 
246
+ /**
247
+ * The in-process client API: the calls HTTP and the TUI make. A source plugin's
248
+ * `start` receives the same `Views` object that serves them, narrowed to these.
249
+ * `act` and `answer` both take an actor naming the person who acted.
250
+ */
251
+ export type ClientApi = Pick<
252
+ Views,
253
+ "list" | "get" | "section" | "events" | "act" | "pending" | "answer"
254
+ >;
255
+
246
256
  /** What answers one open question of a pending item. */
247
257
  export interface AnswerViewOptions {
248
258
  readonly runId: string;
@@ -578,6 +588,7 @@ export class Views {
578
588
  /** The timer that announces an object when its rate window ends. */
579
589
  private readonly growthTimers = new Map<string, ReturnType<typeof setTimeout>>();
580
590
  private readonly unsubscribe: (() => void)[] = [];
591
+ private candidateSource: CandidateSource | undefined;
581
592
  private preparing: Promise<void> | undefined;
582
593
 
583
594
  constructor(options: ViewsOptions) {
@@ -1402,6 +1413,19 @@ export class Views {
1402
1413
  * question is refused, as it is for the command line and a plugin action.
1403
1414
  */
1404
1415
  async answer(options: AnswerViewOptions): Promise<void> {
1416
+ const who: unknown = (options as { actor?: unknown } | undefined)?.actor;
1417
+ if (
1418
+ !isRecord(who) ||
1419
+ typeof who.via !== "string" ||
1420
+ who.via.length === 0 ||
1421
+ typeof who.id !== "string" ||
1422
+ who.id.length === 0
1423
+ ) {
1424
+ throw new ViewError(
1425
+ "args",
1426
+ "answer needs an actor: { via, id } says who answered",
1427
+ );
1428
+ }
1405
1429
  if (this.log === undefined) {
1406
1430
  throw new ViewError(
1407
1431
  "not-available",
@@ -1457,12 +1481,46 @@ export class Views {
1457
1481
  }
1458
1482
  }
1459
1483
 
1484
+ /**
1485
+ * Where `pending` gets the trigger candidates and refused starts, the same
1486
+ * source HTTP passes `listPending`. The host that owns the kernel sets it.
1487
+ */
1488
+ useCandidates(source: CandidateSource | undefined): void {
1489
+ this.candidateSource = source;
1490
+ }
1491
+
1492
+ /** What waits for a person: the pending view, as HTTP serves it. */
1493
+ async pending(): Promise<readonly PendingItem[]> {
1494
+ if (this.log === undefined) {
1495
+ throw new ViewError(
1496
+ "not-available",
1497
+ "this server has no run log, so it cannot list what is pending",
1498
+ );
1499
+ }
1500
+ return listPending(this.log, this.registry, this.candidateSource, this);
1501
+ }
1502
+
1460
1503
  /** Runs one action by `<plugin>:<action>`, honouring note and confirm. */
1461
1504
  async act(
1462
1505
  name: string,
1463
1506
  id: string | undefined,
1464
1507
  options: ActOptions,
1465
1508
  ): Promise<ViewActionRun> {
1509
+ // The type asks for an actor; a caller outside the type checker (a plugin
1510
+ // in plain JavaScript) is refused here, before anything runs.
1511
+ const who: unknown = (options as { actor?: unknown } | undefined)?.actor;
1512
+ if (
1513
+ !isRecord(who) ||
1514
+ typeof who.via !== "string" ||
1515
+ who.via.length === 0 ||
1516
+ typeof who.id !== "string" ||
1517
+ who.id.length === 0
1518
+ ) {
1519
+ throw new ViewError(
1520
+ "args",
1521
+ `action "${name}" needs an actor: { via, id } says who asked`,
1522
+ );
1523
+ }
1466
1524
  // An action that targets no object names no id. The kernel has no such
1467
1525
  // action today, but the HTTP body allows it, so the views say why it
1468
1526
  // cannot run instead of refusing the request before looking it up.