@powerhousedao/ph-cli 6.2.3-dev.84 → 6.2.3-dev.86

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 (43) hide show
  1. package/README.md +21 -0
  2. package/dist/{check-D2r9Qbyf.mjs → check-o9kpHrG_.mjs} +5 -5
  3. package/dist/{check-D2r9Qbyf.mjs.map → check-o9kpHrG_.mjs.map} +1 -1
  4. package/dist/{cli-connect-override-Bv5y96A5.mjs → cli-connect-override-B8h8Dom0.mjs} +4 -4
  5. package/dist/{cli-connect-override-Bv5y96A5.mjs.map → cli-connect-override-B8h8Dom0.mjs.map} +1 -1
  6. package/dist/cli.mjs +3 -3
  7. package/dist/{connect-build-_HyX7OUY.mjs → connect-build-DhGOa9DG.mjs} +4 -4
  8. package/dist/{connect-build-_HyX7OUY.mjs.map → connect-build-DhGOa9DG.mjs.map} +1 -1
  9. package/dist/{connect-config-BD1WzHpY.mjs → connect-config-CSD0KpbH.mjs} +4 -4
  10. package/dist/{connect-config-BD1WzHpY.mjs.map → connect-config-CSD0KpbH.mjs.map} +1 -1
  11. package/dist/{connect-studio-7Bx53D6Z.mjs → connect-studio-CQwzYwYe.mjs} +3 -3
  12. package/dist/{connect-studio-C0LLX1TD.mjs → connect-studio-DMy3hxYS.mjs} +4 -4
  13. package/dist/{connect-studio-C0LLX1TD.mjs.map → connect-studio-DMy3hxYS.mjs.map} +1 -1
  14. package/dist/{dist-BiB5aiS6.mjs → dist-BfUgk19n.mjs} +9 -5
  15. package/dist/dist-BfUgk19n.mjs.map +1 -0
  16. package/dist/{explain-DnKF_KNm.mjs → explain-DD_ZC-9c.mjs} +4 -4
  17. package/dist/{explain-DnKF_KNm.mjs.map → explain-DD_ZC-9c.mjs.map} +1 -1
  18. package/dist/{export-1QvYpjR1.mjs → export-DdkU6JMT.mjs} +4 -4
  19. package/dist/{export-1QvYpjR1.mjs.map → export-DdkU6JMT.mjs.map} +1 -1
  20. package/dist/{get-version-CUoLKAxV.mjs → get-version-D1U-KyKb.mjs} +4 -4
  21. package/dist/{get-version-CUoLKAxV.mjs.map → get-version-D1U-KyKb.mjs.map} +1 -1
  22. package/dist/keyframes-bFo9iDhT.mjs +201 -0
  23. package/dist/keyframes-bFo9iDhT.mjs.map +1 -0
  24. package/dist/{mcp-BANOeLfA.mjs → mcp-tMRVrU0l.mjs} +4 -4
  25. package/dist/{mcp-BANOeLfA.mjs.map → mcp-tMRVrU0l.mjs.map} +1 -1
  26. package/dist/{member-config-ZEe4PlHE.mjs → member-config-CLziqSGm.mjs} +5 -4
  27. package/dist/member-config-CLziqSGm.mjs.map +1 -0
  28. package/dist/ph-cli-commands-BZDpcccA.mjs +4 -0
  29. package/dist/{ph-cli-commands-BS4Nacdg.mjs → ph-cli-commands-DoB_GolD.mjs} +43 -12
  30. package/dist/ph-cli-commands-DoB_GolD.mjs.map +1 -0
  31. package/dist/runners/connect.mjs +3 -3
  32. package/dist/runners/switchboard.d.mts +256 -0
  33. package/dist/runners/switchboard.d.mts.map +1 -1
  34. package/dist/runners/switchboard.mjs +178 -15
  35. package/dist/runners/switchboard.mjs.map +1 -1
  36. package/dist/scripts/generate-commands-docs.ts +2 -0
  37. package/dist/{vetra-Ch4M1DtV.mjs → vetra-rqgE32xv.mjs} +6 -6
  38. package/dist/{vetra-Ch4M1DtV.mjs.map → vetra-rqgE32xv.mjs.map} +1 -1
  39. package/package.json +14 -14
  40. package/dist/dist-BiB5aiS6.mjs.map +0 -1
  41. package/dist/member-config-ZEe4PlHE.mjs.map +0 -1
  42. package/dist/ph-cli-commands-BS4Nacdg.mjs.map +0 -1
  43. package/dist/ph-cli-commands-CWu73AaF.mjs +0 -4
@@ -1,13 +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]="ee4e0810-101f-5cb0-a070-1c0e240ceee3")}catch(e){}}();
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
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
4
  import { g as drivesSchema, m as defineHostSchemas, q as resolveHostPlugins } from "../compound-GhJAA2dK-Cj36zhoQ.mjs";
5
- import { _ as resolveDriveDeclaration, f as protocolConflicts, s as mergeDrivePlan, v as seedDrives } from "../dist-BiB5aiS6.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-ZEe4PlHE.mjs";
5
+ import { _ as resolveDriveDeclaration, f as protocolConflicts, s as mergeDrivePlan, v as seedDrives } from "../dist-BfUgk19n.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-CLziqSGm.mjs";
7
7
  import { command, runSafely } from "cmd-ts";
8
8
  import { switchboardArgs } from "@powerhousedao/shared/clis/args";
9
9
  import path from "node:path";
10
- import { computeProgress } from "@powerhousedao/reactor";
10
+ import { computeProgress, formatCount, formatDuration, rankSlowest, renderDoneSummary, renderSlowLine } from "@powerhousedao/reactor";
11
11
  //#region src/services/classic-args.ts
12
12
  /**
13
13
  * The classic `ph switchboard` argument shape, produced by the SAME cmd-ts
@@ -31,6 +31,47 @@ async function classicSwitchboardArgs(argv = []) {
31
31
  return result.value;
32
32
  }
33
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
34
75
  //#region src/services/run/catch-up-progress.ts
35
76
  function withDrives(label, driveCount) {
36
77
  return `${label} (${driveCount} ${driveCount === 1 ? "drive" : "drives"})`;
@@ -51,6 +92,7 @@ function progressRows(progress) {
51
92
  }
52
93
  /** Rows from a reactor's inspector: its processors, catch-up status and priority. */
53
94
  function inspectorProgressSource(inspector) {
95
+ let memoryReadAt = 0;
54
96
  return async () => {
55
97
  const processors = await inspector.getProcessors();
56
98
  let catchUp;
@@ -70,9 +112,26 @@ function inspectorProgressSource(inspector) {
70
112
  } catch {
71
113
  priority = void 0;
72
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
+ }
73
130
  return {
74
131
  rows: progressRows(computeProgress(processors, catchUp)),
75
- priority
132
+ priority,
133
+ timing,
134
+ memory
76
135
  };
77
136
  };
78
137
  }
@@ -88,6 +147,8 @@ function widthOf(stream) {
88
147
  }
89
148
  const DEFAULT_POLL_MS = 1e3;
90
149
  const DEFAULT_LINE_MS = 1e4;
150
+ const DEFAULT_TOP = 5;
151
+ const MEMORY_READ_MS = 5e3;
91
152
  const MIN_BAR = 10;
92
153
  const MAX_LABEL = 32;
