@operad-io/cli 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.
package/src/main.ts CHANGED
@@ -1,12 +1,26 @@
1
- import { INSTALL_ON_ENABLE, OPTIONAL_PLUGINS, defaultPluginModule, distributionConfig, pluginOffer } from "./defaults.ts";
2
- import { closeSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
1
+ import {
2
+ INIT_HARNESS_PLUGINS,
3
+ INSTALL_ON_ENABLE,
4
+ OPTIONAL_PLUGINS,
5
+ PLUGIN_NEEDS,
6
+ PI_CODING_AGENT_PACKAGE,
7
+ PI_CODING_AGENT_VERSION,
8
+ defaultPluginModule,
9
+ distributionConfig,
10
+ pluginOffer,
11
+ } from "./defaults.ts";
12
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
3
13
  import { userInfo } from "node:os";
4
- import { join } from "node:path";
14
+ import { join, resolve } from "node:path";
5
15
  import { isatty } from "node:tty";
6
16
  import { fileURLToPath, pathToFileURL } from "node:url";
7
17
  import {
8
18
  ConfigError,
9
19
  FileSecretStore,
20
+ addPackage,
21
+ addPluginEntry,
22
+ OPERAD_PLUGIN_VERSION,
23
+ isRecord,
10
24
  Kernel,
11
25
  LockHeldError,
12
26
  acquireLock,
@@ -15,11 +29,7 @@ import {
15
29
  PluginRegistry,
16
30
  Runner,
17
31
  StateError,
18
- TriggerError,
19
32
  ViewError,
20
- applyInput,
21
- cancelRun,
22
- createViews,
23
33
  defaultOperadHome,
24
34
  ensureConfig,
25
35
  ensureInstalledPackage,
@@ -36,22 +46,29 @@ import {
36
46
  loadSourcedTriggerRules,
37
47
  loadTriggerRules,
38
48
  lockHeld,
49
+ definitionName,
39
50
  messageOf,
40
- openConfigLog,
41
51
  Notifier,
42
52
  CodeWatch,
53
+ DEFAULT_CHECK_TIMEOUT_MS,
54
+ DEFAULT_RETRY_MS,
55
+ describeChange,
43
56
  olderCodeNotice,
44
57
  ensureHttpToken,
45
58
  listenAddressKind,
46
59
  pairLink,
60
+ openHome,
47
61
  openPluginStore,
62
+ KERNEL_VERBS,
63
+ formatElapsed,
48
64
  parseObjectKey,
49
65
  readConfig,
50
66
  readState,
51
67
  readStoredStart,
52
68
  runningFromWorkspace,
53
69
  readStoredTrigger,
54
- recordAnswer,
70
+ renderMarkdown,
71
+ removePackage,
55
72
  rotateHttpToken,
56
73
  serve,
57
74
  serveLockPath,
@@ -60,28 +77,40 @@ import {
60
77
  startHttpServer,
61
78
  storeRootOf,
62
79
  ENGINE_VERSION,
80
+ type AddedPackage,
63
81
  type ActionArgsSchema,
64
82
  type ActionArgSchema,
65
83
  type ActionInfo,
66
84
  type Actor,
85
+ type PluginAdmin,
86
+ type PluginInfo,
67
87
  type LogBackend,
68
88
  type GlobalFact,
69
89
  HttpStopError,
70
90
  type HttpServerHandle,
71
91
  type InstallRunner,
72
92
  type OperadConfig,
93
+ type OpenedHome,
73
94
  type RunInfo,
74
95
  type TriggerEvent,
75
96
  type TriggerRule,
76
97
  type ViewAction,
77
98
  type ViewObject,
78
99
  type ViewRow,
79
- type Views,
80
100
  } from "@operad-io/engine";
101
+ import { loginBotFor } from "@operad-io/bot";
102
+ import { findGit, stopAllKeptWorkers } from "@operad-io/engine/platform";
81
103
  import { ChannelTypeError, runMcpServer } from "@operad-io/mcp";
104
+ import {
105
+ guardBackgroundBusy,
106
+ recordServeFailure,
107
+ retryWhileBusy,
108
+ serveStage,
109
+ } from "./serve-guard.ts";
82
110
  import {
83
111
  BIND_FAILED_EXIT,
84
112
  codeChecker,
113
+ PROBE_TIMEOUT_MS,
85
114
  RELOAD_EXIT,
86
115
  superviseServe,
87
116
  listenForStop,
@@ -90,6 +119,7 @@ import {
90
119
  serveSnapshots,
91
120
  } from "./code-reload.ts";
92
121
  import type { CodeSnapshot } from "./code-reload.ts";
122
+ import { formatDoctor, runDoctor, type DoctorAgent, type DoctorEnv, type DoctorReport } from "./doctor.ts";
93
123
  import {
94
124
  BindFailed,
95
125
  HandOverStuck,
@@ -98,11 +128,11 @@ import {
98
128
  serveStartFlags,
99
129
  startWithRetry,
100
130
  } from "./http-bind.ts";
101
- import { renderMarkdown } from "./markdown.ts";
102
131
  import { QrTooLongError, encodeQr, renderQr } from "./qr.ts";
103
132
  import {
104
133
  DEFAULT_STOP_TIMEOUT_SECS,
105
134
  parseStopTimeout,
135
+ recordSupervisor,
106
136
  serveStop,
107
137
  } from "./serve-stop.ts";
108
138
 
@@ -198,9 +228,13 @@ const STDIO: CliIo = {
198
228
 
199
229
  /** A command line mistake; exit code 2. */
200
230
  export class UsageError extends Error {
201
- constructor(message: string) {
231
+ /** The one-line usage of the command that was misused, when it is known. */
232
+ readonly usage: string | undefined;
233
+
234
+ constructor(message: string, usage?: string | undefined) {
202
235
  super(message);
203
236
  this.name = "UsageError";
237
+ this.usage = usage;
204
238
  }
205
239
  }
206
240
 
@@ -214,6 +248,10 @@ export interface MainOptions {
214
248
  readonly columns?: number | undefined;
215
249
  /** Replaces the OpenTUI app in a test; the real one is imported only by `tui`. */
216
250
  readonly tui?: TuiRunner | undefined;
251
+ /** Replaces what `operad doctor` asks the machine; a test supplies the facts. */
252
+ readonly doctor?: DoctorEnv | undefined;
253
+ /** Replaces the `bun add` command in a test for `plugin add`; defaults to Bun. */
254
+ readonly pluginInstall?: InstallRunner | undefined;
217
255
  }
218
256
 
219
257
  /** What the CLI hands the terminal app. */
@@ -227,6 +265,8 @@ export interface TuiCommand {
227
265
  readonly theme?: string | undefined;
228
266
  /** The entry file a started `operad serve` runs: this process's own. */
229
267
  readonly serveEntry?: string | undefined;
268
+ /** The parent whose new chat opens first: `bot:default` for a bare `operad`. */
269
+ readonly startChat?: string | undefined;
230
270
  /** Prints a line before the full screen opens. */
231
271
  readonly write?: ((line: string) => void) | undefined;
232
272
  readonly onError?: ((message: string) => void) | undefined;
@@ -236,33 +276,11 @@ export interface TuiCommand {
236
276
 
237
277
  export type TuiRunner = (command: TuiCommand) => Promise<number>;
238
278
 
239
- const KERNEL_VERBS = [
240
- "init",
241
- "serve",
242
- "pending",
243
- "history",
244
- "running",
245
- "flows",
246
- "trigger",
247
- "list",
248
- "show",
249
- "plugin",
250
- "secret",
251
- "settings",
252
- "http",
253
- "pair",
254
- "tui",
255
- "run-internal",
256
- "check-load",
257
- "mcp",
258
- ] as const;
259
-
260
- const KERNEL_ACTIONS = ["operad:start", "operad:dismiss"] as const;
261
-
262
279
  const HELP = [
263
280
  "usage: operad <command> [options]",
264
281
  "",
265
282
  " init create the operad home and check the plugins",
283
+ " doctor [--json] check the home, plugins, agents and serve; changes nothing",
266
284
  " serve run the kernel loop for this home",
267
285
  " serve stop [--timeout <secs>]",
268
286
  " stop this home's serve (SIGTERM; default timeout 30)",
@@ -273,6 +291,7 @@ const HELP = [
273
291
  " running runs in progress",
274
292
  " flows loaded flows and where they come from",
275
293
  " plugin list plugins with their version and whether they are enabled",
294
+ " plugin add <npm package> install a plugin from npm, off until it is enabled",
276
295
  " plugin enable <name> load a plugin again at the next command",
277
296
  " plugin disable <name> stop loading a plugin at the next command",
278
297
  " plugin check <path> validate a plugin declaration without starting it",
@@ -301,6 +320,192 @@ const HELP = [
301
320
  "",
302
321
  ].join("\n");
303
322
 
323
+ /** One command a mistyped word can be measured against. */
324
+ interface CommandCandidate {
325
+ readonly name: string;
326
+ readonly summary?: string | undefined;
327
+ }
328
+
329
+ const COMMAND_CANDIDATES: readonly CommandCandidate[] = [
330
+ { name: "init", summary: "create the operad home and check the plugins" },
331
+ { name: "doctor", summary: "check the home, plugins, agents and serve" },
332
+ { name: "serve", summary: "run the serve process for this home" },
333
+ { name: "serve stop", summary: "stop this home's serve" },
334
+ { name: "pending", summary: "things waiting for a person" },
335
+ { name: "list", summary: "objects of one type" },
336
+ { name: "show", summary: "one object, its sections and its actions" },
337
+ { name: "history", summary: "steps of a run, or of an object's runs" },
338
+ { name: "running", summary: "runs in progress" },
339
+ { name: "flows", summary: "loaded flows and where they come from" },
340
+ { name: "plugin", summary: "list, add, enable, disable or check plugins" },
341
+ { name: "secret", summary: "set, list or delete a plugin's secrets" },
342
+ { name: "settings", summary: "every setting with its value and default" },
343
+ { name: "http token rotate", summary: "replace the token the operad app uses" },
344
+ { name: "pair", summary: "show the address and token as a QR code" },
345
+ { name: "tui", summary: "open the terminal client" },
346
+ { name: "mcp", summary: "run the MCP server on stdio" },
347
+ { name: "trigger", summary: "send one event through the rules" },
348
+ { name: "operad:start", summary: "start a pending event" },
349
+ { name: "operad:dismiss", summary: "dismiss a pending event" },
350
+ { name: "start", summary: "start a pending event" },
351
+ { name: "dismiss", summary: "dismiss a pending event" },
352
+ { name: "help", summary: "print the whole command table" },
353
+ { name: "--version", summary: "print the operad version" },
354
+ { name: "--help", summary: "print the whole command table" },
355
+ ];
356
+
357
+ function editDistance(left: string, right: string): number {
358
+ const rows: number[][] = [];
359
+ for (let row = 0; row <= left.length; row += 1) {
360
+ rows.push(
361
+ Array.from({ length: right.length + 1 }, (_, column) =>
362
+ row === 0 ? column : column === 0 ? row : 0,
363
+ ),
364
+ );
365
+ }
366
+ for (let row = 1; row <= left.length; row += 1) {
367
+ const above = rows[row - 1] ?? [];
368
+ const current = rows[row] ?? [];
369
+ for (let column = 1; column <= right.length; column += 1) {
370
+ const same = left[row - 1] === right[column - 1] ? 0 : 1;
371
+ current[column] = Math.min(
372
+ (above[column] ?? 0) + 1,
373
+ (current[column - 1] ?? 0) + 1,
374
+ (above[column - 1] ?? 0) + same,
375
+ );
376
+ }
377
+ }
378
+ return rows[left.length]?.[right.length] ?? 0;
379
+ }
380
+
381
+ /** The command nearest to a word that matched nothing, nearest first. */
382
+ function closestCommand(
383
+ wanted: string,
384
+ extra: readonly CommandCandidate[] = [],
385
+ ): CommandCandidate | undefined {
386
+ const lower = wanted.toLowerCase();
387
+ if (lower.length === 0) return undefined;
388
+ // A word further from every command than this is not a mistyping of any.
389
+ const limit = lower.length <= 3 ? 1 : lower.length <= 5 ? 2 : 3;
390
+ let best: { readonly score: number; readonly candidate: CommandCandidate } | undefined;
391
+ for (const candidate of [...COMMAND_CANDIDATES, ...extra]) {
392
+ const text = candidate.name.toLowerCase();
393
+ // A short word matches inside many names; only a longer one counts.
394
+ const near =
395
+ (lower.length >= 3 && text.includes(lower)) || (text.length >= 3 && lower.includes(text));
396
+ const score = near ? 0 : editDistance(lower, text);
397
+ if (score > limit) continue;
398
+ if (
399
+ best === undefined ||
400
+ score < best.score ||
401
+ (score === best.score && candidate.name.localeCompare(best.candidate.name) < 0)
402
+ ) {
403
+ best = { score, candidate };
404
+ }
405
+ }
406
+ return best?.candidate;
407
+ }
408
+
409
+ /** The lines after an unknown command's message: the closest command, if any. */
410
+ function closestCommandLines(
411
+ wanted: string,
412
+ extra: readonly CommandCandidate[] = [],
413
+ ): string {
414
+ const near = closestCommand(wanted, extra);
415
+ if (near === undefined) return "";
416
+ const summary = near.summary === undefined ? "" : ` ${near.summary}`;
417
+ return `\nclosest:\n ${near.name}${summary}`;
418
+ }
419
+
420
+ /** The one-line usage of the command a mistake came from, when it has one. */
421
+ function commandUsage(args: readonly string[]): string | undefined {
422
+ const command = args[0];
423
+ const sub = args[1];
424
+ switch (command) {
425
+ case "init":
426
+ return "usage: operad init";
427
+ case "doctor":
428
+ return "usage: operad doctor [--json]";
429
+ case "serve":
430
+ return sub === "stop"
431
+ ? "usage: operad serve stop [--timeout <secs>]"
432
+ : "usage: operad serve";
433
+ case "pending":
434
+ return "usage: operad pending [--json]";
435
+ case "list":
436
+ return "usage: operad list <type> [options]";
437
+ case "show":
438
+ return "usage: operad show [<id>] [options]";
439
+ case "history":
440
+ return "usage: operad history <id> [--json]";
441
+ case "running":
442
+ return "usage: operad running [--json]";
443
+ case "flows":
444
+ return "usage: operad flows [--json]";
445
+ case "plugin": {
446
+ switch (sub) {
447
+ case "list":
448
+ return "usage: operad plugin list";
449
+ case "add":
450
+ return "usage: operad plugin add <npm package>";
451
+ case "enable":
452
+ return "usage: operad plugin enable <name>";
453
+ case "disable":
454
+ return "usage: operad plugin disable <name>";
455
+ case "check":
456
+ return "usage: operad plugin check <path>";
457
+ default:
458
+ return "usage: operad plugin <list|add|enable|disable|check>";
459
+ }
460
+ }
461
+ case "secret": {
462
+ switch (sub) {
463
+ case "set":
464
+ return "usage: operad secret set <plugin> <name>";
465
+ case "list":
466
+ return "usage: operad secret list <plugin>";
467
+ case "delete":
468
+ return "usage: operad secret delete <plugin> <name>";
469
+ default:
470
+ return "usage: operad secret <set|list|delete>";
471
+ }
472
+ }
473
+ case "settings":
474
+ return sub === "set"
475
+ ? "usage: operad settings set <name> <value> [--repo <name>] [--yes]"
476
+ : "usage: operad settings [--repo <name>] [--json]";
477
+ case "http":
478
+ return "usage: operad http token rotate";
479
+ case "pair":
480
+ return "usage: operad pair [--url <url>] [--show-token]";
481
+ case "tui":
482
+ return "usage: operad tui [--url <url>] [--token <token>] [--no-start] [--theme <name>]";
483
+ case "mcp":
484
+ return "usage: operad mcp [--claude-channel] [--types t,...]";
485
+ case "trigger":
486
+ return sub === "rules"
487
+ ? "usage: operad trigger rules"
488
+ : "usage: operad trigger <source> <key> [--type t] [--object o] [--summary text] [--data file]";
489
+ case "operad:start":
490
+ case "start":
491
+ return `usage: operad ${command} <id>`;
492
+ case "operad:dismiss":
493
+ case "dismiss":
494
+ return `usage: operad ${command} <id>`;
495
+ case "help":
496
+ return "usage: operad help";
497
+ case "--help":
498
+ return "usage: operad --help";
499
+ case "--version":
500
+ return "usage: operad --version";
501
+ default:
502
+ return undefined;
503
+ }
504
+ }
505
+
506
+ /** What every usage mistake ends with, so the whole table stays out of the error. */
507
+ const HELP_POINTER = "run `operad --help` for all commands";
508
+
304
509
  const COLOUR = {
305
510
  reset: "\x1b[0m",
306
511
  attention: "\x1b[33m",
@@ -323,17 +528,7 @@ function rowLine(row: ViewRow, tty: boolean): string {
323
528
  return `${name} ${state}${badge} ${row.title}${note}`;
324
529
  }
325
530
 
326
- interface Context {
327
- readonly home: string;
328
- readonly cwd: string;
329
- readonly config: OperadConfig;
330
- readonly registry: PluginRegistry;
331
- readonly log: LogBackend;
332
- readonly storeRoot: string;
333
- readonly views: Views;
334
- readonly disabled: readonly string[];
335
- /** What did not load, one line each, as the registry reported it. */
336
- readonly problems: string[];
531
+ interface Context extends OpenedHome {
337
532
  /** The code this process loaded, when the caller asked to keep track. */
338
533
  readonly code: CodeSnapshot | undefined;
339
534
  }
@@ -352,7 +547,14 @@ interface OpenContextOptions {
352
547
  readonly follow?: boolean | undefined;
353
548
  }
354
549
 
355
- async function openContext(
550
+ /** Drops the plugin store's database handle; a memory store has none. */
551
+ function closePluginStore(store: unknown): void {
552
+ if (typeof store !== "object" || store === null || !("close" in store)) return;
553
+ const close = store.close;
554
+ if (typeof close === "function") close.call(store);
555
+ }
556
+
557
+ export async function openContext(
356
558
  home: string,
357
559
  io: CliIo,
358
560
  options: OpenContextOptions = {},
@@ -363,89 +565,55 @@ async function openContext(
363
565
  // Taken before anything loads: a file that changes while loading then
364
566
  // counts as changed, never as loaded.
365
567
  const code = trackCode ? takeCodeSnapshot(home, config.plugins) : undefined;
366
- const problems: string[] = [];
367
- const storeRoot = storeRootOf(config);
368
- const store = openPluginStore({
369
- backend: config.store.backend,
370
- root: storeRoot,
371
- follow,
372
- });
373
- const log = openConfigLog(config, { follow });
374
- let loaded: PluginRegistry | undefined;
375
- const registry = await loadPluginRegistry({
376
- installOnEnable: INSTALL_ON_ENABLE,
568
+ // The kernel that emitted events use. `serve` and each command that builds
569
+ // a kernel with rules hands it over, so serve does not build a second one.
570
+ let eventKernel: Kernel | undefined;
571
+ let opened: OpenedHome | undefined;
572
+ const context = await openHome({
377
573
  home,
378
574
  cwd,
379
- store,
380
- kernelVerbs: KERNEL_VERBS,
381
- onLog: (message) => {
382
- problems.push(message);
383
- io.error(`${message}\n`);
384
- },
385
- onAnswer: async (runId, choice, note, actor) => {
386
- const runs = await log.runs();
387
- const run = runs.find((candidate) => candidate.runId === runId);
388
- if (run === undefined) throw new StateError(`no run "${runId}"`);
389
- await recordAnswer({
390
- log,
391
- runId,
392
- choice,
393
- ...(note === undefined ? {} : { note }),
394
- actor,
395
- });
575
+ config,
576
+ follow,
577
+ installOnEnable: INSTALL_ON_ENABLE,
578
+ optional: pluginOffer(home).optional,
579
+ ...(scope === undefined ? {} : { scope }),
580
+ ...(viewsCwd === undefined ? {} : { viewsCwd }),
581
+ cancelSource: "cli",
582
+ onLog: (message) => io.error(`${message}\n`),
583
+ afterAnswer: async () => {
396
584
  if (!lockHeld(serveLockPath(home))) {
397
585
  io.write("recorded; it runs when `operad serve` is running\n");
398
586
  }
399
587
  },
400
588
  onEvent: async (event) => {
401
- if (loaded === undefined) return;
589
+ if (eventKernel !== undefined) {
590
+ await eventKernel.receive(event);
591
+ return;
592
+ }
593
+ if (opened === undefined) return;
402
594
  const rules = await loadTriggerRules({
403
595
  home,
404
- registry: loaded,
596
+ registry: opened.registry,
405
597
  onLog: (message) => io.error(`${message}\n`),
406
598
  });
407
599
  const kernel = new Kernel({
408
- log,
409
- registry: loaded,
600
+ log: opened.log,
601
+ registry: opened.registry,
410
602
  home,
411
- storeRoot,
603
+ storeRoot: opened.storeRoot,
412
604
  rules,
413
605
  onLog: (message) => io.error(`${message}\n`),
414
606
  });
415
607
  await kernel.receive(event);
416
608
  },
417
- onCancelRun: (runId, graph) =>
418
- cancelRun({
419
- log,
420
- flow: (name) => loaded?.flow(name)?.flow,
421
- runId,
422
- graph,
423
- source: "cli",
424
- }),
425
609
  });
426
- loaded = registry;
610
+ opened = context;
427
611
  return {
428
- home,
429
- cwd,
430
- config,
431
- registry,
432
- log,
433
- storeRoot,
434
- problems,
612
+ ...context,
435
613
  code,
436
- disabled: config.plugins
437
- .filter((entry) => !entry.enabled)
438
- .map((entry) => entry.name)
439
- .filter((name): name is string => name !== undefined),
440
- views: createViews({
441
- registry,
442
- store,
443
- log,
444
- cwd: viewsCwd ?? cwd,
445
- follow,
446
- ...(scope === undefined ? {} : { scope }),
447
- onLog: (message) => io.error(`${message}\n`),
448
- }),
614
+ useKernelForEvents(kernel: Kernel): void {
615
+ eventKernel = kernel;
616
+ },
449
617
  };
450
618
  }
451
619
 
@@ -465,6 +633,7 @@ function kernelFor(
465
633
  });
466
634
  // A source plugin's `pending` shows the candidates HTTP shows.
467
635
  context.views.useCandidates(kernel);
636
+ context.useKernelForEvents(kernel);
468
637
  return kernel;
469
638
  }
470
639
 
@@ -490,19 +659,145 @@ function printValue(io: CliIo, value: unknown): void {
490
659
  io.write(`${JSON.stringify(value, null, 2)}\n`);
491
660
  }
492
661
 
493
- async function commandInit(home: string, io: CliIo): Promise<number> {
494
- const ensured = await ensureConfig(home, distributionConfig(home));
495
- io.write(
496
- `${ensured.created ? "created" : "using"} ${ensured.path}\n`,
662
+ /** True when an agent command is a path that exists, or a name on `PATH`. */
663
+ function commandPresent(command: string): boolean {
664
+ if (command.includes("/") || command.includes("\\")) return existsSync(resolve(command));
665
+ return Bun.which(command, { PATH: process.env.PATH ?? "" }) !== null;
666
+ }
667
+
668
+ /** What installing a plugin's package needs beyond the plugin itself. */
669
+ interface PluginInstallOptions {
670
+ readonly home: string;
671
+ readonly entry: OperadConfig["plugins"][number];
672
+ /** A test replaces the command; defaults to Bun. */
673
+ readonly run?: InstallRunner | undefined;
674
+ /** Receives each install line with the plugin it belongs to. */
675
+ readonly onProgress?: ((name: string, line: string) => void) | undefined;
676
+ }
677
+
678
+ /**
679
+ * Installs what an enabled plugin needs beyond its own package (ADR 0012 D4,
680
+ * ADR 0023 D9): claude's SDK package, and pi's library when the machine has no
681
+ * pi of its own. A plugin whose config names another module is left alone.
682
+ */
683
+ async function installPluginPackage(options: PluginInstallOptions): Promise<void> {
684
+ const name = options.entry.name;
685
+ if (name === undefined || !options.entry.enabled) return;
686
+ // A config entry written without `module` is normalised to the plugin's
687
+ // name, which is as much the default as the package name.
688
+ if (options.entry.module !== defaultPluginModule(name) && options.entry.module !== name) return;
689
+ const report =
690
+ options.onProgress === undefined
691
+ ? undefined
692
+ : (line: string) => options.onProgress?.(name, line);
693
+ if (name === "claude") {
694
+ // claude is not a CLI dependency: a home that enables it gets its package
695
+ // and SDK, skipping the platform binaries it does not use.
696
+ await ensureInstalledPackage({
697
+ home: options.home,
698
+ specifier: defaultPluginModule(name),
699
+ version: ENGINE_VERSION,
700
+ from: import.meta.dir,
701
+ omitOptional: true,
702
+ ...(options.run === undefined ? {} : { run: options.run }),
703
+ ...(report === undefined ? {} : { onProgress: report }),
704
+ });
705
+ return;
706
+ }
707
+ if (name === "pi") {
708
+ // pi is the user's own when PATH has one; otherwise operad installs its
709
+ // pinned copy into the home (ADR 0023 D9).
710
+ const settings = isRecord(options.entry.settings) ? options.entry.settings : {};
711
+ const command =
712
+ typeof settings["command"] === "string" && settings["command"] !== ""
713
+ ? settings["command"]
714
+ : "pi";
715
+ if (commandPresent(command)) return;
716
+ await ensureInstalledPackage({
717
+ home: options.home,
718
+ specifier: PI_CODING_AGENT_PACKAGE,
719
+ version: PI_CODING_AGENT_VERSION,
720
+ ...(options.run === undefined ? {} : { run: options.run }),
721
+ ...(report === undefined ? {} : { onProgress: report }),
722
+ });
723
+ }
724
+ }
725
+
726
+ /**
727
+ * Makes sure the home has the distribution's configuration, and installs what
728
+ * its enabled plugins need. `operad init` and a bare `operad` both start here;
729
+ * only `init` prints the checks.
730
+ */
731
+ async function ensureHomeConfig(
732
+ home: string,
733
+ onConfig?: ((made: {
734
+ readonly created: boolean;
735
+ readonly path: string;
736
+ readonly harnesses: readonly string[];
737
+ readonly noAgent: boolean;
738
+ }) => void) | undefined,
739
+ options: {
740
+ readonly run?: InstallRunner | undefined;
741
+ readonly onProgress?: ((name: string, line: string) => void) | undefined;
742
+ } = {},
743
+ ): Promise<{
744
+ readonly created: boolean;
745
+ readonly path: string;
746
+ readonly config: OperadConfig;
747
+ readonly harnesses: readonly string[];
748
+ }> {
749
+ // A new home turns on the agents this machine has. With none, it turns on pi
750
+ // and operad installs its own pi, so a first run needs no agent installed
751
+ // beforehand (ADR 0012 D2, ADR 0022 D6).
752
+ const path = process.env.PATH ?? "";
753
+ const found = INIT_HARNESS_PLUGINS.filter(
754
+ (name) => Bun.which(name, { PATH: path }) !== null,
497
755
  );
498
- const config = await readConfig(home);
756
+ const noAgent = found.length === 0;
757
+ const harnesses = noAgent ? ["pi"] : found;
758
+ const ensured = await ensureConfig(home, distributionConfig(home, harnesses));
759
+ onConfig?.({ created: ensured.created, path: ensured.path, harnesses, noAgent });
760
+ // Reading the config first makes a second init retry an install that failed
761
+ // after the config was written.
762
+ for (const entry of ensured.config.plugins) {
763
+ await installPluginPackage({
764
+ home,
765
+ entry,
766
+ ...(options.run === undefined ? {} : { run: options.run }),
767
+ ...(options.onProgress === undefined ? {} : { onProgress: options.onProgress }),
768
+ });
769
+ }
770
+ return {
771
+ created: ensured.created,
772
+ path: ensured.path,
773
+ config: ensured.config,
774
+ harnesses,
775
+ };
776
+ }
777
+
778
+ async function commandInit(home: string, io: CliIo, installRun?: InstallRunner): Promise<number> {
779
+ const ensured = await ensureHomeConfig(
780
+ home,
781
+ (made) => {
782
+ io.write(`${made.created ? "created" : "using"} ${made.path}\n`);
783
+ if (made.created && made.noAgent) {
784
+ io.write(
785
+ "no agent found on PATH: installing operad's own pi for this home (it needs the network once)\n",
786
+ );
787
+ }
788
+ },
789
+ {
790
+ ...(installRun === undefined ? {} : { run: installRun }),
791
+ onProgress: (name, line) => io.write(`${name}: ${line}\n`),
792
+ },
793
+ );
794
+ const config = ensured.config;
499
795
  const storeRoot = storeRootOf(config);
500
796
  const registry = await loadPluginRegistry({
501
797
  installOnEnable: INSTALL_ON_ENABLE,
502
798
  home,
503
799
  cwd: home,
504
800
  store: openPluginStore({
505
- backend: config.store.backend,
506
801
  root: storeRoot,
507
802
  follow: false,
508
803
  }),
@@ -523,6 +818,136 @@ async function commandInit(home: string, io: CliIo): Promise<number> {
523
818
  return failed ? 1 : 0;
524
819
  }
525
820
 
821
+ /** Asks the machine, not a test, each fact `operad doctor` prints. */
822
+ function systemDoctorEnv(home: string, io: CliIo): DoctorEnv & { close(): Promise<void> } {
823
+ let opened: Promise<Context> | undefined;
824
+ const context = (): Promise<Context> => {
825
+ opened ??= openContext(home, { ...io, error: () => undefined });
826
+ return opened;
827
+ };
828
+ return {
829
+ close: async () => {
830
+ if (opened === undefined) return;
831
+ const ctx = await opened;
832
+ ctx.views.close();
833
+ await ctx.log.close();
834
+ },
835
+ homeExists: () => existsSync(home),
836
+ config: async () => {
837
+ if (!existsSync(join(home, "config.json"))) return { present: false };
838
+ await readConfig(home);
839
+ return { present: true };
840
+ },
841
+ plugins: async () => {
842
+ const { config, registry, problems } = await context();
843
+ const names = new Set(registry.names());
844
+ return config.plugins
845
+ .filter((entry) => entry.enabled)
846
+ .map((entry) => {
847
+ const name = entry.name ?? entry.module;
848
+ if (names.has(name)) return { name, loaded: true };
849
+ const refusal = registry.refusals().find((item) => item.plugin === name);
850
+ const logged = problems.find((line) => line.includes(`"${name}"`) || line.includes(entry.module));
851
+ return {
852
+ name,
853
+ loaded: false,
854
+ problem: refusal?.message ?? logged ?? "it was not loaded",
855
+ };
856
+ });
857
+ },
858
+ agents: async () => {
859
+ const { registry } = await context();
860
+ const checks = await registry.checks();
861
+ const agents: DoctorAgent[] = [];
862
+ const loaded = registry.loadedHarnesses();
863
+ const written = registry.settingsFor("bot").bots;
864
+ const bots: Record<string, unknown> = isRecord(written) ? { ...written } : {};
865
+ bots.default ??= {};
866
+ // The bot whose agent operad can log in: `default` first, then the others.
867
+ const loginBotOf = (name: string): string | undefined =>
868
+ registry.names().includes("bot")
869
+ ? loginBotFor(name, bots, loaded, (item) => registry.stepLoaded(`${item}/login`))
870
+ : undefined;
871
+ for (const name of loaded) {
872
+ const check = checks.find((item) => item.plugin === name);
873
+ const version = check?.message.match(/\d+\.\d+\.\d+[\w.-]*/)?.[0];
874
+ const loginBot = loginBotOf(name);
875
+ agents.push({
876
+ name,
877
+ ...(version === undefined ? {} : { version }),
878
+ signedIn: await registry.signedInFor(name),
879
+ ...(loginBot === undefined ? {} : { loginBot }),
880
+ ...(check !== undefined && !check.ok ? { problem: check.message } : {}),
881
+ });
882
+ }
883
+ return agents;
884
+ },
885
+ serve: async () => {
886
+ if (!lockHeld(serveLockPath(home))) return { answering: false };
887
+ const config = await readConfig(home);
888
+ const address = config.http.listen[0];
889
+ if (address === undefined || config.http.port === 0) return { answering: false };
890
+ const host = address.includes(":") ? `[${address}]` : address;
891
+ try {
892
+ // Any answer proves serve is up; the token is not needed, so none is read or made.
893
+ await fetch(`http://${host}:${config.http.port}/v1/types`, {
894
+ signal: AbortSignal.timeout(2_000),
895
+ });
896
+ return { answering: true };
897
+ } catch {
898
+ return { answering: false };
899
+ }
900
+ },
901
+ gitInstalled: () => findGit() !== undefined,
902
+ testHost: async () => {
903
+ const { registry } = await context();
904
+ const fromEnv = process.env.OPERAD_CHECK_HOST;
905
+ const setting = registry.settingsFor("dev").testHost;
906
+ const host = fromEnv ?? (typeof setting === "string" ? setting : "");
907
+ if (host.length === 0) return undefined;
908
+ const probe = Bun.spawn(
909
+ ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", host, "true"],
910
+ { stdin: "ignore", stdout: "ignore", stderr: "ignore" },
911
+ );
912
+ return { host, reachable: (await probe.exited) === 0 };
913
+ },
914
+ setup: async () => {
915
+ const ctx = await context();
916
+ const pending = await listPending(
917
+ ctx.log,
918
+ ctx.registry,
919
+ kernelFor(ctx, { ...io, error: () => undefined }, []),
920
+ ctx.views,
921
+ );
922
+ return pending
923
+ .filter((item) => item.kind === "standing" && item.object === undefined)
924
+ .map((item) => ({ id: item.runId, prompt: item.prompt }));
925
+ },
926
+ };
927
+ }
928
+
929
+ /** `operad doctor [--json]`: read-only; exits 1 when any line is a problem. */
930
+ async function commandDoctor(
931
+ home: string,
932
+ io: CliIo,
933
+ args: readonly string[],
934
+ env?: DoctorEnv,
935
+ ): Promise<number> {
936
+ const { args: rest, present } = splitFlag(args, "--json");
937
+ if (rest.length > 0) throw new UsageError("doctor takes no arguments");
938
+ // The system's environment opens the home only when a check asks, so an
939
+ // injected one leaves it closed and `close` has nothing to do.
940
+ const system = systemDoctorEnv(home, io);
941
+ let report: DoctorReport;
942
+ try {
943
+ report = await runDoctor(env ?? system);
944
+ } finally {
945
+ await system.close();
946
+ }
947
+ io.write(present ? `${JSON.stringify(report, null, 2)}\n` : formatDoctor(report));
948
+ return report.ok ? 0 : 1;
949
+ }
950
+
526
951
  async function commandPending(
527
952
  context: Context,
528
953
  io: CliIo,
@@ -543,7 +968,9 @@ async function commandPending(
543
968
  return;
544
969
  }
545
970
  for (const item of pending) {
546
- io.write(`${item.runId} ${item.flow} ${item.step ?? "-"}\n`);
971
+ // A standing item is named by its object, which its actions take; a run is named by its id.
972
+ const name = item.kind === "standing" && item.object !== undefined ? item.object : item.runId;
973
+ io.write(`${name} ${item.flow} ${item.step ?? "-"}\n`);
547
974
  if (item.row !== undefined) io.write(` ${item.row.title}\n`);
548
975
  io.write(` waiting: ${item.prompt}\n`);
549
976
  if (item.choices.length > 0) {
@@ -718,14 +1145,15 @@ async function commandList(
718
1145
  async function writeChildren(
719
1146
  context: Context,
720
1147
  io: CliIo,
721
- id: string,
1148
+ object: { readonly type: string; readonly id: string },
722
1149
  tty: boolean,
723
1150
  ): Promise<void> {
724
1151
  let cursor: string | undefined;
725
1152
  let hidden = 0;
726
1153
  for (;;) {
1154
+ // The parent's type is known here; another type may hold the same bare id.
727
1155
  const page = await context.views.listTree(undefined, {
728
- parent: id,
1156
+ parent: `${object.type}:${object.id}`,
729
1157
  ...(cursor === undefined ? {} : { cursor }),
730
1158
  });
731
1159
  for (const row of page.rows) {
@@ -735,14 +1163,14 @@ async function writeChildren(
735
1163
  if (page.next === undefined) break;
736
1164
  cursor = page.next;
737
1165
  }
738
- if (hidden > 0) io.write(`${hidden} hidden (operad list --parent ${shellQuote(id)} --filter all)\n`);
1166
+ if (hidden > 0) io.write(`${hidden} hidden (operad list --parent ${shellQuote(object.id)} --filter all)\n`);
739
1167
  }
740
1168
 
741
1169
  function firstSection(object: ViewObject): string | undefined {
742
1170
  return object.sections[0]?.id;
743
1171
  }
744
1172
 
745
- function actionArgFlags(action: ViewAction | ActionInfo): string[] {
1173
+ function actionArgFlags(action: Pick<ActionInfo, "args">): string[] {
746
1174
  const args: string[] = [];
747
1175
  for (const [name, property] of Object.entries(action.args?.properties ?? {})) {
748
1176
  if (property.enum !== undefined) {
@@ -897,13 +1325,18 @@ async function commandShow(
897
1325
  if (object.unavailable !== undefined) {
898
1326
  io.error(`operad: ${object.unavailable}\n`);
899
1327
  }
900
- await writeChildren(context, io, object.id, tty);
1328
+ await writeChildren(context, io, object, tty);
901
1329
  io.write(
902
1330
  `sections: ${object.sections.map((section) => (section.live === true ? `${section.title} (live)` : section.title)).join(", ")}\n`,
903
1331
  );
904
1332
  io.write(
905
1333
  `actions: ${object.actions.length === 0 ? "none" : object.actions.map(actionLine).join(", ")}\n`,
906
1334
  );
1335
+ if (object.skills !== undefined) {
1336
+ io.write(
1337
+ `skills: ${object.skills.length === 0 ? "none" : object.skills.map((skill) => `/${skill.name}${skill.description === undefined ? "" : ` (${skill.description})`}`).join(", ")}\n`,
1338
+ );
1339
+ }
907
1340
  if (requested === undefined) return;
908
1341
 
909
1342
  const content = await readSection(requested);
@@ -1085,7 +1518,7 @@ export function actorOfCli(username: string = userInfo().username): Actor {
1085
1518
  function actionCandidates(
1086
1519
  context: Context,
1087
1520
  name: string,
1088
- ): readonly { readonly name: string; readonly on: string }[] {
1521
+ ): readonly { readonly name: string; readonly on?: string | undefined }[] {
1089
1522
  return context.registry
1090
1523
  .actions()
1091
1524
  .filter((info) => info.action === name);
@@ -1094,6 +1527,7 @@ function actionCandidates(
1094
1527
  function resolveActionRequest(
1095
1528
  context: Context,
1096
1529
  positionals: readonly string[],
1530
+ usage?: string | undefined,
1097
1531
  ): { readonly name: string; readonly id: string } | undefined {
1098
1532
  const first = positionals[0];
1099
1533
  if (first === undefined) return undefined;
@@ -1101,10 +1535,10 @@ function resolveActionRequest(
1101
1535
  if (splitActionName(first) !== undefined) {
1102
1536
  const id = positionals[1];
1103
1537
  if (id === undefined) {
1104
- throw new UsageError(`action "${first}" needs an object id`);
1538
+ throw new UsageError(`action "${first}" needs an object id`, usage);
1105
1539
  }
1106
1540
  if (positionals.length > 2) {
1107
- throw new UsageError(`action "${first}" takes one object id`);
1541
+ throw new UsageError(`action "${first}" takes one object id`, usage);
1108
1542
  }
1109
1543
  return { name: first, id };
1110
1544
  }
@@ -1118,10 +1552,10 @@ function resolveActionRequest(
1118
1552
  ) {
1119
1553
  const id = positionals[2];
1120
1554
  if (id === undefined) {
1121
- throw new UsageError(`action "${first}:${second}" needs an object id`);
1555
+ throw new UsageError(`action "${first}:${second}" needs an object id`, usage);
1122
1556
  }
1123
1557
  if (positionals.length > 3) {
1124
- throw new UsageError(`action "${first}:${second}" takes one object id`);
1558
+ throw new UsageError(`action "${first}:${second}" takes one object id`, usage);
1125
1559
  }
1126
1560
  return { name: `${first}:${second}`, id };
1127
1561
  }
@@ -1129,17 +1563,18 @@ function resolveActionRequest(
1129
1563
  const candidates = actionCandidates(context, first);
1130
1564
  if (candidates.length === 0) return undefined;
1131
1565
  if (second === undefined) {
1132
- throw new UsageError(`action "${first}" needs an object id`);
1566
+ throw new UsageError(`action "${first}" needs an object id`, usage);
1133
1567
  }
1134
1568
  if (candidates.length > 1) {
1135
1569
  throw new UsageError(
1136
1570
  `action "${first}" is offered by ${candidates
1137
1571
  .map((candidate) => `"${candidate.name}"`)
1138
1572
  .join(", ")}; use "<plugin>:<action>"`,
1573
+ usage,
1139
1574
  );
1140
1575
  }
1141
1576
  if (positionals.length > 2) {
1142
- throw new UsageError(`action "${first}" takes one object id`);
1577
+ throw new UsageError(`action "${first}" takes one object id`, usage);
1143
1578
  }
1144
1579
  return { name: candidates[0]?.name ?? first, id: second };
1145
1580
  }
@@ -1174,11 +1609,15 @@ async function promptConfirm(io: CliIo, name: string): Promise<boolean> {
1174
1609
  return /^y(es)?$/i.test((answer ?? "").trim());
1175
1610
  }
1176
1611
 
1177
- function actionUsage(action: ActionInfo): string {
1612
+ function actionUsageLine(action: Pick<ActionInfo, "name" | "args" | "confirm">): string {
1178
1613
  const flags = actionArgFlags(action);
1179
1614
  if (action.confirm) flags.push("--yes");
1180
1615
  const suffix = flags.length === 0 ? "" : ` ${flags.map((flag) => `[${flag}]`).join(" ")}`;
1181
- return `usage: operad ${action.name} <id>${suffix}\n`;
1616
+ return `usage: operad ${action.name} <id>${suffix}`;
1617
+ }
1618
+
1619
+ function actionUsage(action: ActionInfo): string {
1620
+ return `${actionUsageLine(action)}\n`;
1182
1621
  }
1183
1622
 
1184
1623
  async function commandAction(
@@ -1187,6 +1626,10 @@ async function commandAction(
1187
1626
  argv: readonly string[],
1188
1627
  tty: boolean,
1189
1628
  ): Promise<boolean> {
1629
+ // A plugin command and an action may share a plain name (`plan` is both a
1630
+ // dev command and the action that creates a plan). The command keeps the
1631
+ // plain name; its action is still reached as `dev:plan`.
1632
+ if (context.registry.resolveCommand(argv) !== undefined) return false;
1190
1633
  const help = splitFlag(argv, "--help");
1191
1634
  if (help.present) {
1192
1635
  const info = actionInfoForArgv(context, help.args);
@@ -1197,7 +1640,11 @@ async function commandAction(
1197
1640
 
1198
1641
  const info = actionInfoForArgv(context, argv);
1199
1642
  const args = parseActionArguments(argv, info?.args);
1200
- const request = resolveActionRequest(context, args.positionals);
1643
+ const request = resolveActionRequest(
1644
+ context,
1645
+ args.positionals,
1646
+ info === undefined ? undefined : actionUsageLine(info),
1647
+ );
1201
1648
  if (request === undefined) return false;
1202
1649
 
1203
1650
  const object = await context.views.get(request.id);
@@ -1215,6 +1662,7 @@ async function commandAction(
1215
1662
  }
1216
1663
 
1217
1664
  const actionArgs = actionArgsFromFlags(available, args.values);
1665
+ const usage = actionUsageLine(available);
1218
1666
  const note = noteField(available.args);
1219
1667
  if (
1220
1668
  note !== undefined &&
@@ -1226,11 +1674,12 @@ async function commandAction(
1226
1674
  if (!tty) {
1227
1675
  throw new UsageError(
1228
1676
  `action "${request.name}" needs a note; pass --${note} <text>`,
1677
+ usage,
1229
1678
  );
1230
1679
  }
1231
1680
  const text = await promptNote(io);
1232
1681
  if (text.trim().length === 0) {
1233
- throw new UsageError(`action "${request.name}" needs a note`);
1682
+ throw new UsageError(`action "${request.name}" needs a note`, usage);
1234
1683
  }
1235
1684
  actionArgs[note] = text;
1236
1685
  }
@@ -1239,6 +1688,7 @@ async function commandAction(
1239
1688
  if (!tty) {
1240
1689
  throw new UsageError(
1241
1690
  `action "${request.name}" needs confirmation; pass --yes`,
1691
+ usage,
1242
1692
  );
1243
1693
  }
1244
1694
  if (!(await promptConfirm(io, request.name))) {
@@ -1261,28 +1711,23 @@ async function findHistoryRuns(
1261
1711
  objectTypes: readonly string[],
1262
1712
  id: string,
1263
1713
  ): Promise<readonly RunInfo[]> {
1264
- const runs = await log.runs();
1265
- const exact = runs.find((run) => run.runId === id);
1714
+ const exact = await log.run(id);
1266
1715
  if (exact !== undefined) return [exact];
1267
1716
 
1268
1717
  const parsed = parseObjectKey(id);
1269
1718
  if (parsed !== undefined) {
1270
1719
  // A type no loaded plugin declares is unknown, as it is for a bare id.
1271
1720
  if (!objectTypes.includes(parsed.type)) return [];
1272
- return runs.filter((run) => run.object === `${parsed.type}:${parsed.id}`);
1721
+ return log.runs({ object: `${parsed.type}:${parsed.id}` });
1273
1722
  }
1274
1723
 
1275
- const plain = runs.filter((run) => run.object === id);
1724
+ const plain = await log.runs({ object: id });
1276
1725
  if (plain.length > 0) return plain;
1277
1726
 
1278
1727
  const byType = new Map<string, RunInfo[]>();
1279
- for (const run of runs) {
1280
- const key = parseObjectKey(run.object);
1281
- if (key === undefined || key.id !== id) continue;
1282
- if (!objectTypes.includes(key.type)) continue;
1283
- const list = byType.get(key.type) ?? [];
1284
- list.push(run);
1285
- byType.set(key.type, list);
1728
+ for (const type of objectTypes) {
1729
+ const list = await log.runs({ object: `${type}:${id}` });
1730
+ if (list.length > 0) byType.set(type, list);
1286
1731
  }
1287
1732
  if (byType.size > 1) {
1288
1733
  const names = [...byType.keys()].sort();
@@ -1334,8 +1779,9 @@ async function commandTrigger(
1334
1779
  for (const entry of rules) {
1335
1780
  const rule = entry.rule;
1336
1781
  const schedule = rule.schedule === undefined ? "" : ` every ${rule.schedule}`;
1782
+ const paused = rule.paused === true ? " paused" : "";
1337
1783
  io.write(
1338
- `${rule.source} ${rule.type} -> ${rule.start.flow} on ${rule.object} (${rule.mode})${schedule} from ${entry.from}\n`,
1784
+ `${rule.source} ${rule.type} -> ${rule.start.flow} on ${rule.object} (${rule.mode})${schedule}${paused} from ${entry.from}\n`,
1339
1785
  );
1340
1786
  }
1341
1787
  return;
@@ -1466,12 +1912,14 @@ async function commandHistory(
1466
1912
  ): Promise<void> {
1467
1913
  const types = context.registry.objectTypes().map((entry) => entry.type);
1468
1914
  let runs = await findHistoryRuns(context.log, types, id);
1915
+ // A plugin may scope a bare id to a namespace of its own, as `dev` does for
1916
+ // a repository. Resolve through the views so the run's object key matches,
1917
+ // and keep the type with the id: another type may hold the same bare id.
1918
+ let resolved: string | undefined;
1469
1919
  if (runs.length === 0) {
1470
- // A plugin may scope a bare id to a namespace of its own, as `dev` does for
1471
- // a repository. Resolve through the views so the run's object key matches.
1472
- let resolved: string | undefined;
1473
1920
  try {
1474
- resolved = (await context.views.get(id)).id;
1921
+ const found = await context.views.get(id);
1922
+ resolved = `${found.type}:${found.id}`;
1475
1923
  } catch {
1476
1924
  resolved = undefined;
1477
1925
  }
@@ -1511,7 +1959,7 @@ async function commandHistory(
1511
1959
  // An object that never had a run still has the actions people ran on it.
1512
1960
  let own: readonly string[] = [];
1513
1961
  try {
1514
- own = await context.views.objectHistory(id);
1962
+ own = await context.views.objectHistory(resolved ?? id);
1515
1963
  } catch {
1516
1964
  own = [];
1517
1965
  }
@@ -1589,23 +2037,15 @@ export function runningLine(item: RunningItem): string {
1589
2037
  const parts = [
1590
2038
  item.object ?? item.runId,
1591
2039
  item.stepLabel ?? "-",
1592
- item.stepElapsedMs === null ? "-" : age(item.stepElapsedMs),
2040
+ item.stepElapsedMs === null ? "-" : formatElapsed(item.stepElapsedMs),
1593
2041
  ];
1594
- if (item.queuedMs !== undefined && item.queuedMs > 0) parts.push(`queued ${age(item.queuedMs)}`);
2042
+ if (item.queuedMs !== undefined && item.queuedMs > 0) parts.push(`queued ${formatElapsed(item.queuedMs)}`);
1595
2043
  if (item.title !== null) parts.push(item.title);
1596
- parts.push(`run ${age(item.elapsedMs)}`);
2044
+ parts.push(`run ${formatElapsed(item.elapsedMs)}`);
1597
2045
  if (item.note !== undefined && item.note !== null) parts.push(item.note);
1598
2046
  return parts.join(" ");
1599
2047
  }
1600
2048
 
1601
- function age(ms: number): string {
1602
- const total = Math.floor(Math.max(0, ms) / 1000);
1603
- const hours = Math.floor(total / 3600);
1604
- const minutes = Math.floor((total % 3600) / 60);
1605
- if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m`;
1606
- return minutes > 0 ? `${minutes}m ${String(total % 60).padStart(2, "0")}s` : `${total}s`;
1607
- }
1608
-
1609
2049
  function commandFlows(context: Context, io: CliIo, json: boolean): void {
1610
2050
  const flows = context.registry.flows();
1611
2051
  if (json) {
@@ -1679,7 +2119,6 @@ function spawnChild(
1679
2119
  async function commandServe(
1680
2120
  context: Context,
1681
2121
  io: CliIo,
1682
- argv: readonly string[],
1683
2122
  lock: LockHandle,
1684
2123
  supervised: boolean,
1685
2124
  retryBind: boolean,
@@ -1694,6 +2133,7 @@ async function commandServe(
1694
2133
 
1695
2134
  let rules: readonly TriggerRule[] = [];
1696
2135
  let sourcesAllowed = true;
2136
+ serveStage("loading the trigger rules");
1697
2137
  try {
1698
2138
  rules = await loadTriggerRules({
1699
2139
  home: context.home,
@@ -1705,7 +2145,7 @@ async function commandServe(
1705
2145
  });
1706
2146
  } catch (error) {
1707
2147
  sourcesAllowed = false;
1708
- const message = error instanceof Error ? error.message : String(error);
2148
+ const message = messageOf(error);
1709
2149
  context.problems.push(message);
1710
2150
  io.error(`operad: ${message}\n`);
1711
2151
  }
@@ -1728,6 +2168,7 @@ async function commandServe(
1728
2168
  const olderNotice = olderCodeNotice(context.home);
1729
2169
  olderNotice.clear();
1730
2170
  try {
2171
+ serveStage("starting the http server");
1731
2172
  if (context.config.http.enabled) {
1732
2173
  const startHttp = (): Promise<HttpServerHandle> =>
1733
2174
  startHttpServer({
@@ -1737,6 +2178,7 @@ async function commandServe(
1737
2178
  log: context.log,
1738
2179
  registry: context.registry,
1739
2180
  kernel,
2181
+ plugins: pluginAdminFor(context),
1740
2182
  onListen: (url) => io.write(`http ${url}\n`),
1741
2183
  onLog: (message) => io.error(`${message}\n`),
1742
2184
  });
@@ -1752,16 +2194,19 @@ async function commandServe(
1752
2194
  })
1753
2195
  : await startHttp();
1754
2196
  }
2197
+ serveStage("starting the sources");
1755
2198
  if (sourcesAllowed) {
1756
2199
  await kernel.startSources();
1757
2200
  }
1758
2201
 
2202
+ serveStage("serving");
1759
2203
  io.write(`serving ${context.home}\n`);
1760
2204
  if (context.code !== undefined) {
1761
2205
  const check = codeChecker({
1762
2206
  home: context.home,
1763
2207
  snapshot: context.code,
1764
2208
  known: startProblems,
2209
+ probeTimeoutMs: envNumber("OPERAD_RELOAD_PROBE_MS", PROBE_TIMEOUT_MS),
1765
2210
  onProblem: (message) => io.error(`operad: ${message}\n`),
1766
2211
  });
1767
2212
  watch = new CodeWatch({
@@ -1771,7 +2216,15 @@ async function commandServe(
1771
2216
  declined: context.code.tried,
1772
2217
  quietMs: envNumber("OPERAD_RELOAD_QUIET_MS", 1_000),
1773
2218
  pollMs: envNumber("OPERAD_RELOAD_POLL_MS", 5_000),
2219
+ checkTimeoutMs: envNumber("OPERAD_RELOAD_CHECK_MS", DEFAULT_CHECK_TIMEOUT_MS),
2220
+ retryMs: envNumber("OPERAD_RELOAD_RETRY_MS", DEFAULT_RETRY_MS),
1774
2221
  onOlder: olderNotice.report,
2222
+ // A check that fails or does not finish keeps the old code; say so,
2223
+ // once, and the slow timer tries it again.
2224
+ onKept: (change, reason) =>
2225
+ io.error(
2226
+ `operad: code changed (${describeChange(change)}) but ${reason}; the old code keeps running\n`,
2227
+ ),
1775
2228
  onChange: async () => {
1776
2229
  const what = await check();
1777
2230
  // A stop that came while the new code was tried is not started again.
@@ -1802,13 +2255,16 @@ async function commandServe(
1802
2255
  // The command can take 30 seconds; the loop must not wait for it.
1803
2256
  onPass: () => {
1804
2257
  notifier.pass().catch((error: unknown) => {
1805
- io.error(`notify: ${error instanceof Error ? error.message : String(error)}\n`);
2258
+ io.error(`notify: ${messageOf(error)}\n`);
1806
2259
  });
1807
2260
  },
1808
2261
  });
1809
2262
  } finally {
2263
+ serveStage("stopping");
1810
2264
  watch?.stop();
1811
2265
  olderNotice.clear();
2266
+ // A kept worker would keep running the code this serve loaded.
2267
+ await stopAllKeptWorkers({ home: context.home }).catch(() => undefined);
1812
2268
  await notifier.stop();
1813
2269
  if (http !== undefined) {
1814
2270
  try {
@@ -1841,8 +2297,7 @@ async function commandRunInternal(
1841
2297
  const runId = args[0];
1842
2298
  if (runId === undefined) throw new UsageError("run-internal needs a run id");
1843
2299
 
1844
- const runs = await context.log.runs();
1845
- const run = runs.find((candidate) => candidate.runId === runId);
2300
+ const run = await context.log.run(runId);
1846
2301
  if (run === undefined) throw new Error(`no run "${runId}"`);
1847
2302
  const found = context.registry.flow(run.flow);
1848
2303
  if (found === undefined) {
@@ -1863,7 +2318,7 @@ async function commandRunInternal(
1863
2318
  });
1864
2319
  } catch (error) {
1865
2320
  // The run still has to finish; a broken rule file is not a run error.
1866
- const message = error instanceof Error ? error.message : String(error);
2321
+ const message = messageOf(error);
1867
2322
  context.problems.push(message);
1868
2323
  io.error(`${message}\n`);
1869
2324
  }
@@ -1907,18 +2362,6 @@ async function commandRunInternal(
1907
2362
  await runner.run();
1908
2363
  }
1909
2364
 
1910
- function definitionName(value: unknown): string | undefined {
1911
- if (
1912
- typeof value === "object" &&
1913
- value !== null &&
1914
- "name" in value &&
1915
- typeof (value as { name?: unknown }).name === "string"
1916
- ) {
1917
- return (value as { name: string }).name;
1918
- }
1919
- return undefined;
1920
- }
1921
-
1922
2365
  function definitionVersion(value: unknown): string | undefined {
1923
2366
  if (
1924
2367
  typeof value === "object" &&
@@ -1931,23 +2374,54 @@ function definitionVersion(value: unknown): string | undefined {
1931
2374
  return undefined;
1932
2375
  }
1933
2376
 
2377
+ /** What loading a plugin gave: the name and version it declares. */
2378
+ type PluginIdentity = { readonly name: string | undefined; readonly version: string | undefined };
2379
+
2380
+ /** One configured plugin as `plugin list` prints it, with the key `config.json` files it under. */
2381
+ async function pluginRows(
2382
+ home: string,
2383
+ plugins: OperadConfig["plugins"],
2384
+ loaded?: Map<string, PluginIdentity | null>,
2385
+ load: (module: string, home: string) => Promise<unknown> = loadPlugin,
2386
+ ): Promise<(PluginInfo & { readonly key: string })[]> {
2387
+ const rows: (PluginInfo & { readonly key: string })[] = [];
2388
+ for (const entry of plugins) {
2389
+ let identity: PluginIdentity | null | undefined;
2390
+ if (entry.enabled) {
2391
+ // `serve` passes a cache: loading a path plugin again imports a new copy
2392
+ // of it each time, which a long-running process must not do per request.
2393
+ // A failed load is cached too, as null, so a broken file is not imported
2394
+ // again on every list.
2395
+ identity = loaded?.get(entry.module);
2396
+ if (identity === undefined) {
2397
+ try {
2398
+ const definition = await load(entry.module, home);
2399
+ identity = { name: definitionName(definition), version: definitionVersion(definition) };
2400
+ loaded?.set(entry.module, identity);
2401
+ } catch {
2402
+ identity = null;
2403
+ loaded?.set(entry.module, null);
2404
+ }
2405
+ }
2406
+ }
2407
+ rows.push({
2408
+ key: entry.name ?? entry.module,
2409
+ name: identity?.name ?? entry.name ?? entry.module,
2410
+ version: identity?.version ?? null,
2411
+ enabled: entry.enabled,
2412
+ origin: entry.module.startsWith("@operad-io/") ? "builtin" : "home",
2413
+ });
2414
+ }
2415
+ return rows;
2416
+ }
2417
+
1934
2418
  async function commandPluginList(context: Context, io: CliIo): Promise<number> {
1935
2419
  if (context.config.plugins.length === 0) {
1936
2420
  io.write("no plugins configured\n");
1937
2421
  return 0;
1938
2422
  }
1939
- for (const entry of context.config.plugins) {
1940
- let definition: unknown;
1941
- if (entry.enabled) {
1942
- try {
1943
- definition = await loadPlugin(entry.module, context.home);
1944
- } catch {
1945
- definition = undefined;
1946
- }
1947
- }
1948
- const name = definitionName(definition) ?? entry.name ?? entry.module;
1949
- const version = definitionVersion(definition) ?? "-";
1950
- io.write(`${name} ${version} ${entry.enabled ? "enabled" : "disabled"}\n`);
2423
+ for (const row of await pluginRows(context.home, context.config.plugins)) {
2424
+ io.write(`${row.name} ${row.version ?? "-"} ${row.enabled ? "enabled" : "disabled"}\n`);
1951
2425
  }
1952
2426
  return 0;
1953
2427
  }
@@ -1998,13 +2472,18 @@ function resolvableFrom(specifier: string, from: string): boolean {
1998
2472
  }
1999
2473
  }
2000
2474
 
2475
+ /** What checking one plugin declaration against the configured plugins found. */
2476
+ interface PluginCheckResult {
2477
+ readonly ok: boolean;
2478
+ readonly message: string;
2479
+ }
2480
+
2001
2481
  /** Validates one loaded plugin with the configured plugins, without starting a run. */
2002
- async function checkLoadedDefinition(
2482
+ async function validateLoadedDefinition(
2003
2483
  context: Context,
2004
- io: CliIo,
2005
2484
  name: string,
2006
2485
  definition: unknown,
2007
- ): Promise<number> {
2486
+ ): Promise<PluginCheckResult> {
2008
2487
  const configured = await loadConfiguredPlugins({ home: context.home, installOnEnable: INSTALL_ON_ENABLE });
2009
2488
  const others = configured.loaded
2010
2489
  .map((loaded) => loaded.definition)
@@ -2020,61 +2499,428 @@ async function checkLoadedDefinition(
2020
2499
  onLog: () => undefined,
2021
2500
  });
2022
2501
  } catch (error) {
2023
- io.write(`${name}: ${messageOf(error)}\n`);
2024
- return 1;
2502
+ return { ok: false, message: `${name}: ${messageOf(error)}` };
2025
2503
  }
2026
2504
  if (!registry.names().includes(name)) {
2027
2505
  const refusal = registry.refusals().find((item) => item.plugin === name);
2028
- io.write(`${refusal?.message ?? `${name}: not loaded`}\n`);
2029
- return 1;
2506
+ return { ok: false, message: refusal?.message ?? `${name}: not loaded` };
2030
2507
  }
2031
- io.write(`${name}: ok\n`);
2032
- return 0;
2508
+ return { ok: true, message: `${name}: ok` };
2509
+ }
2510
+
2511
+ /** Validates one loaded plugin with the configured plugins, without starting a run. */
2512
+ async function checkLoadedDefinition(
2513
+ context: Context,
2514
+ io: CliIo,
2515
+ name: string,
2516
+ definition: unknown,
2517
+ ): Promise<number> {
2518
+ const checked = await validateLoadedDefinition(context, name, definition);
2519
+ io.write(`${checked.message}\n`);
2520
+ return checked.ok ? 0 : 1;
2521
+ }
2522
+
2523
+ /** What refuses a plugin change; the command line and `serve` word the same reasons their own way. */
2524
+ interface PluginRefusals {
2525
+ unknown(message: string): Error;
2526
+ active(message: string): Error;
2527
+ }
2528
+
2529
+ const COMMAND_REFUSALS: PluginRefusals = {
2530
+ unknown: (message) => new ConfigError(message),
2531
+ active: (message) => new StateError(message),
2532
+ };
2533
+
2534
+ /** What refuses a plugin `add`; the command line and `serve` word the same reasons their own way. */
2535
+ interface PluginAddRefusals {
2536
+ invalid(message: string): Error;
2537
+ refused(message: string): Error;
2538
+ }
2539
+
2540
+ const COMMAND_ADD_REFUSALS: PluginAddRefusals = {
2541
+ invalid: (message) => new UsageError(message),
2542
+ refused: (message) => new ConfigError(message),
2543
+ };
2544
+
2545
+ const HTTP_ADD_REFUSALS: PluginAddRefusals = {
2546
+ invalid: (message) => new ViewError("args", message),
2547
+ refused: (message) => new ViewError("refused", message),
2548
+ };
2549
+
2550
+ /** An exact npm version: no range, tag or leading v. */
2551
+ const EXACT_NPM_VERSION =
2552
+ /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
2553
+
2554
+ /** Characters npm keeps in a package name; capitals and these were allowed for old packages. */
2555
+ const NPM_NAME_PART = /^[A-Za-z0-9._~!()*'-]+$/;
2556
+
2557
+ function isNpmNamePart(value: string): boolean {
2558
+ const lowered = value.toLowerCase();
2559
+ return (
2560
+ value.length > 0 &&
2561
+ value.length <= 214 &&
2562
+ NPM_NAME_PART.test(value) &&
2563
+ value !== "." &&
2564
+ value !== ".." &&
2565
+ !value.startsWith("-") &&
2566
+ lowered !== "node_modules" &&
2567
+ lowered !== "favicon.ico"
2568
+ );
2569
+ }
2570
+
2571
+ /** The npm rules a package name follows: one part, or `@scope/name`. */
2572
+ function isNpmPackageName(name: string): boolean {
2573
+ if (name.length === 0 || name.length > 214) return false;
2574
+ const scoped = name.startsWith("@");
2575
+ const parts = (scoped ? name.slice(1) : name).split("/");
2576
+ if (scoped ? parts.length !== 2 : parts.length !== 1) return false;
2577
+ return parts.every(isNpmNamePart);
2578
+ }
2579
+
2580
+ /** Splits `<package>[@version]`, refusing a name npm does not allow and a version that is not exact. */
2581
+ function parsePluginPackageSpec(
2582
+ raw: string,
2583
+ refusals: PluginAddRefusals,
2584
+ ): { readonly name: string; readonly version?: string | undefined } {
2585
+ const at = raw.startsWith("@") ? raw.indexOf("@", 1) : raw.indexOf("@");
2586
+ const name = at > 0 ? raw.slice(0, at) : raw;
2587
+ const version = at > 0 ? raw.slice(at + 1) : undefined;
2588
+ if (!isNpmPackageName(name)) {
2589
+ throw refusals.invalid(`"${raw}": not a valid npm package name`);
2590
+ }
2591
+ if (version !== undefined && !EXACT_NPM_VERSION.test(version)) {
2592
+ throw refusals.invalid(
2593
+ `"${raw}": not an exact version; name a version like 1.2.3, or leave it out for the latest`,
2594
+ );
2595
+ }
2596
+ return {
2597
+ name,
2598
+ ...(version === undefined ? {} : { version }),
2599
+ };
2600
+ }
2601
+
2602
+ function withInstallScriptHint(message: string, hasInstallScript: boolean): string {
2603
+ return hasInstallScript
2604
+ ? `${message}; its package declares an install script, and installing runs none of the package scripts, so a package that needs one cannot be added`
2605
+ : message;
2606
+ }
2607
+
2608
+ /** What `plugin add` installed and the name the plugin declares. */
2609
+ interface AddedPlugin {
2610
+ readonly packageName: string;
2611
+ readonly packageVersion: string;
2612
+ readonly declaredName: string;
2613
+ readonly declaredVersion: string;
2614
+ }
2615
+
2616
+ /** Installs one npm package, checks it, and adds it to `config.json` turned off. */
2617
+ async function addPlugin(
2618
+ context: Context,
2619
+ spec: string,
2620
+ refusals: PluginAddRefusals,
2621
+ run?: InstallRunner,
2622
+ ): Promise<AddedPlugin> {
2623
+ const parsed = parsePluginPackageSpec(spec, refusals);
2624
+ let added: AddedPackage;
2625
+ try {
2626
+ added = await addPackage({
2627
+ home: context.home,
2628
+ specifier: parsed.name,
2629
+ ...(parsed.version === undefined ? {} : { version: parsed.version }),
2630
+ ...(run === undefined ? {} : { run }),
2631
+ });
2632
+ } catch (error) {
2633
+ throw refusals.refused(`${parsed.name}: ${messageOf(error)}`);
2634
+ }
2635
+
2636
+ try {
2637
+ let definition: unknown;
2638
+ try {
2639
+ definition = await loadPlugin(added.file, context.home, added.file);
2640
+ } catch (error) {
2641
+ throw refusals.refused(
2642
+ withInstallScriptHint(
2643
+ `${parsed.name}: not an operad plugin: ${messageOf(error)}`,
2644
+ added.hasInstallScript,
2645
+ ),
2646
+ );
2647
+ }
2648
+ if (!isRecord(definition) || definition.operadPlugin !== OPERAD_PLUGIN_VERSION) {
2649
+ throw refusals.refused(
2650
+ withInstallScriptHint(
2651
+ `${parsed.name}: not an operad plugin: its default export declares no operadPlugin`,
2652
+ added.hasInstallScript,
2653
+ ),
2654
+ );
2655
+ }
2656
+ const declaredName = definitionName(definition);
2657
+ if (declaredName === undefined) {
2658
+ throw refusals.refused(
2659
+ withInstallScriptHint(
2660
+ `${parsed.name}: not an operad plugin: its declaration has no name`,
2661
+ added.hasInstallScript,
2662
+ ),
2663
+ );
2664
+ }
2665
+
2666
+ const fresh = await readConfig(context.home);
2667
+ const configured = new Set(
2668
+ fresh.plugins
2669
+ .map((entry) => entry.name)
2670
+ .filter((name): name is string => name !== undefined),
2671
+ );
2672
+ if (configured.has(declaredName) || context.registry.names().includes(declaredName)) {
2673
+ throw refusals.refused(
2674
+ `plugin "${declaredName}": already configured; the package's declared plugin name clashes with it`,
2675
+ );
2676
+ }
2677
+
2678
+ const checked = await validateLoadedDefinition(context, declaredName, definition);
2679
+ if (!checked.ok) {
2680
+ throw refusals.refused(withInstallScriptHint(checked.message, added.hasInstallScript));
2681
+ }
2682
+
2683
+ await addPluginEntry(context.home, declaredName, added.name);
2684
+ return {
2685
+ packageName: added.name,
2686
+ packageVersion: added.version,
2687
+ declaredName,
2688
+ declaredVersion: definitionVersion(definition) ?? "",
2689
+ };
2690
+ } catch (error) {
2691
+ return await removeRefusedPackage(context, added, error, refusals, run);
2692
+ }
2693
+ }
2694
+
2695
+ /** Takes a package a refused `add` installed back out, and keeps the refusal. */
2696
+ async function removeRefusedPackage(
2697
+ context: Context,
2698
+ added: AddedPackage,
2699
+ refusal: unknown,
2700
+ refusals: PluginAddRefusals,
2701
+ run?: InstallRunner,
2702
+ ): Promise<never> {
2703
+ try {
2704
+ await removePackage({
2705
+ home: context.home,
2706
+ name: added.name,
2707
+ ...(added.previousVersion === undefined ? {} : { previous: added.previousVersion }),
2708
+ ...(run === undefined ? {} : { run }),
2709
+ });
2710
+ } catch (error) {
2711
+ throw refusals.refused(
2712
+ `${messageOf(refusal)}; the package stayed in the home's plugin project: ${messageOf(error)}`,
2713
+ );
2714
+ }
2715
+ throw refusal;
2716
+ }
2717
+
2718
+ /** Refuses what `plugin enable` or `plugin disable` refuses, before anything is written or installed. */
2719
+ async function checkPluginChange(
2720
+ context: Context,
2721
+ name: string,
2722
+ enable: boolean,
2723
+ refusals: PluginRefusals,
2724
+ ): Promise<void> {
2725
+ const entry = context.config.plugins.find((item) => item.name === name);
2726
+ if (entry === undefined && !(enable && OPTIONAL_PLUGINS.includes(name))) {
2727
+ throw refusals.unknown(`plugins.${name}: no such plugin`);
2728
+ }
2729
+ if (!enable) {
2730
+ const affected = await activeRunsUsingPlugin(context, name);
2731
+ if (affected.length > 0) {
2732
+ const named = affected.map((run) => `"${run.runId}" (${run.step})`).join(", ");
2733
+ throw refusals.active(`cannot disable "${name}": run ${named} is active`);
2734
+ }
2735
+ }
2736
+ }
2737
+
2738
+ /** Turns one plugin on or off in `config.json`, installing what it needs first. */
2739
+ async function changePlugin(
2740
+ context: Context,
2741
+ name: string,
2742
+ enable: boolean,
2743
+ refusals: PluginRefusals = COMMAND_REFUSALS,
2744
+ beforeWrite?: () => void,
2745
+ options: {
2746
+ readonly run?: InstallRunner | undefined;
2747
+ readonly onProgress?: ((name: string, line: string) => void) | undefined;
2748
+ } = {},
2749
+ ): Promise<readonly string[]> {
2750
+ await checkPluginChange(context, name, enable, refusals);
2751
+ beforeWrite?.();
2752
+ const turnedOn: string[] = [];
2753
+ if (enable) {
2754
+ for (const needed of PLUGIN_NEEDS[name] ?? []) {
2755
+ if (context.config.plugins.some((item) => item.name === needed && item.enabled)) continue;
2756
+ await changePlugin(context, needed, true, refusals, undefined, options);
2757
+ turnedOn.push(needed);
2758
+ }
2759
+ }
2760
+ const entry = context.config.plugins.find((item) => item.name === name);
2761
+ if (enable) {
2762
+ const target = entry === undefined
2763
+ ? { name, module: defaultPluginModule(name), enabled: true, settings: {} }
2764
+ : { ...entry, enabled: true };
2765
+ await installPluginPackage({
2766
+ home: context.home,
2767
+ entry: target,
2768
+ ...(options.run === undefined ? {} : { run: options.run }),
2769
+ ...(options.onProgress === undefined ? {} : { onProgress: options.onProgress }),
2770
+ });
2771
+ }
2772
+ await setPluginEnabled(context.home, name, enable, pluginOffer(context.home));
2773
+ return [...turnedOn, name];
2774
+ }
2775
+
2776
+ /**
2777
+ * The plugin list and switch `serve` gives its HTTP clients. It reads
2778
+ * `config.json` at each call, because the file changes while `serve` runs,
2779
+ * and refuses with the command line's reasons.
2780
+ */
2781
+ export function pluginAdminFor(
2782
+ context: Context,
2783
+ load: (module: string, home: string) => Promise<unknown> = loadPlugin,
2784
+ installRun?: InstallRunner,
2785
+ ): PluginAdmin {
2786
+ const loaded = new Map<string, PluginIdentity | null>();
2787
+ /** The latest install line of a plugin being installed now, by plugin name. */
2788
+ const installing = new Map<string, string>();
2789
+ const rowsNow = async (): Promise<(PluginInfo & { readonly key: string })[]> =>
2790
+ pluginRows(context.home, (await readConfig(context.home)).plugins, loaded, load);
2791
+ const publicRow = ({ key: _key, ...row }: PluginInfo & { readonly key: string }): PluginInfo => row;
2792
+ // The plugin list already reaches every client; a harness adds its agent's
2793
+ // login and its models there, so a client never needs a session to know them.
2794
+ const withHarness = async (row: PluginInfo): Promise<PluginInfo> => {
2795
+ if (!row.enabled) return row;
2796
+ const signedIn = await context.registry.signedInFor(row.name);
2797
+ const models = context.registry.loadedModels()[row.name];
2798
+ const capabilities = context.registry.loadedCapabilities()[row.name];
2799
+ return {
2800
+ ...row,
2801
+ ...(signedIn === undefined ? {} : { signedIn }),
2802
+ ...(models === undefined ? {} : { models }),
2803
+ ...(capabilities === undefined ? {} : { accessLevels: capabilities.accessLevels ?? [] }),
2804
+ };
2805
+ };
2806
+ /** The rows, plus a plugin still being installed before the file names it. */
2807
+ const rowsPublic = async (): Promise<PluginInfo[]> => {
2808
+ const rows = await Promise.all(
2809
+ (await rowsNow()).map(async ({ key: _key, ...row }) => withHarness(row)),
2810
+ );
2811
+ for (const [name, line] of installing) {
2812
+ const row = rows.find((item) => item.name === name);
2813
+ if (row === undefined) {
2814
+ rows.push({ name, version: null, enabled: false, origin: "builtin", progress: line });
2815
+ } else {
2816
+ rows[rows.indexOf(row)] = { ...row, progress: line };
2817
+ }
2818
+ }
2819
+ return rows;
2820
+ };
2821
+ const withGuides = async (): Promise<PluginInfo[]> => {
2822
+ const rows = await rowsPublic();
2823
+ const guides = await context.registry.setupReader().list();
2824
+ return rows.map((row) => (guides.some((item) => item.plugin === row.name) ? { ...row, guide: true } : row));
2825
+ };
2826
+ return {
2827
+ list: withGuides,
2828
+ setup: async (name) => {
2829
+ const found = await context.registry.setupReader().get(name);
2830
+ if (found === undefined) return undefined;
2831
+ return { plugin: found.plugin, enabled: found.enabled, missing: found.missing };
2832
+ },
2833
+ install: async (specifier, options) => {
2834
+ if (!options.confirmed) {
2835
+ throw new ViewError(
2836
+ "confirm",
2837
+ `installing "${specifier}" writes config.json; send "confirmed": true to install it`,
2838
+ );
2839
+ }
2840
+ const added = await addPlugin(context, specifier, HTTP_ADD_REFUSALS, installRun);
2841
+ const row = (await rowsNow()).find((item) => item.key === added.declaredName);
2842
+ if (row === undefined) {
2843
+ throw new ViewError("not-found", `plugins.${added.declaredName}: no such plugin`);
2844
+ }
2845
+ // A new install is off and not in the registry yet, so it has no login to report.
2846
+ return publicRow(row);
2847
+ },
2848
+ set: async (name, enabled, options) => {
2849
+ const fresh: Context = { ...context, config: await readConfig(context.home) };
2850
+ // The list names a plugin by what it declares, and the file may key it
2851
+ // differently; either name finds the entry.
2852
+ const before = await rowsNow();
2853
+ const target = before.find((row) => row.key === name) ?? before.find((row) => row.name === name);
2854
+ const key = target?.key ?? name;
2855
+ const refusals: PluginRefusals = {
2856
+ unknown: (message) => new ViewError("not-found", message),
2857
+ active: (message) => new ViewError("unavailable", message),
2858
+ };
2859
+ try {
2860
+ await changePlugin(
2861
+ fresh,
2862
+ key,
2863
+ enabled,
2864
+ refusals,
2865
+ () => {
2866
+ // Turning a plugin off takes its commands, actions and automatic work
2867
+ // away for every client at the next load, so a client says it meant it.
2868
+ if (!enabled && !options.confirmed) {
2869
+ throw new ViewError(
2870
+ "confirm",
2871
+ `turning off "${name}" removes its commands, actions and automatic work at the next load; send "confirmed": true to turn it off`,
2872
+ );
2873
+ }
2874
+ },
2875
+ {
2876
+ ...(installRun === undefined ? {} : { run: installRun }),
2877
+ onProgress: (_plugin, line) => installing.set(key, line),
2878
+ },
2879
+ );
2880
+ } finally {
2881
+ installing.delete(key);
2882
+ }
2883
+ const row = (await rowsNow()).find((item) => item.key === key);
2884
+ if (row === undefined) throw new ViewError("not-found", `plugins.${name}: no such plugin`);
2885
+ return withHarness(publicRow(row));
2886
+ },
2887
+ };
2033
2888
  }
2034
2889
 
2035
2890
  async function commandPluginAdmin(
2036
2891
  context: Context,
2037
2892
  io: CliIo,
2038
2893
  argv: readonly string[],
2894
+ installRun?: InstallRunner,
2039
2895
  ): Promise<number> {
2040
2896
  const sub = argv[0];
2041
2897
  if (sub === "list") {
2042
2898
  if (argv.length > 1) throw new UsageError("plugin list takes no arguments");
2043
2899
  return commandPluginList(context, io);
2044
2900
  }
2901
+ if (sub === "add") {
2902
+ const spec = argv[1];
2903
+ if (spec === undefined) throw new UsageError("plugin add needs an npm package");
2904
+ if (argv.length > 2) throw new UsageError("plugin add takes one npm package");
2905
+ const added = await addPlugin(context, spec, COMMAND_ADD_REFUSALS, installRun);
2906
+ const version = added.declaredVersion.length === 0 ? "" : ` ${added.declaredVersion}`;
2907
+ io.write(
2908
+ `installed ${added.packageName}@${added.packageVersion} (plugin ${added.declaredName}${version})\n`,
2909
+ );
2910
+ io.write(
2911
+ `\`operad plugin enable ${added.declaredName}\` turns it on; it stays off until then\n`,
2912
+ );
2913
+ return 0;
2914
+ }
2045
2915
  if (sub === "enable" || sub === "disable") {
2046
2916
  const name = argv[1];
2047
2917
  if (name === undefined) throw new UsageError(`plugin ${sub} needs a plugin name`);
2048
2918
  if (argv.length > 2) throw new UsageError(`plugin ${sub} takes one plugin name`);
2049
- const entry = context.config.plugins.find((item) => item.name === name);
2050
- if (entry === undefined && !(sub === "enable" && OPTIONAL_PLUGINS.includes(name))) {
2051
- throw new ConfigError(`plugins.${name}: no such plugin`);
2052
- }
2053
- if (sub === "disable") {
2054
- const affected = await activeRunsUsingPlugin(context, name);
2055
- if (affected.length > 0) {
2056
- const named = affected
2057
- .map((run) => `"${run.runId}" (${run.step})`)
2058
- .join(", ");
2059
- throw new StateError(`cannot disable "${name}": run ${named} is active`);
2060
- }
2061
- }
2062
- if (sub === "enable" && INSTALL_ON_ENABLE.includes(name)) {
2063
- const module = entry?.module ?? defaultPluginModule(name);
2064
- if (module === defaultPluginModule(name)) {
2065
- // The package is not a CLI dependency: put it in the home's Bun project
2066
- // first, with optional dependencies skipped (operad-plugins 11).
2067
- await ensureInstalledPackage({
2068
- home: context.home,
2069
- specifier: module,
2070
- version: ENGINE_VERSION,
2071
- from: import.meta.dir,
2072
- omitOptional: true,
2073
- });
2074
- }
2075
- }
2076
- await setPluginEnabled(context.home, name, sub === "enable", pluginOffer(context.home));
2077
- io.write(`${name}: ${sub === "enable" ? "enabled" : "disabled"}\n`);
2919
+ const changed = await changePlugin(context, name, sub === "enable", COMMAND_REFUSALS, undefined, {
2920
+ ...(installRun === undefined ? {} : { run: installRun }),
2921
+ onProgress: (plugin, line) => io.write(`${plugin}: ${line}\n`),
2922
+ });
2923
+ for (const plugin of changed) io.write(`${plugin}: ${sub === "enable" ? "enabled" : "disabled"}\n`);
2078
2924
  return 0;
2079
2925
  }
2080
2926
  if (sub === "check") {
@@ -2222,6 +3068,7 @@ async function commandSettings(
2222
3068
  settingsCell(item.value),
2223
3069
  `default ${settingsCell(item.default)}`,
2224
3070
  marks,
3071
+ ...(item.title === undefined ? [] : [item.title]),
2225
3072
  ...(item.description === undefined ? [] : [item.description]),
2226
3073
  ].join(" ") + "\n",
2227
3074
  );
@@ -2400,6 +3247,7 @@ async function commandTui(
2400
3247
  argv: readonly string[],
2401
3248
  tty: boolean,
2402
3249
  injected: TuiRunner | undefined,
3250
+ startChat?: string,
2403
3251
  ): Promise<number> {
2404
3252
  let url: string | undefined;
2405
3253
  let token: string | undefined;
@@ -2441,6 +3289,7 @@ async function commandTui(
2441
3289
  ...(token === undefined ? {} : { token }),
2442
3290
  ...(noStart ? { noStart } : {}),
2443
3291
  ...(theme === undefined ? {} : { theme }),
3292
+ ...(startChat === undefined ? {} : { startChat }),
2444
3293
  serveEntry: CLI_ENTRY,
2445
3294
  write: (line) => io.write(`${line}\n`),
2446
3295
  onError: (message) => {
@@ -2481,13 +3330,40 @@ export async function main(
2481
3330
  io.write(`operad ${ENGINE_VERSION}\n`);
2482
3331
  return 0;
2483
3332
  }
2484
- if (command === undefined || command === "help" || command === "--help") {
3333
+ if (command === undefined) {
3334
+ const ensured = await ensureHomeConfig(
3335
+ home,
3336
+ (made) => {
3337
+ io.write(`${made.created ? "created" : "using"} ${made.path}\n`);
3338
+ if (made.created && made.noAgent) {
3339
+ io.write(
3340
+ "no agent found on PATH: installing operad's own pi for this home (it needs the network once)\n",
3341
+ );
3342
+ }
3343
+ },
3344
+ {
3345
+ ...(options.pluginInstall === undefined ? {} : { run: options.pluginInstall }),
3346
+ onProgress: (name, line) => io.write(`${name}: ${line}\n`),
3347
+ },
3348
+ );
3349
+ const startChat = ensured.config.plugins.some(
3350
+ (entry) => entry.name === "bot" && entry.enabled,
3351
+ )
3352
+ ? "bot:default"
3353
+ : undefined;
3354
+ return await commandTui(home, io, [], tty, options.tui, startChat);
3355
+ }
3356
+ if (command === "help" || command === "--help") {
2485
3357
  io.write(HELP);
2486
- return command === undefined ? 2 : 0;
3358
+ return 0;
3359
+ }
3360
+
3361
+ if (command === "doctor") {
3362
+ return await commandDoctor(home, io, args.slice(1), options.doctor);
2487
3363
  }
2488
3364
 
2489
3365
  if (command === "init") {
2490
- return await commandInit(home, io);
3366
+ return await commandInit(home, io, options.pluginInstall);
2491
3367
  }
2492
3368
 
2493
3369
  if (command === "mcp") {
@@ -2566,7 +3442,7 @@ export async function main(
2566
3442
  if (command === "plugin") {
2567
3443
  const context = await openContext(home, io);
2568
3444
  try {
2569
- return await commandPluginAdmin(context, io, args.slice(1));
3445
+ return await commandPluginAdmin(context, io, args.slice(1), options.pluginInstall);
2570
3446
  } finally {
2571
3447
  context.views.close();
2572
3448
  await context.log.close();
@@ -2585,7 +3461,7 @@ export async function main(
2585
3461
  onLog: (message) => context.problems.push(message),
2586
3462
  });
2587
3463
  } catch (error) {
2588
- context.problems.push(error instanceof Error ? error.message : String(error));
3464
+ context.problems.push(messageOf(error));
2589
3465
  }
2590
3466
  for (const line of context.problems) io.write(`${line.replace(/\n/g, " ")}\n`);
2591
3467
  } finally {
@@ -2622,7 +3498,7 @@ export async function main(
2622
3498
  try {
2623
3499
  timeoutSecs = parseStopTimeout(value);
2624
3500
  } catch (error) {
2625
- throw new UsageError(error instanceof Error ? error.message : String(error));
3501
+ throw new UsageError(messageOf(error));
2626
3502
  }
2627
3503
  continue;
2628
3504
  }
@@ -2646,26 +3522,47 @@ export async function main(
2646
3522
  restored: boolean,
2647
3523
  ): Promise<"stopped" | "reload"> => {
2648
3524
  const lock = acquireLock(serveLockPath(home));
3525
+ // `serve stop` reaches the supervisor too, so it can stop a reload that is in flight.
3526
+ if (isSupervised) recordSupervisor(home);
3527
+ // Held across a reload's wait for the stores, so a busy write that
3528
+ // work of the old context left running is never unguarded.
3529
+ const unguard = guardBackgroundBusy({
3530
+ home,
3531
+ log: (message) => io.error(`${message}\n`),
3532
+ });
2649
3533
  try {
2650
3534
  // serve answers clients that are in no directory: a bare id must not
2651
3535
  // be scoped to the repository serve happened to start in, so its
2652
3536
  // views resolve ids from the home, outside every repository.
2653
- const opened = await openContext(home, io, {
2654
- viewsCwd: home,
2655
- trackCode: true,
2656
- follow: true,
2657
- });
3537
+ // A store another process holds is waited for again, not a reason to
3538
+ // end: this is also how new code starts after a reload.
3539
+ serveStage("opening the stores");
3540
+ const opened = await retryWhileBusy(
3541
+ "opening the stores",
3542
+ () =>
3543
+ openContext(home, io, {
3544
+ viewsCwd: home,
3545
+ trackCode: true,
3546
+ follow: true,
3547
+ }),
3548
+ { log: (message) => io.error(`${message}\n`) },
3549
+ );
2658
3550
  const context =
2659
3551
  opened.code === undefined
2660
3552
  ? opened
2661
3553
  : { ...opened, code: snapshotOf(opened.code, restored) };
2662
3554
  try {
2663
- return await commandServe(context, io, args.slice(1), lock, isSupervised, retryBind);
3555
+ return await commandServe(context, io, lock, isSupervised, retryBind);
2664
3556
  } finally {
2665
- context.views.close();
3557
+ // Clean up the old plugin store when a serve context ends. An idle
3558
+ // handle does not block writers; the busy timeout here came from
3559
+ // other processes committing while a log write waited.
3560
+ await context.views.close();
3561
+ closePluginStore(context.registry.store);
2666
3562
  await context.log.close();
2667
3563
  }
2668
3564
  } finally {
3565
+ unguard();
2669
3566
  lock.release();
2670
3567
  }
2671
3568
  };
@@ -2842,20 +3739,45 @@ export async function main(
2842
3739
  await commandKernelAction(context, io, action, actionRepo.args.slice(1));
2843
3740
  return 0;
2844
3741
  }
2845
- if (await commandAction(context, io, actionRepo.args, tty)) return 0;
2846
- if (await commandPlugin(context, io, args)) return 0;
2847
3742
  const attempted = splitActionName(command ?? "")?.plugin ?? command ?? "";
2848
- if (context.disabled.includes(attempted)) {
2849
- throw new StateError(`plugin "${attempted}" is disabled`);
3743
+ // A shipped optional plugin a home has not turned on is not in the
3744
+ // config at all, so its name comes from the distribution's list.
3745
+ const enabledInConfig = context.config.plugins.some(
3746
+ (entry) => entry.name === attempted && entry.enabled,
3747
+ );
3748
+ const off =
3749
+ !context.registry.names().includes(attempted) &&
3750
+ context.registry.resolveCommand(actionRepo.args) === undefined &&
3751
+ (context.disabled.includes(attempted) ||
3752
+ (OPTIONAL_PLUGINS.includes(attempted) && !enabledInConfig));
3753
+ if (off) {
3754
+ throw new StateError(
3755
+ `plugin "${attempted}" is disabled; turn it on with \`operad plugin enable ${attempted}\``,
3756
+ );
2850
3757
  }
3758
+ if (await commandAction(context, io, actionRepo.args, tty)) return 0;
3759
+ if (await commandPlugin(context, io, args)) return 0;
3760
+ const candidates: CommandCandidate[] = [
3761
+ ...context.registry
3762
+ .actions()
3763
+ .map((info) => ({
3764
+ name: info.name,
3765
+ ...(info.command === undefined ? {} : { summary: info.command }),
3766
+ })),
3767
+ ...context.registry.commandNames().map((name) => ({ name })),
3768
+ ];
3769
+ throw new UsageError(
3770
+ `unknown command "${command ?? ""}"${closestCommandLines(command ?? "", candidates)}`,
3771
+ );
2851
3772
  } finally {
2852
3773
  context.views.close();
2853
3774
  await context.log.close();
2854
3775
  }
2855
- throw new UsageError(`unknown command "${command ?? ""}"`);
2856
3776
  } catch (error) {
2857
3777
  if (error instanceof UsageError) {
2858
- io.error(`operad: ${error.message}\n\n${HELP}`);
3778
+ const usage = error.usage ?? commandUsage(args);
3779
+ const usageLine = usage === undefined ? "" : `${usage}\n`;
3780
+ io.error(`operad: ${error.message}\n${usageLine}${HELP_POINTER}\n`);
2859
3781
  return 2;
2860
3782
  }
2861
3783
  if (error instanceof ViewError) {
@@ -2864,6 +3786,7 @@ export async function main(
2864
3786
  error.kind === "confirm" ||
2865
3787
  error.kind === "ambiguous" ||
2866
3788
  error.kind === "args" ||
3789
+ error.kind === "refused" ||
2867
3790
  error.kind === "where" ||
2868
3791
  error.kind === "cursor"
2869
3792
  ) {
@@ -2893,8 +3816,13 @@ export async function main(
2893
3816
  io.error(`operad: ${error.message}\n`);
2894
3817
  return 1;
2895
3818
  }
3819
+ if (command === "serve" && args[1] !== "stop") {
3820
+ // The line names the operation; the stack's first frames go to serve.log.
3821
+ io.error(`operad: ${recordServeFailure(home, serveStage(), error)}\n`);
3822
+ return 1;
3823
+ }
2896
3824
  io.error(
2897
- `operad: ${error instanceof Error ? error.message : String(error)}\n`,
3825
+ `operad: ${messageOf(error)}\n`,
2898
3826
  );
2899
3827
  return 1;
2900
3828
  }