@powerhousedao/ph-run 6.2.3-dev.99 → 6.3.0-dev.2

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 (50) hide show
  1. package/dist/{classic-args-BYccyIIC.mjs → classic-args-BJMDXYLJ.mjs} +11 -5
  2. package/dist/{classic-args-BYccyIIC.mjs.map → classic-args-BJMDXYLJ.mjs.map} +1 -1
  3. package/dist/{classic-args-Dm0_3O5p.d.mts → classic-args-BKI4gEVD.d.mts} +4 -2
  4. package/dist/{classic-args-Dm0_3O5p.d.mts.map → classic-args-BKI4gEVD.d.mts.map} +1 -1
  5. package/dist/cli.mjs +9 -8
  6. package/dist/cli.mjs.map +1 -1
  7. package/dist/{connect-serve-1WAi0KJL.mjs → connect-serve-TZFWyrHe.mjs} +10 -5
  8. package/dist/connect-serve-TZFWyrHe.mjs.map +1 -0
  9. package/dist/{connect-serve-COWXf_41.d.mts → connect-serve-kfNeXmO2.d.mts} +5 -2
  10. package/dist/connect-serve-kfNeXmO2.d.mts.map +1 -0
  11. package/dist/{member-config-Bs3yOT6y.mjs → member-config-BvlBqovs.mjs} +5 -4
  12. package/dist/member-config-BvlBqovs.mjs.map +1 -0
  13. package/dist/observability-CrfdAtHw.mjs +25 -0
  14. package/dist/observability-CrfdAtHw.mjs.map +1 -0
  15. package/dist/runner-args-DduJxV1b.mjs +74 -0
  16. package/dist/runner-args-DduJxV1b.mjs.map +1 -0
  17. package/dist/runners/connect.d.mts +48 -3
  18. package/dist/runners/connect.d.mts.map +1 -1
  19. package/dist/runners/connect.mjs +76 -14
  20. package/dist/runners/connect.mjs.map +1 -1
  21. package/dist/runners/member-config.d.mts +30 -0
  22. package/dist/runners/member-config.d.mts.map +1 -1
  23. package/dist/runners/member-config.mjs +3 -3
  24. package/dist/runners/switchboard.d.mts +126 -1
  25. package/dist/runners/switchboard.d.mts.map +1 -1
  26. package/dist/runners/switchboard.mjs +96 -13
  27. package/dist/runners/switchboard.mjs.map +1 -1
  28. package/dist/services/classic-args.d.mts +2 -2
  29. package/dist/services/classic-args.mjs +4 -4
  30. package/dist/services/connect-serve.d.mts +1 -1
  31. package/dist/services/connect-serve.mjs +3 -3
  32. package/dist/services/connect-server.d.mts +5 -4
  33. package/dist/services/connect-server.d.mts.map +1 -1
  34. package/dist/services/connect-server.mjs +14 -6
  35. package/dist/services/connect-server.mjs.map +1 -1
  36. package/dist/services/run/start-run.d.mts +7 -1
  37. package/dist/services/run/start-run.d.mts.map +1 -1
  38. package/dist/services/run/start-run.mjs +3 -3
  39. package/dist/services/switchboard.d.mts +1 -1
  40. package/dist/{start-run-DWn2cVyi.mjs → start-run-DUfxuOde.mjs} +38 -19
  41. package/dist/start-run-DUfxuOde.mjs.map +1 -0
  42. package/dist/superseded-config-bNn_JyUj.mjs +31 -0
  43. package/dist/superseded-config-bNn_JyUj.mjs.map +1 -0
  44. package/package.json +7 -7
  45. package/dist/connect-serve-1WAi0KJL.mjs.map +0 -1
  46. package/dist/connect-serve-COWXf_41.d.mts.map +0 -1
  47. package/dist/member-config-Bs3yOT6y.mjs.map +0 -1
  48. package/dist/start-run-DWn2cVyi.mjs.map +0 -1
  49. package/dist/superseded-config-CpHrCuNq.mjs +0 -53
  50. package/dist/superseded-config-CpHrCuNq.mjs.map +0 -1