93
154
  function percent(row) {
@@ -95,6 +156,12 @@ function percent(row) {
95
156
  if (row.state === "done") return "done";
96
157
  return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;
97
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
+ }
98
165
  function fit(label, width) {
99
166
  return label.length <= width ? label.padEnd(width) : `…${label.slice(label.length - width + 1)}`;
100
167
  }
@@ -107,10 +174,8 @@ function fit(label, width) {
107
174
  */
108
175
  function renderBars(rows, columns, priority) {
109
176
  const width = Math.max(columns - 1, 1);
110
- const fixed = 9;
111
- const longest = Math.max(...rows.map((row) => row.label.length), 0);
112
- const labelWidth = Math.max(1, Math.min(MAX_LABEL, longest, width - fixed - MIN_BAR));
113
- const barWidth = Math.max(MIN_BAR, width - labelWidth - fixed);
177
+ const labelWidth = barLabelWidth(rows, columns);
178
+ const barWidth = Math.max(MIN_BAR, width - labelWidth - BAR_FIXED);
114
179
  const bars = rows.map((row) => {
115
180
  const fraction = row.state === "done" ? 1 : row.fraction;
116
181
  const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);
@@ -120,6 +185,74 @@ function renderBars(rows, columns, priority) {
120
185
  if (!priority) return bars;
121
186
  return [renderPriority(priority).slice(0, width), ...bars];
122
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
+ }
123
256
  /** One line for a log without a TTY, listing only what is still catching up. */
124
257
  function renderLine(rows, priority) {
125
258
  const line = `catch-up: ${rows.filter((row) => row.state !== "done").map((row) => `${row.label} ${percent(row)}`).join(" · ")}`;
@@ -136,8 +269,13 @@ function busy(rows) {
136
269
  function startProgressDisplay(source, options) {
137
270
  const { stdout, stderr } = options;
138
271
  const tty = stdout.isTTY === true;
272
+ const top = options.top ?? DEFAULT_TOP;
139
273
  let rows = [];
140
274
  let priority;
275
+ let timing;
276
+ let memory;
277
+ let lastMemoryLine = Date.now();
278
+ let busySince;
141
279
  let drawn = 0;
142
280
  let atLineStart = true;
143
281
  let lastLine = 0;
@@ -151,9 +289,11 @@ function startProgressDisplay(source, options) {
151
289
  if (drawn > 0) originalOut(`\x1b[${drawn}A\r\x1b[0J`);
152
290
  drawn = 0;
153
291
  };
292
+ const slowest = () => timing && timing.level !== "off" && top > 0 ? rankSlowest(timing, top, "window") : [];
154
293
  const draw = () => {
155
294
  if (!tty || stopped || !atLineStart || !busy(rows)) return;
156
- const lines = renderBars(rows, widthOf(stdout), priority);
295
+ const columns = widthOf(stdout);
296
+ const lines = [...renderBars(rows, columns, priority), ...renderSlowest(slowest(), columns, barLabelWidth(rows, columns), timing?.windowMs ?? 0)];
157
297
  originalOut(`${lines.join("\n")}\n`);
158
298
  drawn = lines.length;
159
299
  };
@@ -179,19 +319,37 @@ function startProgressDisplay(source, options) {
179
319
  if (reading || stopped) return;
180
320
  reading = true;
181
321
  try {
182
- ({rows, priority} = await source());
322
+ ({rows, priority, timing, memory} = await source());
183
323
  } catch {} finally {
184
324
  reading = false;
185
325
  }
186
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
+ }
187
344
  if (tty) {
188
345
  erase();
189
346
  draw();
190
347
  return;
191
348
  }
192
- const now = Date.now();
193
349
  if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {
194
350
  originalOut(`${renderLine(rows, priority)}\n`);
351
+ const slow = slowest();
352
+ if (slow.length > 0) originalOut(`${renderSlowLine(slow, timing?.windowMs ?? 0)}\n`);
195
353
  lastLine = now;
196
354
  }
197
355
  };
@@ -401,6 +559,10 @@ async function createDeclaredDrive(addDefaultDrive, reactor, drive, port) {
401
559
  }
402
560
  }, port);
403
561
  }
562
+ function catchUpTopFromEnv(raw) {
563
+ const top = Number(raw?.trim() || NaN);
564
+ return Number.isInteger(top) && top >= 0 ? top : void 0;
565
+ }
404
566
  async function start(host, ctx, devMode) {
405
567
  const hostFile = `hosts/${host.name}/host.js`;
406
568
  const env = memberEnvOf(ctx.env);
@@ -457,7 +619,8 @@ async function start(host, ctx, devMode) {
457
619
  }, void 0, memberConfig);
458
620
  const progress = switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== "false" ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {
459
621
  stdout: process.stdout,
460
- stderr: process.stderr
622
+ stderr: process.stderr,
623
+ top: catchUpTopFromEnv(process.env.PH_CATCH_UP_TOP)
461
624
  }) : void 0;
462
625
  const port = switchboard.port;
463
626
  const origin = `http://localhost:${port}`;
@@ -479,7 +642,7 @@ async function start(host, ctx, devMode) {
479
642
  const slug = localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;
480
643
  const driveUrl = driveUrlOf(slug);
481
644
  if (entries === void 0 && switchboard.workflowsEnabled) {
482
- const { seedWorkflowsDrive } = await import("../vetra-Ch4M1DtV.mjs");
645
+ const { seedWorkflowsDrive } = await import("../vetra-rqgE32xv.mjs");
483
646
  const { generateProjectDriveId } = await import("../utils-DAux4Ga7.mjs");
484
647
  const url = await seeding(seedWorkflowsDrive(switchboard.reactor, port));
485
648
  if (url) drives.workflows = {
@@ -567,4 +730,4 @@ async function build(host, _ctx) {
567
730
  export { build, checkBoot, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, switchboardDriveOutputSchema, waitForDrive };
568
731
 
569
732
  //# sourceMappingURL=switchboard.mjs.map
570
- //# debugId=ee4e0810-101f-5cb0-a070-1c0e240ceee3
733
+ //# debugId=8ac355ed-0009-5ab4-98c0-9155899b7f68
@@ -1 +1 @@
1
- {"version":3,"file":"switchboard.mjs","sources":["../../src/services/classic-args.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["import { switchboardArgs } from \"@powerhousedao/shared/clis/args\";\nimport { command, runSafely } from \"cmd-ts\";\nimport type { SwitchboardArgs } from \"../types.js\";\n\n/**\n * The classic `ph switchboard` argument shape, produced by the SAME cmd-ts\n * definitions the classic command parses — not re-derived by hand. A runner\n * starts from this object and overlays only the keys its host file owns, so\n * every key the classic command carries (including the ones it carries as\n * `undefined`, e.g. `dbPath`) reaches the service exactly as it does on the\n * classic path. The uniform-runners switchboard runner once hand-built a\n * partial object that omitted `dbPath`; the service's then-default\n * `.ph/read-model.db` became both the reactor and the read-model PGlite dir —\n * two instances on one PGDATA (see uniform-runners-plan/legacy-parity-rectification.md).\n */\nconst classicSwitchboard = command({\n name: \"switchboard\",\n args: switchboardArgs,\n handler: (args) => args,\n});\n\nexport async function classicSwitchboardArgs(\n argv: string[] = [],\n): Promise<SwitchboardArgs> {\n const result = await runSafely(classicSwitchboard, argv);\n if (result._tag === \"error\") {\n throw new Error(\n `classic switchboard args did not parse: ${result.error.config.message}`,\n );\n }\n return result.value;\n}\n","import {\n computeProgress,\n type CatchUpPriorityState,\n type IInspector,\n type ReactorProgress,\n} from \"@powerhousedao/reactor\";\n\n/** One bar: a processor factory or a read model, and how far its catch-up has got. */\nexport type ProgressRow = {\n readonly label: string;\n /** 0..1 of the current run. */\n readonly fraction: number;\n readonly state: \"catching-up\" | \"done\" | \"errored\";\n};\n\n/** The catch-up priority as the progress display states it. */\nexport type ProgressPriority = {\n readonly mode: CatchUpPriorityState[\"mode\"];\n readonly level: number;\n readonly reason: string;\n};\n\n/** What one read of the source shows: the bars, and the priority when known. */\nexport type ProgressSnapshot = {\n readonly rows: readonly ProgressRow[];\n readonly priority: ProgressPriority | undefined;\n};\n\n/** Reads the current rows; rejects while the reactor cannot answer. */\nexport type ProgressSource = () => Promise<ProgressSnapshot>;\n\nfunction withDrives(label: string, driveCount: number): string {\n return `${label} (${driveCount} ${driveCount === 1 ? \"drive\" : \"drives\"})`;\n}\n\n/** One row per processor factory, then one per reactor read model. */\nexport function progressRows(progress: ReactorProgress): ProgressRow[] {\n const factories = progress.factories.map((factory): ProgressRow => ({\n label: withDrives(factory.label, factory.driveCount),\n fraction: factory.fraction,\n state:\n factory.phase === \"errored\"\n ? \"errored\"\n : factory.phase === \"catching-up\"\n ? \"catching-up\"\n : \"done\",\n }));\n const readModels = progress.readModels.map((model): ProgressRow => ({\n label: model.consumerId,\n fraction: model.fraction,\n state: model.blocked ? \"errored\" : model.complete ? \"done\" : \"catching-up\",\n }));\n return [...factories, ...readModels];\n}\n\n/** Rows from a reactor's inspector: its processors, catch-up status and priority. */\nexport function inspectorProgressSource(inspector: IInspector): ProgressSource {\n return async () => {\n const processors = await inspector.getProcessors();\n let catchUp:\n | Awaited<ReturnType<IInspector[\"getCatchUpStatus\"]>>\n | undefined;\n try {\n catchUp = await inspector.getCatchUpStatus();\n } catch {\n catchUp = undefined;\n }\n let priority: ProgressPriority | undefined;\n try {\n const state = await inspector.getCatchUpPriority();\n priority = { mode: state.mode, level: state.level, reason: state.reason };\n } catch {\n priority = undefined;\n }\n return {\n rows: progressRows(computeProgress(processors, catchUp)),\n priority,\n };\n };\n}\n\n/** `catch-up priority 6 (dynamic, idle 14 s)`, or `catch-up priority 3 (fixed)`. */\nexport function renderPriority(priority: ProgressPriority): string {\n const why =\n priority.mode === \"dynamic\" ? `dynamic, ${priority.reason}` : \"fixed\";\n return `catch-up priority ${priority.level} (${why})`;\n}\n\n/** The slice of a TTY stream the display writes to and intercepts. */\nexport type ProgressStream = {\n write: NodeJS.WriteStream[\"write\"];\n readonly isTTY?: boolean;\n readonly columns?: number;\n /** A TTY stream emits \"resize\" when the terminal's size changes. */\n on?(event: \"resize\", listener: () => void): unknown;\n off?(event: \"resize\", listener: () => void): unknown;\n};\n\n/** The console width the bars are sized for: a reported width, else 80. */\nfunction widthOf(stream: ProgressStream): number {\n const columns = stream.columns;\n return typeof columns === \"number\" && columns > 0 ? columns : 80;\n}\n\nexport type ProgressDisplayOptions = {\n readonly stdout: ProgressStream;\n readonly stderr: ProgressStream;\n /** How often the source is read. */\n readonly pollMs?: number;\n /** Without a TTY: how often a progress line is printed while catching up. */\n readonly lineMs?: number;\n};\n\nexport type ProgressDisplay = {\n /** Stops polling, removes the bars and restores the streams. */\n stop(): void;\n};\n\nconst DEFAULT_POLL_MS = 1_000;\nconst DEFAULT_LINE_MS = 10_000;\nconst MIN_BAR = 10;\nconst MAX_LABEL = 32;\n\nfunction percent(row: ProgressRow): string {\n if (row.state === \"errored\") return \"errored\";\n if (row.state === \"done\") return \"done\";\n return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;\n}\n\nfunction fit(label: string, width: number): string {\n return label.length <= width\n ? label.padEnd(width)\n : `…${label.slice(label.length - width + 1)}`;\n}\n\n/**\n * The bar block, one line per row, under the priority when known. Every line\n * stays short of the terminal's last column: a line that fills it wraps on\n * xterm-based terminals (VS Code, Windows Terminal), and the erase would then\n * lift fewer lines than are on screen, leaving old bars behind. On a narrow\n * terminal the label gives way before the bar.\n */\nexport function renderBars(\n rows: readonly ProgressRow[],\n columns: number,\n priority?: ProgressPriority,\n): string[] {\n const width = Math.max(columns - 1, 1);\n // label, space, bar, space, 7 for \"errored\" / \"100%\"\n const fixed = 9;\n const longest = Math.max(...rows.map((row) => row.label.length), 0);\n const labelWidth = Math.max(\n 1,\n Math.min(MAX_LABEL, longest, width - fixed - MIN_BAR),\n );\n const barWidth = Math.max(MIN_BAR, width - labelWidth - fixed);\n const bars = rows.map((row) => {\n const fraction = row.state === \"done\" ? 1 : row.fraction;\n const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);\n const bar = \"█\".repeat(filled) + \"░\".repeat(barWidth - filled);\n return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`.slice(\n 0,\n width,\n );\n });\n if (!priority) return bars;\n return [renderPriority(priority).slice(0, width), ...bars];\n}\n\n/** One line for a log without a TTY, listing only what is still catching up. */\nexport function renderLine(\n rows: readonly ProgressRow[],\n priority?: ProgressPriority,\n): string {\n const busy = rows.filter((row) => row.state !== \"done\");\n const line = `catch-up: ${busy.map((row) => `${row.label} ${percent(row)}`).join(\" · \")}`;\n return priority\n ? `${line} · priority ${priority.level} ${priority.mode}`\n : line;\n}\n\nfunction busy(rows: readonly ProgressRow[]): boolean {\n return rows.some((row) => row.state !== \"done\");\n}\n\n/**\n * Shows catch-up progress while any row is not done. In a terminal the bars\n * sit below the output and every other write is printed above them; without\n * one, a progress line is printed every `lineMs`.\n */\nexport function startProgressDisplay(\n source: ProgressSource,\n options: ProgressDisplayOptions,\n): ProgressDisplay {\n const { stdout, stderr } = options;\n const tty = stdout.isTTY === true;\n let rows: readonly ProgressRow[] = [];\n let priority: ProgressPriority | undefined;\n let drawn = 0;\n let atLineStart = true;\n let lastLine = 0;\n let stopped = false;\n let reading = false;\n\n const restoreOut = stdout.write;\n const restoreErr = stderr.write;\n const originalOut = restoreOut.bind(stdout);\n const originalErr = restoreErr.bind(stderr);\n\n const erase = () => {\n if (drawn > 0) originalOut(`\\x1b[${drawn}A\\r\\x1b[0J`);\n drawn = 0;\n };\n const draw = () => {\n if (!tty || stopped || !atLineStart || !busy(rows)) return;\n const lines = renderBars(rows, widthOf(stdout), priority);\n originalOut(`${lines.join(\"\\n\")}\\n`);\n drawn = lines.length;\n };\n\n // Every other write goes above the bars: lift them, write, put them back.\n const above =\n (write: (chunk: string | Uint8Array, ...rest: never[]) => boolean) =>\n (chunk: string | Uint8Array, ...rest: never[]): boolean => {\n erase();\n const result = write(chunk, ...rest);\n const text =\n typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n if (text.length > 0) atLineStart = text.endsWith(\"\\n\");\n draw();\n return result;\n };\n // A resized terminal has already reflowed the drawn lines; redraw for the\n // new width right away rather than at the next poll.\n const onResize = () => {\n if (stopped) return;\n erase();\n draw();\n };\n if (tty) {\n stdout.write = above(originalOut as never) as NodeJS.WriteStream[\"write\"];\n stderr.write = above(originalErr as never) as NodeJS.WriteStream[\"write\"];\n stdout.on?.(\"resize\", onResize);\n }\n\n const tick = async () => {\n if (reading || stopped) return;\n reading = true;\n try {\n ({ rows, priority } = await source());\n } catch {\n // The reactor did not answer; keep the last rows until it does.\n } finally {\n reading = false;\n }\n if (stopped) return;\n if (tty) {\n erase();\n draw();\n return;\n }\n const now = Date.now();\n if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {\n originalOut(`${renderLine(rows, priority)}\\n`);\n lastLine = now;\n }\n };\n\n const timer = setInterval(\n () => void tick(),\n options.pollMs ?? DEFAULT_POLL_MS,\n );\n (timer as { unref?: () => void }).unref?.();\n void tick();\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n erase();\n if (tty) {\n stdout.off?.(\"resize\", onResize);\n stdout.write = restoreOut;\n stderr.write = restoreErr;\n }\n },\n };\n}\n","import type * as SwitchboardUtils from \"@powerhousedao/switchboard/utils\";\nimport {\n defineHostSchemas,\n drivesSchema,\n mergeDrivePlan,\n protocolConflicts,\n resolveDriveDeclaration,\n resolveHostPlugins,\n seedDrives,\n type BootCheckContext,\n type BootIssue,\n type DriveSeederClient,\n type ResolvedDrive,\n type ResolvedPlugin,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport path from \"node:path\";\nimport {\n memberEnvOf,\n memberSwitchboardConfig,\n memberSwitchboardConfigSchema,\n prepareMemberStorage,\n reactorBlockConflicts,\n readModelAsReactorStore,\n switchboardDevMode,\n} from \"./member-config.js\";\nimport { z } from \"zod\";\nimport { classicSwitchboardArgs } from \"../services/classic-args.js\";\nimport {\n inspectorProgressSource,\n startProgressDisplay,\n} from \"../services/run/catch-up-progress.js\";\nimport type { BuildArgs, SwitchboardArgs } from \"../types.js\";\n\n/**\n * BRIDGE runner for Switchboard hosts (uniform-runners phase 0): maps a\n * hosts/switchboard/host.js definition onto the SAME `startSwitchboard`\n * service the classic command calls. `run` = production loaders, `dev` =\n * Vite package loader (worker pools refused by the server, as always).\n */\n\nexport const kind = \"reactor\";\n\n/** The switchboard host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails).\n * `config.switchboard` is this member's own switchboard config (auth,\n * inspection, workers, ...); a key the reactor block also sets is refused.\n * One definition, two schemas: `declaredHostSchema` (token-able fields take\n * output tokens; types host files) and `hostSchema` (resolved; checked\n * right before the verb). */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema\n .extend({\n runner: s.runnerBaseSchema\n .extend({\n /** 0 binds a port the OS picks; `origin` reports it. */\n port: z.number().int().min(0).max(65535).optional(),\n /** Dev mode without the `dev` verb (the Vite package loader). */\n dev: z.boolean().optional(),\n /** The project package output dir `build` writes (default \"dist\"). */\n outDir: z.string().min(1).optional(),\n })\n .strict(),\n config: z\n .strictObject({ switchboard: memberSwitchboardConfigSchema.optional() })\n .optional(),\n })\n .superRefine((host, ctx) => {\n for (const message of reactorBlockConflicts(host)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"switchboard\"],\n message,\n });\n }\n }),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a switchboard host.js author writes. */\nexport type SwitchboardHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type SwitchboardHostParsed = z.output<typeof hostSchema>;\n\n/** One drive the switchboard serves: its document id and its URL. */\nexport const switchboardDriveOutputSchema = z.strictObject({\n id: z.string().min(1),\n url: z.url(),\n});\n\n/** What a started switchboard produces. `origin` carries the port the server\n * actually bound. `drives` is keyed by the DECLARED slug (a `projectHash:\n * true` drive is reachable as `vetra`, its URL uses the hashed slug it is\n * served under) and includes plugin-created drives (e.g. `workflows`) and\n * the server's implicit default drive. `endpoints.mcp` is present when MCP\n * is mounted. */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({\n graphql: z.url(),\n mcp: z.url().optional(),\n }),\n drives: z.record(z.string(), switchboardDriveOutputSchema),\n});\nexport type SwitchboardOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/switchboard\": {\n host: SwitchboardHost;\n outputs: SwitchboardOutputs;\n };\n }\n}\n\n/** The classic arg shape with the one switch a composition may leave unset. */\nexport type SwitchboardRunnerArgs = Omit<SwitchboardArgs, \"mcp\"> & {\n mcp: boolean | undefined;\n};\n\n/**\n * Start from the classic `ph switchboard` args (parsed by the classic\n * definitions, no flags) and overlay ONLY the keys the host file owns. Every\n * other key — including the ones the classic command carries as `undefined`,\n * such as `dbPath` — reaches the service exactly as on the classic path. No\n * cast: a key the classic shape has and this object lacks is a type error.\n */\nasync function toSwitchboardArgs(\n host: SwitchboardHostParsed,\n devMode: boolean,\n composed: boolean,\n): Promise<SwitchboardRunnerArgs> {\n const classic = await classicSwitchboardArgs();\n const runner = host.runner;\n return {\n ...classic,\n port: runner.port ?? classic.port,\n dev: switchboardDevMode(devMode, runner) ? true : classic.dev,\n // A declared composition owns the carved switches (R2): the mcp plugin's\n // presence sets it, its absence must deactivate. Classic path: classic.\n mcp: composed ? undefined : classic.mcp,\n };\n}\n\n/** The drive the switchboard service creates by default\n * (services/switchboard.ts `defaultSwitchboardOptions.drive`). */\nconst DEFAULT_DRIVE_SLUG = \"powerhouse\";\n\n/** The `<slug>` of the server-reported `…/d/<slug>` default drive URL. */\nfunction defaultDriveSlug(url: string | undefined): string {\n const match = url ? /\\/d\\/([^/?#]+)\\/?$/.exec(url) : null;\n return match ? decodeURIComponent(match[1]) : DEFAULT_DRIVE_SLUG;\n}\n\n/** A drive in the plan with the slug its declaration used (a `projectHash:\n * true` drive is served under its hashed slug; outputs key it by this one). */\ninterface PlannedDrive {\n declaredSlug: string;\n drive: ResolvedDrive;\n}\n\n/**\n * The drives the composition's plugins contribute, resolved and in plan\n * order, minus the slugs the host declares itself (mergeDrivePlan: the host\n * file wins). A contribution that is not a valid drive declaration fails the\n * boot naming the plugin.\n */\nfunction pluginDrives(\n projectRoot: string,\n hostDrives: readonly PlannedDrive[],\n composition: readonly ResolvedPlugin[] | undefined,\n where: string,\n): PlannedDrive[] {\n if (!composition) return [];\n const contributed = composition.flatMap((resolved) => {\n const drives = resolved.plugin.contributions?.drives ?? [];\n if (drives.length === 0) return [];\n const parsed = drivesSchema.safeParse(drives);\n if (!parsed.success) {\n throw new Error(\n `${where}: plugin \"${resolved.plugin.name}\" contributes an invalid drive declaration:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n return parsed.data.map((declaration) => ({\n declaration,\n source: resolved.plugin.name,\n }));\n });\n if (contributed.length === 0) return [];\n // served slug -> declared slug, for the outputs' keys\n const declaredSlugs = new Map(\n contributed.map(({ declaration }) => [\n resolveDriveDeclaration(projectRoot, declaration).slug,\n declaration.slug,\n ]),\n );\n const hostSlugs = new Set(hostDrives.map((d) => d.drive.slug));\n return mergeDrivePlan(projectRoot, [], contributed)\n .map((entry) => entry.drive)\n .filter((drive) => !hostSlugs.has(drive.slug))\n .map((drive) => ({\n declaredSlug: declaredSlugs.get(drive.slug) ?? drive.slug,\n drive,\n }));\n}\n\n/** Poll the default drive endpoint until the server answers — the compound's\n * readiness gate: Connect auto-connects the drive on first load, so the drive\n * must answer before the connect member serves (the sidecar's\n * waitForSwitchboard, moved behind the handle contract).\n *\n * The probe is anonymous, and a host with authentication on hides a drive\n * from a caller it refuses (`/d/:drive` answers 404 to anyone who may not\n * read it, 401 under the authenticated-caller floor). Those answers prove\n * the server is listening but not whether the drive exists, so `served`,\n * the reactor's own view of the drive, decides then; without it an\n * ADMIN_ONLY host never passes this gate and the compound tears down after\n * the timeout. */\nexport async function waitForDrive(\n url: string,\n timeoutMs: number,\n served?: () => Promise<boolean>,\n fetchImpl: typeof fetch = fetch,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n const HIDDEN = new Set([401, 403, 404]);\n for (;;) {\n try {\n const res = await fetchImpl(url, { signal: AbortSignal.timeout(3000) });\n if (res.ok) return;\n if (HIDDEN.has(res.status) && served && (await served())) return;\n } catch {\n // not listening yet\n }\n if (Date.now() > deadline) {\n throw new Error(\n `Switchboard drive ${url} did not answer within ${timeoutMs}ms.`,\n );\n }\n await new Promise((resolve) => setTimeout(resolve, 400));\n }\n}\n\n/** What a started switchboard returns. */\nexport type SwitchboardHandle = RunnerHandle<SwitchboardOutputs>;\n\n/** The slice of the switchboard's reactor client (IReactorClient) the seeder\n * reads: id-or-slug resolution against the read model (live documents). */\ninterface SlugLookupClient {\n resolveIdOrSlug(identifier: string): Promise<string | undefined>;\n}\n\n/**\n * Adapter from the switchboard's reactor client onto the host-core seeder.\n * Seeding is SLUG-keyed: a live drive that already serves the slug — under\n * whatever id (a store from a run that hashed the project path differently,\n * or a hand-made drive) — is the drive, and nothing is created. addDefaultDrive\n * alone only knows ids: with a different id it would try to create a second\n * drive for the slug, and against a deleted document with that id the create\n * fails on every boot.\n */\nfunction seederClient(\n reactor: unknown,\n port: number,\n seededIds: Map<string, string>,\n): DriveSeederClient {\n return {\n findDriveBySlug: async (slug: string) => {\n try {\n const id = await (reactor as SlugLookupClient).resolveIdOrSlug(slug);\n if (id) seededIds.set(slug, id);\n return id || undefined;\n } catch {\n // not found (or ambiguous): seed as declared\n return undefined;\n }\n },\n createDrive: async (drive: ResolvedDrive) => {\n const { addDefaultDrive } =\n await import(\"@powerhousedao/switchboard/utils\");\n // One drive that cannot be made must not keep the server from starting\n try {\n await createDeclaredDrive(addDefaultDrive, reactor, drive, port);\n } catch (error) {\n console.error(\n `The drive \"${drive.slug}\" was not created: ${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n // Its id: the declared one, or a new one where the store could not take\n // a pinned id (addDefaultDrive then made it under the slug)\n let id: string | undefined;\n try {\n id = await (reactor as SlugLookupClient).resolveIdOrSlug(drive.slug);\n } catch {\n id = undefined;\n }\n seededIds.set(drive.slug, id || drive.id);\n },\n attachRemoteDrive: () => Promise.resolve(), // remotes ride options.remoteDrives\n };\n}\n\n/** A declared local drive, through the switchboard's own default-drive path. */\nasync function createDeclaredDrive(\n addDefaultDrive: typeof SwitchboardUtils.addDefaultDrive,\n reactor: unknown,\n drive: ResolvedDrive,\n port: number,\n): Promise<void> {\n await addDefaultDrive(\n reactor as Parameters<typeof addDefaultDrive>[0],\n {\n id: drive.id,\n slug: drive.slug,\n global: { name: drive.name, icon: drive.icon },\n ...(drive.preferredEditor\n ? { preferredEditor: drive.preferredEditor }\n : {}),\n local: {\n availableOffline: drive.availableOffline,\n listeners: [],\n sharingType: drive.sharingType,\n triggers: [],\n },\n } as Parameters<typeof addDefaultDrive>[1],\n port,\n );\n}\n\nasync function start(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n devMode: boolean,\n): Promise<SwitchboardHandle> {\n const hostFile = `hosts/${host.name}/host.js`;\n // Split before the server import loads the project .env into the env.\n const env = memberEnvOf(ctx.env);\n prepareMemberStorage(host.reactor, env.shell, hostFile);\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n hostFile,\n );\n if (legacyStore) console.warn(legacyStore.warning);\n const { startSwitchboard } = await import(\"../services/switchboard.js\");\n const entries = host.runner.plugins;\n const entriesDeclared = entries !== undefined;\n const classic = await toSwitchboardArgs(host, devMode, entriesDeclared);\n // powerhouse.config.json `reactor.https` is a default, not a flag: it goes\n // under the member's own config instead of over it.\n const { https } = classic;\n const args = { ...classic, https: undefined };\n // This member's own config, under the args: nothing is written to the\n // process env, so compound members do not see each other's settings.\n const memberConfig = await memberSwitchboardConfig(host, env, {\n pluginHost: entriesDeclared,\n defaults: https === undefined ? {} : { server: { https } },\n });\n\n // R2 step 2: a declared composition activates the plugin pipeline — the\n // runner resolves the entries against the PROJECT dependency tree and\n // `features.pluginHost` drives server-side activation. No plugins key =\n // classic path.\n let pluginComposition;\n if (entries !== undefined) {\n pluginComposition = await resolveHostPlugins(\n ctx.projectRoot,\n \"switchboard\",\n ctx.verb,\n entries,\n `hosts/${host.name}/host.js`,\n );\n }\n\n // Core drive declarations (reactor.drives): locals seed after boot via the\n // host-core seeder; remotes ride the existing remoteDrives option; the\n // implicit default powerhouse drive is replaced by the declared set.\n const hostDrives: PlannedDrive[] = (host.reactor?.drives ?? []).map(\n (declaration) => ({\n declaredSlug: declaration.slug,\n drive: resolveDriveDeclaration(ctx.projectRoot, declaration),\n }),\n );\n // Plugin-contributed drives (e.g. the workflows plugin's Workflows drive)\n // join the plan after the host's own: a host declaration with the same slug\n // wins, and the host's drives stay first (the first local one is the\n // readiness gate and the compound's primary drive).\n const contributedDrives = pluginDrives(\n ctx.projectRoot,\n hostDrives,\n pluginComposition,\n `hosts/${host.name}/host.js`,\n );\n const planned = [...hostDrives, ...contributedDrives];\n const resolvedDrives = planned.map((p) => p.drive);\n const remoteDrives = resolvedDrives.flatMap((d) =>\n d.kind === \"remote\" && d.remoteUrl ? [d.remoteUrl] : [],\n );\n const serverArgs = {\n ...args,\n ...(pluginComposition ? { pluginComposition } : {}),\n // Only the HOST's declarations replace the implicit default drive; a\n // contribution adds to whatever the host serves.\n ...(hostDrives.length > 0 ? { drive: undefined } : {}),\n ...(remoteDrives.length > 0 ? { remoteDrives } : {}),\n // A compound member: the compound owns SIGINT/SIGTERM and the exit, and\n // stops this reactor through the handle's shutdown().\n ...(ctx.parent ? { signalHandlers: false } : {}),\n };\n\n // `/ready` waits until the drives seeded below exist.\n let seeded!: { resolve: () => void; reject: (error: unknown) => void };\n const readyAfter = new Promise<void>((resolve, reject) => {\n seeded = { resolve, reject };\n });\n const seeding = async <T>(work: Promise<T>): Promise<T> => {\n try {\n return await work;\n } catch (error) {\n seeded.reject(error);\n throw error;\n }\n };\n const switchboard = await startSwitchboard(\n { ...serverArgs, readyAfter },\n undefined,\n memberConfig,\n );\n // Bars for processor and read-model catch-up, below the server's output;\n // PH_CATCH_UP_PROGRESS=false leaves the output as it was.\n const progress =\n switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== \"false\"\n ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {\n stdout: process.stdout,\n stderr: process.stderr,\n })\n : undefined;\n // The port the server actually bound (it may move off a taken one).\n const port = switchboard.port;\n const origin = `http://localhost:${port}`;\n const driveUrlOf = (slug: string) => `${origin}/d/${slug}`;\n\n const seededIds = new Map<string, string>();\n const localPlanned = planned.filter((p) => p.drive.kind === \"local\");\n if (localPlanned.length > 0) {\n await seeding(\n seedDrives(\n seederClient(switchboard.reactor, port, seededIds),\n localPlanned.map((p) => p.drive),\n ),\n );\n }\n\n const drives: SwitchboardOutputs[\"drives\"] = {};\n // The server creates its implicit default drive only when nothing replaces\n // it: no host declaration and no remote drive (services/switchboard.ts).\n const localHostDrives = hostDrives.filter((d) => d.drive.kind === \"local\");\n const defaultSlug = defaultDriveSlug(switchboard.defaultDriveUrl);\n if (hostDrives.length === 0 && remoteDrives.length === 0) {\n drives[defaultSlug] = { id: defaultSlug, url: driveUrlOf(defaultSlug) };\n }\n for (const { declaredSlug, drive } of localPlanned) {\n drives[declaredSlug] = {\n id: seededIds.get(drive.slug) ?? drive.id,\n url: driveUrlOf(drive.slug),\n };\n }\n\n const slug =\n localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;\n const driveUrl = driveUrlOf(slug);\n\n // No composition declared (the deprecated `reactor.workflows` switch): the\n // workflows flag still seeds the SAME project-hashed drive the classic\n // vetra path seeds. With a composition the workflows PLUGIN declares that\n // drive (contributions.drives above), so nothing implicit happens here.\n if (entries === undefined && switchboard.workflowsEnabled) {\n const { seedWorkflowsDrive } = await import(\"../services/vetra.js\");\n const { generateProjectDriveId } = await import(\"../utils.js\");\n const url = await seeding(seedWorkflowsDrive(switchboard.reactor, port));\n if (url)\n drives.workflows = { id: generateProjectDriveId(\"workflows\"), url };\n }\n seeded.resolve();\n\n // Under an authenticating host the anonymous probe cannot see the drive;\n // the reactor's slug lookup (the seeder's) answers for it.\n const served = async () => {\n try {\n const id = await (\n switchboard.reactor as SlugLookupClient\n ).resolveIdOrSlug(slug);\n return Boolean(id);\n } catch {\n return false;\n }\n };\n const ready = waitForDrive(driveUrl, 180_000, served);\n // A supervisor awaits `ready` and sees the rejection; an unsupervised caller\n // (or a test with the service mocked) must not die of an unhandled one.\n ready.catch(() => undefined);\n const graphql = `${origin}/graphql`;\n // Stops the reactor the server owns, then drains the HTTP server (freeing\n // the port), GraphQL, MCP, attachments, the plugins' onShutdown and the\n // read-model db, then closes the reactor database. SwitchboardReactor\n // memoizes it; standalone, SIGINT/SIGTERM run the same teardown, so a\n // shutdown() during or after a signal joins it instead of draining twice.\n let stopping: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin,\n endpoints: {\n graphql,\n ...(switchboard.mcpEnabled ? { mcp: `${origin}/mcp` } : {}),\n },\n drives,\n }),\n ready,\n shutdown: () => {\n progress?.stop();\n return (stopping ??= switchboard.shutdown());\n },\n };\n}\n\n// The four verbs are orthogonal: each does ONE job.\n// - `run`/`serve`: START the server in production mode (serves the built\n// project package). `serve` is run's alias — a server IS its served stack,\n// and it lets the compound forward one `serve` verb to every member.\n// - `dev`: START the server in dev mode (watch / the Vite package loader).\n// - `build`: PRODUCE the project package this switchboard serves, and start\n// NOTHING. The analog of `ph connect build` on the server side: legacy\n// `ph switchboard build` never existed, but the project still has a build.\n// `build` is what lets a compound forward a single `build` verb to all members\n// (desktop/cli) without the switchboard member failing on an unknown verb.\n\nexport async function run(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, false);\n}\n\nexport const serve = run;\n\nexport async function dev(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, true);\n}\n\n/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */\nexport async function checkBoot(\n host: SwitchboardHostParsed,\n ctx: BootCheckContext,\n): Promise<BootIssue[]> {\n // As `start` splits it: the project .env sits under the host file.\n const env = memberEnvOf(ctx.env, ctx.projectRoot);\n const issues: BootIssue[] = protocolConflicts(\n host.reactor?.protocol,\n env.shell,\n ctx.file,\n ).map((message) => ({ path: \"reactor.protocol\", message }));\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n ctx.file,\n );\n if (legacyStore) {\n issues.push({ path: \"reactor.backends\", message: legacyStore.warning });\n }\n const { getConfig } = await import(\"@powerhousedao/config/node\");\n const { switchboardBootFactsOf, switchboardBootIssues } =\n await import(\"@powerhousedao/switchboard/boot\");\n let config;\n try {\n // As `start` builds it; an env parse error becomes the issue.\n config = await memberSwitchboardConfig(host, env, {\n pluginHost: host.runner.plugins !== undefined,\n });\n } catch (error) {\n issues.push({\n path: \"\",\n message: error instanceof Error ? error.message : String(error),\n });\n return issues;\n }\n const facts = await switchboardBootFactsOf(config, {\n // As the `dev` verb starts it.\n dev: switchboardDevMode(ctx.verb === \"dev\", host.runner),\n configuredRenown: getConfig(\n path.join(ctx.projectRoot, \"powerhouse.config.json\"),\n ).auth?.renown,\n });\n for (const message of switchboardBootIssues(facts)) {\n issues.push({ path: \"\", message });\n }\n return issues;\n}\n\n/** Build the project's reactor package (the SAME service as `ph build`) — what\n * this switchboard serves. Starts no server; orthogonal to run/serve/dev. */\nexport async function build(\n host: SwitchboardHostParsed,\n _ctx: RunnerContext,\n): Promise<void> {\n const { runBuild } = await import(\"../services/build.js\");\n const args: Partial<BuildArgs> = {\n outDir: host.runner.outDir ?? \"dist\",\n };\n await runBuild(args as BuildArgs);\n}\n"],"names":["z.number","z.boolean","z.string","z\n .strictObject","z.strictObject","z.url","z.record","z.prettifyError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,qBAAqB,QAAQ;CACjC,MAAM;CACN,MAAM;CACN,UAAU,SAAS;AACrB,CAAC;AAED,eAAsB,uBACpB,OAAiB,CAAC,GACQ;CAC1B,MAAM,SAAS,MAAM,UAAU,oBAAoB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M;EAAoB,SAAS,YAAY;CAAQ,CAAC;CAExE,MAAM,EAAE,cAAc,MAAM,OAAO;CACnC,MAAM,EAAE,wBAAwB,0BAC9B,MAAM,OAAO;CACf,IAAI;CACJ,IAAI;EAEF,SAAS,MAAM,wBAAwB,MAAM,KAAK,EAChD,YAAY,KAAK,OAAO,YAAY,KAAA,EACtC,CAAC;CACH,SAAS,OAAO;EACd,OAAO,KAAK;GACV,MAAM;GACN,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAChE,CAAC;EACD,OAAO;CACT;CACA,MAAM,QAAQ,MAAM,uBAAuB,QAAQ;EAEjD,KAAK,mBAAmB,IAAI,SAAS,OAAO,KAAK,MAAM;EACvD,kBAAkB,UAChB,KAAK,KAAK,IAAI,aAAa,wBAAwB,CACrD,CAAC,CAAC,MAAM;CACV,CAAC;CACD,KAAK,MAAM,WAAW,sBAAsB,KAAK,GAC/C,OAAO,KAAK;EAAE,MAAM;EAAI;CAAQ,CAAC;CAEnC,OAAO;AACT;;;AAIA,eAAsB,MACpB,MACA,MACe;CACf,MAAM,EAAE,aAAa,MAAM,OAAO;CAIlC,MAAM,SAAS,EAFb,QAAQ,KAAK,OAAO,UAAU,OAEd,CAAc;AAClC","debug_id":"ee4e0810-101f-5cb0-a070-1c0e240ceee3"}
1
+ {"version":3,"file":"switchboard.mjs","sources":["../../src/services/classic-args.ts","../../src/services/run/memory-line.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["import { switchboardArgs } from \"@powerhousedao/shared/clis/args\";\nimport { command, runSafely } from \"cmd-ts\";\nimport type { SwitchboardArgs } from \"../types.js\";\n\n/**\n * The classic `ph switchboard` argument shape, produced by the SAME cmd-ts\n * definitions the classic command parses — not re-derived by hand. A runner\n * starts from this object and overlays only the keys its host file owns, so\n * every key the classic command carries (including the ones it carries as\n * `undefined`, e.g. `dbPath`) reaches the service exactly as it does on the\n * classic path. The uniform-runners switchboard runner once hand-built a\n * partial object that omitted `dbPath`; the service's then-default\n * `.ph/read-model.db` became both the reactor and the read-model PGlite dir —\n * two instances on one PGDATA (see uniform-runners-plan/legacy-parity-rectification.md).\n */\nconst classicSwitchboard = command({\n name: \"switchboard\",\n args: switchboardArgs,\n handler: (args) => args,\n});\n\nexport async function classicSwitchboardArgs(\n argv: string[] = [],\n): Promise<SwitchboardArgs> {\n const result = await runSafely(classicSwitchboard, argv);\n if (result._tag === \"error\") {\n throw new Error(\n `classic switchboard args did not parse: ${result.error.config.message}`,\n );\n }\n return result.value;\n}\n","import type {\n GaugeGrowth,\n MemorySample,\n MemoryTelemetryReport,\n} from \"@powerhousedao/reactor\";\n\nconst MB = 1024 * 1024;\n\nfunction size(bytes: number): string {\n return bytes >= 1024 * MB\n ? `${(bytes / (1024 * MB)).toFixed(2)} GB`\n : `${Math.round(bytes / MB)} MB`;\n}\n\nfunction rate(mbPerMin: number | null): string {\n if (mbPerMin === null) return \"\";\n const rounded = Math.round(mbPerMin);\n return ` (${rounded >= 0 ? \"+\" : \"\"}${rounded} MB/min)`;\n}\n\nfunction growth(gauge: GaugeGrowth): string {\n const perMin = Math.round(gauge.perMin);\n const text =\n Math.abs(perMin) >= 1000 ? `${(perMin / 1000).toFixed(1)}k` : `${perMin}`;\n return `${gauge.gauge} ${perMin >= 0 ? \"+\" : \"\"}${text}/min`;\n}\n\nfunction pglite(sample: MemorySample): number {\n let total = 0;\n for (const worker of Object.values(sample.workers)) total += worker.wasm ?? 0;\n return total;\n}\n\n/** The newest sample on one line; undefined before there is one. */\nexport function renderMemoryLine(\n report: MemoryTelemetryReport,\n): string | undefined {\n const sample = report.samples.at(-1);\n if (!sample) return undefined;\n const { summary } = report;\n const heap =\n sample.postGcHeap === null\n ? `heap ${size(sample.heapUsed)}`\n : `heap ${size(sample.heapUsed)}, post-GC ${size(sample.postGcHeap)}${rate(summary?.postGcMbPerMin ?? null)}`;\n const seconds = Math.round(sample.delta.s);\n const perOps =\n summary?.mbPer1kOps === null || summary?.mbPer1kOps === undefined\n ? \"\"\n : `, ${Math.round(summary.mbPer1kOps)} MB/1k ops`;\n const parts = [\n `memory: rss ${size(sample.rss)}${rate(summary?.rssMbPerMin ?? null)}`,\n heap,\n ];\n const wasm = pglite(sample);\n if (wasm > 0) parts.push(`pglite ${size(wasm)}`);\n parts.push(`${sample.delta.opsWritten} ops/${seconds}s${perOps}`);\n const top = summary?.topGauges[0];\n if (top) parts.push(`top: ${growth(top)}`);\n return parts.join(\" · \");\n}\n\n/** True when the reactor is running telemetry with the console output on. */\nexport function wantsMemoryLine(report: MemoryTelemetryReport): boolean {\n return report.enabled && report.outputs.includes(\"console\");\n}\n","import {\n computeProgress,\n formatCount,\n formatDuration,\n rankSlowest,\n renderDoneSummary,\n renderSlowLine,\n type CatchUpPriorityState,\n type IInspector,\n type InspectorProcessorTimingReport,\n type MemoryTelemetryReport,\n type ReactorProgress,\n type SlowProcessor,\n} from \"@powerhousedao/reactor\";\n\nimport { renderMemoryLine, wantsMemoryLine } from \"./memory-line.js\";\n\n/** One bar: a processor factory or a read model, and how far its catch-up has got. */\nexport type ProgressRow = {\n readonly label: string;\n /** 0..1 of the current run. */\n readonly fraction: number;\n readonly state: \"catching-up\" | \"done\" | \"errored\";\n};\n\n/** The catch-up priority as the progress display states it. */\nexport type ProgressPriority = {\n readonly mode: CatchUpPriorityState[\"mode\"];\n readonly level: number;\n readonly reason: string;\n};\n\n/** What one read of the source shows: the bars, and the priority when known. */\nexport type ProgressSnapshot = {\n readonly rows: readonly ProgressRow[];\n readonly priority: ProgressPriority | undefined;\n /** Undefined when the reactor has no timing, an older one. */\n readonly timing?: InspectorProcessorTimingReport;\n /** The latest sample; undefined when the reactor has no memory telemetry. */\n readonly memory?: MemoryTelemetryReport;\n};\n\n/** Reads the current rows; rejects while the reactor cannot answer. */\nexport type ProgressSource = () => Promise<ProgressSnapshot>;\n\nfunction withDrives(label: string, driveCount: number): string {\n return `${label} (${driveCount} ${driveCount === 1 ? \"drive\" : \"drives\"})`;\n}\n\n/** One row per processor factory, then one per reactor read model. */\nexport function progressRows(progress: ReactorProgress): ProgressRow[] {\n const factories = progress.factories.map((factory): ProgressRow => ({\n label: withDrives(factory.label, factory.driveCount),\n fraction: factory.fraction,\n state:\n factory.phase === \"errored\"\n ? \"errored\"\n : factory.phase === \"catching-up\"\n ? \"catching-up\"\n : \"done\",\n }));\n const readModels = progress.readModels.map((model): ProgressRow => ({\n label: model.consumerId,\n fraction: model.fraction,\n state: model.blocked ? \"errored\" : model.complete ? \"done\" : \"catching-up\",\n }));\n return [...factories, ...readModels];\n}\n\n/** Rows from a reactor's inspector: its processors, catch-up status and priority. */\nexport function inspectorProgressSource(inspector: IInspector): ProgressSource {\n // Its summary reads every sample of the window, too much for each poll.\n let memoryReadAt = 0;\n return async () => {\n const processors = await inspector.getProcessors();\n let catchUp:\n | Awaited<ReturnType<IInspector[\"getCatchUpStatus\"]>>\n | undefined;\n try {\n catchUp = await inspector.getCatchUpStatus();\n } catch {\n catchUp = undefined;\n }\n let priority: ProgressPriority | undefined;\n try {\n const state = await inspector.getCatchUpPriority();\n priority = { mode: state.mode, level: state.level, reason: state.reason };\n } catch {\n priority = undefined;\n }\n let timing: InspectorProcessorTimingReport | undefined;\n try {\n timing = await inspector.getProcessorTiming();\n } catch {\n timing = undefined;\n }\n let memory: MemoryTelemetryReport | undefined;\n if (Date.now() - memoryReadAt >= MEMORY_READ_MS) {\n memoryReadAt = Date.now();\n try {\n memory = await inspector.getMemoryTelemetry(1);\n } catch {\n memory = undefined;\n }\n }\n return {\n rows: progressRows(computeProgress(processors, catchUp)),\n priority,\n timing,\n memory,\n };\n };\n}\n\n/** `catch-up priority 6 (dynamic, idle 14 s)`, or `catch-up priority 3 (fixed)`. */\nexport function renderPriority(priority: ProgressPriority): string {\n const why =\n priority.mode === \"dynamic\" ? `dynamic, ${priority.reason}` : \"fixed\";\n return `catch-up priority ${priority.level} (${why})`;\n}\n\n/** The slice of a TTY stream the display writes to and intercepts. */\nexport type ProgressStream = {\n write: NodeJS.WriteStream[\"write\"];\n readonly isTTY?: boolean;\n readonly columns?: number;\n /** A TTY stream emits \"resize\" when the terminal's size changes. */\n on?(event: \"resize\", listener: () => void): unknown;\n off?(event: \"resize\", listener: () => void): unknown;\n};\n\n/** The console width the bars are sized for: a reported width, else 80. */\nfunction widthOf(stream: ProgressStream): number {\n const columns = stream.columns;\n return typeof columns === \"number\" && columns > 0 ? columns : 80;\n}\n\nexport type ProgressDisplayOptions = {\n readonly stdout: ProgressStream;\n readonly stderr: ProgressStream;\n /** How often the source is read. */\n readonly pollMs?: number;\n /** Without a TTY: how often a progress line is printed while catching up. */\n readonly lineMs?: number;\n /** How many of the slowest processors to show; 0 hides them. */\n readonly top?: number;\n};\n\nexport type ProgressDisplay = {\n /** Stops polling, removes the bars and restores the streams. */\n stop(): void;\n};\n\nconst DEFAULT_POLL_MS = 1_000;\nconst DEFAULT_LINE_MS = 10_000;\nconst DEFAULT_TOP = 5;\nconst MEMORY_READ_MS = 5_000;\nconst MIN_BAR = 10;\nconst MAX_LABEL = 32;\n\nfunction percent(row: ProgressRow): string {\n if (row.state === \"errored\") return \"errored\";\n if (row.state === \"done\") return \"done\";\n return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;\n}\n\n// label, space, bar, space, 7 for \"errored\" / \"100%\"\nconst BAR_FIXED = 9;\n\nfunction barLabelWidth(rows: readonly ProgressRow[], columns: number): number {\n const width = Math.max(columns - 1, 1);\n const longest = Math.max(...rows.map((row) => row.label.length), 0);\n return Math.max(1, Math.min(MAX_LABEL, longest, width - BAR_FIXED - MIN_BAR));\n}\n\nfunction fit(label: string, width: number): string {\n return label.length <= width\n ? label.padEnd(width)\n : `…${label.slice(label.length - width + 1)}`;\n}\n\n/**\n * The bar block, one line per row, under the priority when known. Every line\n * stays short of the terminal's last column: a line that fills it wraps on\n * xterm-based terminals (VS Code, Windows Terminal), and the erase would then\n * lift fewer lines than are on screen, leaving old bars behind. On a narrow\n * terminal the label gives way before the bar.\n */\nexport function renderBars(\n rows: readonly ProgressRow[],\n columns: number,\n priority?: ProgressPriority,\n): string[] {\n const width = Math.max(columns - 1, 1);\n const labelWidth = barLabelWidth(rows, columns);\n const barWidth = Math.max(MIN_BAR, width - labelWidth - BAR_FIXED);\n const bars = rows.map((row) => {\n const fraction = row.state === \"done\" ? 1 : row.fraction;\n const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);\n const bar = \"█\".repeat(filled) + \"░\".repeat(barWidth - filled);\n return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`.slice(\n 0,\n width,\n );\n });\n if (!priority) return bars;\n return [renderPriority(priority).slice(0, width), ...bars];\n}\n\n/** The columns of the slowest block, dropped from the first on a narrow console. */\nconst SLOW_COLUMNS: readonly {\n title: string;\n width: number;\n cell: (row: SlowProcessor) => string;\n}[] = [\n {\n title: \"eta\",\n width: 7,\n cell: (row) => (row.etaMs === null ? \"\" : formatDuration(row.etaMs)),\n },\n {\n title: \"behind\",\n width: 8,\n cell: (row) => formatCount(row.ordinalsBehind),\n },\n { title: \"fill\", width: 7, cell: (row) => formatDuration(row.fillMs) },\n { title: \"read\", width: 7, cell: (row) => formatDuration(row.readMs) },\n { title: \"op/s\", width: 6, cell: (row) => formatCount(row.opsPerSecond) },\n {\n title: \"handler\",\n width: 8,\n cell: (row) => formatDuration(row.handlerMs),\n },\n];\n\nconst BUSY_WIDTH = 7;\nconst SLOW_ORDER = [\"handler\", \"read\", \"fill\", \"op/s\", \"behind\", \"eta\"];\n\n/**\n * The slowest processors as a table, for under the bars. The label column\n * is at least as wide as the bars' and every line stays short of the last\n * column; a narrow console loses `eta`, `behind`, `fill`, `read`, `op/s`,\n * `handler`, in that order, and `busy` always stays.\n */\nexport function renderSlowest(\n rows: readonly SlowProcessor[],\n columns: number,\n labelWidth: number,\n windowMs: number,\n): string[] {\n if (rows.length === 0) return [];\n const width = Math.max(columns - 1, 1);\n const title = `slowest, last ${Math.round(windowMs / 1000)} s`;\n const longest = Math.max(\n title.length,\n ...rows.map((row) => row.label.length),\n );\n const label = Math.max(\n 1,\n Math.min(\n Math.max(labelWidth, Math.min(longest, MAX_LABEL)),\n width - BUSY_WIDTH - 1,\n ),\n );\n let room = width - label - BUSY_WIDTH;\n const kept = new Set<string>();\n for (const column of [...SLOW_COLUMNS].reverse()) {\n if (room < column.width) break;\n room -= column.width;\n kept.add(column.title);\n }\n const shown = SLOW_ORDER.flatMap((name) => {\n const column = SLOW_COLUMNS.find((c) => c.title === name);\n return column && kept.has(name) ? [column] : [];\n });\n const line = (first: string, busy: string, cells: string[]) =>\n `${fit(first, label)}${busy.padStart(BUSY_WIDTH)}${cells.join(\"\")}`.slice(\n 0,\n width,\n );\n return [\n line(\n title,\n \"busy\",\n shown.map((column) => column.title.padStart(column.width)),\n ),\n ...rows.map((row) =>\n line(\n row.label,\n formatDuration(row.busyMs),\n shown.map((column) => column.cell(row).padStart(column.width)),\n ),\n ),\n ];\n}\n\n/** One line for a log without a TTY, listing only what is still catching up. */\nexport function renderLine(\n rows: readonly ProgressRow[],\n priority?: ProgressPriority,\n): string {\n const busy = rows.filter((row) => row.state !== \"done\");\n const line = `catch-up: ${busy.map((row) => `${row.label} ${percent(row)}`).join(\" · \")}`;\n return priority\n ? `${line} · priority ${priority.level} ${priority.mode}`\n : line;\n}\n\nfunction busy(rows: readonly ProgressRow[]): boolean {\n return rows.some((row) => row.state !== \"done\");\n}\n\n/**\n * Shows catch-up progress while any row is not done. In a terminal the bars\n * sit below the output and every other write is printed above them; without\n * one, a progress line is printed every `lineMs`.\n */\nexport function startProgressDisplay(\n source: ProgressSource,\n options: ProgressDisplayOptions,\n): ProgressDisplay {\n const { stdout, stderr } = options;\n const tty = stdout.isTTY === true;\n const top = options.top ?? DEFAULT_TOP;\n let rows: readonly ProgressRow[] = [];\n let priority: ProgressPriority | undefined;\n let timing: InspectorProcessorTimingReport | undefined;\n let memory: MemoryTelemetryReport | undefined;\n let lastMemoryLine = Date.now();\n let busySince: number | undefined;\n let drawn = 0;\n let atLineStart = true;\n let lastLine = 0;\n let stopped = false;\n let reading = false;\n\n const restoreOut = stdout.write;\n const restoreErr = stderr.write;\n const originalOut = restoreOut.bind(stdout);\n const originalErr = restoreErr.bind(stderr);\n\n const erase = () => {\n if (drawn > 0) originalOut(`\\x1b[${drawn}A\\r\\x1b[0J`);\n drawn = 0;\n };\n const slowest = () =>\n timing && timing.level !== \"off\" && top > 0\n ? rankSlowest(timing, top, \"window\")\n : [];\n const draw = () => {\n if (!tty || stopped || !atLineStart || !busy(rows)) return;\n const columns = widthOf(stdout);\n const lines = [\n ...renderBars(rows, columns, priority),\n ...renderSlowest(\n slowest(),\n columns,\n barLabelWidth(rows, columns),\n timing?.windowMs ?? 0,\n ),\n ];\n originalOut(`${lines.join(\"\\n\")}\\n`);\n drawn = lines.length;\n };\n\n // Every other write goes above the bars: lift them, write, put them back.\n const above =\n (write: (chunk: string | Uint8Array, ...rest: never[]) => boolean) =>\n (chunk: string | Uint8Array, ...rest: never[]): boolean => {\n erase();\n const result = write(chunk, ...rest);\n const text =\n typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n if (text.length > 0) atLineStart = text.endsWith(\"\\n\");\n draw();\n return result;\n };\n // A resized terminal has already reflowed the drawn lines; redraw for the\n // new width right away rather than at the next poll.\n const onResize = () => {\n if (stopped) return;\n erase();\n draw();\n };\n if (tty) {\n stdout.write = above(originalOut as never) as NodeJS.WriteStream[\"write\"];\n stderr.write = above(originalErr as never) as NodeJS.WriteStream[\"write\"];\n stdout.on?.(\"resize\", onResize);\n }\n\n const tick = async () => {\n if (reading || stopped) return;\n reading = true;\n try {\n ({ rows, priority, timing, memory } = await source());\n } catch {\n // The reactor did not answer; keep the last rows until it does.\n } finally {\n reading = false;\n }\n if (stopped) return;\n const now = Date.now();\n // Through stderr, so a terminal's bars lift above it like any other output.\n if (\n memory &&\n wantsMemoryLine(memory) &&\n now - lastMemoryLine >= memory.consoleIntervalMs\n ) {\n const line = renderMemoryLine(memory);\n if (line) {\n stderr.write(`${line}\\n`);\n lastMemoryLine = now;\n }\n }\n if (busy(rows)) {\n busySince ??= now;\n } else if (busySince !== undefined) {\n const wallMs = now - busySince;\n busySince = undefined;\n if (timing && timing.level !== \"off\" && top > 0) {\n erase();\n originalOut(\n `${renderDoneSummary(rankSlowest(timing, top, \"total\"), wallMs)}\\n`,\n );\n }\n }\n if (tty) {\n erase();\n draw();\n return;\n }\n if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {\n originalOut(`${renderLine(rows, priority)}\\n`);\n const slow = slowest();\n if (slow.length > 0) {\n originalOut(`${renderSlowLine(slow, timing?.windowMs ?? 0)}\\n`);\n }\n lastLine = now;\n }\n };\n\n const timer = setInterval(\n () => void tick(),\n options.pollMs ?? DEFAULT_POLL_MS,\n );\n (timer as { unref?: () => void }).unref?.();\n void tick();\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n erase();\n if (tty) {\n stdout.off?.(\"resize\", onResize);\n stdout.write = restoreOut;\n stderr.write = restoreErr;\n }\n },\n };\n}\n","import type * as SwitchboardUtils from \"@powerhousedao/switchboard/utils\";\nimport {\n defineHostSchemas,\n drivesSchema,\n mergeDrivePlan,\n protocolConflicts,\n resolveDriveDeclaration,\n resolveHostPlugins,\n seedDrives,\n type BootCheckContext,\n type BootIssue,\n type DriveSeederClient,\n type ResolvedDrive,\n type ResolvedPlugin,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport path from \"node:path\";\nimport {\n memberEnvOf,\n memberSwitchboardConfig,\n memberSwitchboardConfigSchema,\n prepareMemberStorage,\n reactorBlockConflicts,\n readModelAsReactorStore,\n switchboardDevMode,\n} from \"./member-config.js\";\nimport { z } from \"zod\";\nimport { classicSwitchboardArgs } from \"../services/classic-args.js\";\nimport {\n inspectorProgressSource,\n startProgressDisplay,\n} from \"../services/run/catch-up-progress.js\";\nimport type { BuildArgs, SwitchboardArgs } from \"../types.js\";\n\n/**\n * BRIDGE runner for Switchboard hosts (uniform-runners phase 0): maps a\n * hosts/switchboard/host.js definition onto the SAME `startSwitchboard`\n * service the classic command calls. `run` = production loaders, `dev` =\n * Vite package loader (worker pools refused by the server, as always).\n */\n\nexport const kind = \"reactor\";\n\n/** The switchboard host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails).\n * `config.switchboard` is this member's own switchboard config (auth,\n * inspection, workers, ...); a key the reactor block also sets is refused.\n * One definition, two schemas: `declaredHostSchema` (token-able fields take\n * output tokens; types host files) and `hostSchema` (resolved; checked\n * right before the verb). */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema\n .extend({\n runner: s.runnerBaseSchema\n .extend({\n /** 0 binds a port the OS picks; `origin` reports it. */\n port: z.number().int().min(0).max(65535).optional(),\n /** Dev mode without the `dev` verb (the Vite package loader). */\n dev: z.boolean().optional(),\n /** The project package output dir `build` writes (default \"dist\"). */\n outDir: z.string().min(1).optional(),\n })\n .strict(),\n config: z\n .strictObject({ switchboard: memberSwitchboardConfigSchema.optional() })\n .optional(),\n })\n .superRefine((host, ctx) => {\n for (const message of reactorBlockConflicts(host)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"switchboard\"],\n message,\n });\n }\n }),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a switchboard host.js author writes. */\nexport type SwitchboardHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type SwitchboardHostParsed = z.output<typeof hostSchema>;\n\n/** One drive the switchboard serves: its document id and its URL. */\nexport const switchboardDriveOutputSchema = z.strictObject({\n id: z.string().min(1),\n url: z.url(),\n});\n\n/** What a started switchboard produces. `origin` carries the port the server\n * actually bound. `drives` is keyed by the DECLARED slug (a `projectHash:\n * true` drive is reachable as `vetra`, its URL uses the hashed slug it is\n * served under) and includes plugin-created drives (e.g. `workflows`) and\n * the server's implicit default drive. `endpoints.mcp` is present when MCP\n * is mounted. */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({\n graphql: z.url(),\n mcp: z.url().optional(),\n }),\n drives: z.record(z.string(), switchboardDriveOutputSchema),\n});\nexport type SwitchboardOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/switchboard\": {\n host: SwitchboardHost;\n outputs: SwitchboardOutputs;\n };\n }\n}\n\n/** The classic arg shape with the one switch a composition may leave unset. */\nexport type SwitchboardRunnerArgs = Omit<SwitchboardArgs, \"mcp\"> & {\n mcp: boolean | undefined;\n};\n\n/**\n * Start from the classic `ph switchboard` args (parsed by the classic\n * definitions, no flags) and overlay ONLY the keys the host file owns. Every\n * other key — including the ones the classic command carries as `undefined`,\n * such as `dbPath` — reaches the service exactly as on the classic path. No\n * cast: a key the classic shape has and this object lacks is a type error.\n */\nasync function toSwitchboardArgs(\n host: SwitchboardHostParsed,\n devMode: boolean,\n composed: boolean,\n): Promise<SwitchboardRunnerArgs> {\n const classic = await classicSwitchboardArgs();\n const runner = host.runner;\n return {\n ...classic,\n port: runner.port ?? classic.port,\n dev: switchboardDevMode(devMode, runner) ? true : classic.dev,\n // A declared composition owns the carved switches (R2): the mcp plugin's\n // presence sets it, its absence must deactivate. Classic path: classic.\n mcp: composed ? undefined : classic.mcp,\n };\n}\n\n/** The drive the switchboard service creates by default\n * (services/switchboard.ts `defaultSwitchboardOptions.drive`). */\nconst DEFAULT_DRIVE_SLUG = \"powerhouse\";\n\n/** The `<slug>` of the server-reported `…/d/<slug>` default drive URL. */\nfunction defaultDriveSlug(url: string | undefined): string {\n const match = url ? /\\/d\\/([^/?#]+)\\/?$/.exec(url) : null;\n return match ? decodeURIComponent(match[1]) : DEFAULT_DRIVE_SLUG;\n}\n\n/** A drive in the plan with the slug its declaration used (a `projectHash:\n * true` drive is served under its hashed slug; outputs key it by this one). */\ninterface PlannedDrive {\n declaredSlug: string;\n drive: ResolvedDrive;\n}\n\n/**\n * The drives the composition's plugins contribute, resolved and in plan\n * order, minus the slugs the host declares itself (mergeDrivePlan: the host\n * file wins). A contribution that is not a valid drive declaration fails the\n * boot naming the plugin.\n */\nfunction pluginDrives(\n projectRoot: string,\n hostDrives: readonly PlannedDrive[],\n composition: readonly ResolvedPlugin[] | undefined,\n where: string,\n): PlannedDrive[] {\n if (!composition) return [];\n const contributed = composition.flatMap((resolved) => {\n const drives = resolved.plugin.contributions?.drives ?? [];\n if (drives.length === 0) return [];\n const parsed = drivesSchema.safeParse(drives);\n if (!parsed.success) {\n throw new Error(\n `${where}: plugin \"${resolved.plugin.name}\" contributes an invalid drive declaration:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n return parsed.data.map((declaration) => ({\n declaration,\n source: resolved.plugin.name,\n }));\n });\n if (contributed.length === 0) return [];\n // served slug -> declared slug, for the outputs' keys\n const declaredSlugs = new Map(\n contributed.map(({ declaration }) => [\n resolveDriveDeclaration(projectRoot, declaration).slug,\n declaration.slug,\n ]),\n );\n const hostSlugs = new Set(hostDrives.map((d) => d.drive.slug));\n return mergeDrivePlan(projectRoot, [], contributed)\n .map((entry) => entry.drive)\n .filter((drive) => !hostSlugs.has(drive.slug))\n .map((drive) => ({\n declaredSlug: declaredSlugs.get(drive.slug) ?? drive.slug,\n drive,\n }));\n}\n\n/** Poll the default drive endpoint until the server answers — the compound's\n * readiness gate: Connect auto-connects the drive on first load, so the drive\n * must answer before the connect member serves (the sidecar's\n * waitForSwitchboard, moved behind the handle contract).\n *\n * The probe is anonymous, and a host with authentication on hides a drive\n * from a caller it refuses (`/d/:drive` answers 404 to anyone who may not\n * read it, 401 under the authenticated-caller floor). Those answers prove\n * the server is listening but not whether the drive exists, so `served`,\n * the reactor's own view of the drive, decides then; without it an\n * ADMIN_ONLY host never passes this gate and the compound tears down after\n * the timeout. */\nexport async function waitForDrive(\n url: string,\n timeoutMs: number,\n served?: () => Promise<boolean>,\n fetchImpl: typeof fetch = fetch,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n const HIDDEN = new Set([401, 403, 404]);\n for (;;) {\n try {\n const res = await fetchImpl(url, { signal: AbortSignal.timeout(3000) });\n if (res.ok) return;\n if (HIDDEN.has(res.status) && served && (await served())) return;\n } catch {\n // not listening yet\n }\n if (Date.now() > deadline) {\n throw new Error(\n `Switchboard drive ${url} did not answer within ${timeoutMs}ms.`,\n );\n }\n await new Promise((resolve) => setTimeout(resolve, 400));\n }\n}\n\n/** What a started switchboard returns. */\nexport type SwitchboardHandle = RunnerHandle<SwitchboardOutputs>;\n\n/** The slice of the switchboard's reactor client (IReactorClient) the seeder\n * reads: id-or-slug resolution against the read model (live documents). */\ninterface SlugLookupClient {\n resolveIdOrSlug(identifier: string): Promise<string | undefined>;\n}\n\n/**\n * Adapter from the switchboard's reactor client onto the host-core seeder.\n * Seeding is SLUG-keyed: a live drive that already serves the slug — under\n * whatever id (a store from a run that hashed the project path differently,\n * or a hand-made drive) — is the drive, and nothing is created. addDefaultDrive\n * alone only knows ids: with a different id it would try to create a second\n * drive for the slug, and against a deleted document with that id the create\n * fails on every boot.\n */\nfunction seederClient(\n reactor: unknown,\n port: number,\n seededIds: Map<string, string>,\n): DriveSeederClient {\n return {\n findDriveBySlug: async (slug: string) => {\n try {\n const id = await (reactor as SlugLookupClient).resolveIdOrSlug(slug);\n if (id) seededIds.set(slug, id);\n return id || undefined;\n } catch {\n // not found (or ambiguous): seed as declared\n return undefined;\n }\n },\n createDrive: async (drive: ResolvedDrive) => {\n const { addDefaultDrive } =\n await import(\"@powerhousedao/switchboard/utils\");\n // One drive that cannot be made must not keep the server from starting\n try {\n await createDeclaredDrive(addDefaultDrive, reactor, drive, port);\n } catch (error) {\n console.error(\n `The drive \"${drive.slug}\" was not created: ${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n // Its id: the declared one, or a new one where the store could not take\n // a pinned id (addDefaultDrive then made it under the slug)\n let id: string | undefined;\n try {\n id = await (reactor as SlugLookupClient).resolveIdOrSlug(drive.slug);\n } catch {\n id = undefined;\n }\n seededIds.set(drive.slug, id || drive.id);\n },\n attachRemoteDrive: () => Promise.resolve(), // remotes ride options.remoteDrives\n };\n}\n\n/** A declared local drive, through the switchboard's own default-drive path. */\nasync function createDeclaredDrive(\n addDefaultDrive: typeof SwitchboardUtils.addDefaultDrive,\n reactor: unknown,\n drive: ResolvedDrive,\n port: number,\n): Promise<void> {\n await addDefaultDrive(\n reactor as Parameters<typeof addDefaultDrive>[0],\n {\n id: drive.id,\n slug: drive.slug,\n global: { name: drive.name, icon: drive.icon },\n ...(drive.preferredEditor\n ? { preferredEditor: drive.preferredEditor }\n : {}),\n local: {\n availableOffline: drive.availableOffline,\n listeners: [],\n sharingType: drive.sharingType,\n triggers: [],\n },\n } as Parameters<typeof addDefaultDrive>[1],\n port,\n );\n}\n\nfunction catchUpTopFromEnv(raw: string | undefined): number | undefined {\n const top = Number(raw?.trim() || Number.NaN);\n return Number.isInteger(top) && top >= 0 ? top : undefined;\n}\n\nasync function start(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n devMode: boolean,\n): Promise<SwitchboardHandle> {\n const hostFile = `hosts/${host.name}/host.js`;\n // Split before the server import loads the project .env into the env.\n const env = memberEnvOf(ctx.env);\n prepareMemberStorage(host.reactor, env.shell, hostFile);\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n hostFile,\n );\n if (legacyStore) console.warn(legacyStore.warning);\n const { startSwitchboard } = await import(\"../services/switchboard.js\");\n const entries = host.runner.plugins;\n const entriesDeclared = entries !== undefined;\n const classic = await toSwitchboardArgs(host, devMode, entriesDeclared);\n // powerhouse.config.json `reactor.https` is a default, not a flag: it goes\n // under the member's own config instead of over it.\n const { https } = classic;\n const args = { ...classic, https: undefined };\n // This member's own config, under the args: nothing is written to the\n // process env, so compound members do not see each other's settings.\n const memberConfig = await memberSwitchboardConfig(host, env, {\n pluginHost: entriesDeclared,\n defaults: https === undefined ? {} : { server: { https } },\n });\n\n // R2 step 2: a declared composition activates the plugin pipeline — the\n // runner resolves the entries against the PROJECT dependency tree and\n // `features.pluginHost` drives server-side activation. No plugins key =\n // classic path.\n let pluginComposition;\n if (entries !== undefined) {\n pluginComposition = await resolveHostPlugins(\n ctx.projectRoot,\n \"switchboard\",\n ctx.verb,\n entries,\n `hosts/${host.name}/host.js`,\n );\n }\n\n // Core drive declarations (reactor.drives): locals seed after boot via the\n // host-core seeder; remotes ride the existing remoteDrives option; the\n // implicit default powerhouse drive is replaced by the declared set.\n const hostDrives: PlannedDrive[] = (host.reactor?.drives ?? []).map(\n (declaration) => ({\n declaredSlug: declaration.slug,\n drive: resolveDriveDeclaration(ctx.projectRoot, declaration),\n }),\n );\n // Plugin-contributed drives (e.g. the workflows plugin's Workflows drive)\n // join the plan after the host's own: a host declaration with the same slug\n // wins, and the host's drives stay first (the first local one is the\n // readiness gate and the compound's primary drive).\n const contributedDrives = pluginDrives(\n ctx.projectRoot,\n hostDrives,\n pluginComposition,\n `hosts/${host.name}/host.js`,\n );\n const planned = [...hostDrives, ...contributedDrives];\n const resolvedDrives = planned.map((p) => p.drive);\n const remoteDrives = resolvedDrives.flatMap((d) =>\n d.kind === \"remote\" && d.remoteUrl ? [d.remoteUrl] : [],\n );\n const serverArgs = {\n ...args,\n ...(pluginComposition ? { pluginComposition } : {}),\n // Only the HOST's declarations replace the implicit default drive; a\n // contribution adds to whatever the host serves.\n ...(hostDrives.length > 0 ? { drive: undefined } : {}),\n ...(remoteDrives.length > 0 ? { remoteDrives } : {}),\n // A compound member: the compound owns SIGINT/SIGTERM and the exit, and\n // stops this reactor through the handle's shutdown().\n ...(ctx.parent ? { signalHandlers: false } : {}),\n };\n\n // `/ready` waits until the drives seeded below exist.\n let seeded!: { resolve: () => void; reject: (error: unknown) => void };\n const readyAfter = new Promise<void>((resolve, reject) => {\n seeded = { resolve, reject };\n });\n const seeding = async <T>(work: Promise<T>): Promise<T> => {\n try {\n return await work;\n } catch (error) {\n seeded.reject(error);\n throw error;\n }\n };\n const switchboard = await startSwitchboard(\n { ...serverArgs, readyAfter },\n undefined,\n memberConfig,\n );\n // Bars for processor and read-model catch-up, below the server's output;\n // PH_CATCH_UP_PROGRESS=false leaves the output as it was. PH_CATCH_UP_TOP\n // sets how many of the slowest processors they list; 0 hides them.\n const progress =\n switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== \"false\"\n ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {\n stdout: process.stdout,\n stderr: process.stderr,\n top: catchUpTopFromEnv(process.env.PH_CATCH_UP_TOP),\n })\n : undefined;\n // The port the server actually bound (it may move off a taken one).\n const port = switchboard.port;\n const origin = `http://localhost:${port}`;\n const driveUrlOf = (slug: string) => `${origin}/d/${slug}`;\n\n const seededIds = new Map<string, string>();\n const localPlanned = planned.filter((p) => p.drive.kind === \"local\");\n if (localPlanned.length > 0) {\n await seeding(\n seedDrives(\n seederClient(switchboard.reactor, port, seededIds),\n localPlanned.map((p) => p.drive),\n ),\n );\n }\n\n const drives: SwitchboardOutputs[\"drives\"] = {};\n // The server creates its implicit default drive only when nothing replaces\n // it: no host declaration and no remote drive (services/switchboard.ts).\n const localHostDrives = hostDrives.filter((d) => d.drive.kind === \"local\");\n const defaultSlug = defaultDriveSlug(switchboard.defaultDriveUrl);\n if (hostDrives.length === 0 && remoteDrives.length === 0) {\n drives[defaultSlug] = { id: defaultSlug, url: driveUrlOf(defaultSlug) };\n }\n for (const { declaredSlug, drive } of localPlanned) {\n drives[declaredSlug] = {\n id: seededIds.get(drive.slug) ?? drive.id,\n url: driveUrlOf(drive.slug),\n };\n }\n\n const slug =\n localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;\n const driveUrl = driveUrlOf(slug);\n\n // No composition declared (the deprecated `reactor.workflows` switch): the\n // workflows flag still seeds the SAME project-hashed drive the classic\n // vetra path seeds. With a composition the workflows PLUGIN declares that\n // drive (contributions.drives above), so nothing implicit happens here.\n if (entries === undefined && switchboard.workflowsEnabled) {\n const { seedWorkflowsDrive } = await import(\"../services/vetra.js\");\n const { generateProjectDriveId } = await import(\"../utils.js\");\n const url = await seeding(seedWorkflowsDrive(switchboard.reactor, port));\n if (url)\n drives.workflows = { id: generateProjectDriveId(\"workflows\"), url };\n }\n seeded.resolve();\n\n // Under an authenticating host the anonymous probe cannot see the drive;\n // the reactor's slug lookup (the seeder's) answers for it.\n const served = async () => {\n try {\n const id = await (\n switchboard.reactor as SlugLookupClient\n ).resolveIdOrSlug(slug);\n return Boolean(id);\n } catch {\n return false;\n }\n };\n const ready = waitForDrive(driveUrl, 180_000, served);\n // A supervisor awaits `ready` and sees the rejection; an unsupervised caller\n // (or a test with the service mocked) must not die of an unhandled one.\n ready.catch(() => undefined);\n const graphql = `${origin}/graphql`;\n // Stops the reactor the server owns, then drains the HTTP server (freeing\n // the port), GraphQL, MCP, attachments, the plugins' onShutdown and the\n // read-model db, then closes the reactor database. SwitchboardReactor\n // memoizes it; standalone, SIGINT/SIGTERM run the same teardown, so a\n // shutdown() during or after a signal joins it instead of draining twice.\n let stopping: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin,\n endpoints: {\n graphql,\n ...(switchboard.mcpEnabled ? { mcp: `${origin}/mcp` } : {}),\n },\n drives,\n }),\n ready,\n shutdown: () => {\n progress?.stop();\n return (stopping ??= switchboard.shutdown());\n },\n };\n}\n\n// The four verbs are orthogonal: each does ONE job.\n// - `run`/`serve`: START the server in production mode (serves the built\n// project package). `serve` is run's alias — a server IS its served stack,\n// and it lets the compound forward one `serve` verb to every member.\n// - `dev`: START the server in dev mode (watch / the Vite package loader).\n// - `build`: PRODUCE the project package this switchboard serves, and start\n// NOTHING. The analog of `ph connect build` on the server side: legacy\n// `ph switchboard build` never existed, but the project still has a build.\n// `build` is what lets a compound forward a single `build` verb to all members\n// (desktop/cli) without the switchboard member failing on an unknown verb.\n\nexport async function run(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, false);\n}\n\nexport const serve = run;\n\nexport async function dev(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, true);\n}\n\n/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */\nexport async function checkBoot(\n host: SwitchboardHostParsed,\n ctx: BootCheckContext,\n): Promise<BootIssue[]> {\n // As `start` splits it: the project .env sits under the host file.\n const env = memberEnvOf(ctx.env, ctx.projectRoot);\n const issues: BootIssue[] = protocolConflicts(\n host.reactor?.protocol,\n env.shell,\n ctx.file,\n ).map((message) => ({ path: \"reactor.protocol\", message }));\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n ctx.file,\n );\n if (legacyStore) {\n issues.push({ path: \"reactor.backends\", message: legacyStore.warning });\n }\n const { getConfig } = await import(\"@powerhousedao/config/node\");\n const { switchboardBootFactsOf, switchboardBootIssues } =\n await import(\"@powerhousedao/switchboard/boot\");\n let config;\n try {\n // As `start` builds it; an env parse error becomes the issue.\n config = await memberSwitchboardConfig(host, env, {\n pluginHost: host.runner.plugins !== undefined,\n });\n } catch (error) {\n issues.push({\n path: \"\",\n message: error instanceof Error ? error.message : String(error),\n });\n return issues;\n }\n const facts = await switchboardBootFactsOf(config, {\n // As the `dev` verb starts it.\n dev: switchboardDevMode(ctx.verb === \"dev\", host.runner),\n configuredRenown: getConfig(\n path.join(ctx.projectRoot, \"powerhouse.config.json\"),\n ).auth?.renown,\n });\n for (const message of switchboardBootIssues(facts)) {\n issues.push({ path: \"\", message });\n }\n return issues;\n}\n\n/** Build the project's reactor package (the SAME service as `ph build`) — what\n * this switchboard serves. Starts no server; orthogonal to run/serve/dev. */\nexport async function build(\n host: SwitchboardHostParsed,\n _ctx: RunnerContext,\n): Promise<void> {\n const { runBuild } = await import(\"../services/build.js\");\n const args: Partial<BuildArgs> = {\n outDir: host.runner.outDir ?? \"dist\",\n };\n await runBuild(args as BuildArgs);\n}\n"],"names":["z.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ACN,CAAC,CAAC,KAAK,aAAa;EAAE,MAAM;EAAoB;CAAQ,EAAE;CAC1D,MAAM,cAAc,wBAClB,KAAK,SACL,IAAI,OACJ,IAAI,IACN;CACA,IAAI,aACF,OAAO,KAAK;EAAE,MAAM;EAAoB,SAAS,YAAY;CAAQ,CAAC;CAExE,MAAM,EAAE,cAAc,MAAM,OAAO;CACnC,MAAM,EAAE,wBAAwB,0BAC9B,MAAM,OAAO;CACf,IAAI;CACJ,IAAI;EAEF,SAAS,MAAM,wBAAwB,MAAM,KAAK,EAChD,YAAY,KAAK,OAAO,YAAY,KAAA,EACtC,CAAC;CACH,SAAS,OAAO;EACd,OAAO,KAAK;GACV,MAAM;GACN,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAChE,CAAC;EACD,OAAO;CACT;CACA,MAAM,QAAQ,MAAM,uBAAuB,QAAQ;EAEjD,KAAK,mBAAmB,IAAI,SAAS,OAAO,KAAK,MAAM;EACvD,kBAAkB,UAChB,KAAK,KAAK,IAAI,aAAa,wBAAwB,CACrD,CAAC,CAAC,MAAM;CACV,CAAC;CACD,KAAK,MAAM,WAAW,sBAAsB,KAAK,GAC/C,OAAO,KAAK;EAAE,MAAM;EAAI;CAAQ,CAAC;CAEnC,OAAO;AACT;;;AAIA,eAAsB,MACpB,MACA,MACe;CACf,MAAM,EAAE,aAAa,MAAM,OAAO;CAIlC,MAAM,SAAS,EAFb,QAAQ,KAAK,OAAO,UAAU,OAEd,CAAc;AAClC","debug_id":"8ac355ed-0009-5ab4-98c0-9155899b7f68"}
@@ -16,6 +16,7 @@ import { generateSubgraphCmd } from "../src/commands/generate-subgraph.js";
16
16
  import { generate } from "../src/commands/generate.js";
17
17
  import { inspect } from "../src/commands/inspect.js";
18
18
  import { install } from "../src/commands/install.js";
19
+ import { keyframes } from "../src/commands/keyframes.js";
19
20
  import { list } from "../src/commands/list.js";
20
21
  import { login } from "../src/commands/login.js";
21
22
  import { mcp } from "../src/commands/mcp.js";
@@ -46,6 +47,7 @@ const commands = [
46
47
  { name: "connect preview", command: preview },
47
48
  { name: "access token", command: accessToken },
48
49
  { name: "inspect", command: inspect },
50
+ { name: "keyframes", command: keyframes },
49
51
  { name: "list", command: list },
50
52
  { name: "mcp", command: mcp },
51
53
  { name: "migrate", command: migrate },
@@ -1,8 +1,8 @@
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]="e0773f2a-2b75-5778-b630-f96059011524")}catch(e){}}();
3
- import { h as rebaseDriveUrl, o as mergeDefaultDrives } from "./dist-BiB5aiS6.mjs";
4
- import { a as parseDefaultDrivesUrl, i as wasFlagExplicitlyPassed } from "./cli-connect-override-Bv5y96A5.mjs";
5
- import { t as runConnectStudio } from "./connect-studio-C0LLX1TD.mjs";
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]="47561605-e582-514a-b7d9-763432d83b61")}catch(e){}}();
3
+ import { h as rebaseDriveUrl, o as mergeDefaultDrives } from "./dist-BfUgk19n.mjs";
4
+ import { a as parseDefaultDrivesUrl, i as wasFlagExplicitlyPassed } from "./cli-connect-override-B8h8Dom0.mjs";
5
+ import { t as runConnectStudio } from "./connect-studio-DMy3hxYS.mjs";
6
6
  import { a as generateProjectDriveId, t as POWERHOUSE_CONFIG_FILE } from "./utils-9KyRM0mf.mjs";
7
7
  import { a as stopVetra, c as probeVetraRuntime, d as writeVetraRuntime, o as clearVetraRuntime, s as legacyMcpConfigs, u as syncMcpPort } from "./vetra-launch-DQDZxGTV.mjs";
8
8
  import { a as POWERHOUSE_DRIVE_ICON, r as startSwitchboard$1 } from "./switchboard-JcKcWTaT.mjs";
@@ -558,5 +558,5 @@ async function startVetra(args) {
558
558
  //#endregion
559
559
  export { seedWorkflowsDrive, startVetra };
560
560
 
561
- //# sourceMappingURL=vetra-Ch4M1DtV.mjs.map
562
- //# debugId=e0773f2a-2b75-5778-b630-f96059011524
561
+ //# sourceMappingURL=vetra-rqgE32xv.mjs.map
562
+ //# debugId=47561605-e582-514a-b7d9-763432d83b61