@powerhousedao/ph-cli 6.2.3-dev.89 → 6.2.3-dev.90

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