@powerhousedao/ph-run 0.0.0-stage → 6.2.3-dev.88
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 +661 -0
- package/dist/classic-args-BYccyIIC.mjs +33 -0
- package/dist/classic-args-BYccyIIC.mjs.map +1 -0
- package/dist/classic-args-Dm0_3O5p.d.mts +194 -0
- package/dist/classic-args-Dm0_3O5p.d.mts.map +1 -0
- package/dist/cli.d.mts +2 -0
- package/dist/cli.mjs +29 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/connect-plugin-configs-CPRA8hQJ.mjs +47 -0
- package/dist/connect-plugin-configs-CPRA8hQJ.mjs.map +1 -0
- package/dist/connect-serve-0fIQ7xCs.mjs +187 -0
- package/dist/connect-serve-0fIQ7xCs.mjs.map +1 -0
- package/dist/connect-serve-B2u6WAdw.d.mts +62 -0
- package/dist/connect-serve-B2u6WAdw.d.mts.map +1 -0
- package/dist/member-config-BcEWRVq4.mjs +152 -0
- package/dist/member-config-BcEWRVq4.mjs.map +1 -0
- package/dist/runners/connect.d.mts +1263 -0
- package/dist/runners/connect.d.mts.map +1 -0
- package/dist/runners/connect.mjs +268 -0
- package/dist/runners/connect.mjs.map +1 -0
- package/dist/runners/member-config.d.mts +786 -0
- package/dist/runners/member-config.d.mts.map +1 -0
- package/dist/runners/member-config.mjs +2 -0
- package/dist/runners/switchboard.d.mts +1736 -0
- package/dist/runners/switchboard.d.mts.map +1 -0
- package/dist/runners/switchboard.mjs +704 -0
- package/dist/runners/switchboard.mjs.map +1 -0
- package/dist/services/classic-args.d.mts +3 -0
- package/dist/services/classic-args.mjs +2 -0
- package/dist/services/connect-serve.d.mts +3 -0
- package/dist/services/connect-serve.mjs +2 -0
- package/dist/services/connect-server.d.mts +26 -0
- package/dist/services/connect-server.d.mts.map +1 -0
- package/dist/services/connect-server.mjs +215 -0
- package/dist/services/connect-server.mjs.map +1 -0
- package/dist/services/run/start-run.d.mts +29 -0
- package/dist/services/run/start-run.d.mts.map +1 -0
- package/dist/services/run/start-run.mjs +2 -0
- package/dist/services/switchboard.d.mts +79 -0
- package/dist/services/switchboard.d.mts.map +1 -0
- package/dist/services/switchboard.mjs +188 -0
- package/dist/services/switchboard.mjs.map +1 -0
- package/dist/start-run-DWn2cVyi.mjs +122 -0
- package/dist/start-run-DWn2cVyi.mjs.map +1 -0
- package/dist/superseded-config-CpHrCuNq.mjs +50 -0
- package/dist/superseded-config-CpHrCuNq.mjs.map +1 -0
- package/package.json +93 -3
- package/README.md +0 -3
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
import { a as prepareMemberStorage, l as switchboardDevMode, n as memberSwitchboardConfig, o as reactorBlockConflicts, r as memberSwitchboardConfigSchema, s as readModelAsReactorStore, t as memberEnvOf } from "../member-config-BcEWRVq4.mjs";
|
|
2
|
+
import { t as classicSwitchboardArgs } from "../classic-args-BYccyIIC.mjs";
|
|
3
|
+
import { defineHostSchemas, drivesSchema, mergeDrivePlan, protocolConflicts, resolveDriveDeclaration, resolveHostPlugins, seedDrives } from "@powerhousedao/host-core";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { computeProgress, formatCount, formatDuration, rankSlowest, renderDoneSummary, renderSlowLine } from "@powerhousedao/reactor";
|
|
7
|
+
//#region src/services/run/memory-line.ts
|
|
8
|
+
const MB = 1048576;
|
|
9
|
+
function size(bytes) {
|
|
10
|
+
return bytes >= 1024 * MB ? `${(bytes / (1024 * MB)).toFixed(2)} GB` : `${Math.round(bytes / MB)} MB`;
|
|
11
|
+
}
|
|
12
|
+
function rate(mbPerMin) {
|
|
13
|
+
if (mbPerMin === null) return "";
|
|
14
|
+
const rounded = Math.round(mbPerMin);
|
|
15
|
+
return ` (${rounded >= 0 ? "+" : ""}${rounded} MB/min)`;
|
|
16
|
+
}
|
|
17
|
+
function growth(gauge) {
|
|
18
|
+
const perMin = Math.round(gauge.perMin);
|
|
19
|
+
const text = Math.abs(perMin) >= 1e3 ? `${(perMin / 1e3).toFixed(1)}k` : `${perMin}`;
|
|
20
|
+
return `${gauge.gauge} ${perMin >= 0 ? "+" : ""}${text}/min`;
|
|
21
|
+
}
|
|
22
|
+
function pglite(sample) {
|
|
23
|
+
let total = 0;
|
|
24
|
+
for (const worker of Object.values(sample.workers)) total += worker.wasm ?? 0;
|
|
25
|
+
return total;
|
|
26
|
+
}
|
|
27
|
+
/** The newest sample on one line; undefined before there is one. */
|
|
28
|
+
function renderMemoryLine(report) {
|
|
29
|
+
const sample = report.samples.at(-1);
|
|
30
|
+
if (!sample) return void 0;
|
|
31
|
+
const { summary } = report;
|
|
32
|
+
const heap = sample.postGcHeap === null ? `heap ${size(sample.heapUsed)}` : `heap ${size(sample.heapUsed)}, post-GC ${size(sample.postGcHeap)}${rate(summary?.postGcMbPerMin ?? null)}`;
|
|
33
|
+
const seconds = Math.round(sample.delta.s);
|
|
34
|
+
const perOps = summary?.mbPer1kOps === null || summary?.mbPer1kOps === void 0 ? "" : `, ${Math.round(summary.mbPer1kOps)} MB/1k ops`;
|
|
35
|
+
const parts = [`memory: rss ${size(sample.rss)}${rate(summary?.rssMbPerMin ?? null)}`, heap];
|
|
36
|
+
const wasm = pglite(sample);
|
|
37
|
+
if (wasm > 0) parts.push(`pglite ${size(wasm)}`);
|
|
38
|
+
parts.push(`${sample.delta.opsWritten} ops/${seconds}s${perOps}`);
|
|
39
|
+
const top = summary?.topGauges[0];
|
|
40
|
+
if (top) parts.push(`top: ${growth(top)}`);
|
|
41
|
+
return parts.join(" · ");
|
|
42
|
+
}
|
|
43
|
+
/** True when the reactor is running telemetry with the console output on. */
|
|
44
|
+
function wantsMemoryLine(report) {
|
|
45
|
+
return report.enabled && report.outputs.includes("console");
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/services/run/catch-up-progress.ts
|
|
49
|
+
function withDrives(label, driveCount) {
|
|
50
|
+
return `${label} (${driveCount} ${driveCount === 1 ? "drive" : "drives"})`;
|
|
51
|
+
}
|
|
52
|
+
/** One row per processor factory, then one per reactor read model. */
|
|
53
|
+
function progressRows(progress) {
|
|
54
|
+
const factories = progress.factories.map((factory) => ({
|
|
55
|
+
label: withDrives(factory.label, factory.driveCount),
|
|
56
|
+
fraction: factory.fraction,
|
|
57
|
+
state: factory.phase === "errored" ? "errored" : factory.phase === "catching-up" ? "catching-up" : "done"
|
|
58
|
+
}));
|
|
59
|
+
const readModels = progress.readModels.map((model) => ({
|
|
60
|
+
label: model.consumerId,
|
|
61
|
+
fraction: model.fraction,
|
|
62
|
+
state: model.blocked ? "errored" : model.complete ? "done" : "catching-up"
|
|
63
|
+
}));
|
|
64
|
+
return [...factories, ...readModels];
|
|
65
|
+
}
|
|
66
|
+
/** Rows from a reactor's inspector: its processors, catch-up status and priority. */
|
|
67
|
+
function inspectorProgressSource(inspector) {
|
|
68
|
+
let memoryReadAt = 0;
|
|
69
|
+
return async () => {
|
|
70
|
+
const processors = await inspector.getProcessors();
|
|
71
|
+
let catchUp;
|
|
72
|
+
try {
|
|
73
|
+
catchUp = await inspector.getCatchUpStatus();
|
|
74
|
+
} catch {
|
|
75
|
+
catchUp = void 0;
|
|
76
|
+
}
|
|
77
|
+
let priority;
|
|
78
|
+
try {
|
|
79
|
+
const state = await inspector.getCatchUpPriority();
|
|
80
|
+
priority = {
|
|
81
|
+
mode: state.mode,
|
|
82
|
+
level: state.level,
|
|
83
|
+
reason: state.reason
|
|
84
|
+
};
|
|
85
|
+
} catch {
|
|
86
|
+
priority = void 0;
|
|
87
|
+
}
|
|
88
|
+
let timing;
|
|
89
|
+
try {
|
|
90
|
+
timing = await inspector.getProcessorTiming();
|
|
91
|
+
} catch {
|
|
92
|
+
timing = void 0;
|
|
93
|
+
}
|
|
94
|
+
let memory;
|
|
95
|
+
if (Date.now() - memoryReadAt >= MEMORY_READ_MS) {
|
|
96
|
+
memoryReadAt = Date.now();
|
|
97
|
+
try {
|
|
98
|
+
memory = await inspector.getMemoryTelemetry(1);
|
|
99
|
+
} catch {
|
|
100
|
+
memory = void 0;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
rows: progressRows(computeProgress(processors, catchUp)),
|
|
105
|
+
priority,
|
|
106
|
+
timing,
|
|
107
|
+
memory
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** `catch-up priority 6 (dynamic, idle 14 s)`, or `catch-up priority 3 (fixed)`. */
|
|
112
|
+
function renderPriority(priority) {
|
|
113
|
+
const why = priority.mode === "dynamic" ? `dynamic, ${priority.reason}` : "fixed";
|
|
114
|
+
return `catch-up priority ${priority.level} (${why})`;
|
|
115
|
+
}
|
|
116
|
+
/** The console width the bars are sized for: a reported width, else 80. */
|
|
117
|
+
function widthOf(stream) {
|
|
118
|
+
const columns = stream.columns;
|
|
119
|
+
return typeof columns === "number" && columns > 0 ? columns : 80;
|
|
120
|
+
}
|
|
121
|
+
const DEFAULT_POLL_MS = 1e3;
|
|
122
|
+
const DEFAULT_LINE_MS = 1e4;
|
|
123
|
+
const DEFAULT_TOP = 5;
|
|
124
|
+
const MEMORY_READ_MS = 5e3;
|
|
125
|
+
const MIN_BAR = 10;
|
|
126
|
+
const MAX_LABEL = 32;
|
|
127
|
+
function percent(row) {
|
|
128
|
+
if (row.state === "errored") return "errored";
|
|
129
|
+
if (row.state === "done") return "done";
|
|
130
|
+
return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;
|
|
131
|
+
}
|
|
132
|
+
const BAR_FIXED = 9;
|
|
133
|
+
function barLabelWidth(rows, columns) {
|
|
134
|
+
const width = Math.max(columns - 1, 1);
|
|
135
|
+
const longest = Math.max(...rows.map((row) => row.label.length), 0);
|
|
136
|
+
return Math.max(1, Math.min(MAX_LABEL, longest, width - BAR_FIXED - MIN_BAR));
|
|
137
|
+
}
|
|
138
|
+
function fit(label, width) {
|
|
139
|
+
return label.length <= width ? label.padEnd(width) : `…${label.slice(label.length - width + 1)}`;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* The bar block, one line per row, under the priority when known. Every line
|
|
143
|
+
* stays short of the terminal's last column: a line that fills it wraps on
|
|
144
|
+
* xterm-based terminals (VS Code, Windows Terminal), and the erase would then
|
|
145
|
+
* lift fewer lines than are on screen, leaving old bars behind. On a narrow
|
|
146
|
+
* terminal the label gives way before the bar.
|
|
147
|
+
*/
|
|
148
|
+
function renderBars(rows, columns, priority) {
|
|
149
|
+
const width = Math.max(columns - 1, 1);
|
|
150
|
+
const labelWidth = barLabelWidth(rows, columns);
|
|
151
|
+
const barWidth = Math.max(MIN_BAR, width - labelWidth - BAR_FIXED);
|
|
152
|
+
const bars = rows.map((row) => {
|
|
153
|
+
const fraction = row.state === "done" ? 1 : row.fraction;
|
|
154
|
+
const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);
|
|
155
|
+
const bar = "█".repeat(filled) + "░".repeat(barWidth - filled);
|
|
156
|
+
return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`.slice(0, width);
|
|
157
|
+
});
|
|
158
|
+
if (!priority) return bars;
|
|
159
|
+
return [renderPriority(priority).slice(0, width), ...bars];
|
|
160
|
+
}
|
|
161
|
+
/** The columns of the slowest block, dropped from the first on a narrow console. */
|
|
162
|
+
const SLOW_COLUMNS = [
|
|
163
|
+
{
|
|
164
|
+
title: "eta",
|
|
165
|
+
width: 7,
|
|
166
|
+
cell: (row) => row.etaMs === null ? "" : formatDuration(row.etaMs)
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
title: "behind",
|
|
170
|
+
width: 8,
|
|
171
|
+
cell: (row) => formatCount(row.ordinalsBehind)
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
title: "fill",
|
|
175
|
+
width: 7,
|
|
176
|
+
cell: (row) => formatDuration(row.fillMs)
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
title: "read",
|
|
180
|
+
width: 7,
|
|
181
|
+
cell: (row) => formatDuration(row.readMs)
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
title: "op/s",
|
|
185
|
+
width: 6,
|
|
186
|
+
cell: (row) => formatCount(row.opsPerSecond)
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
title: "handler",
|
|
190
|
+
width: 8,
|
|
191
|
+
cell: (row) => formatDuration(row.handlerMs)
|
|
192
|
+
}
|
|
193
|
+
];
|
|
194
|
+
const BUSY_WIDTH = 7;
|
|
195
|
+
const SLOW_ORDER = [
|
|
196
|
+
"handler",
|
|
197
|
+
"read",
|
|
198
|
+
"fill",
|
|
199
|
+
"op/s",
|
|
200
|
+
"behind",
|
|
201
|
+
"eta"
|
|
202
|
+
];
|
|
203
|
+
/**
|
|
204
|
+
* The slowest processors as a table, for under the bars. The label column
|
|
205
|
+
* is at least as wide as the bars' and every line stays short of the last
|
|
206
|
+
* column; a narrow console loses `eta`, `behind`, `fill`, `read`, `op/s`,
|
|
207
|
+
* `handler`, in that order, and `busy` always stays.
|
|
208
|
+
*/
|
|
209
|
+
function renderSlowest(rows, columns, labelWidth, windowMs) {
|
|
210
|
+
if (rows.length === 0) return [];
|
|
211
|
+
const width = Math.max(columns - 1, 1);
|
|
212
|
+
const title = `slowest, last ${Math.round(windowMs / 1e3)} s`;
|
|
213
|
+
const longest = Math.max(title.length, ...rows.map((row) => row.label.length));
|
|
214
|
+
const label = Math.max(1, Math.min(Math.max(labelWidth, Math.min(longest, MAX_LABEL)), width - BUSY_WIDTH - 1));
|
|
215
|
+
let room = width - label - BUSY_WIDTH;
|
|
216
|
+
const kept = /* @__PURE__ */ new Set();
|
|
217
|
+
for (const column of [...SLOW_COLUMNS].reverse()) {
|
|
218
|
+
if (room < column.width) break;
|
|
219
|
+
room -= column.width;
|
|
220
|
+
kept.add(column.title);
|
|
221
|
+
}
|
|
222
|
+
const shown = SLOW_ORDER.flatMap((name) => {
|
|
223
|
+
const column = SLOW_COLUMNS.find((c) => c.title === name);
|
|
224
|
+
return column && kept.has(name) ? [column] : [];
|
|
225
|
+
});
|
|
226
|
+
const line = (first, busy, cells) => `${fit(first, label)}${busy.padStart(BUSY_WIDTH)}${cells.join("")}`.slice(0, width);
|
|
227
|
+
return [line(title, "busy", shown.map((column) => column.title.padStart(column.width))), ...rows.map((row) => line(row.label, formatDuration(row.busyMs), shown.map((column) => column.cell(row).padStart(column.width))))];
|
|
228
|
+
}
|
|
229
|
+
/** One line for a log without a TTY, listing only what is still catching up. */
|
|
230
|
+
function renderLine(rows, priority) {
|
|
231
|
+
const line = `catch-up: ${rows.filter((row) => row.state !== "done").map((row) => `${row.label} ${percent(row)}`).join(" · ")}`;
|
|
232
|
+
return priority ? `${line} · priority ${priority.level} ${priority.mode}` : line;
|
|
233
|
+
}
|
|
234
|
+
function busy(rows) {
|
|
235
|
+
return rows.some((row) => row.state !== "done");
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Shows catch-up progress while any row is not done. In a terminal the bars
|
|
239
|
+
* sit below the output and every other write is printed above them; without
|
|
240
|
+
* one, a progress line is printed every `lineMs`.
|
|
241
|
+
*/
|
|
242
|
+
function startProgressDisplay(source, options) {
|
|
243
|
+
const { stdout, stderr } = options;
|
|
244
|
+
const tty = stdout.isTTY === true;
|
|
245
|
+
const top = options.top ?? DEFAULT_TOP;
|
|
246
|
+
let rows = [];
|
|
247
|
+
let priority;
|
|
248
|
+
let timing;
|
|
249
|
+
let memory;
|
|
250
|
+
let lastMemoryLine = Date.now();
|
|
251
|
+
let busySince;
|
|
252
|
+
let drawn = 0;
|
|
253
|
+
let atLineStart = true;
|
|
254
|
+
let lastLine = 0;
|
|
255
|
+
let stopped = false;
|
|
256
|
+
let reading = false;
|
|
257
|
+
const restoreOut = stdout.write;
|
|
258
|
+
const restoreErr = stderr.write;
|
|
259
|
+
const originalOut = restoreOut.bind(stdout);
|
|
260
|
+
const originalErr = restoreErr.bind(stderr);
|
|
261
|
+
const erase = () => {
|
|
262
|
+
if (drawn > 0) originalOut(`\x1b[${drawn}A\r\x1b[0J`);
|
|
263
|
+
drawn = 0;
|
|
264
|
+
};
|
|
265
|
+
const slowest = () => timing && timing.level !== "off" && top > 0 ? rankSlowest(timing, top, "window") : [];
|
|
266
|
+
const draw = () => {
|
|
267
|
+
if (!tty || stopped || !atLineStart || !busy(rows)) return;
|
|
268
|
+
const columns = widthOf(stdout);
|
|
269
|
+
const lines = [...renderBars(rows, columns, priority), ...renderSlowest(slowest(), columns, barLabelWidth(rows, columns), timing?.windowMs ?? 0)];
|
|
270
|
+
originalOut(`${lines.join("\n")}\n`);
|
|
271
|
+
drawn = lines.length;
|
|
272
|
+
};
|
|
273
|
+
const above = (write) => (chunk, ...rest) => {
|
|
274
|
+
erase();
|
|
275
|
+
const result = write(chunk, ...rest);
|
|
276
|
+
const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString();
|
|
277
|
+
if (text.length > 0) atLineStart = text.endsWith("\n");
|
|
278
|
+
draw();
|
|
279
|
+
return result;
|
|
280
|
+
};
|
|
281
|
+
const onResize = () => {
|
|
282
|
+
if (stopped) return;
|
|
283
|
+
erase();
|
|
284
|
+
draw();
|
|
285
|
+
};
|
|
286
|
+
if (tty) {
|
|
287
|
+
stdout.write = above(originalOut);
|
|
288
|
+
stderr.write = above(originalErr);
|
|
289
|
+
stdout.on?.("resize", onResize);
|
|
290
|
+
}
|
|
291
|
+
const tick = async () => {
|
|
292
|
+
if (reading || stopped) return;
|
|
293
|
+
reading = true;
|
|
294
|
+
try {
|
|
295
|
+
({rows, priority, timing, memory} = await source());
|
|
296
|
+
} catch {} finally {
|
|
297
|
+
reading = false;
|
|
298
|
+
}
|
|
299
|
+
if (stopped) return;
|
|
300
|
+
const now = Date.now();
|
|
301
|
+
if (memory && wantsMemoryLine(memory) && now - lastMemoryLine >= memory.consoleIntervalMs) {
|
|
302
|
+
const line = renderMemoryLine(memory);
|
|
303
|
+
if (line) {
|
|
304
|
+
stderr.write(`${line}\n`);
|
|
305
|
+
lastMemoryLine = now;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (busy(rows)) busySince ??= now;
|
|
309
|
+
else if (busySince !== void 0) {
|
|
310
|
+
const wallMs = now - busySince;
|
|
311
|
+
busySince = void 0;
|
|
312
|
+
if (timing && timing.level !== "off" && top > 0) {
|
|
313
|
+
erase();
|
|
314
|
+
originalOut(`${renderDoneSummary(rankSlowest(timing, top, "total"), wallMs)}\n`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if (tty) {
|
|
318
|
+
erase();
|
|
319
|
+
draw();
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {
|
|
323
|
+
originalOut(`${renderLine(rows, priority)}\n`);
|
|
324
|
+
const slow = slowest();
|
|
325
|
+
if (slow.length > 0) originalOut(`${renderSlowLine(slow, timing?.windowMs ?? 0)}\n`);
|
|
326
|
+
lastLine = now;
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
const timer = setInterval(() => void tick(), options.pollMs ?? DEFAULT_POLL_MS);
|
|
330
|
+
timer.unref?.();
|
|
331
|
+
tick();
|
|
332
|
+
return { stop() {
|
|
333
|
+
if (stopped) return;
|
|
334
|
+
stopped = true;
|
|
335
|
+
clearInterval(timer);
|
|
336
|
+
erase();
|
|
337
|
+
if (tty) {
|
|
338
|
+
stdout.off?.("resize", onResize);
|
|
339
|
+
stdout.write = restoreOut;
|
|
340
|
+
stderr.write = restoreErr;
|
|
341
|
+
}
|
|
342
|
+
} };
|
|
343
|
+
}
|
|
344
|
+
//#endregion
|
|
345
|
+
//#region src/runners/switchboard.ts
|
|
346
|
+
/**
|
|
347
|
+
* BRIDGE runner for Switchboard hosts (uniform-runners phase 0): maps a
|
|
348
|
+
* hosts/switchboard/host.js definition onto the SAME `startSwitchboard`
|
|
349
|
+
* service the classic command calls. `run` = production loaders, `dev` =
|
|
350
|
+
* Vite package loader (worker pools refused by the server, as always).
|
|
351
|
+
*/
|
|
352
|
+
const kind = "reactor";
|
|
353
|
+
/** The switchboard host: the host-core reactor host with every runner option
|
|
354
|
+
* this module reads declared (strict: an unknown runner key fails).
|
|
355
|
+
* `config.switchboard` is this member's own switchboard config (auth,
|
|
356
|
+
* inspection, workers, ...); a key the reactor block also sets is refused.
|
|
357
|
+
* One definition, two schemas: `declaredHostSchema` (token-able fields take
|
|
358
|
+
* output tokens; types host files) and `hostSchema` (resolved; checked
|
|
359
|
+
* right before the verb). */
|
|
360
|
+
const schemas = defineHostSchemas((s) => s.reactorHostSchema.extend({
|
|
361
|
+
runner: s.runnerBaseSchema.extend({
|
|
362
|
+
/** 0 binds a port the OS picks; `origin` reports it. */
|
|
363
|
+
port: z.number().int().min(0).max(65535).optional(),
|
|
364
|
+
/** Dev mode without the `dev` verb (the Vite package loader). */
|
|
365
|
+
dev: z.boolean().optional(),
|
|
366
|
+
/** The project package output dir `build` writes (default "dist"). */
|
|
367
|
+
outDir: z.string().min(1).optional()
|
|
368
|
+
}).strict(),
|
|
369
|
+
config: z.strictObject({ switchboard: memberSwitchboardConfigSchema.optional() }).optional()
|
|
370
|
+
}).superRefine((host, ctx) => {
|
|
371
|
+
for (const message of reactorBlockConflicts(host)) ctx.addIssue({
|
|
372
|
+
code: "custom",
|
|
373
|
+
path: ["config", "switchboard"],
|
|
374
|
+
message
|
|
375
|
+
});
|
|
376
|
+
}));
|
|
377
|
+
const declaredHostSchema = schemas.declaredHostSchema;
|
|
378
|
+
const hostSchema = schemas.hostSchema;
|
|
379
|
+
/** One drive the switchboard serves: its document id and its URL. */
|
|
380
|
+
const switchboardDriveOutputSchema = z.strictObject({
|
|
381
|
+
id: z.string().min(1),
|
|
382
|
+
url: z.url()
|
|
383
|
+
});
|
|
384
|
+
/** What a started switchboard produces. `origin` carries the port the server
|
|
385
|
+
* actually bound. `drives` is keyed by the DECLARED slug (a `projectHash:
|
|
386
|
+
* true` drive is reachable as `vetra`, its URL uses the hashed slug it is
|
|
387
|
+
* served under) and includes plugin-created drives (e.g. `workflows`) and
|
|
388
|
+
* the server's implicit default drive. `endpoints.mcp` is present when MCP
|
|
389
|
+
* is mounted. */
|
|
390
|
+
const outputsSchema = z.strictObject({
|
|
391
|
+
origin: z.url(),
|
|
392
|
+
endpoints: z.strictObject({
|
|
393
|
+
graphql: z.url(),
|
|
394
|
+
mcp: z.url().optional()
|
|
395
|
+
}),
|
|
396
|
+
drives: z.record(z.string(), switchboardDriveOutputSchema)
|
|
397
|
+
});
|
|
398
|
+
/**
|
|
399
|
+
* Start from the classic `ph switchboard` args (parsed by the classic
|
|
400
|
+
* definitions, no flags) and overlay ONLY the keys the host file owns. Every
|
|
401
|
+
* other key — including the ones the classic command carries as `undefined`,
|
|
402
|
+
* such as `dbPath` — reaches the service exactly as on the classic path. No
|
|
403
|
+
* cast: a key the classic shape has and this object lacks is a type error.
|
|
404
|
+
*/
|
|
405
|
+
async function toSwitchboardArgs(host, devMode, composed) {
|
|
406
|
+
const classic = await classicSwitchboardArgs();
|
|
407
|
+
const runner = host.runner;
|
|
408
|
+
return {
|
|
409
|
+
...classic,
|
|
410
|
+
port: runner.port ?? classic.port,
|
|
411
|
+
dev: switchboardDevMode(devMode, runner) ? true : classic.dev,
|
|
412
|
+
mcp: composed ? void 0 : classic.mcp
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
/** The drive the switchboard service creates by default
|
|
416
|
+
* (services/switchboard.ts `defaultSwitchboardOptions.drive`). */
|
|
417
|
+
const DEFAULT_DRIVE_SLUG = "powerhouse";
|
|
418
|
+
/** The `<slug>` of the server-reported `…/d/<slug>` default drive URL. */
|
|
419
|
+
function defaultDriveSlug(url) {
|
|
420
|
+
const match = url ? /\/d\/([^/?#]+)\/?$/.exec(url) : null;
|
|
421
|
+
return match ? decodeURIComponent(match[1]) : DEFAULT_DRIVE_SLUG;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* The drives the composition's plugins contribute, resolved and in plan
|
|
425
|
+
* order, minus the slugs the host declares itself (mergeDrivePlan: the host
|
|
426
|
+
* file wins). A contribution that is not a valid drive declaration fails the
|
|
427
|
+
* boot naming the plugin.
|
|
428
|
+
*/
|
|
429
|
+
function pluginDrives(projectRoot, hostDrives, composition, where) {
|
|
430
|
+
if (!composition) return [];
|
|
431
|
+
const contributed = composition.flatMap((resolved) => {
|
|
432
|
+
const drives = resolved.plugin.contributions?.drives ?? [];
|
|
433
|
+
if (drives.length === 0) return [];
|
|
434
|
+
const parsed = drivesSchema.safeParse(drives);
|
|
435
|
+
if (!parsed.success) throw new Error(`${where}: plugin "${resolved.plugin.name}" contributes an invalid drive declaration:\n${z.prettifyError(parsed.error)}`);
|
|
436
|
+
return parsed.data.map((declaration) => ({
|
|
437
|
+
declaration,
|
|
438
|
+
source: resolved.plugin.name
|
|
439
|
+
}));
|
|
440
|
+
});
|
|
441
|
+
if (contributed.length === 0) return [];
|
|
442
|
+
const declaredSlugs = new Map(contributed.map(({ declaration }) => [resolveDriveDeclaration(projectRoot, declaration).slug, declaration.slug]));
|
|
443
|
+
const hostSlugs = new Set(hostDrives.map((d) => d.drive.slug));
|
|
444
|
+
return mergeDrivePlan(projectRoot, [], contributed).map((entry) => entry.drive).filter((drive) => !hostSlugs.has(drive.slug)).map((drive) => ({
|
|
445
|
+
declaredSlug: declaredSlugs.get(drive.slug) ?? drive.slug,
|
|
446
|
+
drive
|
|
447
|
+
}));
|
|
448
|
+
}
|
|
449
|
+
/** Poll the default drive endpoint until the server answers — the compound's
|
|
450
|
+
* readiness gate: Connect auto-connects the drive on first load, so the drive
|
|
451
|
+
* must answer before the connect member serves (the sidecar's
|
|
452
|
+
* waitForSwitchboard, moved behind the handle contract).
|
|
453
|
+
*
|
|
454
|
+
* The probe is anonymous, and a host with authentication on hides a drive
|
|
455
|
+
* from a caller it refuses (`/d/:drive` answers 404 to anyone who may not
|
|
456
|
+
* read it, 401 under the authenticated-caller floor). Those answers prove
|
|
457
|
+
* the server is listening but not whether the drive exists, so `served`,
|
|
458
|
+
* the reactor's own view of the drive, decides then; without it an
|
|
459
|
+
* ADMIN_ONLY host never passes this gate and the compound tears down after
|
|
460
|
+
* the timeout. */
|
|
461
|
+
async function waitForDrive(url, timeoutMs, served, fetchImpl = fetch) {
|
|
462
|
+
const deadline = Date.now() + timeoutMs;
|
|
463
|
+
const HIDDEN = /* @__PURE__ */ new Set([
|
|
464
|
+
401,
|
|
465
|
+
403,
|
|
466
|
+
404
|
|
467
|
+
]);
|
|
468
|
+
for (;;) {
|
|
469
|
+
try {
|
|
470
|
+
const res = await fetchImpl(url, { signal: AbortSignal.timeout(3e3) });
|
|
471
|
+
if (res.ok) return;
|
|
472
|
+
if (HIDDEN.has(res.status) && served && await served()) return;
|
|
473
|
+
} catch {}
|
|
474
|
+
if (Date.now() > deadline) throw new Error(`Switchboard drive ${url} did not answer within ${timeoutMs}ms.`);
|
|
475
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Adapter from the switchboard's reactor client onto the host-core seeder.
|
|
480
|
+
* Seeding is SLUG-keyed: a live drive that already serves the slug — under
|
|
481
|
+
* whatever id (a store from a run that hashed the project path differently,
|
|
482
|
+
* or a hand-made drive) — is the drive, and nothing is created. addDefaultDrive
|
|
483
|
+
* alone only knows ids: with a different id it would try to create a second
|
|
484
|
+
* drive for the slug, and against a deleted document with that id the create
|
|
485
|
+
* fails on every boot.
|
|
486
|
+
*/
|
|
487
|
+
function seederClient(reactor, port, seededIds) {
|
|
488
|
+
return {
|
|
489
|
+
findDriveBySlug: async (slug) => {
|
|
490
|
+
try {
|
|
491
|
+
const id = await reactor.resolveIdOrSlug(slug);
|
|
492
|
+
if (id) seededIds.set(slug, id);
|
|
493
|
+
return id || void 0;
|
|
494
|
+
} catch {
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
},
|
|
498
|
+
createDrive: async (drive) => {
|
|
499
|
+
const { ensureDrive } = await import("@powerhousedao/switchboard/utils");
|
|
500
|
+
try {
|
|
501
|
+
await createDeclaredDrive(ensureDrive, reactor, drive, port);
|
|
502
|
+
} catch (error) {
|
|
503
|
+
console.error(`The drive "${drive.slug}" was not created: ${error instanceof Error ? error.message : String(error)}`);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
let id;
|
|
507
|
+
try {
|
|
508
|
+
id = await reactor.resolveIdOrSlug(drive.slug);
|
|
509
|
+
} catch {
|
|
510
|
+
id = void 0;
|
|
511
|
+
}
|
|
512
|
+
seededIds.set(drive.slug, id || drive.id || drive.slug);
|
|
513
|
+
},
|
|
514
|
+
attachRemoteDrive: () => Promise.resolve()
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
/** A declared local drive, through the switchboard's own default-drive path. */
|
|
518
|
+
async function createDeclaredDrive(ensureDrive, reactor, drive, port) {
|
|
519
|
+
await ensureDrive(reactor, {
|
|
520
|
+
...drive.id ? { id: drive.id } : {},
|
|
521
|
+
...drive.documentType ? { documentType: drive.documentType } : {},
|
|
522
|
+
slug: drive.slug,
|
|
523
|
+
global: {
|
|
524
|
+
name: drive.name,
|
|
525
|
+
icon: drive.icon
|
|
526
|
+
},
|
|
527
|
+
...drive.preferredEditor ? { preferredEditor: drive.preferredEditor } : {},
|
|
528
|
+
local: {
|
|
529
|
+
availableOffline: drive.availableOffline,
|
|
530
|
+
listeners: [],
|
|
531
|
+
sharingType: drive.sharingType,
|
|
532
|
+
triggers: []
|
|
533
|
+
}
|
|
534
|
+
}, port);
|
|
535
|
+
}
|
|
536
|
+
function catchUpTopFromEnv(raw) {
|
|
537
|
+
const top = Number(raw?.trim() || NaN);
|
|
538
|
+
return Number.isInteger(top) && top >= 0 ? top : void 0;
|
|
539
|
+
}
|
|
540
|
+
async function start(host, ctx, devMode) {
|
|
541
|
+
const hostFile = `hosts/${host.name}/host.js`;
|
|
542
|
+
const env = memberEnvOf(ctx.env);
|
|
543
|
+
prepareMemberStorage(host.reactor, env.shell, hostFile);
|
|
544
|
+
const legacyStore = readModelAsReactorStore(host.reactor, env.shell, hostFile);
|
|
545
|
+
if (legacyStore) console.warn(legacyStore.warning);
|
|
546
|
+
const { startSwitchboard } = await import("../services/switchboard.mjs");
|
|
547
|
+
const entries = host.runner.plugins;
|
|
548
|
+
const entriesDeclared = entries !== void 0;
|
|
549
|
+
const classic = await toSwitchboardArgs(host, devMode, entriesDeclared);
|
|
550
|
+
const { https } = classic;
|
|
551
|
+
const args = {
|
|
552
|
+
...classic,
|
|
553
|
+
https: void 0
|
|
554
|
+
};
|
|
555
|
+
const memberConfig = await memberSwitchboardConfig(host, env, {
|
|
556
|
+
pluginHost: entriesDeclared,
|
|
557
|
+
defaults: https === void 0 ? {} : { server: { https } }
|
|
558
|
+
});
|
|
559
|
+
let pluginComposition;
|
|
560
|
+
if (entries !== void 0) pluginComposition = await resolveHostPlugins(ctx.projectRoot, "switchboard", ctx.verb, entries, `hosts/${host.name}/host.js`);
|
|
561
|
+
const hostDrives = (host.reactor?.drives ?? []).map((declaration) => ({
|
|
562
|
+
declaredSlug: declaration.slug,
|
|
563
|
+
drive: resolveDriveDeclaration(ctx.projectRoot, declaration)
|
|
564
|
+
}));
|
|
565
|
+
const contributedDrives = pluginDrives(ctx.projectRoot, hostDrives, pluginComposition, `hosts/${host.name}/host.js`);
|
|
566
|
+
const planned = [...hostDrives, ...contributedDrives];
|
|
567
|
+
const remoteDrives = planned.map((p) => p.drive).flatMap((d) => d.kind === "remote" && d.remoteUrl ? [d.remoteUrl] : []);
|
|
568
|
+
const serverArgs = {
|
|
569
|
+
...args,
|
|
570
|
+
...pluginComposition ? { pluginComposition } : {},
|
|
571
|
+
...hostDrives.length > 0 ? { drive: void 0 } : {},
|
|
572
|
+
...remoteDrives.length > 0 ? { remoteDrives } : {},
|
|
573
|
+
...ctx.parent ? { signalHandlers: false } : {}
|
|
574
|
+
};
|
|
575
|
+
let seeded;
|
|
576
|
+
const readyAfter = new Promise((resolve, reject) => {
|
|
577
|
+
seeded = {
|
|
578
|
+
resolve,
|
|
579
|
+
reject
|
|
580
|
+
};
|
|
581
|
+
});
|
|
582
|
+
const seeding = async (work) => {
|
|
583
|
+
try {
|
|
584
|
+
return await work;
|
|
585
|
+
} catch (error) {
|
|
586
|
+
seeded.reject(error);
|
|
587
|
+
throw error;
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
const switchboard = await startSwitchboard({
|
|
591
|
+
...serverArgs,
|
|
592
|
+
readyAfter
|
|
593
|
+
}, void 0, memberConfig);
|
|
594
|
+
const progress = switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== "false" ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {
|
|
595
|
+
stdout: process.stdout,
|
|
596
|
+
stderr: process.stderr,
|
|
597
|
+
top: catchUpTopFromEnv(process.env.PH_CATCH_UP_TOP)
|
|
598
|
+
}) : void 0;
|
|
599
|
+
const port = switchboard.port;
|
|
600
|
+
const origin = `http://localhost:${port}`;
|
|
601
|
+
const driveUrlOf = (slug) => `${origin}/d/${slug}`;
|
|
602
|
+
const seededIds = /* @__PURE__ */ new Map();
|
|
603
|
+
const localPlanned = planned.filter((p) => p.drive.kind === "local");
|
|
604
|
+
if (localPlanned.length > 0) await seeding(seedDrives(seederClient(switchboard.reactor, port, seededIds), localPlanned.map((p) => p.drive)));
|
|
605
|
+
const drives = {};
|
|
606
|
+
const localHostDrives = hostDrives.filter((d) => d.drive.kind === "local");
|
|
607
|
+
const defaultSlug = defaultDriveSlug(switchboard.defaultDriveUrl);
|
|
608
|
+
if (hostDrives.length === 0 && remoteDrives.length === 0) drives[defaultSlug] = {
|
|
609
|
+
id: defaultSlug,
|
|
610
|
+
url: driveUrlOf(defaultSlug)
|
|
611
|
+
};
|
|
612
|
+
for (const { declaredSlug, drive } of localPlanned) drives[declaredSlug] = {
|
|
613
|
+
id: seededIds.get(drive.slug) ?? drive.id ?? drive.slug,
|
|
614
|
+
url: driveUrlOf(drive.slug)
|
|
615
|
+
};
|
|
616
|
+
const slug = localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;
|
|
617
|
+
const driveUrl = driveUrlOf(slug);
|
|
618
|
+
if (entries === void 0 && switchboard.workflowsEnabled) {
|
|
619
|
+
const { projectDriveId, seedWorkflowsDrive } = await import("../services/switchboard.mjs");
|
|
620
|
+
const url = await seeding(seedWorkflowsDrive(switchboard.reactor, port, ctx.projectRoot));
|
|
621
|
+
if (url) drives.workflows = {
|
|
622
|
+
id: projectDriveId("workflows", ctx.projectRoot),
|
|
623
|
+
url
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
seeded.resolve();
|
|
627
|
+
const served = async () => {
|
|
628
|
+
try {
|
|
629
|
+
const id = await switchboard.reactor.resolveIdOrSlug(slug);
|
|
630
|
+
return Boolean(id);
|
|
631
|
+
} catch {
|
|
632
|
+
return false;
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
const ready = waitForDrive(driveUrl, 18e4, served);
|
|
636
|
+
ready.catch(() => void 0);
|
|
637
|
+
const graphql = `${origin}/graphql`;
|
|
638
|
+
let stopping;
|
|
639
|
+
return {
|
|
640
|
+
outputs: outputsSchema.parse({
|
|
641
|
+
origin,
|
|
642
|
+
endpoints: {
|
|
643
|
+
graphql,
|
|
644
|
+
...switchboard.mcpEnabled ? { mcp: `${origin}/mcp` } : {}
|
|
645
|
+
},
|
|
646
|
+
drives
|
|
647
|
+
}),
|
|
648
|
+
ready,
|
|
649
|
+
shutdown: () => {
|
|
650
|
+
progress?.stop();
|
|
651
|
+
return stopping ??= switchboard.shutdown();
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
async function run(host, ctx) {
|
|
656
|
+
return start(host, ctx, false);
|
|
657
|
+
}
|
|
658
|
+
const serve = run;
|
|
659
|
+
const verbs = [
|
|
660
|
+
"run",
|
|
661
|
+
"serve",
|
|
662
|
+
"dev"
|
|
663
|
+
];
|
|
664
|
+
async function dev(host, ctx) {
|
|
665
|
+
return start(host, ctx, true);
|
|
666
|
+
}
|
|
667
|
+
/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */
|
|
668
|
+
async function checkBoot(host, ctx) {
|
|
669
|
+
const env = memberEnvOf(ctx.env, ctx.projectRoot);
|
|
670
|
+
const issues = protocolConflicts(host.reactor?.protocol, env.shell, ctx.file).map((message) => ({
|
|
671
|
+
path: "reactor.protocol",
|
|
672
|
+
message
|
|
673
|
+
}));
|
|
674
|
+
const legacyStore = readModelAsReactorStore(host.reactor, env.shell, ctx.file);
|
|
675
|
+
if (legacyStore) issues.push({
|
|
676
|
+
path: "reactor.backends",
|
|
677
|
+
message: legacyStore.warning
|
|
678
|
+
});
|
|
679
|
+
const { getConfig } = await import("@powerhousedao/config/node");
|
|
680
|
+
const { switchboardBootFactsOf, switchboardBootIssues } = await import("@powerhousedao/switchboard/boot");
|
|
681
|
+
let config;
|
|
682
|
+
try {
|
|
683
|
+
config = await memberSwitchboardConfig(host, env, { pluginHost: host.runner.plugins !== void 0 });
|
|
684
|
+
} catch (error) {
|
|
685
|
+
issues.push({
|
|
686
|
+
path: "",
|
|
687
|
+
message: error instanceof Error ? error.message : String(error)
|
|
688
|
+
});
|
|
689
|
+
return issues;
|
|
690
|
+
}
|
|
691
|
+
const facts = await switchboardBootFactsOf(config, {
|
|
692
|
+
dev: switchboardDevMode(ctx.verb === "dev", host.runner),
|
|
693
|
+
configuredRenown: getConfig(path.join(ctx.projectRoot, "powerhouse.config.json")).auth?.renown
|
|
694
|
+
});
|
|
695
|
+
for (const message of switchboardBootIssues(facts)) issues.push({
|
|
696
|
+
path: "",
|
|
697
|
+
message
|
|
698
|
+
});
|
|
699
|
+
return issues;
|
|
700
|
+
}
|
|
701
|
+
//#endregion
|
|
702
|
+
export { checkBoot, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, switchboardDriveOutputSchema, verbs, waitForDrive };
|
|
703
|
+
|
|
704
|
+
//# sourceMappingURL=switchboard.mjs.map
|