@@ -1,8 +1,11 @@
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]="22235455-173a-50c8-ac05-c56d3ed43f16")}catch(e){}}();
3
- import { c as readModelAsReactorStore, i as missingPostgresUrl, n as memberSwitchboardConfig, o as prepareMemberStorage, r as memberSwitchboardConfigSchema, s as reactorBlockConflicts, t as memberEnvOf, u as switchboardDevMode } from "../member-config-Bs3yOT6y.mjs";
4
- import { t as classicSwitchboardArgs } from "../classic-args-BYccyIIC.mjs";
5
- import { defineHostSchemas, drivesSchema, mergeDrivePlan, protocolConflicts, resolveDriveDeclaration, resolveHostPlugins, seedDrives } from "@powerhousedao/host-core";
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]="30f027d7-4932-5e43-9b68-9a06f98cbd73")}catch(e){}}();
3
+ import { i as reactorWorkflowsDeprecation, n as runnerArgsSchemaOf, t as onlyPassed } from "../runner-args-DduJxV1b.mjs";
4
+ import { n as classicSwitchboardArgs } from "../classic-args-BJMDXYLJ.mjs";
5
+ import { c as readModelAsReactorStore, i as missingPostgresUrl, n as memberSwitchboardConfig, o as prepareMemberStorage, r as memberSwitchboardConfigSchema, s as reactorBlockConflicts, t as memberEnvOf, u as switchboardDevMode } from "../member-config-BvlBqovs.mjs";
6
+ import { RunnerError, defineHostSchemas, drivesSchema, mergeDrivePlan, protocolConflicts, resolveDriveDeclaration, resolveHostPlugins, seedDrives } from "@powerhousedao/host-core";
7
+ import { commonServerArgs, switchboardArgs, vetraArgs } from "@powerhousedao/shared/clis/args";
8
+ import { command, runSafely } from "cmd-ts";
6
9
  import { z } from "zod";
7
10
  import path from "node:path";
8
11
  import { computeProgress, formatCount, formatDuration, rankSlowest, renderDoneSummary, renderSlowLine } from "@powerhousedao/reactor";
