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