@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yinghai Zhao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/bin/operad.ts ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env bun
2
+ import { EXIT_CLOSED_PIPE, main, outputWasClosed } from "../src/main.ts";
3
+
4
+ const code = await main(process.argv.slice(2));
5
+ process.exitCode = code;
6
+ // A write to a closed pipe can fail after main returned; look again as the
7
+ // process ends. A status other than 0 (a failure, a reload) is kept.
8
+ process.on("exit", () => {
9
+ if (code === 0 && outputWasClosed()) process.exitCode = EXIT_CLOSED_PIPE;
10
+ });
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@operad-io/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "operad: an open orchestration layer for coding agents (in development)",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/operad-io/operad.git",
9
+ "directory": "packages/cli"
10
+ },
11
+ "bin": {
12
+ "operad": "bin/operad.ts"
13
+ },
14
+ "dependencies": {
15
+ "@operad-io/engine": "0.0.1",
16
+ "@operad-io/mcp": "0.0.1",
17
+ "@operad-io/shell": "0.0.1",
18
+ "@operad-io/chat": "0.0.1",
19
+ "@operad-io/dev": "0.0.1",
20
+ "@operad-io/harness-codex": "0.0.1",
21
+ "@operad-io/harness-pi": "0.0.1",
22
+ "@operad-io/harness-radian": "0.0.1",
23
+ "@operad-io/pool": "0.0.1",
24
+ "@operad-io/bot": "0.0.1"
25
+ },
26
+ "license": "MIT",
27
+ "files": [
28
+ "bin",
29
+ "src",
30
+ "LICENSE"
31
+ ]
32
+ }
@@ -0,0 +1,355 @@
1
+ /**
2
+ * Keeping `serve` and each run's process on the code that is on disk.
3
+ *
4
+ * A process records a fingerprint of the code it loaded. When the files change,
5
+ * a fresh process is started to load them (`check-load`) before anything is
6
+ * given up: code that does not load leaves the old process running and its
7
+ * problems on the error stream, and the next change tries again.
8
+ */
9
+
10
+ import {
11
+ describeChange,
12
+ diffFingerprints,
13
+ fingerprintCode,
14
+ newHashCache,
15
+ codeRoots,
16
+ pluginFile,
17
+ waitForCodeChange,
18
+ } from "@operad-io/engine";
19
+ import type { CodeFingerprint, CodeRoot } from "@operad-io/engine";
20
+ import { basename, extname, join } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+
23
+ const CLI_ENTRY = fileURLToPath(new URL("../bin/operad.ts", import.meta.url));
24
+
25
+ /** The cli package: its sources and schemas are code every process loads. */
26
+ export const CLI_CODE_ROOT: CodeRoot = {
27
+ label: "cli",
28
+ path: fileURLToPath(new URL("../", import.meta.url)),
29
+ };
30
+
31
+ /** The files of the home a process reads at each use; a failed load tries again when they change. */
32
+ export function settingsRoots(home: string): CodeRoot[] {
33
+ return ["config.json", "triggers.json", "keys.json"].map((name) => ({
34
+ label: "settings",
35
+ path: join(home, name),
36
+ }));
37
+ }
38
+
39
+ /** The code a process loaded, and where to read it again. */
40
+ export interface CodeSnapshot {
41
+ readonly roots: readonly CodeRoot[];
42
+ readonly baseline: CodeFingerprint;
43
+ readonly cache: ReturnType<typeof newHashCache>;
44
+ /**
45
+ * The entry files of the plugins given as a path: the loader imports each with
46
+ * a fresh instance, so a restored serve runs the disk's copy of these files.
47
+ * Every other plugin file comes from the module cache once it was loaded.
48
+ */
49
+ readonly entries?: ReadonlySet<string> | undefined;
50
+ /**
51
+ * The files on disk when a restart was already tried and fell back: the
52
+ * restored serve does not try that same change again.
53
+ */
54
+ readonly tried?: CodeFingerprint | undefined;
55
+ }
56
+
57
+ export function takeCodeSnapshot(
58
+ home: string,
59
+ plugins: readonly { readonly name: string | undefined; readonly module: string; readonly enabled: boolean }[],
60
+ ): CodeSnapshot {
61
+ const roots = codeRoots({
62
+ home,
63
+ extra: [CLI_CODE_ROOT],
64
+ plugins: plugins
65
+ .filter((plugin) => plugin.enabled)
66
+ .map((plugin) => ({ name: plugin.name ?? basename(plugin.module, extname(plugin.module)), module: plugin.module })),
67
+ });
68
+ // config.json holds each plugin's settings, which a plugin is given when it
69
+ // loads: a change to it (by hand or through `settings set`) is taken up the
70
+ // way changed code is.
71
+ roots.push({ label: "settings", path: join(home, "config.json") });
72
+ const cache = newHashCache();
73
+ const entries = new Set<string>();
74
+ for (const plugin of plugins) {
75
+ if (!plugin.enabled || !/^(file:|~|\.|\/)/.test(plugin.module)) continue;
76
+ const file = pluginFile(plugin.module, home);
77
+ if (file !== undefined) entries.add(file);
78
+ }
79
+ return { roots, baseline: fingerprintCode(roots, cache), cache, entries };
80
+ }
81
+
82
+ /**
83
+ * Keeps the snapshot a process took when it first served. A serve restored in
84
+ * the same process after a restart could not listen runs the engine and cli
85
+ * modules that process loaded at its first start (Bun keeps them in its
86
+ * module cache) and the plugin files that were cached; it imports again only
87
+ * what `restoredBaseline` names. The watch then sees a change to a cached
88
+ * file that caused the failed restart and the older-code item shows; the
89
+ * files on disk now count as already tried, so the same change is not tried again in a loop. The next
90
+ * different change goes through the normal load check.
91
+ */
92
+ export function serveSnapshots(): (fresh: CodeSnapshot, restored: boolean) => CodeSnapshot {
93
+ let first: CodeSnapshot | undefined;
94
+ return (fresh, restored) => {
95
+ first ??= fresh;
96
+ return restored
97
+ ? { ...fresh, baseline: restoredBaseline(first, fresh), tried: fresh.baseline }
98
+ : fresh;
99
+ };
100
+ }
101
+
102
+ /**
103
+ * What a restored serve runs: the modules of the first start (the module cache
104
+ * keeps them) except what is loaded again: the settings, the entry file of a
105
+ * plugin given as a path, and every file of a plugin that was not loaded at
106
+ * the first start. A plugin given by package name, and the other files of a
107
+ * path plugin, stay as the first start had them.
108
+ */
109
+ function restoredBaseline(first: CodeSnapshot, fresh: CodeSnapshot): CodeFingerprint {
110
+ const firstLabels = new Set(first.baseline.labels.values());
111
+ const freshLabels = new Set(fresh.baseline.labels.values());
112
+ const again = (file: string, label: string | undefined, fromFirst: boolean): boolean =>
113
+ label === "settings" ||
114
+ (first.entries?.has(file) ?? false) ||
115
+ (fresh.entries?.has(file) ?? false) ||
116
+ (!fromFirst && label !== undefined && !firstLabels.has(label));
117
+ const hashes = new Map<string, string>();
118
+ const labels = new Map<string, string>();
119
+ for (const [source, fromFirst] of [
120
+ [first.baseline, true],
121
+ [fresh.baseline, false],
122
+ ] as const) {
123
+ for (const [file, hash] of source.hashes) {
124
+ const label = source.labels.get(file);
125
+ // A plugin the restored serve no longer loads has no files in its baseline.
126
+ if (fromFirst && label !== undefined && !freshLabels.has(label)) continue;
127
+ if (again(file, label, fromFirst) === fromFirst) continue;
128
+ hashes.set(file, hash);
129
+ if (label !== undefined) labels.set(file, label);
130
+ }
131
+ }
132
+ return {
133
+ hashes,
134
+ labels,
135
+ directories: new Set([...first.baseline.directories, ...fresh.baseline.directories]),
136
+ };
137
+ }
138
+
139
+ /**
140
+ * A problem line, without the counter the loader adds to every import. Two
141
+ * lines are the same problem only when they say the same thing: a plugin that
142
+ * fails in another way (an import that no longer works, after its tick failed)
143
+ * is a new problem.
144
+ */
145
+ export function problemKey(line: string): string {
146
+ return line
147
+ .replace(/[?&]operad-plugin-load=\d+/g, "")
148
+ .replace(/\s*\n\s*/g, " ")
149
+ .trim();
150
+ }
151
+
152
+ /**
153
+ * New code may be taken up when it loads, or when its only problems are ones
154
+ * the process already had.
155
+ */
156
+ export function loadsAsWellAs(
157
+ problems: readonly string[],
158
+ known: readonly string[],
159
+ ): boolean {
160
+ const keys = new Set(known.map(problemKey));
161
+ return problems.every((line) => keys.has(problemKey(line)));
162
+ }
163
+
164
+ /**
165
+ * Starts a fresh process that loads the code on disk and reports what did not
166
+ * load, one line each. A process that cannot start reports that as the problem.
167
+ */
168
+ export async function probeLoad(home: string): Promise<string[]> {
169
+ const child = Bun.spawn({
170
+ cmd: [process.execPath, CLI_ENTRY, "check-load"],
171
+ cwd: home,
172
+ env: { ...process.env, OPERAD_HOME: home },
173
+ stdin: "ignore",
174
+ stdout: "pipe",
175
+ stderr: "pipe",
176
+ });
177
+ const [code, out, err] = await Promise.all([
178
+ child.exited,
179
+ new Response(child.stdout).text(),
180
+ new Response(child.stderr).text(),
181
+ ]);
182
+ if (code !== 0) {
183
+ const last = err
184
+ .split("\n")
185
+ .map((line) => line.trim())
186
+ .filter((line) => line.length > 0)
187
+ .slice(-3)
188
+ .join(" ");
189
+ return [`operad does not start: ${last.length > 0 ? last : `exit ${code}`}`];
190
+ }
191
+ return out.split("\n").filter((line) => line.length > 0);
192
+ }
193
+
194
+ export interface CodeCheckOptions {
195
+ readonly home: string;
196
+ readonly snapshot: CodeSnapshot;
197
+ /** The problems this process had when it loaded. */
198
+ readonly known: readonly string[];
199
+ readonly onProblem: (message: string) => void;
200
+ /**
201
+ * When set, a change that does not load is waited out instead of skipped:
202
+ * the check does not return until the files load or match what the process
203
+ * loaded again. A run's process needs this, because the next step's code is
204
+ * read from disk.
205
+ */
206
+ readonly waitPollMs?: number | undefined;
207
+ }
208
+
209
+ /**
210
+ * Compares the code on disk with what the process loaded. Returns what changed
211
+ * when the new code loads, and undefined when nothing changed or the change
212
+ * does not load. With `waitPollMs` a change that does not load is waited out.
213
+ */
214
+ export function codeChecker(
215
+ options: CodeCheckOptions,
216
+ ): () => Promise<string | undefined> {
217
+ return async () => {
218
+ let current = fingerprintCode(options.snapshot.roots, options.snapshot.cache);
219
+ for (;;) {
220
+ // What the wait compares with is read before the load is tried, so a fix
221
+ // that lands during the try is not missed.
222
+ const watched = [...options.snapshot.roots, ...settingsRoots(options.home)];
223
+ const seen = fingerprintCode(watched, options.snapshot.cache);
224
+ const change = diffFingerprints(options.snapshot.baseline, current);
225
+ if (change === undefined) return undefined;
226
+ const problems = await probeLoad(options.home);
227
+ if (loadsAsWellAs(problems, options.known)) return describeChange(change);
228
+ options.onProblem(
229
+ `code changed (${describeChange(change)}) but does not load; the old code keeps running: ${problems.join("; ")}`,
230
+ );
231
+ if (options.waitPollMs === undefined) return undefined;
232
+ // A settings file that did not read may be fixed, so it wakes the wait
233
+ // too; the code is judged again either way.
234
+ await waitForCodeChange({
235
+ roots: watched,
236
+ since: seen,
237
+ cache: options.snapshot.cache,
238
+ pollMs: options.waitPollMs,
239
+ });
240
+ current = fingerprintCode(options.snapshot.roots, options.snapshot.cache);
241
+ }
242
+ };
243
+ }
244
+
245
+ /** Set in the environment of a serve that a supervisor started. */
246
+ export const SUPERVISED_ENV = "OPERAD_SERVE_SUPERVISED";
247
+
248
+ /**
249
+ * True when a supervisor started this serve. Removes the flag from `env`, so
250
+ * no process the serve starts (run processes, steps, their commands) sees it.
251
+ */
252
+ export function takeSupervisedFlag(env: NodeJS.ProcessEnv = process.env): boolean {
253
+ const supervised = env[SUPERVISED_ENV] === "1";
254
+ delete env[SUPERVISED_ENV];
255
+ return supervised;
256
+ }
257
+
258
+ /** The exit code of a serve that stopped only to load new code. */
259
+ export const RELOAD_EXIT = 75;
260
+
261
+ /**
262
+ * The exit code of a supervised serve that could not listen on every address
263
+ * in time: the supervisor then serves with the code it already has.
264
+ */
265
+ export const BIND_FAILED_EXIT = 76;
266
+
267
+ /**
268
+ * Starts the same command line again, in place: the process the user (or a
269
+ * supervisor) started stays, with its terminal and its process group, and runs
270
+ * the serve as a child with the same arguments and environment. It starts the
271
+ * child again each time the child stops for new code, passes a stop signal on,
272
+ * and ends with the child's exit code.
273
+ */
274
+ export async function superviseServe(
275
+ restore?: () => Promise<"stopped" | "reload">,
276
+ log: (message: string) => void = () => undefined,
277
+ ): Promise<number> {
278
+ let stopping: NodeJS.Signals | undefined;
279
+ let child: Bun.Subprocess | undefined;
280
+ const pass = (signal: NodeJS.Signals) => (): void => {
281
+ stopping = signal;
282
+ child?.kill(signal);
283
+ };
284
+ const interrupt = pass("SIGINT");
285
+ const terminate = pass("SIGTERM");
286
+ const attach = (): void => {
287
+ process.on("SIGINT", interrupt);
288
+ process.on("SIGTERM", terminate);
289
+ };
290
+ const detach = (): void => {
291
+ process.removeListener("SIGINT", interrupt);
292
+ process.removeListener("SIGTERM", terminate);
293
+ };
294
+ attach();
295
+ try {
296
+ for (;;) {
297
+ child = Bun.spawn({
298
+ cmd: [process.execPath, ...process.argv.slice(1)],
299
+ cwd: process.cwd(),
300
+ env: { ...process.env, [SUPERVISED_ENV]: "1" },
301
+ stdin: "inherit",
302
+ stdout: "inherit",
303
+ stderr: "inherit",
304
+ });
305
+ if (stopping !== undefined) child.kill(stopping);
306
+ const code = await child.exited;
307
+ // A stop that reached the supervisor while the child left for new code is still a stop.
308
+ if (stopping !== undefined) return code === RELOAD_EXIT ? 0 : code;
309
+ if (code === BIND_FAILED_EXIT && restore !== undefined) {
310
+ // The new code could not take the addresses. The code this process
311
+ // runs served them before: it serves again, and takes its own signals.
312
+ child = undefined;
313
+ detach();
314
+ let outcome: "stopped" | "reload";
315
+ try {
316
+ outcome = await restore();
317
+ } catch (error) {
318
+ // The old code is gone too: say so rather than leave the one line
319
+ // that promised its addresses standing as the last word.
320
+ log(
321
+ `reload: the old code could not listen either (${error instanceof Error ? error.message : String(error)}); this serve ends\n`,
322
+ );
323
+ throw error;
324
+ } finally {
325
+ attach();
326
+ }
327
+ if (outcome === "stopped") return 0;
328
+ continue;
329
+ }
330
+ if (code !== RELOAD_EXIT) return code;
331
+ }
332
+ } finally {
333
+ detach();
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Calls `stop` on SIGINT and SIGTERM and returns what to call when the serve's
339
+ * stop is done. Under a supervisor a stop signal can arrive twice (the
340
+ * terminal sends it to the whole group and the supervisor passes it on,
341
+ * asynchronously), so the handlers stay for good: one arriving after the stop
342
+ * is done and before the process ends must not reach the default action, which
343
+ * would end it with 130. Without a supervisor the first signal is the only
344
+ * one, and the handlers are removed.
345
+ */
346
+ export function listenForStop(supervised: boolean, stop: () => void): () => void {
347
+ const listen = supervised ? process.on.bind(process) : process.once.bind(process);
348
+ listen("SIGINT", stop);
349
+ listen("SIGTERM", stop);
350
+ return () => {
351
+ if (supervised) return;
352
+ process.removeListener("SIGINT", stop);
353
+ process.removeListener("SIGTERM", stop);
354
+ };
355
+ }
@@ -0,0 +1,67 @@
1
+ /** The distribution's defaults: what `operad init` writes into a new home. */
2
+
3
+ import {
4
+ DEFAULT_MCP_CHANNEL,
5
+ defaultConfig,
6
+ type OperadConfig,
7
+ type PluginOffer,
8
+ } from "@operad-io/engine";
9
+
10
+ /** The plugins `operad init` installs, in load order. */
11
+ export const DEFAULT_PLUGINS: readonly string[] = ["shell", "radian", "chat", "dev"];
12
+
13
+ /**
14
+ * Plugins shipped with operad that `operad init` does not install. They are
15
+ * not in the default config; `plugin enable <name>` adds them.
16
+ */
17
+ export const OPTIONAL_PLUGINS: readonly string[] = ["pi", "claude", "codex", "pool", "bot"];
18
+
19
+ /** The plugins whose package is installed into the home rather than shipped with the CLI. */
20
+ export const INSTALL_ON_ENABLE: readonly string[] = ["claude"];
21
+
22
+ /** Harness plugins are named after their agent; their npm packages are `harness-<agent>`. */
23
+ const HARNESS_PLUGINS: readonly string[] = ["claude", "codex", "pi", "radian"];
24
+
25
+ /** The package name of a plugin shipped with operad. */
26
+ export function defaultPluginModule(name: string): string {
27
+ return HARNESS_PLUGINS.includes(name) ? `@operad-io/harness-${name}` : `@operad-io/${name}`;
28
+ }
29
+
30
+ /** The actions `operad init` lets a lead run: the dev plugin's rework family and the chat plugin's close. */
31
+ export const DEFAULT_LEAD_ACTIONS: readonly string[] = [
32
+ "dev:rework",
33
+ "dev:reverify",
34
+ "dev:reject",
35
+ "dev:priority",
36
+ "dev:concurrency",
37
+ "chat:close",
38
+ ];
39
+
40
+ /** The allowed actions that also need the confirmation. */
41
+ export const DEFAULT_CONFIRM_ACTIONS: readonly string[] = ["chat:close"];
42
+
43
+ /** The config a new home starts with. */
44
+ export function distributionConfig(home: string): OperadConfig {
45
+ return {
46
+ ...defaultConfig(home),
47
+ plugins: DEFAULT_PLUGINS.map((name) => ({
48
+ name,
49
+ module: defaultPluginModule(name),
50
+ enabled: true,
51
+ settings: {},
52
+ })),
53
+ mcp: {
54
+ channel: DEFAULT_MCP_CHANNEL,
55
+ actions: DEFAULT_LEAD_ACTIONS,
56
+ confirmActions: DEFAULT_CONFIRM_ACTIONS,
57
+ },
58
+ };
59
+ }
60
+
61
+ /** What `plugin enable` may add to a home: the optional shipped plugins. */
62
+ export function pluginOffer(home: string): PluginOffer {
63
+ return {
64
+ optional: Object.fromEntries(OPTIONAL_PLUGINS.map((name) => [name, defaultPluginModule(name)])),
65
+ defaults: distributionConfig(home),
66
+ };
67
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Starting the listeners of a serve that took over from another one. The old
3
+ * serve has released its addresses before the new one starts, but the system
4
+ * may need a moment to hand them back, so a failed bind is tried again for a
5
+ * bounded time before the new code gives up.
6
+ */
7
+
8
+ import { ConfigError, HttpStopError } from "@operad-io/engine";
9
+ import { RELOAD_EXIT, takeSupervisedFlag } from "./code-reload.ts";
10
+
11
+ export interface BindRetryOptions {
12
+ /** How long to keep trying, in milliseconds. */
13
+ readonly retryMs: number;
14
+ /** The wait between two tries. */
15
+ readonly stepMs: number;
16
+ readonly now: () => number;
17
+ readonly wait: (ms: number) => Promise<void>;
18
+ /** Called with each failure that will be tried again. */
19
+ readonly onRetry?: ((error: unknown) => void) | undefined;
20
+ }
21
+
22
+ /** The new code could not listen in time; the old code has to serve. */
23
+ export class BindFailed extends Error {
24
+ constructor(cause: unknown) {
25
+ super(cause instanceof Error ? cause.message : String(cause));
26
+ this.name = "BindFailed";
27
+ }
28
+ }
29
+
30
+ /** Runs `start` until it succeeds or `retryMs` has passed; a bad configuration is not retried. */
31
+ export async function startWithRetry<T>(
32
+ start: () => Promise<T>,
33
+ options: BindRetryOptions,
34
+ ): Promise<T> {
35
+ const deadline = options.now() + options.retryMs;
36
+ for (;;) {
37
+ try {
38
+ return await start();
39
+ } catch (error) {
40
+ if (error instanceof ConfigError || error instanceof HttpStopError) throw error;
41
+ if (options.now() >= deadline) throw new BindFailed(error);
42
+ options.onRetry?.(error);
43
+ }
44
+ await options.wait(options.stepMs);
45
+ }
46
+ }
47
+
48
+ /** A serve whose listener would not release its address: this process cannot go on. */
49
+ export class HandOverStuck extends Error {
50
+ readonly reload: boolean;
51
+ constructor(cause: Error, reload: boolean) {
52
+ super(cause.message);
53
+ this.name = "HandOverStuck";
54
+ this.reload = reload;
55
+ }
56
+ }
57
+
58
+ /** Set in the environment of a serve that a stuck serve started in its place. */
59
+ export const REPLACES_ENV = "OPERAD_SERVE_REPLACES";
60
+
61
+ /** True when a stuck serve started this one; removes the flag from `env`. */
62
+ export function takeReplacesFlag(env: NodeJS.ProcessEnv = process.env): boolean {
63
+ const replaces = env[REPLACES_ENV] === "1";
64
+ delete env[REPLACES_ENV];
65
+ return replaces;
66
+ }
67
+
68
+ export interface ServeStartFlags {
69
+ readonly supervised: boolean;
70
+ readonly replaces: boolean;
71
+ /** A serve that is supervised or takes over from one asks again for its port. */
72
+ readonly retryBind: boolean;
73
+ }
74
+
75
+ /** Takes the start flags from the environment, so no child sees them. */
76
+ export function serveStartFlags(env: NodeJS.ProcessEnv = process.env): ServeStartFlags {
77
+ const supervised = takeSupervisedFlag(env);
78
+ const replaces = takeReplacesFlag(env);
79
+ return { supervised, replaces, retryBind: supervised || replaces };
80
+ }
81
+
82
+ /** The environment of a replacement a stuck serve starts in its place. */
83
+ export function replacementEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
84
+ return { ...env, [REPLACES_ENV]: "1" };
85
+ }
86
+
87
+ export interface StuckActions {
88
+ readonly supervised: boolean;
89
+ /** Starts the same command line as a new process that retries its bind. */
90
+ readonly startReplacement: () => void;
91
+ /** Ends this process now, whatever handles it still holds. */
92
+ readonly exit: (code: number) => never;
93
+ readonly log: (message: string) => void;
94
+ }
95
+
96
+ /**
97
+ * A listener that will not release its address is still a live handle, so the
98
+ * process must end rather than return: it would go on serving only that
99
+ * address. A reload still needs a serve afterwards: under a supervisor the
100
+ * supervisor starts the next one; otherwise a replacement starts here, after
101
+ * the home lock was released and before this process ends.
102
+ */
103
+ export function leaveStuck(error: HandOverStuck, actions: StuckActions): never {
104
+ actions.log(`${error.message}; this serve ends${error.reload ? " and a new one starts" : ""}\n`);
105
+ if (error.reload && actions.supervised) return actions.exit(RELOAD_EXIT);
106
+ if (error.reload) actions.startReplacement();
107
+ return actions.exit(1);
108
+ }