@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
@@ -69,7 +69,8 @@
69
69
  "type": "integer",
70
70
  "minimum": 0,
71
71
  "maximum": 65535,
72
- "default": 7480
72
+ "default": 8765,
73
+ "description": "The port serve binds on every address it listens on. The default is 8765; 0 asks the system for a port."
73
74
  },
74
75
  "listen": {
75
76
  "type": "array",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@operad-io/engine",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts",
@@ -1,20 +1,25 @@
1
1
  /** The operad home config: JSON, read by the kernel, never by a plugin kind. */
2
2
 
3
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { defaultOperadHome } from "../plugin/home.ts";
6
6
  import { MAX_ASK_GRACE_SECS } from "../plugin/types.ts";
7
+ import {
8
+ withLockFile,
9
+ writeJsonAtomic,
10
+ type AsyncAtomicWriteOptions,
11
+ type LockFileOptions,
12
+ } from "../platform/index.ts";
7
13
  import {
8
14
  openLog,
9
15
  type LogBackend,
10
- type LogBackendName,
11
16
  type LogBackendOptions,
12
17
  } from "../log/index.ts";
13
18
  import { SQLITE_FILE_NAME } from "../log/sqlite.ts";
14
- import { isRecord } from "../util.ts";
19
+ import { isMissingFile, isRecord } from "../util.ts";
15
20
 
16
21
  /** The storage backend the log uses. */
17
- export type StoreBackend = LogBackendName;
22
+ export type StoreBackend = "sqlite";
18
23
 
19
24
  /** Where the log lives: the sqlite file. */
20
25
  export interface StoreConfig {
@@ -41,10 +46,10 @@ export interface HttpConfig {
41
46
  readonly listen: readonly string[];
42
47
  }
43
48
 
44
- /** The HTTP defaults: on, port 7480, loopback only. */
49
+ /** The HTTP defaults: on, port 8765, loopback only. */
45
50
  export const DEFAULT_HTTP: HttpConfig = {
46
51
  enabled: true,
47
- port: 7480,
52
+ port: 8765,
48
53
  listen: ["127.0.0.1"],
49
54
  };
50
55
 
@@ -397,12 +402,7 @@ export async function readConfig(
397
402
  try {
398
403
  text = await readFile(file, "utf8");
399
404
  } catch (error) {
400
- if (
401
- typeof error === "object" &&
402
- error !== null &&
403
- "code" in error &&
404
- error.code === "ENOENT"
405
- ) {
405
+ if (isMissingFile(error)) {
406
406
  return defaultConfig(home);
407
407
  }
408
408
  throw new ConfigError(`${file}: ${String(error)}`, { cause: error });
@@ -477,23 +477,15 @@ export function configJson(config: OperadConfig): Record<string, unknown> {
477
477
  };
478
478
  }
479
479
 
480
- /** Writes a config file, replacing it atomically enough for one command. */
481
- export async function writeConfig(
482
- home: string,
483
- config: OperadConfig,
484
- ): Promise<void> {
485
- await mkdir(home, { recursive: true });
486
- await writeFile(
487
- configPath(home),
488
- `${JSON.stringify(configJson(config), null, 2)}\n`,
489
- );
490
- }
491
-
492
480
  /**
493
481
  * A config that does not mention `plugins` is a config someone wrote for the
494
482
  * store only; `init` installs the given plugins into it and leaves the rest.
495
483
  */
496
- async function addDefaultPlugins(defaults: OperadConfig, file: string): Promise<void> {
484
+ async function addDefaultPlugins(
485
+ defaults: OperadConfig,
486
+ file: string,
487
+ hooks: AsyncAtomicWriteOptions,
488
+ ): Promise<void> {
497
489
  let raw: unknown;
498
490
  try {
499
491
  raw = JSON.parse(await readFile(file, "utf8"));
@@ -502,26 +494,19 @@ async function addDefaultPlugins(defaults: OperadConfig, file: string): Promise<
502
494
  }
503
495
  if (!isRecord(raw) || raw.plugins !== undefined) return;
504
496
  const plugins = configJson(defaults).plugins;
505
- // Write beside the config and rename over it, so a crash or a full disk
506
- // leaves the old file whole instead of a truncated one.
507
- const temp = `${file}.tmp`;
508
- try {
509
- await writeFile(temp, `${JSON.stringify({ ...raw, plugins }, null, 2)}\n`);
510
- await rename(temp, file);
511
- } catch (error) {
512
- await rm(temp, { force: true }).catch(() => undefined);
513
- throw error;
514
- }
497
+ await writeJsonAtomic(file, { ...raw, plugins }, { ...hooks, space: 2 });
515
498
  }
516
499
 
517
500
  /**
518
501
  * Writes `defaults` (the distribution's config for a new home) when the home
519
502
  * has none. An existing file is kept; only a missing `plugins` section is
520
- * filled in from `defaults`. Idempotent.
503
+ * filled in from `defaults`. Idempotent. `hooks` lets a test stop the write
504
+ * before it replaces the file.
521
505
  */
522
506
  export async function ensureConfig(
523
507
  home: string,
524
508
  defaults: OperadConfig = defaultConfig(home),
509
+ hooks: AsyncAtomicWriteOptions = {},
525
510
  ): Promise<{
526
511
  readonly created: boolean;
527
512
  readonly path: string;
@@ -542,7 +527,7 @@ export async function ensureConfig(
542
527
  "code" in error &&
543
528
  error.code === "EEXIST"
544
529
  ) {
545
- await addDefaultPlugins(defaults, file);
530
+ await addDefaultPlugins(defaults, file, hooks);
546
531
  return { created: false, path: file, config: await readConfig(home) };
547
532
  }
548
533
  throw error;
@@ -561,12 +546,14 @@ export interface PluginOffer {
561
546
  * Turns one configured plugin on or off, preserving the rest of the file.
562
547
  * A plugin in `offer.optional` that the file does not list is added.
563
548
  * The change takes effect at the next command or `serve` reload.
549
+ * `hooks` lets a test stop the write before it replaces the file.
564
550
  */
565
551
  export async function setPluginEnabled(
566
552
  home: string,
567
553
  name: string,
568
554
  enabled: boolean,
569
555
  offer: PluginOffer = { optional: {} },
556
+ hooks: AsyncAtomicWriteOptions = {},
570
557
  ): Promise<void> {
571
558
  const file = configPath(home);
572
559
  let raw: Record<string, unknown> = {};
@@ -576,12 +563,7 @@ export async function setPluginEnabled(
576
563
  if (!isRecord(parsed)) throw new ConfigError(`${file}: must be a JSON object`);
577
564
  raw = parsed;
578
565
  } catch (error) {
579
- if (!(
580
- typeof error === "object" &&
581
- error !== null &&
582
- "code" in error &&
583
- error.code === "ENOENT"
584
- )) {
566
+ if (!isMissingFile(error)) {
585
567
  if (error instanceof ConfigError) throw error;
586
568
  throw new ConfigError(`${file}: invalid JSON: ${String(error)}`, {
587
569
  cause: error,
@@ -611,7 +593,55 @@ export async function setPluginEnabled(
611
593
  throw new ConfigError(`${file}: plugins.${name}: must be a module name or an object`);
612
594
  }
613
595
  await mkdir(home, { recursive: true });
614
- await writeFile(file, `${JSON.stringify(raw, null, 2)}\n`);
596
+ await writeJsonAtomic(file, raw, { ...hooks, space: 2 });
597
+ }
598
+
599
+ /**
600
+ * Adds one plugin to `config.json` turned off, keeping every other key. The
601
+ * name is the plugin's declared name, and `module` is the npm package it was
602
+ * installed from; turning it on is a separate command, so a person sees what
603
+ * they enable. The read and write take the config lock, so another writer's
604
+ * change is not lost.
605
+ */
606
+ export async function addPluginEntry(
607
+ home: string,
608
+ name: string,
609
+ module: string,
610
+ options: LockFileOptions & AsyncAtomicWriteOptions = {},
611
+ ): Promise<void> {
612
+ const file = configPath(home);
613
+ return withLockFile(`${file}.lock`, async () => {
614
+ let raw: Record<string, unknown>;
615
+ try {
616
+ const text = await readFile(file, "utf8");
617
+ const parsed: unknown = JSON.parse(text);
618
+ if (!isRecord(parsed)) throw new ConfigError(`${file}: must be a JSON object`);
619
+ raw = parsed;
620
+ } catch (error) {
621
+ if (!isMissingFile(error)) {
622
+ if (error instanceof ConfigError) throw error;
623
+ throw new ConfigError(`${file}: invalid JSON: ${String(error)}`, {
624
+ cause: error,
625
+ });
626
+ }
627
+ raw = configJson(defaultConfig(home));
628
+ }
629
+
630
+ if (raw.plugins === undefined) {
631
+ raw.plugins = {};
632
+ }
633
+ if (!isRecord(raw.plugins)) {
634
+ throw new ConfigError(
635
+ `${file}: plugins: must be an object keyed by plugin name to add one`,
636
+ );
637
+ }
638
+ if (Object.hasOwn(raw.plugins, name)) {
639
+ throw new ConfigError(`${file}: plugins.${name}: already exists`);
640
+ }
641
+ raw.plugins[name] = { module, enabled: false };
642
+ await mkdir(home, { recursive: true });
643
+ await writeJsonAtomic(file, raw, { ...options, space: 2 });
644
+ }, options);
615
645
  }
616
646
 
617
647
  /** Opens the log the config selects. Options pass through to the backend. */
@@ -621,7 +651,6 @@ export function openConfigLog(
621
651
  ): LogBackend {
622
652
  return openLog({
623
653
  ...options,
624
- backend: config.store.backend,
625
654
  path: config.store.path,
626
655
  });
627
656
  }
package/src/flow/types.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { ChoiceInfo } from "../plugin/types.ts";
2
+
1
3
  /** How a step behaves when a run resumes after a crash. */
2
4
  export type Replay = "safe" | "unsafe";
3
5
 
@@ -54,6 +56,8 @@ export interface WaitPersonStep extends StepBase {
54
56
  readonly params: {
55
57
  readonly prompt: string;
56
58
  readonly choices: readonly string[];
59
+ /** What each choice is, keyed by the choice string an answer sends. */
60
+ readonly choiceInfo?: Readonly<Record<string, ChoiceInfo>> | undefined;
57
61
  /**
58
62
  * Answers a timed-out step may hand over that this wait does not offer by
59
63
  * itself. They need an edge in `next`, and are shown only when the step
@@ -7,6 +7,7 @@ import {
7
7
  type StepTypeRegistry,
8
8
  } from "./types.ts";
9
9
  import { isRecord } from "../util.ts";
10
+ import { choiceInfoProblem } from "../plugin/choice-info.ts";
10
11
 
11
12
  /** A flow is not usable; the message names the flow, step and field. */
12
13
  export class FlowError extends Error {
@@ -117,6 +118,10 @@ function checkStep(
117
118
  if (!isStringArray(lateChoices)) {
118
119
  throw new FlowError(at("params.lateChoices: must be an array of strings"));
119
120
  }
121
+ const infoProblem = choiceInfoProblem(params.choiceInfo, choices);
122
+ if (infoProblem !== undefined) {
123
+ throw new FlowError(at(`params.choiceInfo: ${infoProblem}`));
124
+ }
120
125
  if (
121
126
  params.note !== undefined &&
122
127
  (typeof params.note !== "string" || params.note.length === 0)
package/src/http/index.ts CHANGED
@@ -4,6 +4,7 @@ export {
4
4
  validateListenAddresses,
5
5
  type ListenAddressKind,
6
6
  } from "./address.ts";
7
+ export type { PluginAdmin, PluginInfo, PluginOrigin, PluginSetup, PluginSwitchOptions } from "./plugins.ts";
7
8
  export { LINK_SCHEME, objectLink, pairLink } from "./link.ts";
8
9
  export {
9
10
  DEFAULT_HTTP_TOKEN_LABEL,
@@ -19,6 +20,7 @@ export {
19
20
  DEFAULT_STOP_TIMEOUT_MS,
20
21
  displayNameOf,
21
22
  HttpStopError,
23
+ MAX_SSE_EVENT_BYTES,
22
24
  startHttpServer,
23
25
  type HttpServerHandle,
24
26
  type HttpServerOptions,
@@ -0,0 +1,68 @@
1
+ /** The plugin list and switch a client of `serve` reaches; the home's plugin loading is the kernel's. */
2
+
3
+ import type { Actor, HarnessModels, MissingItem } from "../plugin/types.ts";
4
+
5
+ /**
6
+ * Where a plugin comes from: `builtin` is a package operad ships, `home` is
7
+ * anything else the home's `config.json` names (a path or another package).
8
+ * Plugins of a project are not loaded yet, so there is no `project`.
9
+ */
10
+ export type PluginOrigin = "builtin" | "home";
11
+
12
+ /** One configured plugin: the facts `operad plugin list` prints, plus where it comes from. */
13
+ export interface PluginInfo {
14
+ readonly name: string;
15
+ /** The version the loaded plugin declares; `null` for a plugin that is off or did not load. */
16
+ readonly version: string | null;
17
+ readonly enabled: boolean;
18
+ readonly origin: PluginOrigin;
19
+ /**
20
+ * A loaded harness plugin's answer about its agent's login: `true` or
21
+ * `false`, absent when it cannot tell. Only the answer is exposed.
22
+ */
23
+ readonly signedIn?: boolean | undefined;
24
+ /**
25
+ * A loaded harness plugin's models, with what it knows about each one. A
26
+ * client that reads only `list` keeps working.
27
+ */
28
+ readonly models?: HarnessModels | undefined;
29
+ /** A loaded harness plugin's access levels it can carry, by id; empty when it carries none. */
30
+ readonly accessLevels?: readonly string[] | undefined;
31
+ /**
32
+ * The latest line the package install printed, while this plugin is being
33
+ * installed. A plugin being installed is listed before `config.json` names
34
+ * it, with `version: null` and `enabled: false`.
35
+ */
36
+ readonly progress?: string | undefined;
37
+ /** True when the plugin ships a setup guide (ADR 0010 D7): a client offers "Setup <name>". */
38
+ readonly guide?: true | undefined;
39
+ }
40
+
41
+ /** What is missing from one plugin's setup; never the guide's text (ADR 0010 D7). */
42
+ export interface PluginSetup {
43
+ readonly plugin: string;
44
+ readonly enabled: boolean;
45
+ readonly missing: readonly MissingItem[];
46
+ }
47
+
48
+ export interface PluginSwitchOptions {
49
+ /** The client confirmed turning a plugin off. */
50
+ readonly confirmed: boolean;
51
+ /** Who asked. */
52
+ readonly actor: Actor;
53
+ }
54
+
55
+ /**
56
+ * What the HTTP interface calls to list and switch plugins. The caller that
57
+ * owns the home supplies it, so the answers and refusals are the command
58
+ * line's. A refusal is a `ViewError`.
59
+ */
60
+ export interface PluginAdmin {
61
+ list(): Promise<readonly PluginInfo[]>;
62
+ /** Installs `<package>[@version]` and adds it turned off; it needs the confirmation. */
63
+ install(specifier: string, options: PluginSwitchOptions): Promise<PluginInfo>;
64
+ /** Writes `plugins.<name>.enabled` in `config.json`; it takes effect at the next load. */
65
+ set(name: string, enabled: boolean, options: PluginSwitchOptions): Promise<PluginInfo>;
66
+ /** What one plugin's setup is missing; undefined when the plugin has no guide. */
67
+ setup?(name: string): Promise<PluginSetup | undefined>;
68
+ }