@@ -363,6 +366,8 @@ const schemas = defineHostSchemas((s) => s.reactorHostSchema.extend({
363
366
  runner: s.runnerBaseSchema.extend({
364
367
  /** 0 binds a port the OS picks; `origin` reports it. */
365
368
  port: z.number().int().min(0).max(65535).optional(),
369
+ /** Fail on a taken port instead of moving to a free one. */
370
+ strictPort: z.boolean().optional(),
366
371
  /** Dev mode without the `dev` verb (the Vite package loader). */
367
372
  dev: z.boolean().optional(),
368
373
  /** The project package output dir `build` writes (default "dist"). */
@@ -397,19 +402,60 @@ const outputsSchema = z.strictObject({
397
402
  }),
398
403
  drives: z.record(z.string(), switchboardDriveOutputSchema)
399
404
  });
405
+ /** What a switchboard accepts after `ph run <host> [verb]`: the classic
406
+ * `ph switchboard` and `ph vetra` definitions of the same names. */
407
+ const invocationArgs = {
408
+ port: switchboardArgs.port,
409
+ strictPort: commonServerArgs.strictPort,
410
+ dbPath: switchboardArgs.dbPath,
411
+ https: switchboardArgs.https,
412
+ httpsKeyFile: switchboardArgs.httpsKeyFile,
413
+ httpsCertFile: switchboardArgs.httpsCertFile,
414
+ remoteDrives: switchboardArgs.remoteDrives,
415
+ remoteDrive: vetraArgs.remoteDrive,
416
+ interactive: vetraArgs.interactive,
417
+ yes: switchboardArgs.yes
418
+ };
419
+ const invocation = command({
420
+ name: "switchboard",
421
+ args: invocationArgs,
422
+ handler: (args) => args
423
+ });
424
+ const WATCH_RETIRED = "it is no longer needed.";
425
+ const argsSchema = runnerArgsSchemaOf(invocationArgs, {
426
+ memberOptions: { "--switchboard-port": "--port" },
427
+ retired: {
428
+ "--watch": WATCH_RETIRED,
429
+ "-w": WATCH_RETIRED,
430
+ "--disable-connect": "use `ph run switchboard dev` instead."
431
+ }
432
+ });
433
+ /** This invocation's arguments (`ctx.argv`), parsed by the classic
434
+ * definitions; only the ones passed. */
435
+ async function invocationArgsOf(ctx, hostFile) {
436
+ const argv = [...ctx.argv ?? []];
437
+ if (argv.length === 0) return {};
438
+ const result = await runSafely(invocation, argv);
439
+ if (result._tag === "error") throw new RunnerError(`${hostFile}: ${result.error.config.message}`);
440
+ return onlyPassed(result.value, invocationArgs, argv);
441
+ }
400
442
  /**
401
443
  * Start from the classic `ph switchboard` args (parsed by the classic
402
444
  * definitions, no flags) and overlay ONLY the keys the host file owns. Every
403
445
  * other key — including the ones the classic command carries as `undefined`,
404
446
  * such as `dbPath` — reaches the service exactly as on the classic path. No
405
447
  * cast: a key the classic shape has and this object lacks is a type error.
448
+ * An argument of this invocation (`passed`) wins over the host file.
406
449
  */
407
- async function toSwitchboardArgs(host, devMode, composed) {
450
+ async function toSwitchboardArgs(host, devMode, composed, passed) {
408
451
  const classic = await classicSwitchboardArgs();
409
452
  const runner = host.runner;
410
453
  return {
411
454
  ...classic,
412
- port: runner.port ?? classic.port,
455
+ port: passed.port ?? runner.port ?? classic.port,
456
+ dbPath: passed.dbPath ?? classic.dbPath,
457
+ httpsKeyFile: passed.httpsKeyFile ?? classic.httpsKeyFile,
458
+ httpsCertFile: passed.httpsCertFile ?? classic.httpsCertFile,
413
459
  dev: switchboardDevMode(devMode, runner) ? true : classic.dev,
414
460
  mcp: composed ? void 0 : classic.mcp
415
461
  };
@@ -545,14 +591,20 @@ async function start(host, ctx, devMode) {
545
591
  prepareMemberStorage(host.reactor, env.shell, hostFile);
546
592
  const legacyStore = readModelAsReactorStore(host.reactor, env.shell, hostFile);
547
593
  if (legacyStore) console.warn(legacyStore.warning);
594
+ const workflowsBoolean = reactorWorkflowsDeprecation(host.reactor, hostFile, "@powerhousedao/switchboard/plugins/workflows");
595
+ if (workflowsBoolean) console.warn(workflowsBoolean);
596
+ const { loadObservability } = await import("../observability-CrfdAtHw.mjs");
597
+ const observability = await loadObservability();
598
+ if (!ctx.parent) observability?.installObservabilitySignals();
548
599
  const { startSwitchboard } = await import("../services/switchboard.mjs");
549
600
  const entries = host.runner.plugins;
550
601
  const entriesDeclared = entries !== void 0;
551
- const classic = await toSwitchboardArgs(host, devMode, entriesDeclared);
602
+ const passed = await invocationArgsOf(ctx, hostFile);
603
+ const classic = await toSwitchboardArgs(host, devMode, entriesDeclared, passed);
552
604
  const { https } = classic;
553
605
  const args = {
554
606
  ...classic,
555
- https: void 0
607
+ https: passed.https
556
608
  };
557
609
  const memberConfig = await memberSwitchboardConfig(host, env, {
558
610
  pluginHost: entriesDeclared,
@@ -568,12 +620,18 @@ async function start(host, ctx, devMode) {
568
620
  }));
569
621
  const contributedDrives = pluginDrives(ctx.projectRoot, hostDrives, pluginComposition, `hosts/${host.name}/host.js`);
570
622
  const planned = [...hostDrives, ...contributedDrives];
571
- const remoteDrives = planned.map((p) => p.drive).flatMap((d) => d.kind === "remote" && d.remoteUrl ? [d.remoteUrl] : []);
623
+ const remoteDrives = [
624
+ ...planned.map((p) => p.drive).flatMap((d) => d.kind === "remote" && d.remoteUrl ? [d.remoteUrl] : []),
625
+ ...passed.remoteDrives ?? [],
626
+ ...passed.remoteDrive ? [passed.remoteDrive] : []
627
+ ];
628
+ const strictPort = passed.strictPort ?? host.runner.strictPort;
572
629
  const serverArgs = {
573
630
  ...args,
574
631
  ...pluginComposition ? { pluginComposition } : {},
575
632
  ...hostDrives.length > 0 ? { drive: void 0 } : {},
576
633
  ...remoteDrives.length > 0 ? { remoteDrives } : {},
634
+ ...strictPort === void 0 ? {} : { strictPort },
577
635
  ...ctx.parent ? { signalHandlers: false } : {}
578
636
  };
579
637
  let seeded;
@@ -594,7 +652,10 @@ async function start(host, ctx, devMode) {
594
652
  const switchboard = await startSwitchboard({
595
653
  ...serverArgs,
596
654
  readyAfter
597
- }, void 0, memberConfig);
655
+ }, void 0, memberConfig).catch(async (error) => {
656
+ await observability?.reportBootFailure(error);
657
+ throw error;
658
+ });
598
659
  const progress = switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== "false" ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {
599
660
  stdout: process.stdout,
600
661
  stderr: process.stderr,
@@ -640,6 +701,13 @@ async function start(host, ctx, devMode) {
640
701
  ready.catch(() => void 0);
641
702
  const graphql = `${origin}/graphql`;
642
703
  let stopping;
704
+ const stop = async () => {
705
+ try {
706
+ await switchboard.shutdown();
707
+ } finally {
708
+ await observability?.flushObservability();
709
+ }
710
+ };
643
711
  return {
644
712
  outputs: outputsSchema.parse({
645
713
  origin,
@@ -652,7 +720,7 @@ async function start(host, ctx, devMode) {
652
720
  ready,
653
721
  shutdown: () => {
654
722
  progress?.stop();
655
- return stopping ??= switchboard.shutdown();
723
+ return stopping ??= stop();
656
724
  }
657
725
  };
658
726
  }
@@ -668,6 +736,21 @@ const verbs = [
668
736
  async function dev(host, ctx) {
669
737
  return start(host, ctx, true);
670
738
  }
739
+ /** The stores `run` would open for this host: the same env split and member
740
+ * config as `start`, whose args name no store (`dbPath` is unset without
741
+ * flags). Starts nothing and creates nothing. */
742
+ async function resolveStores(host, ctx) {
743
+ const hostFile = `hosts/${host.name}/host.js`;
744
+ const env = memberEnvOf(ctx.env);
745
+ const config = await memberSwitchboardConfig(host, env, { pluginHost: host.runner.plugins !== void 0 });
746
+ const noDatabase = missingPostgresUrl(host.reactor, config, hostFile);
747
+ if (noDatabase) throw new Error(noDatabase);
748
+ return {
749
+ reactor: config.storage?.reactor?.url,
750
+ readModel: config.storage?.readModel?.url,
751
+ userDataDir: config.storage?.userDataDir
752
+ };
753
+ }
671
754
  /** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */
672
755
  async function checkBoot(host, ctx) {
673
756
  const env = memberEnvOf(ctx.env, ctx.projectRoot);
@@ -708,7 +791,7 @@ async function checkBoot(host, ctx) {
708
791
  return issues;
709
792
  }
710
793
  //#endregion
711
- export { checkBoot, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, switchboardDriveOutputSchema, verbs, waitForDrive };
794
+ export { argsSchema, checkBoot, declaredHostSchema, dev, hostSchema, invocationArgsOf, kind, outputsSchema, resolveStores, run, serve, switchboardDriveOutputSchema, verbs, waitForDrive };
712
795
 
713
796
  //# sourceMappingURL=switchboard.mjs.map
714
- //# debugId=22235455-173a-50c8-ac05-c56d3ed43f16
797
+ //# debugId=30f027d7-4932-5e43-9b68-9a06f98cbd73
@@ -1 +1 @@
1
- {"version":3,"file":"switchboard.mjs","sources":["../../src/services/run/memory-line.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["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 missingPostgresUrl,\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 { SwitchboardArgs } from \"../services/classic-args.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 { ensureDrive } = await import(\"@powerhousedao/switchboard/utils\");\n // One drive that cannot be made must not keep the server from starting\n try {\n await createDeclaredDrive(ensureDrive, 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 the one the reactor generated\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 || drive.slug);\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 ensureDrive: typeof SwitchboardUtils.ensureDrive,\n reactor: unknown,\n drive: ResolvedDrive,\n port: number,\n): Promise<void> {\n await ensureDrive(\n reactor as Parameters<typeof ensureDrive>[0],\n {\n ...(drive.id ? { id: drive.id } : {}),\n ...(drive.documentType ? { documentType: drive.documentType } : {}),\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 ensureDrive>[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 const noDatabase = missingPostgresUrl(host.reactor, memberConfig, hostFile);\n if (noDatabase) throw new Error(noDatabase);\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 ?? drive.slug,\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 { projectDriveId, seedWorkflowsDrive } =\n await import(\"../services/switchboard.js\");\n const url = await seeding(\n seedWorkflowsDrive(switchboard.reactor, port, ctx.projectRoot),\n );\n if (url) {\n drives.workflows = {\n id: projectDriveId(\"workflows\", ctx.projectRoot),\n url,\n };\n }\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 const verbs = [\"run\", \"serve\", \"dev\"];\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 noDatabase = missingPostgresUrl(host.reactor, config, ctx.file);\n if (noDatabase) {\n issues.push({ path: \"reactor.backends\", message: noDatabase });\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"],"names":[],"mappings":";;;;;;;;;AAMA,MAAM,KAAK;AAEX,SAAS,KAAK,OAAuB;CACnC,OAAO,SAAS,OAAO,KACnB,IAAI,SAAS,OAAO,IAAA,CAAK,QAAQ,CAAC,EAAE,OACpC,GAAG,KAAK,MAAM,QAAQ,EAAE,EAAE;AAChC;AAEA,SAAS,KAAK,UAAiC;CAC7C,IAAI,aAAa,MAAM,OAAO;CAC9B,MAAM,UAAU,KAAK,MAAM,QAAQ;CACnC,OAAO,KAAK,WAAW,IAAI,MAAM,KAAK,QAAQ;AAChD;AAEA,SAAS,OAAO,OAA4B;CAC1C,MAAM,SAAS,KAAK,MAAM,MAAM,MAAM;CACtC,MAAM,OACJ,KAAK,IAAI,MAAM,KAAK,MAAO,IAAI,SAAS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;EAChE,CAAC;EACD,OAAO;CACT;CACA,MAAM,aAAa,mBAAmB,KAAK,SAAS,QAAQ,IAAI,IAAI;CACpE,IAAI,YACF,OAAO,KAAK;EAAE,MAAM;EAAoB,SAAS;CAAW,CAAC;CAE/D,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","debug_id":"22235455-173a-50c8-ac05-c56d3ed43f16"}
1
+ {"version":3,"file":"switchboard.mjs","sources":["../../src/services/run/memory-line.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["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 RunnerError,\n type ResolvedPlugin,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport type { ParsedCmdResult } from \"@powerhousedao/shared/clis\";\nimport {\n commonServerArgs,\n switchboardArgs,\n vetraArgs,\n} from \"@powerhousedao/shared/clis/args\";\nimport { command, runSafely } from \"cmd-ts\";\nimport path from \"node:path\";\nimport {\n memberEnvOf,\n memberSwitchboardConfig,\n memberSwitchboardConfigSchema,\n missingPostgresUrl,\n prepareMemberStorage,\n reactorBlockConflicts,\n readModelAsReactorStore,\n switchboardDevMode,\n} from \"./member-config.js\";\nimport { reactorWorkflowsDeprecation } from \"./host-deprecations.js\";\nimport { onlyPassed, runnerArgsSchemaOf } from \"./runner-args.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 { SwitchboardArgs } from \"../services/classic-args.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 /** Fail on a taken port instead of moving to a free one. */\n strictPort: z.boolean().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/** What a switchboard accepts after `ph run <host> [verb]`: the classic\n * `ph switchboard` and `ph vetra` definitions of the same names. */\nconst invocationArgs = {\n port: switchboardArgs.port,\n strictPort: commonServerArgs.strictPort,\n dbPath: switchboardArgs.dbPath,\n https: switchboardArgs.https,\n httpsKeyFile: switchboardArgs.httpsKeyFile,\n httpsCertFile: switchboardArgs.httpsCertFile,\n remoteDrives: switchboardArgs.remoteDrives,\n remoteDrive: vetraArgs.remoteDrive,\n // Read by the ph-cli runner, for the codegen processor of a vetra host.\n interactive: vetraArgs.interactive,\n // Read by the `reset` verb.\n yes: switchboardArgs.yes,\n};\n\nconst invocation = command({\n name: \"switchboard\",\n args: invocationArgs,\n handler: (args) => args,\n});\n\nexport type InvocationArgs = ParsedCmdResult<typeof invocation>;\n\nconst WATCH_RETIRED = \"it is no longer needed.\";\n\nexport const argsSchema = runnerArgsSchemaOf(invocationArgs, {\n // `ph vetra --switchboard-port`\n memberOptions: { \"--switchboard-port\": \"--port\" },\n retired: {\n \"--watch\": WATCH_RETIRED,\n \"-w\": WATCH_RETIRED,\n \"--disable-connect\": \"use `ph run switchboard dev` instead.\",\n },\n});\n\n/** This invocation's arguments (`ctx.argv`), parsed by the classic\n * definitions; only the ones passed. */\nexport async function invocationArgsOf(\n ctx: RunnerContext,\n hostFile: string,\n): Promise<Partial<InvocationArgs>> {\n const argv = [...(ctx.argv ?? [])];\n if (argv.length === 0) return {};\n const result = await runSafely(invocation, argv);\n if (result._tag === \"error\") {\n throw new RunnerError(`${hostFile}: ${result.error.config.message}`);\n }\n return onlyPassed(result.value, invocationArgs, argv);\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 * An argument of this invocation (`passed`) wins over the host file.\n */\nasync function toSwitchboardArgs(\n host: SwitchboardHostParsed,\n devMode: boolean,\n composed: boolean,\n passed: Partial<InvocationArgs>,\n): Promise<SwitchboardRunnerArgs> {\n const classic = await classicSwitchboardArgs();\n const runner = host.runner;\n return {\n ...classic,\n port: passed.port ?? runner.port ?? classic.port,\n dbPath: passed.dbPath ?? classic.dbPath,\n httpsKeyFile: passed.httpsKeyFile ?? classic.httpsKeyFile,\n httpsCertFile: passed.httpsCertFile ?? classic.httpsCertFile,\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 { ensureDrive } = await import(\"@powerhousedao/switchboard/utils\");\n // One drive that cannot be made must not keep the server from starting\n try {\n await createDeclaredDrive(ensureDrive, 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 the one the reactor generated\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 || drive.slug);\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 ensureDrive: typeof SwitchboardUtils.ensureDrive,\n reactor: unknown,\n drive: ResolvedDrive,\n port: number,\n): Promise<void> {\n await ensureDrive(\n reactor as Parameters<typeof ensureDrive>[0],\n {\n ...(drive.id ? { id: drive.id } : {}),\n ...(drive.documentType ? { documentType: drive.documentType } : {}),\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 ensureDrive>[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 workflowsBoolean = reactorWorkflowsDeprecation(\n host.reactor,\n hostFile,\n \"@powerhousedao/switchboard/plugins/workflows\",\n );\n if (workflowsBoolean) console.warn(workflowsBoolean);\n // Already loaded by `ph run`, before the host; here for a caller that\n // starts the runner itself, and to reach its flush.\n const { loadObservability } = await import(\"../services/observability.js\");\n const observability = await loadObservability();\n // Standalone, a signal flushes telemetry and exits, as in the switchboard\n // bin. A compound owns the signals and the exit: its members flush from\n // shutdown() below.\n if (!ctx.parent) observability?.installObservabilitySignals();\n const { startSwitchboard } = await import(\"../services/switchboard.js\");\n const entries = host.runner.plugins;\n const entriesDeclared = entries !== undefined;\n const passed = await invocationArgsOf(ctx, hostFile);\n const classic = await toSwitchboardArgs(\n host,\n devMode,\n entriesDeclared,\n passed,\n );\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. `--https` is a flag.\n const { https } = classic;\n const args = { ...classic, https: passed.https };\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 const noDatabase = missingPostgresUrl(host.reactor, memberConfig, hostFile);\n if (noDatabase) throw new Error(noDatabase);\n\n // R2 step 2: a declared composition is resolved here, against the PROJECT\n // dependency tree, and `features.pluginHost: true` tells the server to boot\n // it. No plugins key = nothing to resolve: the server boots its default\n // composition (the subsystems MCP_ENABLED, PH_WORKFLOWS_ENABLED and the\n // config file turn on), which contributes no drives through this runner.\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 // `--remote-drives` and vetra's `--remote-drive` add to the declared ones.\n const remoteDrives = [\n ...resolvedDrives.flatMap((d) =>\n d.kind === \"remote\" && d.remoteUrl ? [d.remoteUrl] : [],\n ),\n ...(passed.remoteDrives ?? []),\n ...(passed.remoteDrive ? [passed.remoteDrive] : []),\n ];\n const strictPort = passed.strictPort ?? host.runner.strictPort;\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 ...(strictPort === undefined ? {} : { strictPort }),\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 ).catch(async (error: unknown) => {\n // The bin's boot failure: captured and flushed before the exit.\n await observability?.reportBootFailure(error);\n throw error;\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 ?? drive.slug,\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 { projectDriveId, seedWorkflowsDrive } =\n await import(\"../services/switchboard.js\");\n const url = await seeding(\n seedWorkflowsDrive(switchboard.reactor, port, ctx.projectRoot),\n );\n if (url) {\n drives.workflows = {\n id: projectDriveId(\"workflows\", ctx.projectRoot),\n url,\n };\n }\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 // Telemetry flushes after the drain, so the drain's own spans are sent.\n let stopping: Promise<void> | undefined;\n const stop = async () => {\n try {\n await switchboard.shutdown();\n } finally {\n await observability?.flushObservability();\n }\n };\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 ??= stop());\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 const verbs = [\"run\", \"serve\", \"dev\"];\n\nexport async function dev(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, true);\n}\n\n/** Where a started switchboard keeps its two stores: a Postgres url or a\n * PGlite dir each; undefined is the server's default dir under `.ph`. */\nexport interface SwitchboardStores {\n reactor: string | undefined;\n readModel: string | undefined;\n /** The relocated `.ph` root the default dirs sit under. */\n userDataDir: string | undefined;\n}\n\n/** The stores `run` would open for this host: the same env split and member\n * config as `start`, whose args name no store (`dbPath` is unset without\n * flags). Starts nothing and creates nothing. */\nexport async function resolveStores(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardStores> {\n const hostFile = `hosts/${host.name}/host.js`;\n const env = memberEnvOf(ctx.env);\n const config = await memberSwitchboardConfig(host, env, {\n pluginHost: host.runner.plugins !== undefined,\n });\n const noDatabase = missingPostgresUrl(host.reactor, config, hostFile);\n if (noDatabase) throw new Error(noDatabase);\n return {\n reactor: config.storage?.reactor?.url,\n readModel: config.storage?.readModel?.url,\n userDataDir: config.storage?.userDataDir,\n };\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 noDatabase = missingPostgresUrl(host.reactor, config, ctx.file);\n if (noDatabase) {\n issues.push({ path: \"reactor.backends\", message: noDatabase });\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"],"names":[],"mappings":";;;;;;;;;;;;AAMA,MAAM,KAAK;AAEX,SAAS,KAAK,OAAuB;CACnC,OAAO,SAAS,OAAO,KACnB,IAAI,SAAS,OAAO,IAAA,CAAK,QAAQ,CAAC,EAAE,OACpC,GAAG,KAAK,MAAM,QAAQ,EAAE,EAAE;AAChC;AAEA,SAAS,KAAK,UAAiC;CAC7C,IAAI,aAAa,MAAM,OAAO;CAC9B,MAAM,UAAU,KAAK,MAAM,QAAQ;CACnC,OAAO,KAAK,WAAW,IAAI,MAAM,KAAK,QAAQ;AAChD;AAEA,SAAS,OAAO,OAA4B;CAC1C,MAAM,SAAS,KAAK,MAAM,MAAM,MAAM;CACtC,MAAM,OACJ,KAAK,IAAI,MAAM,KAAK,MAAO,IAAI,SAAS,IAAA,CAAM,QAAQ,CAAC,EAAE,KAAK,GAAG;CACnE,OAAO,GAAG,MAAM,MAAM,GAAG,UAAU,IAAI,MAAM,KAAK,KAAK;AACzD;AAEA,SAAS,OAAO,QAA8B;CAC5C,IAAI,QAAQ;CACZ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UACpB,MACA,KACsB;CAEtB,MAAM,MAAM,YAAY,IAAI,KAAK,IAAI,WAAW;CAChD,MAAM,SAAsB,kBAC1B,KAAK,SAAS,UACd,IAAI,OACJ,IAAI,IACN,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,aAAa,mBAAmB,KAAK,SAAS,QAAQ,IAAI,IAAI;CACpE,IAAI,YACF,OAAO,KAAK;EAAE,MAAM;EAAoB,SAAS;CAAW,CAAC;CAE/D,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","debug_id":"30f027d7-4932-5e43-9b68-9a06f98cbd73"}
@@ -1,3 +1,3 @@
1
- import { n as SwitchboardArgs, r as classicSwitchboardArgs, t as ConnectPreviewArgs } from "../classic-args-Dm0_3O5p.mjs";
2
- export { ConnectPreviewArgs, SwitchboardArgs, classicSwitchboardArgs };
1
+ import { i as classicSwitchboardArgs, n as SwitchboardArgs, r as classicConnectPreviewArgs, t as ConnectPreviewArgs } from "../classic-args-BKI4gEVD.mjs";
2
+ export { ConnectPreviewArgs, SwitchboardArgs, classicConnectPreviewArgs, classicSwitchboardArgs };
3
3
  export {};
@@ -1,4 +1,4 @@
1
- import { t as classicSwitchboardArgs } from "../classic-args-BYccyIIC.mjs";
2
- export { classicSwitchboardArgs };
3
- !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]="1a9483b2-e70b-583b-b445-a26ef3d57a1c")}catch(e){}}();
4
- //# debugId=1a9483b2-e70b-583b-b445-a26ef3d57a1c
1
+ import { n as classicSwitchboardArgs, t as classicConnectPreviewArgs } from "../classic-args-BJMDXYLJ.mjs";
2
+ export { classicConnectPreviewArgs, classicSwitchboardArgs };
3
+ !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]="d7bcfffb-7f61-567b-8931-04fade316a1e")}catch(e){}}();
4
+ //# debugId=d7bcfffb-7f61-567b-8931-04fade316a1e
@@ -1,3 +1,3 @@
1
- import { a as cacheHeaders, c as overrideFromEnv, d as previewCacheControl, f as resolvePreviewBase, h as stripBase, i as assertConnectBuild, l as patchCspScriptSrc, m as shellSwapFor, n as ConnectServeOverride, o as connectBaseOf, p as serveOverrideStep, r as PRECOMPRESS_EXTENSIONS, s as isProxiedRequest, t as ConnectMiddleware, u as precompressedAssets } from "../connect-serve-COWXf_41.mjs";
1
+ import { a as cacheHeaders, c as overrideFromEnv, d as previewCacheControl, f as resolvePreviewBase, h as stripBase, i as assertConnectBuild, l as patchCspScriptSrc, m as shellSwapFor, n as ConnectServeOverride, o as connectBaseOf, p as serveOverrideStep, r as PRECOMPRESS_EXTENSIONS, s as isProxiedRequest, t as ConnectMiddleware, u as precompressedAssets } from "../connect-serve-kfNeXmO2.mjs";
2
2
  export { ConnectMiddleware, ConnectServeOverride, PRECOMPRESS_EXTENSIONS, assertConnectBuild, cacheHeaders, connectBaseOf, isProxiedRequest, overrideFromEnv, patchCspScriptSrc, precompressedAssets, previewCacheControl, resolvePreviewBase, serveOverrideStep, shellSwapFor, stripBase };
3
3
  export {};
@@ -1,4 +1,4 @@
1
- import { a as isProxiedRequest, c as precompressedAssets, d as serveOverrideStep, f as shellSwapFor, i as connectBaseOf, l as previewCacheControl, n as assertConnectBuild, o as overrideFromEnv, p as stripBase, r as cacheHeaders, s as patchCspScriptSrc, t as PRECOMPRESS_EXTENSIONS, u as resolvePreviewBase } from "../connect-serve-1WAi0KJL.mjs";
1
+ import { a as isProxiedRequest, c as precompressedAssets, d as serveOverrideStep, f as shellSwapFor, i as connectBaseOf, l as previewCacheControl, n as assertConnectBuild, o as overrideFromEnv, p as stripBase, r as cacheHeaders, s as patchCspScriptSrc, t as PRECOMPRESS_EXTENSIONS, u as resolvePreviewBase } from "../connect-serve-TZFWyrHe.mjs";
2
2
  export { PRECOMPRESS_EXTENSIONS, assertConnectBuild, cacheHeaders, connectBaseOf, isProxiedRequest, overrideFromEnv, patchCspScriptSrc, precompressedAssets, previewCacheControl, resolvePreviewBase, serveOverrideStep, shellSwapFor, stripBase };
3
- !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]="c740d281-162b-5921-8086-fae159dcfaa6")}catch(e){}}();
4
- //# debugId=c740d281-162b-5921-8086-fae159dcfaa6
3
+ !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]="7d9daacd-8b49-5dde-8540-b9909a31ad2b")}catch(e){}}();
4
+ //# debugId=7d9daacd-8b49-5dde-8540-b9909a31ad2b
@@ -1,5 +1,5 @@
1
- import { t as ConnectPreviewArgs } from "../classic-args-Dm0_3O5p.mjs";
2
- import { n as ConnectServeOverride } from "../connect-serve-COWXf_41.mjs";
1
+ import { t as ConnectPreviewArgs } from "../classic-args-BKI4gEVD.mjs";
2
+ import { n as ConnectServeOverride } from "../connect-serve-kfNeXmO2.mjs";
3
3
  //#region src/services/connect-server.d.ts
