@powerhousedao/ph-run 0.0.0-stage → 6.2.3-dev.100

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