@operad-io/cli 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/bin/operad.ts +10 -0
- package/package.json +30 -4
- package/src/code-reload.ts +355 -0
- package/src/defaults.ts +67 -0
- package/src/http-bind.ts +108 -0
- package/src/main.ts +2871 -0
- package/src/markdown.ts +11 -0
- package/src/qr.ts +405 -0
- package/src/serve-stop.ts +108 -0
- package/README.md +0 -3
package/src/main.ts
ADDED
|
@@ -0,0 +1,2871 @@
|
|
|
1
|
+
import { INSTALL_ON_ENABLE, OPTIONAL_PLUGINS, defaultPluginModule, distributionConfig, pluginOffer } from "./defaults.ts";
|
|
2
|
+
import { closeSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
|
|
3
|
+
import { userInfo } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
import {
|
|
7
|
+
ConfigError,
|
|
8
|
+
FileSecretStore,
|
|
9
|
+
Kernel,
|
|
10
|
+
LockHeldError,
|
|
11
|
+
acquireLock,
|
|
12
|
+
type LockHandle,
|
|
13
|
+
MemoryPluginStore,
|
|
14
|
+
PluginRegistry,
|
|
15
|
+
Runner,
|
|
16
|
+
StateError,
|
|
17
|
+
TriggerError,
|
|
18
|
+
ViewError,
|
|
19
|
+
applyInput,
|
|
20
|
+
cancelRun,
|
|
21
|
+
createViews,
|
|
22
|
+
defaultOperadHome,
|
|
23
|
+
ensureConfig,
|
|
24
|
+
ensureInstalledPackage,
|
|
25
|
+
formatHistoryEntry,
|
|
26
|
+
historyEntry,
|
|
27
|
+
historyEntries,
|
|
28
|
+
installedPackageFile,
|
|
29
|
+
listPending,
|
|
30
|
+
listRunning,
|
|
31
|
+
type RunningItem,
|
|
32
|
+
loadConfiguredPlugins,
|
|
33
|
+
loadPlugin,
|
|
34
|
+
loadPluginRegistry,
|
|
35
|
+
loadSourcedTriggerRules,
|
|
36
|
+
loadTriggerRules,
|
|
37
|
+
lockHeld,
|
|
38
|
+
messageOf,
|
|
39
|
+
openConfigLog,
|
|
40
|
+
Notifier,
|
|
41
|
+
CodeWatch,
|
|
42
|
+
olderCodeNotice,
|
|
43
|
+
ensureHttpToken,
|
|
44
|
+
listenAddressKind,
|
|
45
|
+
pairLink,
|
|
46
|
+
openPluginStore,
|
|
47
|
+
parseObjectKey,
|
|
48
|
+
readConfig,
|
|
49
|
+
readState,
|
|
50
|
+
readStoredStart,
|
|
51
|
+
runningFromWorkspace,
|
|
52
|
+
readStoredTrigger,
|
|
53
|
+
recordAnswer,
|
|
54
|
+
rotateHttpToken,
|
|
55
|
+
serve,
|
|
56
|
+
serveLockPath,
|
|
57
|
+
setPluginEnabled,
|
|
58
|
+
splitActionName,
|
|
59
|
+
startHttpServer,
|
|
60
|
+
storeRootOf,
|
|
61
|
+
ENGINE_VERSION,
|
|
62
|
+
type ActionArgsSchema,
|
|
63
|
+
type ActionArgSchema,
|
|
64
|
+
type ActionInfo,
|
|
65
|
+
type Actor,
|
|
66
|
+
type LogBackend,
|
|
67
|
+
type GlobalFact,
|
|
68
|
+
HttpStopError,
|
|
69
|
+
type HttpServerHandle,
|
|
70
|
+
type InstallRunner,
|
|
71
|
+
type OperadConfig,
|
|
72
|
+
type RunInfo,
|
|
73
|
+
type TriggerEvent,
|
|
74
|
+
type TriggerRule,
|
|
75
|
+
type ViewAction,
|
|
76
|
+
type ViewObject,
|
|
77
|
+
type ViewRow,
|
|
78
|
+
type Views,
|
|
79
|
+
} from "@operad-io/engine";
|
|
80
|
+
import { ChannelTypeError, runMcpServer } from "@operad-io/mcp";
|
|
81
|
+
import {
|
|
82
|
+
BIND_FAILED_EXIT,
|
|
83
|
+
codeChecker,
|
|
84
|
+
RELOAD_EXIT,
|
|
85
|
+
superviseServe,
|
|
86
|
+
listenForStop,
|
|
87
|
+
settingsRoots,
|
|
88
|
+
takeCodeSnapshot,
|
|
89
|
+
serveSnapshots,
|
|
90
|
+
} from "./code-reload.ts";
|
|
91
|
+
import type { CodeSnapshot } from "./code-reload.ts";
|
|
92
|
+
import {
|
|
93
|
+
BindFailed,
|
|
94
|
+
HandOverStuck,
|
|
95
|
+
leaveStuck,
|
|
96
|
+
replacementEnv,
|
|
97
|
+
serveStartFlags,
|
|
98
|
+
startWithRetry,
|
|
99
|
+
} from "./http-bind.ts";
|
|
100
|
+
import { renderMarkdown } from "./markdown.ts";
|
|
101
|
+
import { QrTooLongError, encodeQr, renderQr } from "./qr.ts";
|
|
102
|
+
import {
|
|
103
|
+
DEFAULT_STOP_TIMEOUT_SECS,
|
|
104
|
+
parseStopTimeout,
|
|
105
|
+
serveStop,
|
|
106
|
+
} from "./serve-stop.ts";
|
|
107
|
+
|
|
108
|
+
/** Where a command writes. Tests pass a collector instead of the process. */
|
|
109
|
+
export interface CliIo {
|
|
110
|
+
write(text: string): void;
|
|
111
|
+
error(text: string): void;
|
|
112
|
+
/** Reads one line, for a prompt in a terminal. Tests inject it. */
|
|
113
|
+
readLine?(prompt: string): Promise<string | undefined>;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The exit status of a command whose reader closed the pipe: 128 + SIGPIPE. */
|
|
117
|
+
export const EXIT_CLOSED_PIPE = 141;
|
|
118
|
+
|
|
119
|
+
let outputClosed = false;
|
|
120
|
+
|
|
121
|
+
/** True once stdout or stderr reported EPIPE; later writes are dropped. */
|
|
122
|
+
export function outputWasClosed(): boolean {
|
|
123
|
+
return outputClosed;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function isClosedPipe(error: unknown): boolean {
|
|
127
|
+
return (
|
|
128
|
+
typeof error === "object" &&
|
|
129
|
+
error !== null &&
|
|
130
|
+
(error as { code?: unknown }).code === "EPIPE"
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Writes to a process stream. A closed pipe (EPIPE) stops all output without a
|
|
136
|
+
* message; any other write error is thrown as before. The write is synchronous
|
|
137
|
+
* on the descriptor: Bun reports a write queued behind a full pipe as done and
|
|
138
|
+
* drops it at exit, so a reader that closes meanwhile went unseen and the
|
|
139
|
+
* status was 0.
|
|
140
|
+
*/
|
|
141
|
+
function writeStream(stream: NodeJS.WriteStream, text: string): void {
|
|
142
|
+
if (outputClosed) return;
|
|
143
|
+
const fd = stream === process.stderr ? 2 : 1;
|
|
144
|
+
try {
|
|
145
|
+
const bytes = Buffer.from(text);
|
|
146
|
+
let offset = 0;
|
|
147
|
+
while (offset < bytes.length) {
|
|
148
|
+
try {
|
|
149
|
+
offset += writeSync(fd, bytes, offset);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if ((error as { code?: unknown }).code !== "EAGAIN") throw error;
|
|
152
|
+
// A non-blocking pipe is full: wait for the reader to take some.
|
|
153
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (!isClosedPipe(error)) throw error;
|
|
158
|
+
outputClosed = true;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// A write that fails later arrives as an error event; EPIPE ends output the
|
|
163
|
+
// same way, anything else stays an unhandled error as it was.
|
|
164
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
165
|
+
stream.on("error", (error) => {
|
|
166
|
+
if (isClosedPipe(error)) {
|
|
167
|
+
outputClosed = true;
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
throw error;
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const STDIO: CliIo = {
|
|
175
|
+
write: (text) => writeStream(process.stdout, text),
|
|
176
|
+
error: (text) => writeStream(process.stderr, text),
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/** A command line mistake; exit code 2. */
|
|
180
|
+
export class UsageError extends Error {
|
|
181
|
+
constructor(message: string) {
|
|
182
|
+
super(message);
|
|
183
|
+
this.name = "UsageError";
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export interface MainOptions {
|
|
188
|
+
/** The operad home; defaults to `$OPERAD_HOME` or `~/.operad`. */
|
|
189
|
+
readonly home?: string | undefined;
|
|
190
|
+
readonly io?: CliIo | undefined;
|
|
191
|
+
/** Whether prompts and colours are available; defaults to the real terminal. */
|
|
192
|
+
readonly isTTY?: boolean | undefined;
|
|
193
|
+
/** The terminal's width in columns; defaults to stdout's. */
|
|
194
|
+
readonly columns?: number | undefined;
|
|
195
|
+
/** Replaces the OpenTUI app in a test; the real one is imported only by `tui`. */
|
|
196
|
+
readonly tui?: TuiRunner | undefined;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** What the CLI hands the terminal app. */
|
|
200
|
+
export interface TuiCommand {
|
|
201
|
+
readonly home: string;
|
|
202
|
+
readonly url?: string | undefined;
|
|
203
|
+
readonly token?: string | undefined;
|
|
204
|
+
/** `--no-start`: never start `operad serve`. */
|
|
205
|
+
readonly noStart?: boolean | undefined;
|
|
206
|
+
/** `--theme`: the colour theme for this session. */
|
|
207
|
+
readonly theme?: string | undefined;
|
|
208
|
+
/** The entry file a started `operad serve` runs: this process's own. */
|
|
209
|
+
readonly serveEntry?: string | undefined;
|
|
210
|
+
/** Prints a line before the full screen opens. */
|
|
211
|
+
readonly write?: ((line: string) => void) | undefined;
|
|
212
|
+
readonly onError?: ((message: string) => void) | undefined;
|
|
213
|
+
/** What the app logged while the screen was open. */
|
|
214
|
+
readonly onLog?: ((message: string) => void) | undefined;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export type TuiRunner = (command: TuiCommand) => Promise<number>;
|
|
218
|
+
|
|
219
|
+
const KERNEL_VERBS = [
|
|
220
|
+
"init",
|
|
221
|
+
"serve",
|
|
222
|
+
"pending",
|
|
223
|
+
"history",
|
|
224
|
+
"running",
|
|
225
|
+
"flows",
|
|
226
|
+
"trigger",
|
|
227
|
+
"list",
|
|
228
|
+
"show",
|
|
229
|
+
"plugin",
|
|
230
|
+
"secret",
|
|
231
|
+
"settings",
|
|
232
|
+
"http",
|
|
233
|
+
"pair",
|
|
234
|
+
"tui",
|
|
235
|
+
"run-internal",
|
|
236
|
+
"check-load",
|
|
237
|
+
"mcp",
|
|
238
|
+
] as const;
|
|
239
|
+
|
|
240
|
+
const KERNEL_ACTIONS = ["operad:start", "operad:dismiss"] as const;
|
|
241
|
+
|
|
242
|
+
const HELP = [
|
|
243
|
+
"usage: operad <command> [options]",
|
|
244
|
+
"",
|
|
245
|
+
" init create the operad home and check the plugins",
|
|
246
|
+
" serve run the kernel loop for this home",
|
|
247
|
+
" serve stop [--timeout <secs>]",
|
|
248
|
+
" stop this home's serve (SIGTERM; default timeout 30)",
|
|
249
|
+
" pending [--json] things waiting for a person",
|
|
250
|
+
" list <type> objects of one type (--filter <name>, --repo <name>, --parent <id>, --root)",
|
|
251
|
+
" show <id> one object, its sections and its actions (--section <id> --page <label or number>)",
|
|
252
|
+
" history <id> [--json] steps of a run, or of a plugin object's runs",
|
|
253
|
+
" running runs in progress",
|
|
254
|
+
" flows loaded flows and where they come from",
|
|
255
|
+
" plugin list plugins with their version and whether they are enabled",
|
|
256
|
+
" plugin enable <name> load a plugin again at the next command",
|
|
257
|
+
" plugin disable <name> stop loading a plugin at the next command",
|
|
258
|
+
" plugin check <path> validate a plugin declaration without starting it",
|
|
259
|
+
" secret set <plugin> <name> store a secret (value from the terminal or stdin)",
|
|
260
|
+
" secret list <plugin> secret names, never values",
|
|
261
|
+
" secret delete <plugin> <name>",
|
|
262
|
+
" settings [--repo <name>] [--json]",
|
|
263
|
+
" every setting with its value, default and whether it can be changed",
|
|
264
|
+
" settings set <name> <value> [--repo <name>] [--yes]",
|
|
265
|
+
" change a setting (the value is JSON, or a plain string)",
|
|
266
|
+
" http token rotate replace the token the operad app uses",
|
|
267
|
+
" pair [--url <url>] [--show-token]",
|
|
268
|
+
" show the address and token as a QR code for the operad app",
|
|
269
|
+
" tui [--url <url>] [--token <token>] [--no-start] [--theme <name>]",
|
|
270
|
+
" open the terminal client; starts serve when none answers",
|
|
271
|
+
" mcp [--claude-channel] [--types t,...]",
|
|
272
|
+
" run the MCP server on stdio; --claude-channel",
|
|
273
|
+
" pushes object changes to Claude Code",
|
|
274
|
+
" trigger <source> <key> [--type t] [--object o] [--summary text] [--data file]",
|
|
275
|
+
" send one event through the rules",
|
|
276
|
+
" trigger rules the rules in force, with where each came from",
|
|
277
|
+
" operad:start <id> start a pending event",
|
|
278
|
+
" operad:dismiss <id> dismiss a pending event",
|
|
279
|
+
" <plugin>:<action> an action on one object",
|
|
280
|
+
" <plugin> <verb> a verb a loaded plugin declares",
|
|
281
|
+
"",
|
|
282
|
+
].join("\n");
|
|
283
|
+
|
|
284
|
+
const COLOUR = {
|
|
285
|
+
reset: "\x1b[0m",
|
|
286
|
+
attention: "\x1b[33m",
|
|
287
|
+
running: "\x1b[34m",
|
|
288
|
+
} as const;
|
|
289
|
+
|
|
290
|
+
function paintState(row: ViewRow, text: string, tty: boolean): string {
|
|
291
|
+
if (!tty) return text;
|
|
292
|
+
if (row.waiting) return `${COLOUR.attention}${text}${COLOUR.reset}`;
|
|
293
|
+
if (row.running) return `${COLOUR.running}${text}${COLOUR.reset}`;
|
|
294
|
+
return text;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** One row's line: name, state, badge when it has one, title, then the note. */
|
|
298
|
+
function rowLine(row: ViewRow, tty: boolean): string {
|
|
299
|
+
const state = paintState(row, row.state, tty);
|
|
300
|
+
const badge = row.badge === undefined ? "" : ` ${row.badge}`;
|
|
301
|
+
const note = row.note === undefined ? "" : ` ${row.note}`;
|
|
302
|
+
const name = row.scope === undefined ? row.id : `${row.scope}/${row.id}`;
|
|
303
|
+
return `${name} ${state}${badge} ${row.title}${note}`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
interface Context {
|
|
307
|
+
readonly home: string;
|
|
308
|
+
readonly cwd: string;
|
|
309
|
+
readonly config: OperadConfig;
|
|
310
|
+
readonly registry: PluginRegistry;
|
|
311
|
+
readonly log: LogBackend;
|
|
312
|
+
readonly storeRoot: string;
|
|
313
|
+
readonly views: Views;
|
|
314
|
+
readonly disabled: readonly string[];
|
|
315
|
+
/** What did not load, one line each, as the registry reported it. */
|
|
316
|
+
readonly problems: string[];
|
|
317
|
+
/** The code this process loaded, when the caller asked to keep track. */
|
|
318
|
+
readonly code: CodeSnapshot | undefined;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
interface OpenContextOptions {
|
|
322
|
+
/** A namespace named explicitly, handed to each type's `resolve`. */
|
|
323
|
+
readonly scope?: string | undefined;
|
|
324
|
+
/** Where view ids resolve; defaults to this process's directory. */
|
|
325
|
+
readonly viewsCwd?: string | undefined;
|
|
326
|
+
/** Whether to snapshot the code this process loaded. */
|
|
327
|
+
readonly trackCode?: boolean | undefined;
|
|
328
|
+
/**
|
|
329
|
+
* Whether this process follows changes. A command that answers once and
|
|
330
|
+
* exits leaves this false; a long-lived process passes true.
|
|
331
|
+
*/
|
|
332
|
+
readonly follow?: boolean | undefined;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function openContext(
|
|
336
|
+
home: string,
|
|
337
|
+
io: CliIo,
|
|
338
|
+
options: OpenContextOptions = {},
|
|
339
|
+
): Promise<Context> {
|
|
340
|
+
const { scope, viewsCwd, trackCode = false, follow = false } = options;
|
|
341
|
+
const cwd = process.cwd();
|
|
342
|
+
const config = await readConfig(home);
|
|
343
|
+
// Taken before anything loads: a file that changes while loading then
|
|
344
|
+
// counts as changed, never as loaded.
|
|
345
|
+
const code = trackCode ? takeCodeSnapshot(home, config.plugins) : undefined;
|
|
346
|
+
const problems: string[] = [];
|
|
347
|
+
const storeRoot = storeRootOf(config);
|
|
348
|
+
const store = openPluginStore({
|
|
349
|
+
backend: config.store.backend,
|
|
350
|
+
root: storeRoot,
|
|
351
|
+
follow,
|
|
352
|
+
});
|
|
353
|
+
const log = openConfigLog(config, { follow });
|
|
354
|
+
let loaded: PluginRegistry | undefined;
|
|
355
|
+
const registry = await loadPluginRegistry({
|
|
356
|
+
installOnEnable: INSTALL_ON_ENABLE,
|
|
357
|
+
home,
|
|
358
|
+
cwd,
|
|
359
|
+
store,
|
|
360
|
+
kernelVerbs: KERNEL_VERBS,
|
|
361
|
+
onLog: (message) => {
|
|
362
|
+
problems.push(message);
|
|
363
|
+
io.error(`${message}\n`);
|
|
364
|
+
},
|
|
365
|
+
onAnswer: async (runId, choice, note, actor) => {
|
|
366
|
+
const runs = await log.runs();
|
|
367
|
+
const run = runs.find((candidate) => candidate.runId === runId);
|
|
368
|
+
if (run === undefined) throw new StateError(`no run "${runId}"`);
|
|
369
|
+
await recordAnswer({
|
|
370
|
+
log,
|
|
371
|
+
runId,
|
|
372
|
+
choice,
|
|
373
|
+
...(note === undefined ? {} : { note }),
|
|
374
|
+
actor,
|
|
375
|
+
});
|
|
376
|
+
if (!lockHeld(serveLockPath(home))) {
|
|
377
|
+
io.write("recorded; it runs when `operad serve` is running\n");
|
|
378
|
+
}
|
|
379
|
+
},
|
|
380
|
+
onEvent: async (event) => {
|
|
381
|
+
if (loaded === undefined) return;
|
|
382
|
+
const rules = await loadTriggerRules({
|
|
383
|
+
home,
|
|
384
|
+
registry: loaded,
|
|
385
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
386
|
+
});
|
|
387
|
+
const kernel = new Kernel({
|
|
388
|
+
log,
|
|
389
|
+
registry: loaded,
|
|
390
|
+
home,
|
|
391
|
+
storeRoot,
|
|
392
|
+
rules,
|
|
393
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
394
|
+
});
|
|
395
|
+
await kernel.receive(event);
|
|
396
|
+
},
|
|
397
|
+
onCancelRun: (runId, graph) =>
|
|
398
|
+
cancelRun({
|
|
399
|
+
log,
|
|
400
|
+
flow: (name) => loaded?.flow(name)?.flow,
|
|
401
|
+
runId,
|
|
402
|
+
graph,
|
|
403
|
+
source: "cli",
|
|
404
|
+
}),
|
|
405
|
+
});
|
|
406
|
+
loaded = registry;
|
|
407
|
+
return {
|
|
408
|
+
home,
|
|
409
|
+
cwd,
|
|
410
|
+
config,
|
|
411
|
+
registry,
|
|
412
|
+
log,
|
|
413
|
+
storeRoot,
|
|
414
|
+
problems,
|
|
415
|
+
code,
|
|
416
|
+
disabled: config.plugins
|
|
417
|
+
.filter((entry) => !entry.enabled)
|
|
418
|
+
.map((entry) => entry.name)
|
|
419
|
+
.filter((name): name is string => name !== undefined),
|
|
420
|
+
views: createViews({
|
|
421
|
+
registry,
|
|
422
|
+
store,
|
|
423
|
+
log,
|
|
424
|
+
cwd: viewsCwd ?? cwd,
|
|
425
|
+
follow,
|
|
426
|
+
...(scope === undefined ? {} : { scope }),
|
|
427
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
428
|
+
}),
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function kernelFor(
|
|
433
|
+
context: Context,
|
|
434
|
+
io: CliIo,
|
|
435
|
+
rules: readonly TriggerRule[],
|
|
436
|
+
): Kernel {
|
|
437
|
+
return new Kernel({
|
|
438
|
+
log: context.log,
|
|
439
|
+
registry: context.registry,
|
|
440
|
+
home: context.home,
|
|
441
|
+
storeRoot: context.storeRoot,
|
|
442
|
+
rules,
|
|
443
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function splitFlag(
|
|
448
|
+
argv: readonly string[],
|
|
449
|
+
flag: string,
|
|
450
|
+
): { readonly args: string[]; readonly present: boolean } {
|
|
451
|
+
const args: string[] = [];
|
|
452
|
+
let present = false;
|
|
453
|
+
for (const arg of argv) {
|
|
454
|
+
if (arg === flag) present = true;
|
|
455
|
+
else args.push(arg);
|
|
456
|
+
}
|
|
457
|
+
return { args, present };
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function printValue(io: CliIo, value: unknown): void {
|
|
461
|
+
if (value === undefined) return;
|
|
462
|
+
if (typeof value === "string") {
|
|
463
|
+
io.write(`${value}\n`);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
io.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async function commandInit(home: string, io: CliIo): Promise<number> {
|
|
470
|
+
const ensured = await ensureConfig(home, distributionConfig(home));
|
|
471
|
+
io.write(
|
|
472
|
+
`${ensured.created ? "created" : "using"} ${ensured.path}\n`,
|
|
473
|
+
);
|
|
474
|
+
const config = await readConfig(home);
|
|
475
|
+
const storeRoot = storeRootOf(config);
|
|
476
|
+
const registry = await loadPluginRegistry({
|
|
477
|
+
installOnEnable: INSTALL_ON_ENABLE,
|
|
478
|
+
home,
|
|
479
|
+
cwd: home,
|
|
480
|
+
store: openPluginStore({
|
|
481
|
+
backend: config.store.backend,
|
|
482
|
+
root: storeRoot,
|
|
483
|
+
follow: false,
|
|
484
|
+
}),
|
|
485
|
+
kernelVerbs: KERNEL_VERBS,
|
|
486
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
const checks = await registry.checks();
|
|
490
|
+
if (checks.length === 0) {
|
|
491
|
+
io.write("no plugins loaded\n");
|
|
492
|
+
return 0;
|
|
493
|
+
}
|
|
494
|
+
let failed = false;
|
|
495
|
+
for (const check of checks) {
|
|
496
|
+
if (!check.ok) failed = true;
|
|
497
|
+
io.write(`${check.plugin}: ${check.message}\n`);
|
|
498
|
+
}
|
|
499
|
+
return failed ? 1 : 0;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function commandPending(
|
|
503
|
+
context: Context,
|
|
504
|
+
io: CliIo,
|
|
505
|
+
json: boolean,
|
|
506
|
+
): Promise<void> {
|
|
507
|
+
const pending = await listPending(
|
|
508
|
+
context.log,
|
|
509
|
+
context.registry,
|
|
510
|
+
kernelFor(context, io, []),
|
|
511
|
+
context.views,
|
|
512
|
+
);
|
|
513
|
+
if (json) {
|
|
514
|
+
io.write(`${JSON.stringify(pending, null, 2)}\n`);
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
if (pending.length === 0) {
|
|
518
|
+
io.write("nothing is waiting\n");
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
for (const item of pending) {
|
|
522
|
+
io.write(`${item.runId} ${item.flow} ${item.step ?? "-"}\n`);
|
|
523
|
+
if (item.row !== undefined) io.write(` ${item.row.title}\n`);
|
|
524
|
+
io.write(` waiting: ${item.prompt}\n`);
|
|
525
|
+
if (item.choices.length > 0) {
|
|
526
|
+
io.write(` choices: ${item.choices.join(", ")}\n`);
|
|
527
|
+
}
|
|
528
|
+
if (item.actions.length > 0) {
|
|
529
|
+
io.write(
|
|
530
|
+
` actions: ${item.actions
|
|
531
|
+
.map((action) => `${action.plugin}:${action.action}`)
|
|
532
|
+
.join(", ")}\n`,
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Resolves what `history <id>` names: a run id, a typed plugin object such as
|
|
540
|
+
* `task:42`, or an untyped object id. A bare id that only one declared object
|
|
541
|
+
* type owns resolves to that type; one owned by several is ambiguous.
|
|
542
|
+
*/
|
|
543
|
+
function takeValueFlag(
|
|
544
|
+
argv: readonly string[],
|
|
545
|
+
flag: string,
|
|
546
|
+
): { readonly args: string[]; readonly value: string | undefined; readonly present: boolean } {
|
|
547
|
+
const args: string[] = [];
|
|
548
|
+
let value: string | undefined;
|
|
549
|
+
let present = false;
|
|
550
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
551
|
+
const arg = argv[index] ?? "";
|
|
552
|
+
if (arg === flag) {
|
|
553
|
+
present = true;
|
|
554
|
+
const next = argv[index + 1];
|
|
555
|
+
if (next === undefined) {
|
|
556
|
+
throw new UsageError(`${flag} needs a value`);
|
|
557
|
+
}
|
|
558
|
+
value = next;
|
|
559
|
+
index += 1;
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
if (arg.startsWith(`${flag}=`)) {
|
|
563
|
+
present = true;
|
|
564
|
+
value = arg.slice(flag.length + 1);
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
args.push(arg);
|
|
568
|
+
}
|
|
569
|
+
return { args, value, present };
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function takeRepeatedFlag(
|
|
573
|
+
argv: readonly string[],
|
|
574
|
+
flag: string,
|
|
575
|
+
): { readonly args: string[]; readonly values: string[] } {
|
|
576
|
+
const args: string[] = [];
|
|
577
|
+
const values: string[] = [];
|
|
578
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
579
|
+
const arg = argv[index] ?? "";
|
|
580
|
+
if (arg === flag) {
|
|
581
|
+
const next = argv[index + 1];
|
|
582
|
+
if (next === undefined) throw new UsageError(`${flag} needs a value`);
|
|
583
|
+
values.push(next);
|
|
584
|
+
index += 1;
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
if (arg.startsWith(`${flag}=`)) {
|
|
588
|
+
values.push(arg.slice(flag.length + 1));
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
args.push(arg);
|
|
592
|
+
}
|
|
593
|
+
return { args, values };
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** A `--where` value keeps its text unless it is an obvious JSON scalar. */
|
|
597
|
+
function whereValue(text: string): unknown {
|
|
598
|
+
if (text === "true") return true;
|
|
599
|
+
if (text === "false") return false;
|
|
600
|
+
if (text === "null") return null;
|
|
601
|
+
if (/^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/.test(text)) return Number(text);
|
|
602
|
+
return text;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function parseWhere(values: readonly string[]): Record<string, unknown> {
|
|
606
|
+
const where: Record<string, unknown> = {};
|
|
607
|
+
for (const value of values) {
|
|
608
|
+
const at = value.indexOf("=");
|
|
609
|
+
if (at <= 0) {
|
|
610
|
+
throw new UsageError(`--where needs field=value, got "${value}"`);
|
|
611
|
+
}
|
|
612
|
+
where[value.slice(0, at)] = whereValue(value.slice(at + 1));
|
|
613
|
+
}
|
|
614
|
+
return where;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function parseLimit(value: string | undefined): number | undefined {
|
|
618
|
+
if (value === undefined) return undefined;
|
|
619
|
+
const parsed = Number(value);
|
|
620
|
+
if (!Number.isInteger(parsed) || parsed < 1) {
|
|
621
|
+
throw new UsageError(`--limit needs a positive integer, got "${value}"`);
|
|
622
|
+
}
|
|
623
|
+
return parsed;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
function shellQuote(value: string): string {
|
|
627
|
+
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
async function commandList(
|
|
631
|
+
context: Context,
|
|
632
|
+
io: CliIo,
|
|
633
|
+
type: string,
|
|
634
|
+
json: boolean,
|
|
635
|
+
tty: boolean,
|
|
636
|
+
options: {
|
|
637
|
+
readonly where: readonly string[];
|
|
638
|
+
readonly limit: string | undefined;
|
|
639
|
+
readonly cursor: string | undefined;
|
|
640
|
+
readonly filter: string | undefined;
|
|
641
|
+
readonly repo: string | undefined;
|
|
642
|
+
readonly parent: string | undefined;
|
|
643
|
+
readonly root: boolean;
|
|
644
|
+
},
|
|
645
|
+
): Promise<void> {
|
|
646
|
+
const limit = parseLimit(options.limit);
|
|
647
|
+
if (options.root && options.parent !== undefined) {
|
|
648
|
+
throw new UsageError("list takes --root or --parent, not both");
|
|
649
|
+
}
|
|
650
|
+
const filter = options.filter ?? context.views.defaultFilterOf(type);
|
|
651
|
+
const page = await context.views.list(type, {
|
|
652
|
+
...(options.root ? { root: true } : {}),
|
|
653
|
+
...(options.parent === undefined ? {} : { parent: options.parent }),
|
|
654
|
+
...(filter === undefined ? {} : { filter }),
|
|
655
|
+
...(options.where.length === 0 && options.repo === undefined
|
|
656
|
+
? {}
|
|
657
|
+
: {
|
|
658
|
+
where: {
|
|
659
|
+
...parseWhere(options.where),
|
|
660
|
+
...(options.repo === undefined ? {} : { repository: options.repo }),
|
|
661
|
+
},
|
|
662
|
+
}),
|
|
663
|
+
...(limit === undefined ? {} : { limit }),
|
|
664
|
+
...(options.cursor === undefined ? {} : { cursor: options.cursor }),
|
|
665
|
+
});
|
|
666
|
+
if (json) {
|
|
667
|
+
io.write(`${JSON.stringify(page, null, 2)}\n`);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
if (page.rows.length === 0) {
|
|
671
|
+
io.write(`no objects of type "${type}"\n`);
|
|
672
|
+
} else {
|
|
673
|
+
for (const row of page.rows) {
|
|
674
|
+
io.write(`${rowLine(row, tty)}\n`);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
if (page.next !== undefined) {
|
|
678
|
+
const withFilter = options.filter === undefined ? "" : ` --filter ${shellQuote(options.filter)}`;
|
|
679
|
+
const withRepo = options.repo === undefined ? "" : ` --repo ${shellQuote(options.repo)}`;
|
|
680
|
+
const withLevel = options.root
|
|
681
|
+
? " --root"
|
|
682
|
+
: options.parent === undefined
|
|
683
|
+
? ""
|
|
684
|
+
: ` --parent ${shellQuote(options.parent)}`;
|
|
685
|
+
const withWhere = options.where.map((item) => ` --where ${shellQuote(item)}`).join("");
|
|
686
|
+
io.write(`next: operad list ${type}${withLevel}${withFilter}${withRepo}${withWhere} --cursor ${page.next}\n`);
|
|
687
|
+
}
|
|
688
|
+
if (page.hidden !== undefined && page.hidden > 0) {
|
|
689
|
+
io.write(`${page.hidden} hidden (--filter all to show)\n`);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/** The object's children as rows, the same line `list` prints, when it has any. */
|
|
694
|
+
async function writeChildren(
|
|
695
|
+
context: Context,
|
|
696
|
+
io: CliIo,
|
|
697
|
+
id: string,
|
|
698
|
+
tty: boolean,
|
|
699
|
+
): Promise<void> {
|
|
700
|
+
let cursor: string | undefined;
|
|
701
|
+
let hidden = 0;
|
|
702
|
+
for (;;) {
|
|
703
|
+
const page = await context.views.listTree(undefined, {
|
|
704
|
+
parent: id,
|
|
705
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
706
|
+
});
|
|
707
|
+
for (const row of page.rows) {
|
|
708
|
+
io.write(`${rowLine(row, tty)}\n`);
|
|
709
|
+
}
|
|
710
|
+
hidden = page.hidden ?? hidden;
|
|
711
|
+
if (page.next === undefined) break;
|
|
712
|
+
cursor = page.next;
|
|
713
|
+
}
|
|
714
|
+
if (hidden > 0) io.write(`${hidden} hidden (operad list --parent ${shellQuote(id)} --filter all)\n`);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function firstSection(object: ViewObject): string | undefined {
|
|
718
|
+
return object.sections[0]?.id;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function actionArgFlags(action: ViewAction | ActionInfo): string[] {
|
|
722
|
+
const args: string[] = [];
|
|
723
|
+
for (const [name, property] of Object.entries(action.args?.properties ?? {})) {
|
|
724
|
+
if (property.enum !== undefined) {
|
|
725
|
+
args.push(`--${name} ${property.enum.map((item) => String(item)).join("|")}`);
|
|
726
|
+
} else {
|
|
727
|
+
args.push(`--${name} <${property.type ?? "value"}>`);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return args;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function actionLine(action: ViewAction): string {
|
|
734
|
+
const key = action.key === undefined ? "" : ` (${action.key})`;
|
|
735
|
+
const needs: string[] = [];
|
|
736
|
+
if (action.noteRequired) needs.push("needs a note");
|
|
737
|
+
if (action.confirm) needs.push("asks to confirm");
|
|
738
|
+
const args = actionArgFlags(action);
|
|
739
|
+
const suffix = needs.length === 0 ? "" : ` ${needs.join(", ")}`;
|
|
740
|
+
const list = args.length === 0 ? "" : ` ${args.join(" ")}`;
|
|
741
|
+
return `${action.name}${key}${suffix}${list}`;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/** `show` with no id: the objects that changed last, and how to open one. */
|
|
745
|
+
async function showRecent(
|
|
746
|
+
context: Context,
|
|
747
|
+
io: CliIo,
|
|
748
|
+
json: boolean,
|
|
749
|
+
): Promise<void> {
|
|
750
|
+
const recent = await context.views.recent(10);
|
|
751
|
+
if (json) {
|
|
752
|
+
io.write(`${JSON.stringify(recent, null, 2)}\n`);
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
for (const entry of recent) {
|
|
756
|
+
io.write(`${entry.type} ${entry.id} ${entry.state} ${entry.title}\n`);
|
|
757
|
+
}
|
|
758
|
+
io.write("operad show <id>\n");
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
async function commandShow(
|
|
762
|
+
context: Context,
|
|
763
|
+
io: CliIo,
|
|
764
|
+
argv: readonly string[],
|
|
765
|
+
tty: boolean,
|
|
766
|
+
columns?: number | undefined,
|
|
767
|
+
): Promise<void> {
|
|
768
|
+
let rest = [...argv];
|
|
769
|
+
const sectionFlag = takeValueFlag(rest, "--section");
|
|
770
|
+
rest = sectionFlag.args;
|
|
771
|
+
const cursorFlag = takeValueFlag(rest, "--cursor");
|
|
772
|
+
rest = cursorFlag.args;
|
|
773
|
+
const pageFlag = takeValueFlag(rest, "--page");
|
|
774
|
+
rest = pageFlag.args;
|
|
775
|
+
const full = splitFlag(rest, "--full");
|
|
776
|
+
rest = full.args;
|
|
777
|
+
const raw = splitFlag(rest, "--raw");
|
|
778
|
+
rest = raw.args;
|
|
779
|
+
const json = splitFlag(rest, "--json");
|
|
780
|
+
rest = json.args;
|
|
781
|
+
|
|
782
|
+
const id = rest[0];
|
|
783
|
+
if (id === undefined) {
|
|
784
|
+
await showRecent(context, io, json.present);
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
787
|
+
if (rest.length > 1) throw new UsageError("show takes one object id");
|
|
788
|
+
|
|
789
|
+
let object: ViewObject;
|
|
790
|
+
try {
|
|
791
|
+
object = await context.views.get(id);
|
|
792
|
+
} catch (error) {
|
|
793
|
+
if (error instanceof ViewError && error.kind === "not-found") {
|
|
794
|
+
const near = await context.views.closest(id, 5);
|
|
795
|
+
if (near.length === 0) throw error;
|
|
796
|
+
throw new ViewError(
|
|
797
|
+
"not-found",
|
|
798
|
+
`${error.message}\nclosest:\n${near
|
|
799
|
+
.map((entry) => ` ${entry.id} (${entry.type})`)
|
|
800
|
+
.join("\n")}`,
|
|
801
|
+
{ cause: error },
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
throw error;
|
|
805
|
+
}
|
|
806
|
+
const requested = sectionFlag.value ?? firstSection(object);
|
|
807
|
+
|
|
808
|
+
let cursor = cursorFlag.value;
|
|
809
|
+
let preloaded: Awaited<ReturnType<typeof context.views.section>> | undefined;
|
|
810
|
+
if (pageFlag.value !== undefined) {
|
|
811
|
+
if (cursor !== undefined) throw new UsageError("--page and --cursor cannot be used together");
|
|
812
|
+
if (requested === undefined) throw new Error(`object "${id}" has no section to page`);
|
|
813
|
+
// The table of contents is only sent with a section read (the section API
|
|
814
|
+
// has no read of the contents alone), so one read of the first page comes
|
|
815
|
+
// first. The page asked for is read again, unless it is that first page.
|
|
816
|
+
const first = await context.views.section(id, requested, undefined, { full: false });
|
|
817
|
+
const pages = first.pages;
|
|
818
|
+
if (pages === undefined || pages.length === 0) {
|
|
819
|
+
throw new Error(`section "${requested}" of "${id}" has no pages`);
|
|
820
|
+
}
|
|
821
|
+
// A number is the page at that position, even when another page is labelled with it.
|
|
822
|
+
const number = /^[0-9]+$/.test(pageFlag.value) ? Number(pageFlag.value) : undefined;
|
|
823
|
+
const chosen =
|
|
824
|
+
(number === undefined ? undefined : pages[number - 1]) ??
|
|
825
|
+
pages.find((entry) => entry.label === pageFlag.value);
|
|
826
|
+
if (chosen === undefined) {
|
|
827
|
+
throw new Error(
|
|
828
|
+
`section "${requested}" of "${id}" has no page "${pageFlag.value}"; it has ${pages.length}: ${pages
|
|
829
|
+
.map((entry, at) => `${at + 1} ${entry.label}`)
|
|
830
|
+
.join(", ")}`,
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
cursor = chosen.cursor;
|
|
834
|
+
if (cursor === undefined && !full.present) preloaded = first;
|
|
835
|
+
}
|
|
836
|
+
const readSection = (section: string) =>
|
|
837
|
+
preloaded !== undefined && cursor === undefined && !full.present
|
|
838
|
+
? Promise.resolve(preloaded)
|
|
839
|
+
: context.views.section(id, section, cursor, { full: full.present });
|
|
840
|
+
|
|
841
|
+
if (json.present) {
|
|
842
|
+
if (requested === undefined) {
|
|
843
|
+
io.write(`${JSON.stringify(object, null, 2)}\n`);
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
const content = await readSection(requested);
|
|
847
|
+
io.write(`${JSON.stringify({ ...object, section: content }, null, 2)}\n`);
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
if (requested !== undefined) {
|
|
852
|
+
const exists = object.sections.some((section) => section.id === requested);
|
|
853
|
+
if (!exists) {
|
|
854
|
+
throw new Error(`object "${id}" has no section "${requested}"`);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
if (raw.present) {
|
|
859
|
+
if (requested === undefined) {
|
|
860
|
+
io.write("");
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
const content = await readSection(requested);
|
|
864
|
+
io.write(`${content.markdown.replace(/\n?$/, "\n")}`);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
io.write(`${rowLine(object.row, tty)}\n`);
|
|
869
|
+
if (object.row.parent !== undefined) io.write(`parent: ${object.row.parent}\n`);
|
|
870
|
+
if (object.dependents !== undefined) {
|
|
871
|
+
io.write(`after this one: ${object.dependents.join(", ")}\n`);
|
|
872
|
+
}
|
|
873
|
+
if (object.unavailable !== undefined) {
|
|
874
|
+
io.error(`operad: ${object.unavailable}\n`);
|
|
875
|
+
}
|
|
876
|
+
await writeChildren(context, io, object.id, tty);
|
|
877
|
+
io.write(
|
|
878
|
+
`sections: ${object.sections.map((section) => (section.live === true ? `${section.title} (live)` : section.title)).join(", ")}\n`,
|
|
879
|
+
);
|
|
880
|
+
io.write(
|
|
881
|
+
`actions: ${object.actions.length === 0 ? "none" : object.actions.map(actionLine).join(", ")}\n`,
|
|
882
|
+
);
|
|
883
|
+
if (requested === undefined) return;
|
|
884
|
+
|
|
885
|
+
const content = await readSection(requested);
|
|
886
|
+
io.write(`\n${renderMarkdown(content.markdown, {
|
|
887
|
+
colour: tty,
|
|
888
|
+
width: tty ? columns : undefined,
|
|
889
|
+
})}`);
|
|
890
|
+
if (content.next !== undefined) {
|
|
891
|
+
io.write(
|
|
892
|
+
`next: operad show ${id} --section ${requested} --cursor ${content.next}\n`,
|
|
893
|
+
);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
interface ActionArguments {
|
|
898
|
+
readonly positionals: readonly string[];
|
|
899
|
+
readonly values: ReadonlyMap<string, string | true>;
|
|
900
|
+
readonly yes: boolean;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** The action an argv names, found before its flags are classified. */
|
|
904
|
+
function actionInfoForArgv(
|
|
905
|
+
context: Context,
|
|
906
|
+
argv: readonly string[],
|
|
907
|
+
): ActionInfo | undefined {
|
|
908
|
+
const actions = context.registry.actions();
|
|
909
|
+
const tokens = argv.filter((arg) => !arg.startsWith("--"));
|
|
910
|
+
for (let index = 0; index < tokens.length; index += 1) {
|
|
911
|
+
const token = tokens[index] ?? "";
|
|
912
|
+
const split = splitActionName(token);
|
|
913
|
+
if (split !== undefined) {
|
|
914
|
+
const found = actions.find(
|
|
915
|
+
(info) => info.plugin === split.plugin && info.action === split.action,
|
|
916
|
+
);
|
|
917
|
+
if (found !== undefined) return found;
|
|
918
|
+
}
|
|
919
|
+
const next = tokens[index + 1];
|
|
920
|
+
if (next !== undefined) {
|
|
921
|
+
const found = actions.find(
|
|
922
|
+
(info) => info.plugin === token && info.action === next,
|
|
923
|
+
);
|
|
924
|
+
if (found !== undefined) return found;
|
|
925
|
+
}
|
|
926
|
+
const candidates = actions.filter((info) => info.action === token);
|
|
927
|
+
if (candidates.length === 1) return candidates[0];
|
|
928
|
+
}
|
|
929
|
+
return undefined;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/** Reads `--flag value`, `--flag=value` and a bare boolean `--flag`. */
|
|
933
|
+
function parseActionArguments(
|
|
934
|
+
argv: readonly string[],
|
|
935
|
+
args?: ActionArgsSchema,
|
|
936
|
+
): ActionArguments {
|
|
937
|
+
const positionals: string[] = [];
|
|
938
|
+
const values = new Map<string, string | true>();
|
|
939
|
+
const properties = args?.properties ?? {};
|
|
940
|
+
const note = noteField(args);
|
|
941
|
+
let yes = false;
|
|
942
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
943
|
+
const arg = argv[index] ?? "";
|
|
944
|
+
if (!arg.startsWith("--") || arg === "--") {
|
|
945
|
+
positionals.push(arg);
|
|
946
|
+
continue;
|
|
947
|
+
}
|
|
948
|
+
const body = arg.slice(2);
|
|
949
|
+
const at = body.indexOf("=");
|
|
950
|
+
if (at >= 0) {
|
|
951
|
+
values.set(body.slice(0, at), body.slice(at + 1));
|
|
952
|
+
continue;
|
|
953
|
+
}
|
|
954
|
+
if (body === "yes") {
|
|
955
|
+
yes = true;
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
const next = argv[index + 1];
|
|
959
|
+
const property = properties[body];
|
|
960
|
+
if (property?.type === "boolean") {
|
|
961
|
+
if (next === "true" || next === "false") {
|
|
962
|
+
values.set(body, next);
|
|
963
|
+
index += 1;
|
|
964
|
+
} else {
|
|
965
|
+
values.set(body, true);
|
|
966
|
+
}
|
|
967
|
+
continue;
|
|
968
|
+
}
|
|
969
|
+
const takesValue = property !== undefined || (note !== undefined && body === "note");
|
|
970
|
+
if (!takesValue) {
|
|
971
|
+
// An unknown flag stays bare, so a following object id is not swallowed.
|
|
972
|
+
values.set(body, true);
|
|
973
|
+
continue;
|
|
974
|
+
}
|
|
975
|
+
// A schema value may look like an object id or a negative number.
|
|
976
|
+
if (next === undefined || next.startsWith("--")) {
|
|
977
|
+
values.set(body, true);
|
|
978
|
+
continue;
|
|
979
|
+
}
|
|
980
|
+
values.set(body, next);
|
|
981
|
+
index += 1;
|
|
982
|
+
}
|
|
983
|
+
return { positionals, values, yes };
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
/** Turns one flag's text into the value the schema's type names. */
|
|
987
|
+
function actionArgValue(
|
|
988
|
+
name: string,
|
|
989
|
+
property: ActionArgSchema,
|
|
990
|
+
raw: string | true,
|
|
991
|
+
): unknown {
|
|
992
|
+
if (property.type === "boolean") {
|
|
993
|
+
if (raw === true || raw === "true") return true;
|
|
994
|
+
if (raw === "false") return false;
|
|
995
|
+
throw new UsageError(`--${name}: expected true or false, got "${String(raw)}"`);
|
|
996
|
+
}
|
|
997
|
+
if (raw === true) {
|
|
998
|
+
throw new UsageError(`--${name}: needs a value`);
|
|
999
|
+
}
|
|
1000
|
+
if (property.type === "integer" || property.type === "number") {
|
|
1001
|
+
const value = Number(raw);
|
|
1002
|
+
if (!Number.isFinite(value) || (property.type === "integer" && !Number.isInteger(value))) {
|
|
1003
|
+
throw new UsageError(`--${name}: expected a ${property.type}, got "${raw}"`);
|
|
1004
|
+
}
|
|
1005
|
+
return value;
|
|
1006
|
+
}
|
|
1007
|
+
if (property.type === "array" || property.type === "object") {
|
|
1008
|
+
try {
|
|
1009
|
+
return JSON.parse(raw) as unknown;
|
|
1010
|
+
} catch {
|
|
1011
|
+
throw new UsageError(`--${name}: expected JSON, got "${raw}"`);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
return raw;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
function actionArgsFromFlags(
|
|
1018
|
+
action: ViewAction,
|
|
1019
|
+
values: ReadonlyMap<string, string | true>,
|
|
1020
|
+
): Record<string, unknown> {
|
|
1021
|
+
const properties = action.args?.properties ?? {};
|
|
1022
|
+
const known = new Set(Object.keys(properties));
|
|
1023
|
+
const copied = new Map(values);
|
|
1024
|
+
const note = noteField(action.args);
|
|
1025
|
+
if (note !== undefined && note !== "note" && copied.has("note") && !copied.has(note)) {
|
|
1026
|
+
copied.set(note, copied.get("note") ?? true);
|
|
1027
|
+
copied.delete("note");
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
const args: Record<string, unknown> = {};
|
|
1031
|
+
for (const [name, raw] of copied) {
|
|
1032
|
+
if (name === "yes") continue;
|
|
1033
|
+
if (!known.has(name)) {
|
|
1034
|
+
const hint =
|
|
1035
|
+
note !== undefined && name === "note"
|
|
1036
|
+
? ` (the note argument is --${note})`
|
|
1037
|
+
: "";
|
|
1038
|
+
throw new UsageError(
|
|
1039
|
+
`action "${action.name}" has no argument "--${name}"${hint}`,
|
|
1040
|
+
);
|
|
1041
|
+
}
|
|
1042
|
+
const property = properties[name];
|
|
1043
|
+
if (property === undefined) continue;
|
|
1044
|
+
args[name] = actionArgValue(name, property, raw);
|
|
1045
|
+
}
|
|
1046
|
+
return args;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
function noteField(args: ActionArgsSchema | undefined): string | undefined {
|
|
1050
|
+
for (const [name, property] of Object.entries(args?.properties ?? {})) {
|
|
1051
|
+
if (property.role === "note") return name;
|
|
1052
|
+
}
|
|
1053
|
+
return undefined;
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
function actorOfCli(): Actor {
|
|
1057
|
+
return { via: "cli", id: userInfo().username };
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
function actionCandidates(
|
|
1061
|
+
context: Context,
|
|
1062
|
+
name: string,
|
|
1063
|
+
): readonly { readonly name: string; readonly on: string }[] {
|
|
1064
|
+
return context.registry
|
|
1065
|
+
.actions()
|
|
1066
|
+
.filter((info) => info.action === name);
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
function resolveActionRequest(
|
|
1070
|
+
context: Context,
|
|
1071
|
+
positionals: readonly string[],
|
|
1072
|
+
): { readonly name: string; readonly id: string } | undefined {
|
|
1073
|
+
const first = positionals[0];
|
|
1074
|
+
if (first === undefined) return undefined;
|
|
1075
|
+
|
|
1076
|
+
if (splitActionName(first) !== undefined) {
|
|
1077
|
+
const id = positionals[1];
|
|
1078
|
+
if (id === undefined) {
|
|
1079
|
+
throw new UsageError(`action "${first}" needs an object id`);
|
|
1080
|
+
}
|
|
1081
|
+
if (positionals.length > 2) {
|
|
1082
|
+
throw new UsageError(`action "${first}" takes one object id`);
|
|
1083
|
+
}
|
|
1084
|
+
return { name: first, id };
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
const second = positionals[1];
|
|
1088
|
+
if (
|
|
1089
|
+
second !== undefined &&
|
|
1090
|
+
context.registry.actions().some(
|
|
1091
|
+
(info) => info.plugin === first && info.action === second,
|
|
1092
|
+
)
|
|
1093
|
+
) {
|
|
1094
|
+
const id = positionals[2];
|
|
1095
|
+
if (id === undefined) {
|
|
1096
|
+
throw new UsageError(`action "${first}:${second}" needs an object id`);
|
|
1097
|
+
}
|
|
1098
|
+
if (positionals.length > 3) {
|
|
1099
|
+
throw new UsageError(`action "${first}:${second}" takes one object id`);
|
|
1100
|
+
}
|
|
1101
|
+
return { name: `${first}:${second}`, id };
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
const candidates = actionCandidates(context, first);
|
|
1105
|
+
if (candidates.length === 0) return undefined;
|
|
1106
|
+
if (second === undefined) {
|
|
1107
|
+
throw new UsageError(`action "${first}" needs an object id`);
|
|
1108
|
+
}
|
|
1109
|
+
if (candidates.length > 1) {
|
|
1110
|
+
throw new UsageError(
|
|
1111
|
+
`action "${first}" is offered by ${candidates
|
|
1112
|
+
.map((candidate) => `"${candidate.name}"`)
|
|
1113
|
+
.join(", ")}; use "<plugin>:<action>"`,
|
|
1114
|
+
);
|
|
1115
|
+
}
|
|
1116
|
+
if (positionals.length > 2) {
|
|
1117
|
+
throw new UsageError(`action "${first}" takes one object id`);
|
|
1118
|
+
}
|
|
1119
|
+
return { name: candidates[0]?.name ?? first, id: second };
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
async function promptNote(io: CliIo): Promise<string> {
|
|
1123
|
+
const lines: string[] = [];
|
|
1124
|
+
for (;;) {
|
|
1125
|
+
const line = await readLine(io, lines.length === 0 ? "note: " : " ");
|
|
1126
|
+
if (line === undefined || line.length === 0) break;
|
|
1127
|
+
lines.push(line);
|
|
1128
|
+
}
|
|
1129
|
+
return lines.join("\n");
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
async function readLine(io: CliIo, prompt: string): Promise<string | undefined> {
|
|
1133
|
+
if (io.readLine !== undefined) return io.readLine(prompt);
|
|
1134
|
+
const { createInterface } = await import("node:readline/promises");
|
|
1135
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
1136
|
+
try {
|
|
1137
|
+
return await rl.question(prompt);
|
|
1138
|
+
} finally {
|
|
1139
|
+
rl.close();
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
async function promptConfirm(io: CliIo, name: string): Promise<boolean> {
|
|
1144
|
+
const answer = await readLine(io, `${name}: confirm? [y/N] `);
|
|
1145
|
+
return /^y(es)?$/i.test((answer ?? "").trim());
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
function actionUsage(action: ActionInfo): string {
|
|
1149
|
+
const flags = actionArgFlags(action);
|
|
1150
|
+
if (action.confirm) flags.push("--yes");
|
|
1151
|
+
const suffix = flags.length === 0 ? "" : ` ${flags.map((flag) => `[${flag}]`).join(" ")}`;
|
|
1152
|
+
return `usage: operad ${action.name} <id>${suffix}\n`;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
async function commandAction(
|
|
1156
|
+
context: Context,
|
|
1157
|
+
io: CliIo,
|
|
1158
|
+
argv: readonly string[],
|
|
1159
|
+
tty: boolean,
|
|
1160
|
+
): Promise<boolean> {
|
|
1161
|
+
const help = splitFlag(argv, "--help");
|
|
1162
|
+
if (help.present) {
|
|
1163
|
+
const info = actionInfoForArgv(context, help.args);
|
|
1164
|
+
if (info === undefined) return false;
|
|
1165
|
+
io.write(actionUsage(info));
|
|
1166
|
+
return true;
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
const info = actionInfoForArgv(context, argv);
|
|
1170
|
+
const args = parseActionArguments(argv, info?.args);
|
|
1171
|
+
const request = resolveActionRequest(context, args.positionals);
|
|
1172
|
+
if (request === undefined) return false;
|
|
1173
|
+
|
|
1174
|
+
const object = await context.views.get(request.id);
|
|
1175
|
+
const available = object.actions.find((action) => action.name === request.name);
|
|
1176
|
+
if (available === undefined) {
|
|
1177
|
+
// Let the kernel say why: unavailable now, or not declared at all.
|
|
1178
|
+
// A result that is already true succeeds with its line instead.
|
|
1179
|
+
const run = await context.views.act(request.name, request.id, {
|
|
1180
|
+
args: {},
|
|
1181
|
+
yes: args.yes,
|
|
1182
|
+
actor: actorOfCli(),
|
|
1183
|
+
});
|
|
1184
|
+
printValue(io, run.value);
|
|
1185
|
+
return true;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
const actionArgs = actionArgsFromFlags(available, args.values);
|
|
1189
|
+
const note = noteField(available.args);
|
|
1190
|
+
if (
|
|
1191
|
+
note !== undefined &&
|
|
1192
|
+
available.noteRequired &&
|
|
1193
|
+
(actionArgs[note] === undefined ||
|
|
1194
|
+
(typeof actionArgs[note] === "string" &&
|
|
1195
|
+
(actionArgs[note] as string).trim().length === 0))
|
|
1196
|
+
) {
|
|
1197
|
+
if (!tty) {
|
|
1198
|
+
throw new UsageError(
|
|
1199
|
+
`action "${request.name}" needs a note; pass --${note} <text>`,
|
|
1200
|
+
);
|
|
1201
|
+
}
|
|
1202
|
+
const text = await promptNote(io);
|
|
1203
|
+
if (text.trim().length === 0) {
|
|
1204
|
+
throw new UsageError(`action "${request.name}" needs a note`);
|
|
1205
|
+
}
|
|
1206
|
+
actionArgs[note] = text;
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
if (available.confirm && args.yes !== true) {
|
|
1210
|
+
if (!tty) {
|
|
1211
|
+
throw new UsageError(
|
|
1212
|
+
`action "${request.name}" needs confirmation; pass --yes`,
|
|
1213
|
+
);
|
|
1214
|
+
}
|
|
1215
|
+
if (!(await promptConfirm(io, request.name))) {
|
|
1216
|
+
io.write("cancelled\n");
|
|
1217
|
+
return true;
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
const run = await context.views.act(request.name, request.id, {
|
|
1222
|
+
args: actionArgs,
|
|
1223
|
+
yes: args.yes || available.confirm,
|
|
1224
|
+
actor: actorOfCli(),
|
|
1225
|
+
});
|
|
1226
|
+
printValue(io, run.value);
|
|
1227
|
+
return true;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
async function findHistoryRuns(
|
|
1231
|
+
log: LogBackend,
|
|
1232
|
+
objectTypes: readonly string[],
|
|
1233
|
+
id: string,
|
|
1234
|
+
): Promise<readonly RunInfo[]> {
|
|
1235
|
+
const runs = await log.runs();
|
|
1236
|
+
const exact = runs.find((run) => run.runId === id);
|
|
1237
|
+
if (exact !== undefined) return [exact];
|
|
1238
|
+
|
|
1239
|
+
const parsed = parseObjectKey(id);
|
|
1240
|
+
if (parsed !== undefined) {
|
|
1241
|
+
// A type no loaded plugin declares is unknown, as it is for a bare id.
|
|
1242
|
+
if (!objectTypes.includes(parsed.type)) return [];
|
|
1243
|
+
return runs.filter((run) => run.object === `${parsed.type}:${parsed.id}`);
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
const plain = runs.filter((run) => run.object === id);
|
|
1247
|
+
if (plain.length > 0) return plain;
|
|
1248
|
+
|
|
1249
|
+
const byType = new Map<string, RunInfo[]>();
|
|
1250
|
+
for (const run of runs) {
|
|
1251
|
+
const key = parseObjectKey(run.object);
|
|
1252
|
+
if (key === undefined || key.id !== id) continue;
|
|
1253
|
+
if (!objectTypes.includes(key.type)) continue;
|
|
1254
|
+
const list = byType.get(key.type) ?? [];
|
|
1255
|
+
list.push(run);
|
|
1256
|
+
byType.set(key.type, list);
|
|
1257
|
+
}
|
|
1258
|
+
if (byType.size > 1) {
|
|
1259
|
+
const names = [...byType.keys()].sort();
|
|
1260
|
+
throw new Error(
|
|
1261
|
+
`"${id}" is ambiguous: use ${names.map((type) => `${type}:${id}`).join(", ")}`,
|
|
1262
|
+
);
|
|
1263
|
+
}
|
|
1264
|
+
return byType.values().next().value ?? [];
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
async function streamEntriesJson(
|
|
1268
|
+
log: LogBackend,
|
|
1269
|
+
runId: string,
|
|
1270
|
+
io: CliIo,
|
|
1271
|
+
indent: string,
|
|
1272
|
+
): Promise<void> {
|
|
1273
|
+
let first = true;
|
|
1274
|
+
for await (const entry of historyEntries(log.read(runId))) {
|
|
1275
|
+
if (!first) io.write(",\n");
|
|
1276
|
+
first = false;
|
|
1277
|
+
io.write(
|
|
1278
|
+
`${indent}${JSON.stringify({
|
|
1279
|
+
time: new Date(entry.time).toISOString(),
|
|
1280
|
+
step: entry.step,
|
|
1281
|
+
what: entry.what,
|
|
1282
|
+
why: entry.why,
|
|
1283
|
+
...(entry.actor === undefined ? {} : { actor: entry.actor }),
|
|
1284
|
+
})}`,
|
|
1285
|
+
);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
async function commandTrigger(
|
|
1290
|
+
context: Context,
|
|
1291
|
+
io: CliIo,
|
|
1292
|
+
argv: readonly string[],
|
|
1293
|
+
): Promise<void> {
|
|
1294
|
+
if (argv[0] === "rules") {
|
|
1295
|
+
if (argv.length > 1) throw new UsageError("trigger rules takes no arguments");
|
|
1296
|
+
const rules = await loadSourcedTriggerRules({
|
|
1297
|
+
home: context.home,
|
|
1298
|
+
registry: context.registry,
|
|
1299
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
1300
|
+
});
|
|
1301
|
+
if (rules.length === 0) {
|
|
1302
|
+
io.write("no trigger rules\n");
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
for (const entry of rules) {
|
|
1306
|
+
const rule = entry.rule;
|
|
1307
|
+
const schedule = rule.schedule === undefined ? "" : ` every ${rule.schedule}`;
|
|
1308
|
+
io.write(
|
|
1309
|
+
`${rule.source} ${rule.type} -> ${rule.start.flow} on ${rule.object} (${rule.mode})${schedule} from ${entry.from}\n`,
|
|
1310
|
+
);
|
|
1311
|
+
}
|
|
1312
|
+
return;
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
const flags = parseValueFlags(argv, ["--type", "--object", "--summary", "--data"]);
|
|
1316
|
+
const source = flags.positionals[0];
|
|
1317
|
+
const key = flags.positionals[1];
|
|
1318
|
+
if (source === undefined || key === undefined) {
|
|
1319
|
+
throw new UsageError("trigger needs a source and a key");
|
|
1320
|
+
}
|
|
1321
|
+
if (flags.positionals.length > 2) {
|
|
1322
|
+
throw new UsageError("trigger takes one source and one key");
|
|
1323
|
+
}
|
|
1324
|
+
if (source === "operad") {
|
|
1325
|
+
throw new UsageError('trigger: the source "operad" is reserved');
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
const dataFile = flags.values.get("--data");
|
|
1329
|
+
let data: string | undefined;
|
|
1330
|
+
if (dataFile !== undefined) {
|
|
1331
|
+
try {
|
|
1332
|
+
data = readFileSync(dataFile, "utf8");
|
|
1333
|
+
} catch (error) {
|
|
1334
|
+
throw new UsageError(`trigger: cannot read ${dataFile}: ${String(error)}`);
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
const rules = await loadTriggerRules({
|
|
1339
|
+
home: context.home,
|
|
1340
|
+
registry: context.registry,
|
|
1341
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
1342
|
+
});
|
|
1343
|
+
const kernel = kernelFor(context, io, rules);
|
|
1344
|
+
const type = flags.values.get("--type") ?? "event";
|
|
1345
|
+
const object = flags.values.get("--object");
|
|
1346
|
+
const summary = flags.values.get("--summary");
|
|
1347
|
+
const event: TriggerEvent = {
|
|
1348
|
+
source,
|
|
1349
|
+
key,
|
|
1350
|
+
type,
|
|
1351
|
+
hops: 0,
|
|
1352
|
+
...(object === undefined ? {} : { object }),
|
|
1353
|
+
...(summary === undefined ? {} : { summary }),
|
|
1354
|
+
...(data === undefined ? {} : { data }),
|
|
1355
|
+
};
|
|
1356
|
+
const result = await kernel.receive(event);
|
|
1357
|
+
if (result.kind === "started" && result.runId !== undefined) {
|
|
1358
|
+
io.write(`started ${result.runId}\n`);
|
|
1359
|
+
} else if (result.kind === "candidate" && result.pendingId !== undefined) {
|
|
1360
|
+
io.write(`waiting ${result.pendingId}\n`);
|
|
1361
|
+
} else if (result.kind === "active" && result.runId !== undefined) {
|
|
1362
|
+
io.write(`recorded in ${result.runId}\n`);
|
|
1363
|
+
} else if (result.kind === "observed") {
|
|
1364
|
+
io.write(`observed ${result.flow ?? ""} on ${result.object ?? ""}\n`);
|
|
1365
|
+
} else if (result.kind === "skipped") {
|
|
1366
|
+
io.write(`not started: ${result.reason ?? "the chain is too deep"}\n`);
|
|
1367
|
+
} else {
|
|
1368
|
+
io.write(`recorded ${result.inputId}\n`);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
interface ValueFlags {
|
|
1373
|
+
readonly positionals: readonly string[];
|
|
1374
|
+
readonly values: ReadonlyMap<string, string>;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
function parseValueFlags(argv: readonly string[], allowed: readonly string[]): ValueFlags {
|
|
1378
|
+
const positionals: string[] = [];
|
|
1379
|
+
const values = new Map<string, string>();
|
|
1380
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
1381
|
+
const arg = argv[index];
|
|
1382
|
+
if (arg === undefined) continue;
|
|
1383
|
+
if (!arg.startsWith("--")) {
|
|
1384
|
+
positionals.push(arg);
|
|
1385
|
+
continue;
|
|
1386
|
+
}
|
|
1387
|
+
if (!allowed.includes(arg)) {
|
|
1388
|
+
throw new UsageError(`unknown option "${arg}"`);
|
|
1389
|
+
}
|
|
1390
|
+
const value = argv[index + 1];
|
|
1391
|
+
if (value === undefined) {
|
|
1392
|
+
throw new UsageError(`${arg} needs a value`);
|
|
1393
|
+
}
|
|
1394
|
+
values.set(arg, value);
|
|
1395
|
+
index += 1;
|
|
1396
|
+
}
|
|
1397
|
+
return { positionals, values };
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
function kernelAction(
|
|
1401
|
+
command: string,
|
|
1402
|
+
registry: PluginRegistry,
|
|
1403
|
+
): "start" | "dismiss" | undefined {
|
|
1404
|
+
if (command === "operad:start") return "start";
|
|
1405
|
+
if (command === "operad:dismiss") return "dismiss";
|
|
1406
|
+
if (command !== "start" && command !== "dismiss") return undefined;
|
|
1407
|
+
return registry.resolveCommand([command]) === undefined ? command : undefined;
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
async function commandKernelAction(
|
|
1411
|
+
context: Context,
|
|
1412
|
+
io: CliIo,
|
|
1413
|
+
action: "start" | "dismiss",
|
|
1414
|
+
argv: readonly string[],
|
|
1415
|
+
): Promise<void> {
|
|
1416
|
+
const id = argv[0];
|
|
1417
|
+
if (id === undefined) throw new UsageError(`${action} needs a pending id`);
|
|
1418
|
+
if (argv.length > 1) throw new UsageError(`${action} takes one pending id`);
|
|
1419
|
+
const kernel = kernelFor(context, io, []);
|
|
1420
|
+
if (action === "dismiss") {
|
|
1421
|
+
await kernel.dismiss(id);
|
|
1422
|
+
io.write(`dismissed ${id}\n`);
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
const result = await kernel.startCandidate(id);
|
|
1426
|
+
if (result.kind !== "started") {
|
|
1427
|
+
throw new StateError(`pending item "${id}" could not be started`);
|
|
1428
|
+
}
|
|
1429
|
+
io.write(`started ${result.runId}\n`);
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
async function commandHistory(
|
|
1433
|
+
context: Context,
|
|
1434
|
+
io: CliIo,
|
|
1435
|
+
id: string,
|
|
1436
|
+
json: boolean,
|
|
1437
|
+
): Promise<void> {
|
|
1438
|
+
const types = context.registry.objectTypes().map((entry) => entry.type);
|
|
1439
|
+
let runs = await findHistoryRuns(context.log, types, id);
|
|
1440
|
+
if (runs.length === 0) {
|
|
1441
|
+
// A plugin may scope a bare id to a namespace of its own, as `dev` does for
|
|
1442
|
+
// a repository. Resolve through the views so the run's object key matches.
|
|
1443
|
+
let resolved: string | undefined;
|
|
1444
|
+
try {
|
|
1445
|
+
resolved = (await context.views.get(id)).id;
|
|
1446
|
+
} catch {
|
|
1447
|
+
resolved = undefined;
|
|
1448
|
+
}
|
|
1449
|
+
if (resolved !== undefined && resolved !== id) {
|
|
1450
|
+
runs = await findHistoryRuns(context.log, types, resolved);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
if (runs.length === 0) {
|
|
1454
|
+
// An observed event belongs to no run; its fact is in the global log.
|
|
1455
|
+
const globals: GlobalFact[] = [];
|
|
1456
|
+
for await (const fact of context.log.readGlobal()) {
|
|
1457
|
+
if (fact.cause === id) globals.push(fact);
|
|
1458
|
+
}
|
|
1459
|
+
if (globals.length > 0) {
|
|
1460
|
+
if (json) {
|
|
1461
|
+
io.write("[\n");
|
|
1462
|
+
for (const [index, fact] of globals.entries()) {
|
|
1463
|
+
if (index > 0) io.write(",\n");
|
|
1464
|
+
const entry = historyEntry(fact);
|
|
1465
|
+
io.write(
|
|
1466
|
+
` ${JSON.stringify({
|
|
1467
|
+
time: new Date(entry.time).toISOString(),
|
|
1468
|
+
step: entry.step,
|
|
1469
|
+
what: entry.what,
|
|
1470
|
+
why: entry.why,
|
|
1471
|
+
})}`,
|
|
1472
|
+
);
|
|
1473
|
+
}
|
|
1474
|
+
io.write("\n]\n");
|
|
1475
|
+
return;
|
|
1476
|
+
}
|
|
1477
|
+
for (const fact of globals) {
|
|
1478
|
+
io.write(`${formatHistoryEntry(historyEntry(fact))}\n`);
|
|
1479
|
+
}
|
|
1480
|
+
return;
|
|
1481
|
+
}
|
|
1482
|
+
// An object that never had a run still has the actions people ran on it.
|
|
1483
|
+
let own: readonly string[] = [];
|
|
1484
|
+
try {
|
|
1485
|
+
own = await context.views.objectHistory(id);
|
|
1486
|
+
} catch {
|
|
1487
|
+
own = [];
|
|
1488
|
+
}
|
|
1489
|
+
if (own.length > 0) {
|
|
1490
|
+
if (json) {
|
|
1491
|
+
io.write(`${JSON.stringify(own.map((what) => ({ what })), null, 2)}\n`);
|
|
1492
|
+
return;
|
|
1493
|
+
}
|
|
1494
|
+
for (const line of own) io.write(`${line}\n`);
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1497
|
+
throw new Error(`no run or object "${id}"`);
|
|
1498
|
+
}
|
|
1499
|
+
const ordered = [...runs].sort(
|
|
1500
|
+
(left, right) => left.startedAt - right.startedAt,
|
|
1501
|
+
);
|
|
1502
|
+
|
|
1503
|
+
if (json && ordered.length === 1) {
|
|
1504
|
+
const run = ordered[0];
|
|
1505
|
+
if (run === undefined) return;
|
|
1506
|
+
io.write("[\n");
|
|
1507
|
+
await streamEntriesJson(context.log, run.runId, io, " ");
|
|
1508
|
+
io.write("\n]\n");
|
|
1509
|
+
return;
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
if (json) {
|
|
1513
|
+
io.write("[\n");
|
|
1514
|
+
for (const [index, run] of ordered.entries()) {
|
|
1515
|
+
if (index > 0) io.write(",\n");
|
|
1516
|
+
io.write(
|
|
1517
|
+
`${JSON.stringify({ id: run.runId, flow: run.flow }).slice(0, -1)},"entries":[\n`,
|
|
1518
|
+
);
|
|
1519
|
+
await streamEntriesJson(context.log, run.runId, io, " ");
|
|
1520
|
+
io.write("\n ]}");
|
|
1521
|
+
}
|
|
1522
|
+
io.write("\n]\n");
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
for (const [index, run] of ordered.entries()) {
|
|
1527
|
+
if (index > 0) io.write("\n");
|
|
1528
|
+
if (ordered.length > 1) {
|
|
1529
|
+
io.write(`run ${run.runId} (${run.flow})\n`);
|
|
1530
|
+
}
|
|
1531
|
+
for await (const entry of historyEntries(context.log.read(run.runId))) {
|
|
1532
|
+
io.write(`${formatHistoryEntry(entry)}\n`);
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
async function commandRunning(
|
|
1538
|
+
context: Context,
|
|
1539
|
+
io: CliIo,
|
|
1540
|
+
json: boolean,
|
|
1541
|
+
): Promise<void> {
|
|
1542
|
+
const running = await listRunning(context.log, undefined, context.views);
|
|
1543
|
+
if (json) {
|
|
1544
|
+
io.write(`${JSON.stringify(running, null, 2)}\n`);
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
if (running.length === 0) {
|
|
1548
|
+
io.write("nothing is running\n");
|
|
1549
|
+
return;
|
|
1550
|
+
}
|
|
1551
|
+
for (const item of running) {
|
|
1552
|
+
io.write(
|
|
1553
|
+
`${runningLine(item)}\n`,
|
|
1554
|
+
);
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
/** One `operad running` line: object (run id without one), step, step time, title, run age. */
|
|
1559
|
+
export function runningLine(item: RunningItem): string {
|
|
1560
|
+
const parts = [
|
|
1561
|
+
item.object ?? item.runId,
|
|
1562
|
+
item.stepLabel ?? "-",
|
|
1563
|
+
item.stepElapsedMs === null ? "-" : age(item.stepElapsedMs),
|
|
1564
|
+
];
|
|
1565
|
+
if (item.queuedMs !== undefined && item.queuedMs > 0) parts.push(`queued ${age(item.queuedMs)}`);
|
|
1566
|
+
if (item.title !== null) parts.push(item.title);
|
|
1567
|
+
parts.push(`run ${age(item.elapsedMs)}`);
|
|
1568
|
+
if (item.note !== undefined && item.note !== null) parts.push(item.note);
|
|
1569
|
+
return parts.join(" ");
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
function age(ms: number): string {
|
|
1573
|
+
const total = Math.floor(Math.max(0, ms) / 1000);
|
|
1574
|
+
const hours = Math.floor(total / 3600);
|
|
1575
|
+
const minutes = Math.floor((total % 3600) / 60);
|
|
1576
|
+
if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m`;
|
|
1577
|
+
return minutes > 0 ? `${minutes}m ${String(total % 60).padStart(2, "0")}s` : `${total}s`;
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
function commandFlows(context: Context, io: CliIo, json: boolean): void {
|
|
1581
|
+
const flows = context.registry.flows();
|
|
1582
|
+
if (json) {
|
|
1583
|
+
io.write(
|
|
1584
|
+
`${JSON.stringify(
|
|
1585
|
+
flows.map((entry) => {
|
|
1586
|
+
const problem = context.registry.startProblem(entry.flow.name);
|
|
1587
|
+
return {
|
|
1588
|
+
name: entry.flow.name,
|
|
1589
|
+
plugin: entry.plugin,
|
|
1590
|
+
source: entry.source ?? null,
|
|
1591
|
+
startable: problem === undefined,
|
|
1592
|
+
...(problem === undefined ? {} : { problem }),
|
|
1593
|
+
};
|
|
1594
|
+
}),
|
|
1595
|
+
null,
|
|
1596
|
+
2,
|
|
1597
|
+
)}\n`,
|
|
1598
|
+
);
|
|
1599
|
+
return;
|
|
1600
|
+
}
|
|
1601
|
+
if (flows.length === 0) {
|
|
1602
|
+
io.write("no flows loaded\n");
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
for (const entry of flows) {
|
|
1606
|
+
const source =
|
|
1607
|
+
entry.source === undefined || entry.source === entry.plugin
|
|
1608
|
+
? ""
|
|
1609
|
+
: ` (${entry.source})`;
|
|
1610
|
+
const problem = context.registry.startProblem(entry.flow.name);
|
|
1611
|
+
io.write(
|
|
1612
|
+
`${entry.flow.name} ${entry.plugin}${source}${problem === undefined ? "" : ` ${problem}`}\n`,
|
|
1613
|
+
);
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
const CLI_ENTRY = fileURLToPath(new URL("../bin/operad.ts", import.meta.url));
|
|
1618
|
+
|
|
1619
|
+
function spawnChild(
|
|
1620
|
+
home: string,
|
|
1621
|
+
storeRoot: string,
|
|
1622
|
+
): (runId: string, options: { readonly recover: boolean }) => void {
|
|
1623
|
+
return (runId, options) => {
|
|
1624
|
+
const directory = join(storeRoot, "logs", "runs");
|
|
1625
|
+
mkdirSync(directory, { recursive: true });
|
|
1626
|
+
const output = join(directory, `${runId}.out`);
|
|
1627
|
+
const fd = openSync(output, "a");
|
|
1628
|
+
try {
|
|
1629
|
+
const child = Bun.spawn({
|
|
1630
|
+
cmd: [
|
|
1631
|
+
process.execPath,
|
|
1632
|
+
CLI_ENTRY,
|
|
1633
|
+
"run-internal",
|
|
1634
|
+
runId,
|
|
1635
|
+
...(options.recover ? ["--recover"] : []),
|
|
1636
|
+
],
|
|
1637
|
+
cwd: home,
|
|
1638
|
+
env: { ...process.env, OPERAD_HOME: home },
|
|
1639
|
+
stdin: "ignore",
|
|
1640
|
+
stdout: fd,
|
|
1641
|
+
stderr: fd,
|
|
1642
|
+
});
|
|
1643
|
+
child.unref();
|
|
1644
|
+
} finally {
|
|
1645
|
+
closeSync(fd);
|
|
1646
|
+
}
|
|
1647
|
+
};
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
async function commandServe(
|
|
1651
|
+
context: Context,
|
|
1652
|
+
io: CliIo,
|
|
1653
|
+
argv: readonly string[],
|
|
1654
|
+
lock: LockHandle,
|
|
1655
|
+
supervised: boolean,
|
|
1656
|
+
retryBind: boolean,
|
|
1657
|
+
): Promise<"stopped" | "reload"> {
|
|
1658
|
+
const interval = process.env.OPERAD_SERVE_INTERVAL_MS;
|
|
1659
|
+
const parsed = interval === undefined ? Number.NaN : Number(interval);
|
|
1660
|
+
const controller = new AbortController();
|
|
1661
|
+
const stop = (): void => {
|
|
1662
|
+
controller.abort();
|
|
1663
|
+
};
|
|
1664
|
+
const releaseStop = listenForStop(supervised, stop);
|
|
1665
|
+
|
|
1666
|
+
let rules: readonly TriggerRule[] = [];
|
|
1667
|
+
let sourcesAllowed = true;
|
|
1668
|
+
try {
|
|
1669
|
+
rules = await loadTriggerRules({
|
|
1670
|
+
home: context.home,
|
|
1671
|
+
registry: context.registry,
|
|
1672
|
+
onLog: (message) => {
|
|
1673
|
+
context.problems.push(message);
|
|
1674
|
+
io.error(`${message}\n`);
|
|
1675
|
+
},
|
|
1676
|
+
});
|
|
1677
|
+
} catch (error) {
|
|
1678
|
+
sourcesAllowed = false;
|
|
1679
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1680
|
+
context.problems.push(message);
|
|
1681
|
+
io.error(`operad: ${message}\n`);
|
|
1682
|
+
}
|
|
1683
|
+
// What did not load at start; later log lines are failures of a running
|
|
1684
|
+
// plugin, not a measure of what the process loaded.
|
|
1685
|
+
const startProblems = [...context.problems];
|
|
1686
|
+
const kernel = kernelFor(context, io, rules);
|
|
1687
|
+
const notifier = new Notifier({
|
|
1688
|
+
home: context.home,
|
|
1689
|
+
config: context.config.notify,
|
|
1690
|
+
log: context.log,
|
|
1691
|
+
titleOf: async (type, id) => (await context.views.get(`${type}:${id}`)).row.title,
|
|
1692
|
+
answeredAutomatically: (object) => context.registry.answeredAutomatically(object),
|
|
1693
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
1694
|
+
});
|
|
1695
|
+
let http: HttpServerHandle | undefined;
|
|
1696
|
+
let outcome = "stopped" as "stopped" | "reload";
|
|
1697
|
+
let unreleased: HttpStopError | undefined;
|
|
1698
|
+
let watch: CodeWatch | undefined;
|
|
1699
|
+
const olderNotice = olderCodeNotice(context.home);
|
|
1700
|
+
olderNotice.clear();
|
|
1701
|
+
try {
|
|
1702
|
+
if (context.config.http.enabled) {
|
|
1703
|
+
const startHttp = (): Promise<HttpServerHandle> =>
|
|
1704
|
+
startHttpServer({
|
|
1705
|
+
home: context.home,
|
|
1706
|
+
config: context.config.http,
|
|
1707
|
+
views: context.views,
|
|
1708
|
+
log: context.log,
|
|
1709
|
+
registry: context.registry,
|
|
1710
|
+
kernel,
|
|
1711
|
+
onListen: (url) => io.write(`http ${url}\n`),
|
|
1712
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
1713
|
+
});
|
|
1714
|
+
// A serve that took over from another one tries again for a while: the
|
|
1715
|
+
// old code released its addresses, the system may be slow to hand them
|
|
1716
|
+
// back. A first start fails at once, as before.
|
|
1717
|
+
http = retryBind
|
|
1718
|
+
? await startWithRetry(startHttp, {
|
|
1719
|
+
retryMs: envNumber("OPERAD_BIND_RETRY_MS", 10_000),
|
|
1720
|
+
stepMs: envNumber("OPERAD_BIND_RETRY_STEP_MS", 250),
|
|
1721
|
+
now: () => Date.now(),
|
|
1722
|
+
wait: (ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)),
|
|
1723
|
+
})
|
|
1724
|
+
: await startHttp();
|
|
1725
|
+
}
|
|
1726
|
+
if (sourcesAllowed) {
|
|
1727
|
+
await kernel.startSources();
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
io.write(`serving ${context.home}\n`);
|
|
1731
|
+
if (context.code !== undefined) {
|
|
1732
|
+
const check = codeChecker({
|
|
1733
|
+
home: context.home,
|
|
1734
|
+
snapshot: context.code,
|
|
1735
|
+
known: startProblems,
|
|
1736
|
+
onProblem: (message) => io.error(`operad: ${message}\n`),
|
|
1737
|
+
});
|
|
1738
|
+
watch = new CodeWatch({
|
|
1739
|
+
roots: context.code.roots,
|
|
1740
|
+
alsoWatch: settingsRoots(context.home),
|
|
1741
|
+
baseline: context.code.baseline,
|
|
1742
|
+
declined: context.code.tried,
|
|
1743
|
+
quietMs: envNumber("OPERAD_RELOAD_QUIET_MS", 1_000),
|
|
1744
|
+
pollMs: envNumber("OPERAD_RELOAD_POLL_MS", 5_000),
|
|
1745
|
+
onOlder: olderNotice.report,
|
|
1746
|
+
onChange: async () => {
|
|
1747
|
+
const what = await check();
|
|
1748
|
+
// A stop that came while the new code was tried is not started again.
|
|
1749
|
+
if (what === undefined || controller.signal.aborted) return "keep";
|
|
1750
|
+
io.write(`reloading: ${what}\n`);
|
|
1751
|
+
outcome = "reload";
|
|
1752
|
+
controller.abort();
|
|
1753
|
+
return "reload";
|
|
1754
|
+
},
|
|
1755
|
+
});
|
|
1756
|
+
watch.start();
|
|
1757
|
+
// A stop that is under way (a signal) ends the watch: a change then does nothing more.
|
|
1758
|
+
const watching = watch;
|
|
1759
|
+
controller.signal.addEventListener("abort", () => watching.stop(), { once: true });
|
|
1760
|
+
}
|
|
1761
|
+
await serve({
|
|
1762
|
+
home: context.home,
|
|
1763
|
+
lock,
|
|
1764
|
+
log: context.log,
|
|
1765
|
+
registry: context.registry,
|
|
1766
|
+
lockRoot: context.storeRoot,
|
|
1767
|
+
kernel,
|
|
1768
|
+
spawnRun: spawnChild(context.home, context.storeRoot),
|
|
1769
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
1770
|
+
intervalMs: Number.isFinite(parsed) && parsed > 0 ? parsed : 1_000,
|
|
1771
|
+
signal: controller.signal,
|
|
1772
|
+
clock: () => Date.now(),
|
|
1773
|
+
// The command can take 30 seconds; the loop must not wait for it.
|
|
1774
|
+
onPass: () => {
|
|
1775
|
+
notifier.pass().catch((error: unknown) => {
|
|
1776
|
+
io.error(`notify: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1777
|
+
});
|
|
1778
|
+
},
|
|
1779
|
+
});
|
|
1780
|
+
} finally {
|
|
1781
|
+
watch?.stop();
|
|
1782
|
+
olderNotice.clear();
|
|
1783
|
+
await notifier.stop();
|
|
1784
|
+
if (http !== undefined) {
|
|
1785
|
+
try {
|
|
1786
|
+
await http.stop();
|
|
1787
|
+
} catch (error) {
|
|
1788
|
+
// An address that did not release cannot be handed over, and this
|
|
1789
|
+
// process may not go on serving only some of its addresses.
|
|
1790
|
+
if (!(error instanceof HttpStopError)) throw error;
|
|
1791
|
+
unreleased = error;
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
await kernel.stopSources();
|
|
1795
|
+
releaseStop();
|
|
1796
|
+
}
|
|
1797
|
+
if (unreleased !== undefined) throw new HandOverStuck(unreleased, outcome === "reload");
|
|
1798
|
+
return outcome;
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
function envNumber(name: string, fallback: number): number {
|
|
1802
|
+
const value = Number(process.env[name]);
|
|
1803
|
+
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
async function commandRunInternal(
|
|
1807
|
+
context: Context,
|
|
1808
|
+
io: CliIo,
|
|
1809
|
+
argv: readonly string[],
|
|
1810
|
+
): Promise<void> {
|
|
1811
|
+
const { args, present } = splitFlag(argv, "--recover");
|
|
1812
|
+
const runId = args[0];
|
|
1813
|
+
if (runId === undefined) throw new UsageError("run-internal needs a run id");
|
|
1814
|
+
|
|
1815
|
+
const runs = await context.log.runs();
|
|
1816
|
+
const run = runs.find((candidate) => candidate.runId === runId);
|
|
1817
|
+
if (run === undefined) throw new Error(`no run "${runId}"`);
|
|
1818
|
+
const found = context.registry.flow(run.flow);
|
|
1819
|
+
if (found === undefined) {
|
|
1820
|
+
throw new StateError(`run "${runId}": flow "${run.flow}" is not loaded`);
|
|
1821
|
+
}
|
|
1822
|
+
const problem = context.registry.startProblem(run.flow);
|
|
1823
|
+
if (problem !== undefined) throw new StateError(`run "${runId}": ${problem}`);
|
|
1824
|
+
const object = parseObjectKey(run.object);
|
|
1825
|
+
let rules: readonly TriggerRule[] = [];
|
|
1826
|
+
try {
|
|
1827
|
+
rules = await loadTriggerRules({
|
|
1828
|
+
home: context.home,
|
|
1829
|
+
registry: context.registry,
|
|
1830
|
+
onLog: (message) => {
|
|
1831
|
+
context.problems.push(message);
|
|
1832
|
+
io.error(`${message}\n`);
|
|
1833
|
+
},
|
|
1834
|
+
});
|
|
1835
|
+
} catch (error) {
|
|
1836
|
+
// The run still has to finish; a broken rule file is not a run error.
|
|
1837
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1838
|
+
context.problems.push(message);
|
|
1839
|
+
io.error(`${message}\n`);
|
|
1840
|
+
}
|
|
1841
|
+
const startProblems = [...context.problems];
|
|
1842
|
+
const kernel = kernelFor(context, io, rules);
|
|
1843
|
+
// A start that died after creating its run left no start files; restore
|
|
1844
|
+
// them so this runner starts from the input and event that were recorded.
|
|
1845
|
+
kernel.adoptStart(run);
|
|
1846
|
+
const startInput = readStoredStart(context.storeRoot, runId);
|
|
1847
|
+
const trigger = readStoredTrigger(context.storeRoot, runId);
|
|
1848
|
+
const runner = new Runner({
|
|
1849
|
+
log: context.log,
|
|
1850
|
+
flow: found.flow,
|
|
1851
|
+
runId,
|
|
1852
|
+
registry: context.registry,
|
|
1853
|
+
lockRoot: context.storeRoot,
|
|
1854
|
+
askGraceSecs: context.config.ask.graceSecs,
|
|
1855
|
+
recover: present,
|
|
1856
|
+
...(run.access === undefined ? {} : { access: run.access }),
|
|
1857
|
+
...(object === undefined ? {} : { object }),
|
|
1858
|
+
...(startInput === undefined ? {} : { startInput }),
|
|
1859
|
+
...(trigger === undefined ? {} : { trigger }),
|
|
1860
|
+
onEnded: async (endedRunId, state) => {
|
|
1861
|
+
await kernel.emitRunEnd(endedRunId, state);
|
|
1862
|
+
},
|
|
1863
|
+
emit: async (plugin, event) => {
|
|
1864
|
+
await kernel.emitStep(runId, plugin, event, run.object);
|
|
1865
|
+
},
|
|
1866
|
+
...(context.code === undefined
|
|
1867
|
+
? {}
|
|
1868
|
+
: {
|
|
1869
|
+
handover: codeChecker({
|
|
1870
|
+
home: context.home,
|
|
1871
|
+
snapshot: context.code,
|
|
1872
|
+
known: startProblems,
|
|
1873
|
+
onProblem: (message) => io.error(`operad: ${message}\n`),
|
|
1874
|
+
waitPollMs: envNumber("OPERAD_RELOAD_POLL_MS", 5_000),
|
|
1875
|
+
}),
|
|
1876
|
+
}),
|
|
1877
|
+
});
|
|
1878
|
+
await runner.run();
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
function definitionName(value: unknown): string | undefined {
|
|
1882
|
+
if (
|
|
1883
|
+
typeof value === "object" &&
|
|
1884
|
+
value !== null &&
|
|
1885
|
+
"name" in value &&
|
|
1886
|
+
typeof (value as { name?: unknown }).name === "string"
|
|
1887
|
+
) {
|
|
1888
|
+
return (value as { name: string }).name;
|
|
1889
|
+
}
|
|
1890
|
+
return undefined;
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
function definitionVersion(value: unknown): string | undefined {
|
|
1894
|
+
if (
|
|
1895
|
+
typeof value === "object" &&
|
|
1896
|
+
value !== null &&
|
|
1897
|
+
"version" in value &&
|
|
1898
|
+
typeof (value as { version?: unknown }).version === "string"
|
|
1899
|
+
) {
|
|
1900
|
+
return (value as { version: string }).version;
|
|
1901
|
+
}
|
|
1902
|
+
return undefined;
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
async function commandPluginList(context: Context, io: CliIo): Promise<number> {
|
|
1906
|
+
if (context.config.plugins.length === 0) {
|
|
1907
|
+
io.write("no plugins configured\n");
|
|
1908
|
+
return 0;
|
|
1909
|
+
}
|
|
1910
|
+
for (const entry of context.config.plugins) {
|
|
1911
|
+
let definition: unknown;
|
|
1912
|
+
if (entry.enabled) {
|
|
1913
|
+
try {
|
|
1914
|
+
definition = await loadPlugin(entry.module, context.home);
|
|
1915
|
+
} catch {
|
|
1916
|
+
definition = undefined;
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
const name = definitionName(definition) ?? entry.name ?? entry.module;
|
|
1920
|
+
const version = definitionVersion(definition) ?? "-";
|
|
1921
|
+
io.write(`${name} ${version} ${entry.enabled ? "enabled" : "disabled"}\n`);
|
|
1922
|
+
}
|
|
1923
|
+
return 0;
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
/**
|
|
1927
|
+
* The active runs that would be affected by switching a plugin off: a run of
|
|
1928
|
+
* a flow that declares one of the plugin's steps, or is in one now.
|
|
1929
|
+
*/
|
|
1930
|
+
async function activeRunsUsingPlugin(
|
|
1931
|
+
context: Context,
|
|
1932
|
+
name: string,
|
|
1933
|
+
): Promise<readonly { readonly runId: string; readonly step: string }[]> {
|
|
1934
|
+
const prefix = `${name}/`;
|
|
1935
|
+
const affected: { runId: string; step: string }[] = [];
|
|
1936
|
+
const runs = await context.log.runs({ active: true });
|
|
1937
|
+
for (const run of runs) {
|
|
1938
|
+
const found = context.registry.flow(run.flow);
|
|
1939
|
+
if (found === undefined) continue;
|
|
1940
|
+
const state = await readState(context.log, run.runId);
|
|
1941
|
+
const uses: string[] = [];
|
|
1942
|
+
const effectUse = state.effect?.use;
|
|
1943
|
+
if (typeof effectUse === "string" && effectUse.startsWith(prefix)) {
|
|
1944
|
+
uses.push(effectUse);
|
|
1945
|
+
}
|
|
1946
|
+
const effectCheck = state.effect?.check;
|
|
1947
|
+
if (typeof effectCheck === "string" && effectCheck.startsWith(prefix)) {
|
|
1948
|
+
uses.push(effectCheck);
|
|
1949
|
+
}
|
|
1950
|
+
for (const step of found.flow.steps) {
|
|
1951
|
+
if (step.kind !== "plugin") continue;
|
|
1952
|
+
const use = (step.params as { readonly use?: unknown }).use;
|
|
1953
|
+
if (typeof use === "string" && use.startsWith(prefix)) {
|
|
1954
|
+
uses.push(`${step.id} (${use})`);
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
if (uses.length > 0) affected.push({ runId: run.runId, step: uses[0] ?? prefix });
|
|
1958
|
+
}
|
|
1959
|
+
return affected;
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
/** True when `specifier` resolves from the package at `from`. */
|
|
1963
|
+
function resolvableFrom(specifier: string, from: string): boolean {
|
|
1964
|
+
try {
|
|
1965
|
+
Bun.resolveSync(specifier, join(from, "package.json"));
|
|
1966
|
+
return true;
|
|
1967
|
+
} catch {
|
|
1968
|
+
return false;
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
/** Validates one loaded plugin with the configured plugins, without starting a run. */
|
|
1973
|
+
async function checkLoadedDefinition(
|
|
1974
|
+
context: Context,
|
|
1975
|
+
io: CliIo,
|
|
1976
|
+
name: string,
|
|
1977
|
+
definition: unknown,
|
|
1978
|
+
): Promise<number> {
|
|
1979
|
+
const configured = await loadConfiguredPlugins({ home: context.home, installOnEnable: INSTALL_ON_ENABLE });
|
|
1980
|
+
const others = configured.loaded
|
|
1981
|
+
.map((loaded) => loaded.definition)
|
|
1982
|
+
.filter((item) => definitionName(item) !== name);
|
|
1983
|
+
let registry: PluginRegistry;
|
|
1984
|
+
try {
|
|
1985
|
+
registry = new PluginRegistry([...others, definition], {
|
|
1986
|
+
home: context.home,
|
|
1987
|
+
cwd: context.home,
|
|
1988
|
+
store: new MemoryPluginStore({ root: join(context.storeRoot, "plugin-check") }),
|
|
1989
|
+
settings: {},
|
|
1990
|
+
validateSettings: false,
|
|
1991
|
+
onLog: () => undefined,
|
|
1992
|
+
});
|
|
1993
|
+
} catch (error) {
|
|
1994
|
+
io.write(`${name}: ${messageOf(error)}\n`);
|
|
1995
|
+
return 1;
|
|
1996
|
+
}
|
|
1997
|
+
if (!registry.names().includes(name)) {
|
|
1998
|
+
const refusal = registry.refusals().find((item) => item.plugin === name);
|
|
1999
|
+
io.write(`${refusal?.message ?? `${name}: not loaded`}\n`);
|
|
2000
|
+
return 1;
|
|
2001
|
+
}
|
|
2002
|
+
io.write(`${name}: ok\n`);
|
|
2003
|
+
return 0;
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
async function commandPluginAdmin(
|
|
2007
|
+
context: Context,
|
|
2008
|
+
io: CliIo,
|
|
2009
|
+
argv: readonly string[],
|
|
2010
|
+
): Promise<number> {
|
|
2011
|
+
const sub = argv[0];
|
|
2012
|
+
if (sub === "list") {
|
|
2013
|
+
if (argv.length > 1) throw new UsageError("plugin list takes no arguments");
|
|
2014
|
+
return commandPluginList(context, io);
|
|
2015
|
+
}
|
|
2016
|
+
if (sub === "enable" || sub === "disable") {
|
|
2017
|
+
const name = argv[1];
|
|
2018
|
+
if (name === undefined) throw new UsageError(`plugin ${sub} needs a plugin name`);
|
|
2019
|
+
if (argv.length > 2) throw new UsageError(`plugin ${sub} takes one plugin name`);
|
|
2020
|
+
const entry = context.config.plugins.find((item) => item.name === name);
|
|
2021
|
+
if (entry === undefined && !(sub === "enable" && OPTIONAL_PLUGINS.includes(name))) {
|
|
2022
|
+
throw new ConfigError(`plugins.${name}: no such plugin`);
|
|
2023
|
+
}
|
|
2024
|
+
if (sub === "disable") {
|
|
2025
|
+
const affected = await activeRunsUsingPlugin(context, name);
|
|
2026
|
+
if (affected.length > 0) {
|
|
2027
|
+
const named = affected
|
|
2028
|
+
.map((run) => `"${run.runId}" (${run.step})`)
|
|
2029
|
+
.join(", ");
|
|
2030
|
+
throw new StateError(`cannot disable "${name}": run ${named} is active`);
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
if (sub === "enable" && INSTALL_ON_ENABLE.includes(name)) {
|
|
2034
|
+
const module = entry?.module ?? defaultPluginModule(name);
|
|
2035
|
+
if (module === defaultPluginModule(name)) {
|
|
2036
|
+
// The package is not a CLI dependency: put it in the home's Bun project
|
|
2037
|
+
// first, with optional dependencies skipped (operad-plugins 11).
|
|
2038
|
+
await ensureInstalledPackage({
|
|
2039
|
+
home: context.home,
|
|
2040
|
+
specifier: module,
|
|
2041
|
+
version: ENGINE_VERSION,
|
|
2042
|
+
from: import.meta.dir,
|
|
2043
|
+
omitOptional: true,
|
|
2044
|
+
});
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
await setPluginEnabled(context.home, name, sub === "enable", pluginOffer(context.home));
|
|
2048
|
+
io.write(`${name}: ${sub === "enable" ? "enabled" : "disabled"}\n`);
|
|
2049
|
+
return 0;
|
|
2050
|
+
}
|
|
2051
|
+
if (sub === "check") {
|
|
2052
|
+
const asked = argv[1];
|
|
2053
|
+
if (asked === undefined) throw new UsageError("plugin check needs a path");
|
|
2054
|
+
if (argv.length > 2) throw new UsageError("plugin check takes one path");
|
|
2055
|
+
const configured = context.config.plugins.find((item) => item.name === asked);
|
|
2056
|
+
const module =
|
|
2057
|
+
configured?.module ??
|
|
2058
|
+
(OPTIONAL_PLUGINS.includes(asked) ? defaultPluginModule(asked) : undefined);
|
|
2059
|
+
if (module !== undefined) {
|
|
2060
|
+
const installed = installedPackageFile(context.home, module);
|
|
2061
|
+
if (
|
|
2062
|
+
installed === undefined &&
|
|
2063
|
+
!(runningFromWorkspace() && resolvableFrom(module, import.meta.dir))
|
|
2064
|
+
) {
|
|
2065
|
+
io.write(`${asked}: not installed; run \`operad plugin enable ${asked}\` to install it\n`);
|
|
2066
|
+
return 1;
|
|
2067
|
+
}
|
|
2068
|
+
const source = installed !== undefined && !runningFromWorkspace() ? installed : module;
|
|
2069
|
+
const definition = await loadPlugin(source, context.home, installed);
|
|
2070
|
+
return await checkLoadedDefinition(context, io, definitionName(definition) ?? module, definition);
|
|
2071
|
+
}
|
|
2072
|
+
const definition = await loadPlugin(asked, context.home);
|
|
2073
|
+
return await checkLoadedDefinition(context, io, definitionName(definition) ?? asked, definition);
|
|
2074
|
+
}
|
|
2075
|
+
throw new UsageError("plugin needs list, enable, disable or check");
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
/** Reads a secret without echo in a terminal, or the first line of stdin. */
|
|
2079
|
+
async function readSecretValue(io: CliIo): Promise<string> {
|
|
2080
|
+
if (io.readLine !== undefined) {
|
|
2081
|
+
const line = await io.readLine("secret value: ");
|
|
2082
|
+
if (line === undefined) throw new UsageError("secret set: no value was read");
|
|
2083
|
+
return line.replace(/\r?\n$/, "");
|
|
2084
|
+
}
|
|
2085
|
+
if (process.stdin.isTTY !== true) {
|
|
2086
|
+
const text = await Bun.stdin.text();
|
|
2087
|
+
const line = text.split(/\r?\n/, 1)[0];
|
|
2088
|
+
if (line === undefined) throw new UsageError("secret set: no value was read");
|
|
2089
|
+
return line;
|
|
2090
|
+
}
|
|
2091
|
+
const { createInterface } = await import("node:readline/promises");
|
|
2092
|
+
const rl = createInterface({
|
|
2093
|
+
input: process.stdin,
|
|
2094
|
+
output: process.stderr,
|
|
2095
|
+
terminal: true,
|
|
2096
|
+
});
|
|
2097
|
+
const muted = rl as unknown as { _writeToOutput?: (text: string) => void };
|
|
2098
|
+
muted._writeToOutput = () => undefined;
|
|
2099
|
+
writeStream(process.stderr, "secret value: ");
|
|
2100
|
+
try {
|
|
2101
|
+
return (await rl.question("")).replace(/\r?\n$/, "");
|
|
2102
|
+
} finally {
|
|
2103
|
+
rl.close();
|
|
2104
|
+
writeStream(process.stderr, "\n");
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
|
|
2108
|
+
async function commandSecret(
|
|
2109
|
+
home: string,
|
|
2110
|
+
io: CliIo,
|
|
2111
|
+
argv: readonly string[],
|
|
2112
|
+
): Promise<number> {
|
|
2113
|
+
const sub = argv[0];
|
|
2114
|
+
if (sub === "set") {
|
|
2115
|
+
const plugin = argv[1];
|
|
2116
|
+
const name = argv[2];
|
|
2117
|
+
if (plugin === undefined || name === undefined) {
|
|
2118
|
+
throw new UsageError("secret set needs a plugin and a secret name");
|
|
2119
|
+
}
|
|
2120
|
+
if (argv.length > 3) throw new UsageError("secret set takes a plugin and a name");
|
|
2121
|
+
const value = await readSecretValue(io);
|
|
2122
|
+
await new FileSecretStore({ home, plugin }).set(name, value);
|
|
2123
|
+
io.write(`secret "${name}" set for plugin "${plugin}"\n`);
|
|
2124
|
+
return 0;
|
|
2125
|
+
}
|
|
2126
|
+
if (sub === "list") {
|
|
2127
|
+
const plugin = argv[1];
|
|
2128
|
+
if (plugin === undefined) throw new UsageError("secret list needs a plugin");
|
|
2129
|
+
if (argv.length > 2) throw new UsageError("secret list takes one plugin");
|
|
2130
|
+
const names = await new FileSecretStore({ home, plugin }).names();
|
|
2131
|
+
if (names.length === 0) {
|
|
2132
|
+
io.write(`no secrets for plugin "${plugin}"\n`);
|
|
2133
|
+
} else {
|
|
2134
|
+
for (const name of names) io.write(`${name}\n`);
|
|
2135
|
+
}
|
|
2136
|
+
return 0;
|
|
2137
|
+
}
|
|
2138
|
+
if (sub === "delete") {
|
|
2139
|
+
const plugin = argv[1];
|
|
2140
|
+
const name = argv[2];
|
|
2141
|
+
if (plugin === undefined || name === undefined) {
|
|
2142
|
+
throw new UsageError("secret delete needs a plugin and a secret name");
|
|
2143
|
+
}
|
|
2144
|
+
if (argv.length > 3) throw new UsageError("secret delete takes a plugin and a name");
|
|
2145
|
+
await new FileSecretStore({ home, plugin }).delete(name);
|
|
2146
|
+
io.write(`secret "${name}" deleted for plugin "${plugin}"\n`);
|
|
2147
|
+
return 0;
|
|
2148
|
+
}
|
|
2149
|
+
throw new UsageError("secret needs set, list or delete");
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
function settingsCell(value: unknown): string {
|
|
2153
|
+
return value === undefined ? "-" : JSON.stringify(value);
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
/** `operad settings` and `operad settings set`: the views' two settings calls. */
|
|
2157
|
+
async function commandSettings(
|
|
2158
|
+
home: string,
|
|
2159
|
+
io: CliIo,
|
|
2160
|
+
args: readonly string[],
|
|
2161
|
+
): Promise<number> {
|
|
2162
|
+
const repoFlag = takeValueFlag(args, "--repo");
|
|
2163
|
+
const jsonFlag = splitFlag(repoFlag.args, "--json");
|
|
2164
|
+
const yesFlag = splitFlag(jsonFlag.args, "--yes");
|
|
2165
|
+
const rest = yesFlag.args;
|
|
2166
|
+
const setting = rest[0] === "set";
|
|
2167
|
+
const context = await openContext(home, io);
|
|
2168
|
+
try {
|
|
2169
|
+
if (!setting) {
|
|
2170
|
+
if (rest.length > 0) throw new UsageError("settings takes no arguments");
|
|
2171
|
+
if (yesFlag.present) throw new UsageError("settings does not take --yes");
|
|
2172
|
+
const settings = await context.views.settings(repoFlag.value);
|
|
2173
|
+
if (jsonFlag.present) {
|
|
2174
|
+
io.write(`${JSON.stringify(settings, null, 2)}\n`);
|
|
2175
|
+
return 0;
|
|
2176
|
+
}
|
|
2177
|
+
if (settings.length === 0) {
|
|
2178
|
+
io.write("no settings\n");
|
|
2179
|
+
return 0;
|
|
2180
|
+
}
|
|
2181
|
+
for (const item of settings) {
|
|
2182
|
+
const marks = [
|
|
2183
|
+
item.editable ? "editable" : "read-only",
|
|
2184
|
+
...(item.confirm ? ["confirm"] : []),
|
|
2185
|
+
].join(",");
|
|
2186
|
+
io.write(
|
|
2187
|
+
[
|
|
2188
|
+
item.scope,
|
|
2189
|
+
item.name,
|
|
2190
|
+
settingsCell(item.value),
|
|
2191
|
+
`default ${settingsCell(item.default)}`,
|
|
2192
|
+
marks,
|
|
2193
|
+
...(item.description === undefined ? [] : [item.description]),
|
|
2194
|
+
].join(" ") + "\n",
|
|
2195
|
+
);
|
|
2196
|
+
}
|
|
2197
|
+
return 0;
|
|
2198
|
+
}
|
|
2199
|
+
const [, name, raw, ...extra] = rest;
|
|
2200
|
+
if (name === undefined || raw === undefined) {
|
|
2201
|
+
throw new UsageError("settings set needs a name and a value");
|
|
2202
|
+
}
|
|
2203
|
+
if (extra.length > 0) throw new UsageError("settings set takes a name and one value");
|
|
2204
|
+
if (jsonFlag.present) throw new UsageError("settings set does not take --json");
|
|
2205
|
+
let value: unknown;
|
|
2206
|
+
try {
|
|
2207
|
+
value = JSON.parse(raw);
|
|
2208
|
+
} catch {
|
|
2209
|
+
value = raw;
|
|
2210
|
+
}
|
|
2211
|
+
try {
|
|
2212
|
+
const changed = await context.views.set(name, value, {
|
|
2213
|
+
...(repoFlag.value === undefined ? {} : { scope: repoFlag.value }),
|
|
2214
|
+
confirmed: yesFlag.present,
|
|
2215
|
+
});
|
|
2216
|
+
io.write(
|
|
2217
|
+
`${changed.name} = ${settingsCell(changed.value)}${
|
|
2218
|
+
changed.scope === "global" ? "" : ` (${changed.scope})`
|
|
2219
|
+
}\n`,
|
|
2220
|
+
);
|
|
2221
|
+
return 0;
|
|
2222
|
+
} catch (error) {
|
|
2223
|
+
if (error instanceof ViewError && error.kind === "confirm") {
|
|
2224
|
+
throw new ViewError("confirm", `${error.message}; pass --yes to change it`);
|
|
2225
|
+
}
|
|
2226
|
+
throw error;
|
|
2227
|
+
}
|
|
2228
|
+
} finally {
|
|
2229
|
+
context.views.close();
|
|
2230
|
+
await context.log.close();
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
async function commandHttp(
|
|
2235
|
+
home: string,
|
|
2236
|
+
io: CliIo,
|
|
2237
|
+
argv: readonly string[],
|
|
2238
|
+
): Promise<number> {
|
|
2239
|
+
if (argv.length !== 2 || argv[0] !== "token" || argv[1] !== "rotate") {
|
|
2240
|
+
throw new UsageError("http needs `token rotate`");
|
|
2241
|
+
}
|
|
2242
|
+
await rotateHttpToken(home);
|
|
2243
|
+
io.write("http token rotated\n");
|
|
2244
|
+
return 0;
|
|
2245
|
+
}
|
|
2246
|
+
|
|
2247
|
+
/** The base URL the app should use: `--url`, or the first address a phone can reach. */
|
|
2248
|
+
function pairBaseUrl(config: OperadConfig, given: string | undefined): string {
|
|
2249
|
+
if (!config.http.enabled) {
|
|
2250
|
+
throw new UsageError('pair needs "http.enabled" in config.json');
|
|
2251
|
+
}
|
|
2252
|
+
if (given !== undefined) {
|
|
2253
|
+
let url: URL;
|
|
2254
|
+
try {
|
|
2255
|
+
url = new URL(given);
|
|
2256
|
+
} catch {
|
|
2257
|
+
throw new UsageError("--url must be an http or https URL");
|
|
2258
|
+
}
|
|
2259
|
+
if (
|
|
2260
|
+
(url.protocol !== "http:" && url.protocol !== "https:") ||
|
|
2261
|
+
url.username !== "" ||
|
|
2262
|
+
url.password !== "" ||
|
|
2263
|
+
url.search !== "" ||
|
|
2264
|
+
url.hash !== ""
|
|
2265
|
+
) {
|
|
2266
|
+
throw new UsageError("--url must be an http or https URL without credentials or a query");
|
|
2267
|
+
}
|
|
2268
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
2269
|
+
}
|
|
2270
|
+
const address = config.http.listen.find(
|
|
2271
|
+
(entry) => listenAddressKind(entry) !== "loopback",
|
|
2272
|
+
);
|
|
2273
|
+
if (address === undefined) {
|
|
2274
|
+
throw new UsageError(
|
|
2275
|
+
"http.listen has only loopback addresses, which a phone cannot reach; add one or pass --url",
|
|
2276
|
+
);
|
|
2277
|
+
}
|
|
2278
|
+
if (config.http.port === 0) {
|
|
2279
|
+
throw new UsageError('http.port is 0; set a port in config.json or pass --url');
|
|
2280
|
+
}
|
|
2281
|
+
const host = address.includes(":") ? `[${address}]` : address;
|
|
2282
|
+
return `http://${host}:${config.http.port}`;
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
async function commandPair(
|
|
2286
|
+
home: string,
|
|
2287
|
+
io: CliIo,
|
|
2288
|
+
argv: readonly string[],
|
|
2289
|
+
terminal: boolean,
|
|
2290
|
+
): Promise<number> {
|
|
2291
|
+
let given: string | undefined;
|
|
2292
|
+
let showToken = false;
|
|
2293
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
2294
|
+
const arg = argv[index] ?? "";
|
|
2295
|
+
if (arg === "--show-token") {
|
|
2296
|
+
showToken = true;
|
|
2297
|
+
} else if (arg === "--url") {
|
|
2298
|
+
given = argv[index + 1];
|
|
2299
|
+
index += 1;
|
|
2300
|
+
if (given === undefined) throw new UsageError("--url needs a value");
|
|
2301
|
+
} else if (arg.startsWith("--url=")) {
|
|
2302
|
+
given = arg.slice("--url=".length);
|
|
2303
|
+
} else {
|
|
2304
|
+
throw new UsageError(`pair: unknown argument "${arg}"`);
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
if (!terminal && !showToken) {
|
|
2308
|
+
throw new UsageError(
|
|
2309
|
+
"pair prints the token and needs a terminal; pass --show-token to print it anyway",
|
|
2310
|
+
);
|
|
2311
|
+
}
|
|
2312
|
+
const config = await readConfig(home);
|
|
2313
|
+
const url = pairBaseUrl(config, given);
|
|
2314
|
+
const { token } = await ensureHttpToken(home);
|
|
2315
|
+
const link = pairLink(url, token);
|
|
2316
|
+
|
|
2317
|
+
io.write(`url ${url}\ntoken ${token}\n`);
|
|
2318
|
+
if (!terminal) {
|
|
2319
|
+
io.write(`link ${link}\n`);
|
|
2320
|
+
return 0;
|
|
2321
|
+
}
|
|
2322
|
+
try {
|
|
2323
|
+
io.write(`\nScan this in the operad app:\n\n${renderQr(encodeQr(link))}`);
|
|
2324
|
+
} catch (error) {
|
|
2325
|
+
if (!(error instanceof QrTooLongError)) throw error;
|
|
2326
|
+
io.write("\nThe link is too long for a QR code; enter the url and token by hand.\n");
|
|
2327
|
+
}
|
|
2328
|
+
return 0;
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
/** Where `loadTui` installs from and how a test replaces the install. */
|
|
2332
|
+
export interface LoadTuiOptions {
|
|
2333
|
+
/** A package directory to resolve the workspace copy from; defaults to the CLI. */
|
|
2334
|
+
readonly from?: string | undefined;
|
|
2335
|
+
/** A test replaces the install command. */
|
|
2336
|
+
readonly run?: InstallRunner | undefined;
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
/**
|
|
2340
|
+
* The terminal client: the workspace's own copy in a checkout, otherwise the
|
|
2341
|
+
* copy installed into the home's Bun project. The client's UI library is a
|
|
2342
|
+
* third-party package, so the CLI does not depend on it; its install keeps the
|
|
2343
|
+
* optional packages the UI library needs.
|
|
2344
|
+
*/
|
|
2345
|
+
export async function loadTui(home: string, options: LoadTuiOptions = {}): Promise<TuiRunner> {
|
|
2346
|
+
const installed = await ensureInstalledPackage({
|
|
2347
|
+
home,
|
|
2348
|
+
specifier: "@operad-io/tui",
|
|
2349
|
+
version: ENGINE_VERSION,
|
|
2350
|
+
from: options.from ?? import.meta.dir,
|
|
2351
|
+
...(options.run === undefined ? {} : { run: options.run }),
|
|
2352
|
+
});
|
|
2353
|
+
// A string variable keeps the type checker from requiring the package,
|
|
2354
|
+
// which the CLI deliberately does not depend on.
|
|
2355
|
+
const entry: string = "@operad-io/tui/app";
|
|
2356
|
+
const loaded = (
|
|
2357
|
+
installed === undefined
|
|
2358
|
+
? await import(entry)
|
|
2359
|
+
: await import(pathToFileURL(installed).href)
|
|
2360
|
+
) as { readonly runTui: TuiRunner };
|
|
2361
|
+
return loaded.runTui;
|
|
2362
|
+
}
|
|
2363
|
+
|
|
2364
|
+
/** `operad tui [--url <url>] [--token <token>] [--no-start] [--theme <name>]`. */
|
|
2365
|
+
async function commandTui(
|
|
2366
|
+
home: string,
|
|
2367
|
+
io: CliIo,
|
|
2368
|
+
argv: readonly string[],
|
|
2369
|
+
tty: boolean,
|
|
2370
|
+
injected: TuiRunner | undefined,
|
|
2371
|
+
): Promise<number> {
|
|
2372
|
+
let url: string | undefined;
|
|
2373
|
+
let token: string | undefined;
|
|
2374
|
+
let noStart = false;
|
|
2375
|
+
let theme: string | undefined;
|
|
2376
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
2377
|
+
const arg = argv[index] ?? "";
|
|
2378
|
+
if (arg === "--no-start") {
|
|
2379
|
+
noStart = true;
|
|
2380
|
+
} else if (arg === "--url" || arg === "--token" || arg === "--theme") {
|
|
2381
|
+
const value = argv[index + 1];
|
|
2382
|
+
if (value === undefined) throw new UsageError(`${arg} needs a value`);
|
|
2383
|
+
if (arg === "--url") url = value;
|
|
2384
|
+
else if (arg === "--theme") theme = value;
|
|
2385
|
+
else token = value;
|
|
2386
|
+
index += 1;
|
|
2387
|
+
} else if (arg.startsWith("--url=")) {
|
|
2388
|
+
url = arg.slice("--url=".length);
|
|
2389
|
+
} else if (arg.startsWith("--token=")) {
|
|
2390
|
+
token = arg.slice("--token=".length);
|
|
2391
|
+
} else if (arg.startsWith("--theme=")) {
|
|
2392
|
+
theme = arg.slice("--theme=".length);
|
|
2393
|
+
} else {
|
|
2394
|
+
throw new UsageError(`tui: unknown argument "${arg}"`);
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2397
|
+
if (injected === undefined && !tty) {
|
|
2398
|
+
throw new UsageError("tui needs a terminal");
|
|
2399
|
+
}
|
|
2400
|
+
const runner: TuiRunner =
|
|
2401
|
+
injected ??
|
|
2402
|
+
(async (command) => {
|
|
2403
|
+
const runTui = await loadTui(home);
|
|
2404
|
+
return await runTui(command);
|
|
2405
|
+
});
|
|
2406
|
+
return await runner({
|
|
2407
|
+
home,
|
|
2408
|
+
...(url === undefined ? {} : { url }),
|
|
2409
|
+
...(token === undefined ? {} : { token }),
|
|
2410
|
+
...(noStart ? { noStart } : {}),
|
|
2411
|
+
...(theme === undefined ? {} : { theme }),
|
|
2412
|
+
serveEntry: CLI_ENTRY,
|
|
2413
|
+
write: (line) => io.write(`${line}\n`),
|
|
2414
|
+
onError: (message) => {
|
|
2415
|
+
io.error(`operad: ${message}\n`);
|
|
2416
|
+
},
|
|
2417
|
+
onLog: (message) => io.error(`${message}\n`),
|
|
2418
|
+
});
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
async function commandPlugin(
|
|
2422
|
+
context: Context,
|
|
2423
|
+
io: CliIo,
|
|
2424
|
+
argv: readonly string[],
|
|
2425
|
+
): Promise<boolean> {
|
|
2426
|
+
const run = await context.registry.runCommand(argv, {
|
|
2427
|
+
cwd: context.cwd,
|
|
2428
|
+
});
|
|
2429
|
+
if (run === undefined) return false;
|
|
2430
|
+
printValue(io, run.value);
|
|
2431
|
+
return true;
|
|
2432
|
+
}
|
|
2433
|
+
|
|
2434
|
+
/**
|
|
2435
|
+
* The `operad` command. Returns the exit code; the caller sets it and exits.
|
|
2436
|
+
* 0 ok, 1 error, 2 usage, 3 state does not allow it, 4 a lock is held.
|
|
2437
|
+
*/
|
|
2438
|
+
export async function main(
|
|
2439
|
+
args: readonly string[],
|
|
2440
|
+
options: MainOptions = {},
|
|
2441
|
+
): Promise<number> {
|
|
2442
|
+
const io = options.io ?? STDIO;
|
|
2443
|
+
const home = options.home ?? defaultOperadHome();
|
|
2444
|
+
const tty =
|
|
2445
|
+
options.isTTY ??
|
|
2446
|
+
(process.stdout.isTTY === true && process.stdin.isTTY === true);
|
|
2447
|
+
const command = args[0];
|
|
2448
|
+
|
|
2449
|
+
try {
|
|
2450
|
+
if (command === "--version" || command === "-V") {
|
|
2451
|
+
io.write(`operad ${ENGINE_VERSION}\n`);
|
|
2452
|
+
return 0;
|
|
2453
|
+
}
|
|
2454
|
+
if (command === undefined || command === "help" || command === "--help") {
|
|
2455
|
+
io.write(HELP);
|
|
2456
|
+
return command === undefined ? 2 : 0;
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
if (command === "init") {
|
|
2460
|
+
return await commandInit(home, io);
|
|
2461
|
+
}
|
|
2462
|
+
|
|
2463
|
+
if (command === "mcp") {
|
|
2464
|
+
let claudeChannel = false;
|
|
2465
|
+
let types: string[] | undefined;
|
|
2466
|
+
const rest = args.slice(1);
|
|
2467
|
+
for (let index = 0; index < rest.length; index += 1) {
|
|
2468
|
+
const arg = rest[index] ?? "";
|
|
2469
|
+
if (arg === "--claude-channel") {
|
|
2470
|
+
claudeChannel = true;
|
|
2471
|
+
continue;
|
|
2472
|
+
}
|
|
2473
|
+
if (arg === "--types" || arg.startsWith("--types=")) {
|
|
2474
|
+
const value =
|
|
2475
|
+
arg === "--types" ? rest[index + 1] : arg.slice("--types=".length);
|
|
2476
|
+
if (value === undefined || value.startsWith("--")) {
|
|
2477
|
+
throw new UsageError("mcp --types needs a comma-separated list of object types");
|
|
2478
|
+
}
|
|
2479
|
+
if (arg === "--types") index += 1;
|
|
2480
|
+
const names = value
|
|
2481
|
+
.split(",")
|
|
2482
|
+
.map((name) => name.trim())
|
|
2483
|
+
.filter((name) => name.length > 0);
|
|
2484
|
+
if (names.length === 0) {
|
|
2485
|
+
throw new UsageError("mcp --types needs at least one object type");
|
|
2486
|
+
}
|
|
2487
|
+
types = [...new Set([...(types ?? []), ...names])];
|
|
2488
|
+
continue;
|
|
2489
|
+
}
|
|
2490
|
+
throw new UsageError(`mcp does not take "${arg}"`);
|
|
2491
|
+
}
|
|
2492
|
+
try {
|
|
2493
|
+
await runMcpServer({
|
|
2494
|
+
home,
|
|
2495
|
+
cwd: process.cwd(),
|
|
2496
|
+
write: (text) => io.write(text),
|
|
2497
|
+
error: (text) => io.error(text),
|
|
2498
|
+
installOnEnable: INSTALL_ON_ENABLE,
|
|
2499
|
+
...(claudeChannel ? { claudeChannel: true } : {}),
|
|
2500
|
+
...(types === undefined ? {} : { types }),
|
|
2501
|
+
});
|
|
2502
|
+
} catch (error) {
|
|
2503
|
+
if (error instanceof ChannelTypeError) {
|
|
2504
|
+
throw new UsageError(error.message);
|
|
2505
|
+
}
|
|
2506
|
+
throw error;
|
|
2507
|
+
}
|
|
2508
|
+
return 0;
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2511
|
+
if (command === "secret") {
|
|
2512
|
+
return await commandSecret(home, io, args.slice(1));
|
|
2513
|
+
}
|
|
2514
|
+
|
|
2515
|
+
if (command === "settings") {
|
|
2516
|
+
return await commandSettings(home, io, args.slice(1));
|
|
2517
|
+
}
|
|
2518
|
+
|
|
2519
|
+
if (command === "http") {
|
|
2520
|
+
return await commandHttp(home, io, args.slice(1));
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
if (command === "pair") {
|
|
2524
|
+
return await commandPair(
|
|
2525
|
+
home,
|
|
2526
|
+
io,
|
|
2527
|
+
args.slice(1),
|
|
2528
|
+
options.isTTY ?? process.stdout.isTTY === true,
|
|
2529
|
+
);
|
|
2530
|
+
}
|
|
2531
|
+
|
|
2532
|
+
if (command === "tui") {
|
|
2533
|
+
return await commandTui(home, io, args.slice(1), tty, options.tui);
|
|
2534
|
+
}
|
|
2535
|
+
|
|
2536
|
+
if (command === "plugin") {
|
|
2537
|
+
const context = await openContext(home, io);
|
|
2538
|
+
try {
|
|
2539
|
+
return await commandPluginAdmin(context, io, args.slice(1));
|
|
2540
|
+
} finally {
|
|
2541
|
+
context.views.close();
|
|
2542
|
+
await context.log.close();
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2546
|
+
if (command === "check-load") {
|
|
2547
|
+
// What a fresh process would not load, one line each, for a process that
|
|
2548
|
+
// wants to know before it gives up the code it runs.
|
|
2549
|
+
const context = await openContext(home, { ...io, error: () => undefined });
|
|
2550
|
+
try {
|
|
2551
|
+
try {
|
|
2552
|
+
await loadTriggerRules({
|
|
2553
|
+
home,
|
|
2554
|
+
registry: context.registry,
|
|
2555
|
+
onLog: (message) => context.problems.push(message),
|
|
2556
|
+
});
|
|
2557
|
+
} catch (error) {
|
|
2558
|
+
context.problems.push(error instanceof Error ? error.message : String(error));
|
|
2559
|
+
}
|
|
2560
|
+
for (const line of context.problems) io.write(`${line.replace(/\n/g, " ")}\n`);
|
|
2561
|
+
} finally {
|
|
2562
|
+
context.views.close();
|
|
2563
|
+
await context.log.close();
|
|
2564
|
+
}
|
|
2565
|
+
return 0;
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2568
|
+
if (command === "run-internal") {
|
|
2569
|
+
const context = await openContext(home, io, {
|
|
2570
|
+
trackCode: true,
|
|
2571
|
+
follow: true,
|
|
2572
|
+
});
|
|
2573
|
+
try {
|
|
2574
|
+
await commandRunInternal(context, io, args.slice(1));
|
|
2575
|
+
} finally {
|
|
2576
|
+
context.views.close();
|
|
2577
|
+
await context.log.close();
|
|
2578
|
+
}
|
|
2579
|
+
return 0;
|
|
2580
|
+
}
|
|
2581
|
+
|
|
2582
|
+
if (command === "serve" && args[1] === "stop") {
|
|
2583
|
+
let timeoutSecs = DEFAULT_STOP_TIMEOUT_SECS;
|
|
2584
|
+
const rest = args.slice(2);
|
|
2585
|
+
for (let index = 0; index < rest.length; index += 1) {
|
|
2586
|
+
const arg = rest[index] ?? "";
|
|
2587
|
+
if (arg === "--timeout" || arg.startsWith("--timeout=")) {
|
|
2588
|
+
const value =
|
|
2589
|
+
arg === "--timeout" ? rest[index + 1] : arg.slice("--timeout=".length);
|
|
2590
|
+
if (value === undefined) throw new UsageError("serve stop --timeout needs a value");
|
|
2591
|
+
if (arg === "--timeout") index += 1;
|
|
2592
|
+
try {
|
|
2593
|
+
timeoutSecs = parseStopTimeout(value);
|
|
2594
|
+
} catch (error) {
|
|
2595
|
+
throw new UsageError(error instanceof Error ? error.message : String(error));
|
|
2596
|
+
}
|
|
2597
|
+
continue;
|
|
2598
|
+
}
|
|
2599
|
+
throw new UsageError(`serve stop does not take "${arg}"`);
|
|
2600
|
+
}
|
|
2601
|
+
await serveStop({ home, timeoutSecs, write: (text) => io.write(text) });
|
|
2602
|
+
return 0;
|
|
2603
|
+
}
|
|
2604
|
+
|
|
2605
|
+
if (command === "serve") {
|
|
2606
|
+
if (args.length > 1) throw new UsageError("serve takes no arguments");
|
|
2607
|
+
// The home lock comes first, before the store, the plugins or the port:
|
|
2608
|
+
// a second serve fails here, with exit 4, and touches nothing. The lock
|
|
2609
|
+
// is handed to `serve`, so there is no check and then act.
|
|
2610
|
+
const { supervised, replaces, retryBind } = serveStartFlags();
|
|
2611
|
+
// What this process loaded when it first served: a serve restored here runs that code.
|
|
2612
|
+
const snapshotOf = serveSnapshots();
|
|
2613
|
+
const runChecked = async (
|
|
2614
|
+
isSupervised: boolean,
|
|
2615
|
+
retryBind: boolean,
|
|
2616
|
+
restored: boolean,
|
|
2617
|
+
): Promise<"stopped" | "reload"> => {
|
|
2618
|
+
const lock = acquireLock(serveLockPath(home));
|
|
2619
|
+
try {
|
|
2620
|
+
// serve answers clients that are in no directory: a bare id must not
|
|
2621
|
+
// be scoped to the repository serve happened to start in, so its
|
|
2622
|
+
// views resolve ids from the home, outside every repository.
|
|
2623
|
+
const opened = await openContext(home, io, {
|
|
2624
|
+
viewsCwd: home,
|
|
2625
|
+
trackCode: true,
|
|
2626
|
+
follow: true,
|
|
2627
|
+
});
|
|
2628
|
+
const context =
|
|
2629
|
+
opened.code === undefined
|
|
2630
|
+
? opened
|
|
2631
|
+
: { ...opened, code: snapshotOf(opened.code, restored) };
|
|
2632
|
+
try {
|
|
2633
|
+
return await commandServe(context, io, args.slice(1), lock, isSupervised, retryBind);
|
|
2634
|
+
} finally {
|
|
2635
|
+
context.views.close();
|
|
2636
|
+
await context.log.close();
|
|
2637
|
+
}
|
|
2638
|
+
} finally {
|
|
2639
|
+
lock.release();
|
|
2640
|
+
}
|
|
2641
|
+
};
|
|
2642
|
+
const startReplacement = (): void => {
|
|
2643
|
+
Bun.spawn({
|
|
2644
|
+
cmd: [process.execPath, ...process.argv.slice(1)],
|
|
2645
|
+
cwd: process.cwd(),
|
|
2646
|
+
env: replacementEnv(),
|
|
2647
|
+
stdin: "ignore",
|
|
2648
|
+
stdout: "inherit",
|
|
2649
|
+
stderr: "inherit",
|
|
2650
|
+
}).unref();
|
|
2651
|
+
};
|
|
2652
|
+
const runOnce = async (
|
|
2653
|
+
isSupervised: boolean,
|
|
2654
|
+
retryBind: boolean,
|
|
2655
|
+
restored = false,
|
|
2656
|
+
): Promise<"stopped" | "reload"> => {
|
|
2657
|
+
try {
|
|
2658
|
+
return await runChecked(isSupervised, retryBind, restored);
|
|
2659
|
+
} catch (error) {
|
|
2660
|
+
// The lock is released by now; see leaveStuck.
|
|
2661
|
+
if (!(error instanceof HandOverStuck)) throw error;
|
|
2662
|
+
return leaveStuck(error, {
|
|
2663
|
+
supervised: isSupervised,
|
|
2664
|
+
log: (message) => io.error(message),
|
|
2665
|
+
exit: (code) => process.exit(code),
|
|
2666
|
+
startReplacement,
|
|
2667
|
+
});
|
|
2668
|
+
}
|
|
2669
|
+
};
|
|
2670
|
+
let result: "stopped" | "reload";
|
|
2671
|
+
try {
|
|
2672
|
+
result = await runOnce(supervised, retryBind);
|
|
2673
|
+
} catch (error) {
|
|
2674
|
+
if (error instanceof BindFailed) {
|
|
2675
|
+
if (supervised) {
|
|
2676
|
+
// One line, then the process that started the serve serves again.
|
|
2677
|
+
io.error(
|
|
2678
|
+
`reload: the new code could not listen (${error.message}); the old code tries every address again\n`,
|
|
2679
|
+
);
|
|
2680
|
+
return BIND_FAILED_EXIT;
|
|
2681
|
+
}
|
|
2682
|
+
if (replaces) {
|
|
2683
|
+
// There is no supervisor to restore the old code: try once more in
|
|
2684
|
+
// a new process rather than leave the home with no serve.
|
|
2685
|
+
io.error(
|
|
2686
|
+
`reload: the new code could not listen (${error.message}); starting another serve\n`,
|
|
2687
|
+
);
|
|
2688
|
+
startReplacement();
|
|
2689
|
+
return BIND_FAILED_EXIT;
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
throw error;
|
|
2693
|
+
}
|
|
2694
|
+
// The home lock and the port are free; the same command line starts
|
|
2695
|
+
// again under the process that was started: a supervised serve hands
|
|
2696
|
+
// the restart back with a code, the first one becomes the supervisor.
|
|
2697
|
+
if (result === "reload") {
|
|
2698
|
+
return supervised
|
|
2699
|
+
? RELOAD_EXIT
|
|
2700
|
+
: await superviseServe(
|
|
2701
|
+
() => runOnce(false, true, true),
|
|
2702
|
+
(message) => io.error(message),
|
|
2703
|
+
);
|
|
2704
|
+
}
|
|
2705
|
+
return 0;
|
|
2706
|
+
}
|
|
2707
|
+
|
|
2708
|
+
if (command === "trigger") {
|
|
2709
|
+
const context = await openContext(home, io);
|
|
2710
|
+
try {
|
|
2711
|
+
await commandTrigger(context, io, args.slice(1));
|
|
2712
|
+
} finally {
|
|
2713
|
+
await context.log.close();
|
|
2714
|
+
}
|
|
2715
|
+
return 0;
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
if (
|
|
2719
|
+
command === "pending" ||
|
|
2720
|
+
command === "history" ||
|
|
2721
|
+
command === "running" ||
|
|
2722
|
+
command === "flows" ||
|
|
2723
|
+
command === "list" ||
|
|
2724
|
+
command === "show"
|
|
2725
|
+
) {
|
|
2726
|
+
// `show` accepts `--repo <name>` to say where a bare id lives.
|
|
2727
|
+
const showRepo =
|
|
2728
|
+
command === "show" ? takeValueFlag(args.slice(1), "--repo") : undefined;
|
|
2729
|
+
const context = await openContext(home, io, {
|
|
2730
|
+
...(showRepo?.value === undefined ? {} : { scope: showRepo.value }),
|
|
2731
|
+
});
|
|
2732
|
+
try {
|
|
2733
|
+
if (command === "pending") {
|
|
2734
|
+
const { args: rest, present } = splitFlag(args.slice(1), "--json");
|
|
2735
|
+
if (rest.length > 0) {
|
|
2736
|
+
throw new UsageError("pending takes no arguments");
|
|
2737
|
+
}
|
|
2738
|
+
await commandPending(context, io, present);
|
|
2739
|
+
return 0;
|
|
2740
|
+
}
|
|
2741
|
+
if (command === "history") {
|
|
2742
|
+
const { args: rest, present } = splitFlag(args.slice(1), "--json");
|
|
2743
|
+
const id = rest[0];
|
|
2744
|
+
if (id === undefined) throw new UsageError("history needs a run id");
|
|
2745
|
+
if (rest.length > 1) throw new UsageError("history takes one id");
|
|
2746
|
+
await commandHistory(context, io, id, present);
|
|
2747
|
+
return 0;
|
|
2748
|
+
}
|
|
2749
|
+
if (command === "running") {
|
|
2750
|
+
const { args: rest, present } = splitFlag(args.slice(1), "--json");
|
|
2751
|
+
if (rest.length > 0) {
|
|
2752
|
+
throw new UsageError("running takes no arguments");
|
|
2753
|
+
}
|
|
2754
|
+
await commandRunning(context, io, present);
|
|
2755
|
+
return 0;
|
|
2756
|
+
}
|
|
2757
|
+
if (command === "list") {
|
|
2758
|
+
let rest = args.slice(1);
|
|
2759
|
+
const jsonFlag = splitFlag(rest, "--json");
|
|
2760
|
+
rest = jsonFlag.args;
|
|
2761
|
+
const whereFlag = takeRepeatedFlag(rest, "--where");
|
|
2762
|
+
rest = whereFlag.args;
|
|
2763
|
+
const limitFlag = takeValueFlag(rest, "--limit");
|
|
2764
|
+
rest = limitFlag.args;
|
|
2765
|
+
const cursorFlag = takeValueFlag(rest, "--cursor");
|
|
2766
|
+
rest = cursorFlag.args;
|
|
2767
|
+
const filterFlag = takeValueFlag(rest, "--filter");
|
|
2768
|
+
rest = filterFlag.args;
|
|
2769
|
+
const repoFlag = takeValueFlag(rest, "--repo");
|
|
2770
|
+
rest = repoFlag.args;
|
|
2771
|
+
const parentFlag = takeValueFlag(rest, "--parent");
|
|
2772
|
+
rest = parentFlag.args;
|
|
2773
|
+
const rootFlag = splitFlag(rest, "--root");
|
|
2774
|
+
rest = rootFlag.args;
|
|
2775
|
+
const type = rest[0];
|
|
2776
|
+
if (type === undefined) throw new UsageError("list needs an object type");
|
|
2777
|
+
if (rest.length > 1) throw new UsageError("list takes one object type");
|
|
2778
|
+
await commandList(context, io, type, jsonFlag.present, tty, {
|
|
2779
|
+
where: whereFlag.values,
|
|
2780
|
+
limit: limitFlag.value,
|
|
2781
|
+
cursor: cursorFlag.value,
|
|
2782
|
+
filter: filterFlag.value,
|
|
2783
|
+
repo: repoFlag.value,
|
|
2784
|
+
parent: parentFlag.value,
|
|
2785
|
+
root: rootFlag.present,
|
|
2786
|
+
});
|
|
2787
|
+
return 0;
|
|
2788
|
+
}
|
|
2789
|
+
if (command === "show") {
|
|
2790
|
+
await commandShow(context, io, showRepo?.args ?? args.slice(1), tty, options.columns ?? process.stdout.columns);
|
|
2791
|
+
return 0;
|
|
2792
|
+
}
|
|
2793
|
+
const { args: rest, present } = splitFlag(args.slice(1), "--json");
|
|
2794
|
+
if (rest.length > 0) throw new UsageError("flows takes no arguments");
|
|
2795
|
+
commandFlows(context, io, present);
|
|
2796
|
+
return 0;
|
|
2797
|
+
} finally {
|
|
2798
|
+
context.views.close();
|
|
2799
|
+
await context.log.close();
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
|
|
2803
|
+
// An action takes `--repo <name>` to say where a bare id lives; a plugin
|
|
2804
|
+
// command reads its own `--repo`, so it still gets the arguments whole.
|
|
2805
|
+
const actionRepo = takeValueFlag(args, "--repo");
|
|
2806
|
+
const context = await openContext(home, io, {
|
|
2807
|
+
...(actionRepo.value === undefined ? {} : { scope: actionRepo.value }),
|
|
2808
|
+
});
|
|
2809
|
+
try {
|
|
2810
|
+
const action = kernelAction(command, context.registry);
|
|
2811
|
+
if (action !== undefined) {
|
|
2812
|
+
await commandKernelAction(context, io, action, actionRepo.args.slice(1));
|
|
2813
|
+
return 0;
|
|
2814
|
+
}
|
|
2815
|
+
if (await commandAction(context, io, actionRepo.args, tty)) return 0;
|
|
2816
|
+
if (await commandPlugin(context, io, args)) return 0;
|
|
2817
|
+
const attempted = splitActionName(command ?? "")?.plugin ?? command ?? "";
|
|
2818
|
+
if (context.disabled.includes(attempted)) {
|
|
2819
|
+
throw new StateError(`plugin "${attempted}" is disabled`);
|
|
2820
|
+
}
|
|
2821
|
+
} finally {
|
|
2822
|
+
context.views.close();
|
|
2823
|
+
await context.log.close();
|
|
2824
|
+
}
|
|
2825
|
+
throw new UsageError(`unknown command "${command ?? ""}"`);
|
|
2826
|
+
} catch (error) {
|
|
2827
|
+
if (error instanceof UsageError) {
|
|
2828
|
+
io.error(`operad: ${error.message}\n\n${HELP}`);
|
|
2829
|
+
return 2;
|
|
2830
|
+
}
|
|
2831
|
+
if (error instanceof ViewError) {
|
|
2832
|
+
if (
|
|
2833
|
+
error.kind === "note" ||
|
|
2834
|
+
error.kind === "confirm" ||
|
|
2835
|
+
error.kind === "ambiguous" ||
|
|
2836
|
+
error.kind === "args" ||
|
|
2837
|
+
error.kind === "where" ||
|
|
2838
|
+
error.kind === "cursor"
|
|
2839
|
+
) {
|
|
2840
|
+
io.error(`operad: ${error.message}\n`);
|
|
2841
|
+
return 2;
|
|
2842
|
+
}
|
|
2843
|
+
if (
|
|
2844
|
+
error.kind === "action" ||
|
|
2845
|
+
error.kind === "not-available" ||
|
|
2846
|
+
error.kind === "unavailable"
|
|
2847
|
+
) {
|
|
2848
|
+
io.error(`operad: ${error.message}\n`);
|
|
2849
|
+
return 3;
|
|
2850
|
+
}
|
|
2851
|
+
io.error(`operad: ${error.message}\n`);
|
|
2852
|
+
return 1;
|
|
2853
|
+
}
|
|
2854
|
+
if (error instanceof LockHeldError) {
|
|
2855
|
+
io.error(`operad: ${error.message}\n`);
|
|
2856
|
+
return 4;
|
|
2857
|
+
}
|
|
2858
|
+
if (error instanceof StateError) {
|
|
2859
|
+
io.error(`operad: ${error.message}\n`);
|
|
2860
|
+
return 3;
|
|
2861
|
+
}
|
|
2862
|
+
if (error instanceof ConfigError) {
|
|
2863
|
+
io.error(`operad: ${error.message}\n`);
|
|
2864
|
+
return 1;
|
|
2865
|
+
}
|
|
2866
|
+
io.error(
|
|
2867
|
+
`operad: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
2868
|
+
);
|
|
2869
|
+
return 1;
|
|
2870
|
+
}
|
|
2871
|
+
}
|