4
4
  /**
5
5
  * Serves a built Connect with what a running app has anyway. The other way to
@@ -15,8 +15,9 @@ export interface ConnectServer {
15
15
  };
16
16
  close(): Promise<void>;
17
17
  }
18
- /** The hosts a browser may reach this by: a rebinding attack needs a name. */
19
- export declare function isAllowedHost(hostHeader: string | undefined): boolean;
18
+ /** The hosts a browser may reach this by: a rebinding attack needs a name.
19
+ * This computer's own names, and the one name the environment adds. */
20
+ export declare function isAllowedHost(hostHeader: string | undefined, env?: Record<string, string | undefined>): boolean;
20
21
  export declare function runConnectServer(args: ConnectPreviewArgs, serveOverride?: ConnectServeOverride, dirname?: string, { proxy }?: {
21
22
  /** The switchboard origin whose paths this server proxies (runner.proxy). */
22
23
  proxy?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"connect-server.d.mts","names":[],"sources":["../../src/services/connect-server.ts"],"mappings":";;;;;;;;;;iBAqCiB;EACf;IAAgB;IAAiB;;EACjC,SAAS;;;wBAIK,cAAc;wBAsMR,iBACpB,MAAM,oBACN,gBAAgB,sBAChB,oBAEE;;EAGA;IAED,QAAQ"}
1
+ {"version":3,"file":"connect-server.d.mts","names":[],"sources":["../../src/services/connect-server.ts"],"mappings":";;;;;;;;;;iBAqCiB;EACf;IAAgB;IAAiB;;EACjC,SAAS;;;;wBASK,cACd,gCACA,MAAK;wBAkNe,iBACpB,MAAM,oBACN,gBAAgB,sBAChB,oBAEE;;EAGA;IAED,QAAQ"}
@@ -1,6 +1,6 @@
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]="5e8d8724-35d4-59a8-b0be-fd13032d99f5")}catch(e){}}();
3
- import { a as isProxiedRequest, c as precompressedAssets, d as serveOverrideStep, f as shellSwapFor, i as connectBaseOf, n as assertConnectBuild, o as overrideFromEnv, r as cacheHeaders } from "../connect-serve-1WAi0KJL.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]="033dc401-9c8e-5a4c-804a-1bd41290dfa9")}catch(e){}}();
3
+ import { a as isProxiedRequest, c as precompressedAssets, d as serveOverrideStep, f as shellSwapFor, i as connectBaseOf, n as assertConnectBuild, o as overrideFromEnv, r as cacheHeaders } from "../connect-serve-TZFWyrHe.mjs";
4
4
  import { isHtmlNavigation } from "@powerhousedao/shared/connect/origin-placeholder";
5
5
  import path from "node:path";
6
6
  import { existsSync } from "node:fs";
@@ -10,11 +10,19 @@ import { request as request$1 } from "node:https";
10
10
  import net from "node:net";
11
11
  import tls from "node:tls";
12
12
  //#region src/services/connect-server.ts
13
- /** The hosts a browser may reach this by: a rebinding attack needs a name. */
14
- function isAllowedHost(hostHeader) {
13
+ /** The public name a deployment serves this under, in the variable
14
+ * `vite preview` reads for the same purpose. */
15
+ const ADDITIONAL_HOST_ENV = "__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS";
16
+ /** The hosts a browser may reach this by: a rebinding attack needs a name.
17
+ * This computer's own names, and the one name the environment adds. */
18
+ function isAllowedHost(hostHeader, env = process.env) {
15
19
  if (!hostHeader) return false;
16
20
  const name = hostHeader.replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
17
- return name === "localhost" || name.endsWith(".localhost") || net.isIP(name) !== 0;
21
+ if (name === "localhost" || name.endsWith(".localhost") || net.isIP(name) !== 0) return true;
22
+ const added = env[ADDITIONAL_HOST_ENV]?.trim().toLowerCase();
23
+ if (!added) return false;
24
+ const asked = name.toLowerCase();
25
+ return added.startsWith(".") ? asked === added.slice(1) || asked.endsWith(added) : asked === added;
18
26
  }
19
27
  const hostCheck = (req, res, next) => {
20
28
  if (isAllowedHost(req.headers.host)) {
@@ -216,4 +224,4 @@ async function runConnectServer(args, serveOverride, dirname = process.cwd(), {
216
224
  export { isAllowedHost, runConnectServer };
217
225
 
218
226
  //# sourceMappingURL=connect-server.mjs.map
219
- //# debugId=5e8d8724-35d4-59a8-b0be-fd13032d99f5
227
+ //# debugId=033dc401-9c8e-5a4c-804a-1bd41290dfa9