@powerhousedao/ph-cli 6.2.3-dev.76 → 6.2.3-dev.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -10,7 +10,7 @@ import { phCliHelpCommands } from "@powerhousedao/shared/clis/args";
10
10
  import { bold, yellow } from "colorette";
11
11
  //#region src/get-version.ts
12
12
  function getVersion() {
13
- return "6.2.3-dev.76";
13
+ return "6.2.3-dev.77";
14
14
  }
15
15
  //#endregion
16
16
  //#region src/utils/constants.ts
@@ -1 +1 @@
1
- {"version":3,"file":"connect.d.mts","names":[],"sources":["../../src/runners/connect.ts"],"mappings":";;;;;;;;;qBAwCa;qBA+BA,oBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAA6B;qBAC/C,YAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAiBrB,IACpB,MAAM,mBACN,KAAK,gBACJ,QAAQ,aAAa;;;qBAgBX,YAAG;;wBAGM,MACpB,MAAM,mBACN,KAAK,gBACJ;;;;;;;;;wBAuBmB,MACpB,MAAM,mBACN,KAAK,gBACJ,QAAQ,aAAa"}
@@ -1,5 +1,5 @@
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]="7cd9d76a-0126-553f-ac1f-1cdb2d9cc69e")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bc999a09-5124-54df-901c-a561fbab3730")}catch(e){}}();
3
3
  import { c as strictObject, f as url, i as literal, l as string, r as boolean, u as union } from "../schemas-D5N5U_Mf.mjs";
4
4
  import { _ as findDeadConnectConfig, f as defineHostSchemas, h as entryActiveForVerb, j as normalizePluginEntries } from "../compound-Gjt5rBfF-BmSW1XPB.mjs";
5
5
  import { a as mergeDefaultDrives, c as projectDrivesIntoConnect, i as isStructuralMultiReactor, l as projectReactorToConnect, m as resolveDriveDeclaration, p as remoteBackendUrls } from "../dist-BVqNlv1z.mjs";
@@ -71,6 +71,7 @@ function toStudioArgs(host) {
71
71
  const runner = host.runner;
72
72
  return {
73
73
  port: runner.port ?? DEFAULT_CONNECT_STUDIO_PORT,
74
+ ...runner.host ? { host: runner.host } : {},
74
75
  open: runner.openBrowser === true,
75
76
  strictPort: runner.strictPort === true,
76
77
  printUrls: true,
@@ -272,4 +273,4 @@ async function serve(host, ctx) {
272
273
  export { build, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, withoutBuiltImages };
273
274
 
274
275
  //# sourceMappingURL=connect.mjs.map
275
- //# debugId=7cd9d76a-0126-553f-ac1f-1cdb2d9cc69e
276
+ //# debugId=bc999a09-5124-54df-901c-a561fbab3730
@@ -1 +1 @@
1
- {"version":3,"file":"connect.mjs","sources":["../../src/runners/connect.ts"],"sourcesContent":["import {\n DEFAULT_CONNECT_OUTDIR,\n DEFAULT_CONNECT_STUDIO_PORT,\n type PHConnectCompositionEntry,\n type PHConnectDefaultDrive,\n type PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport { connectConfigSchemaWith } from \"@powerhousedao/shared/connect/connect-config-schema\";\nimport { isPassthroughImageRef } from \"@powerhousedao/shared/connect/image-ref\";\nimport {\n defineHostSchemas,\n entryActiveForVerb,\n findDeadConnectConfig,\n isStructuralMultiReactor,\n mergeDefaultDrives,\n normalizePluginEntries,\n resolveDriveDeclaration,\n type DriveDeclaration,\n projectDrivesIntoConnect,\n projectReactorToConnect,\n remoteBackendUrls,\n type ReactorConfig,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\nimport type {\n ConnectBuildArgs,\n ConnectPreviewArgs,\n ConnectStudioArgs,\n} from \"../types.js\";\n\n/**\n * BRIDGE runner for Connect hosts (uniform-runners phase 0): maps a\n * hosts/connect/host.js definition onto the SAME service the classic\n * `ph connect studio` (dev/run), `ph connect build` and `ph connect preview`\n * (serve) commands call — no forked behavior.\n */\n\nexport const kind = \"reactor\";\n\n/** The connect host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails), and\n * `config` typed by Connect's own zod schema (the authored `connect` block),\n * whose URL fields that name another host's outputs\n * (`drives.defaultDrives[].url`, `renown.switchboardUrl`) are token-able.\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.extend({\n runner: s.runnerBaseSchema\n .extend({\n /** Open a browser tab once listening (dev/serve). */\n openBrowser: z.boolean().optional(),\n /** Fail instead of moving to the next free port when `port` is taken. */\n strictPort: z.boolean().optional(),\n /** The Connect build output dir (`build` writes it, `serve` serves it). */\n outDir: z.string().min(1).optional(),\n /** Patch the baked CSP for the runtime registry (`serve`); a\n * compound's wiring sets it on its connect member. */\n cspRegistrySync: z.boolean().optional(),\n /** The host's routes folder, project-relative; false for none.\n * Default: hosts/connect/routes. */\n routes: z.union([z.string(), z.literal(false)]).optional(),\n })\n .strict(),\n config: connectConfigSchemaWith(s.tokenable).optional(),\n }),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a connect host.js author writes. */\nexport type ConnectHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type ConnectHostParsed = z.output<typeof hostSchema>;\n\n/** What a started Connect (`dev`/`run`/`serve`) produces: the origin it\n * actually listens on and the app URL (origin plus base path). */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({ connect: z.url() }),\n});\nexport type ConnectOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/connect\": {\n host: ConnectHost;\n outputs: ConnectOutputs;\n };\n }\n}\n\n/** The slice of a vite dev/preview server a handle needs. */\ninterface ListeningServer {\n resolvedUrls: { local: string[] } | null;\n close(): Promise<void>;\n}\n\n/** A started Connect as a runner handle. vite has already listened when the\n * service returns, so `ready` is settled; the outputs carry the URL vite\n * resolved (the port it actually bound), falling back to the requested one. */\nfunction connectHandle(\n server: ListeningServer,\n requested: { host: string; port: number },\n): RunnerHandle<ConnectOutputs> {\n const fallback = `http://${requested.host}:${requested.port}/`;\n const app = server.resolvedUrls?.local[0] ?? fallback;\n let closing: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin: new URL(app).origin,\n endpoints: { connect: app },\n }),\n ready: Promise.resolve(),\n shutdown: () => (closing ??= server.close()),\n };\n}\n\n/** The studio arg surface is wide (commonArgs + server args); the service only\n * reads a known subset, and the repo's own tests build these objects the same\n * way (Partial + cast — see connect-build.test.ts `mk()`). */\nfunction toStudioArgs(host: ConnectHostParsed): ConnectStudioArgs {\n const runner = host.runner;\n const args: Partial<ConnectStudioArgs> = {\n port: runner.port ?? DEFAULT_CONNECT_STUDIO_PORT,\n open: runner.openBrowser === true,\n strictPort: runner.strictPort === true,\n printUrls: true,\n bindCLIShortcuts: false,\n };\n return args as ConnectStudioArgs;\n}\n\n/** Merge the reactor-block projection (protocol → connect.reactor,\n * backend kind → instance.reactorWorker, workflows → app.workflowsEnabled)\n * into the host's connect config, which rides the studio caller-override.\n * The host config wins on conflict (an explicit connect.* value is intent) —\n * EXCEPT structural multi-reactor (P4.2): declaring a remote backend next to\n * a local one IS the intent, so it beats a scaffold-default\n * instance.multiReactor: false, and the remote's drive url merges FIRST into\n * drives.defaultDrives (the first url entry is what the routing client dials). */\n/** host.js reactor.drives -> the served drives.defaultDrives shapes: locals\n * carry id/name/icon and the preferredEditor under its Connect alias `app`;\n * remotes carry their URL. */\nfunction declaredDrivesToDefaults(\n projectRoot: string,\n declarations: readonly DriveDeclaration[],\n): PHConnectDefaultDrive[] {\n return declarations.map((declaration) => {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n if (drive.kind === \"remote\") {\n return {\n url: drive.remoteUrl!,\n name: drive.name,\n icon: drive.icon ?? null,\n };\n }\n return {\n local: true as const,\n id: drive.id,\n name: drive.name,\n icon: drive.icon ?? null,\n ...(drive.preferredEditor ? { app: drive.preferredEditor } : {}),\n };\n });\n}\n\nfunction callerOverride(\n host: ConnectHostParsed,\n ctx?: RunnerContext,\n verb = \"dev\",\n): PHConnectRuntimeConfig | undefined {\n // A copy: the projection below adds served-only keys (composition, …).\n const base: PHConnectRuntimeConfig = { ...host.config };\n const reactor: ReactorConfig | undefined = host.reactor;\n\n // R3: the composition (verb-filtered, projected as DATA — the browser\n // pipeline resolves and runs the entries), declared drives, and the\n // reactor-core identity/namespace keys.\n const entries = host.runner.plugins;\n const composition: PHConnectCompositionEntry[] | undefined =\n entries === undefined\n ? undefined\n : normalizePluginEntries(entries, `hosts/${host.name}/host.js`)\n .filter((entry) => entryActiveForVerb(entry, verb))\n .map((entry) => ({ module: entry.module, config: entry.config }));\n // Entry configs arrive RESOLVED: output tokens (e.g. the workflows\n // plugin's `drive: switchboard.drives.workflows.url`) were replaced by\n // `ph run` (standalone: the producer's run record; in a compound: the\n // member's live outputs) before validateHost let this verb run.\n if (entries !== undefined) {\n // Change 2: show the composition plan on the `ph run connect` terminal.\n // The pipeline itself runs in the browser (hook execution logs to the\n // browser console); here we report WHAT will be served and for which verb.\n const all = normalizePluginEntries(entries, `hosts/${host.name}/host.js`);\n console.log(\n `[connect] composition plan (verb=${verb}): ${composition?.length ?? 0} active of ${all.length} declared`,\n );\n for (const entry of all) {\n const active = entryActiveForVerb(entry, verb);\n const scope =\n entry.verbs === \"*\" ? \"\" : ` verbs=[${entry.verbs.join(\",\")}]`;\n const cfg = Object.keys(entry.config);\n console.log(\n `[connect] ${active ? \"•\" : \"○\"} ${entry.module}${scope}` +\n (cfg.length ? ` config: {${cfg.join(\", \")}}` : \"\") +\n (active ? \"\" : \" (inactive for this verb)\"),\n );\n }\n }\n // Config a Connect plugin owns, set on the host while that plugin is not\n // composed for this verb: Connect serves the plugin-absent value instead.\n for (const warning of findDeadConnectConfig(\n host.config,\n entries,\n verb,\n `hosts/${host.name}/host.js`,\n )) {\n console.warn(warning.message);\n }\n const declared = reactor?.drives;\n const declaredDefaults =\n declared && ctx\n ? declaredDrivesToDefaults(ctx.projectRoot, declared)\n : undefined;\n const reactorRenown = reactor?.renown;\n const reactorNamespace = reactor?.namespace;\n base.drives = declaredDefaults\n ? {\n ...base.drives,\n defaultDrives: mergeDefaultDrives(\n declaredDefaults,\n base.drives?.defaultDrives ?? [],\n ),\n preserveStrategy: base.drives?.preserveStrategy ?? \"preserve-all\",\n }\n : base.drives;\n if (composition) base.composition = composition;\n if (reactorRenown) base.renown = { ...reactorRenown, ...base.renown };\n if (reactorNamespace !== undefined)\n base.instance = {\n ...base.instance,\n namespace: base.instance?.namespace ?? reactorNamespace,\n } as typeof base.instance;\n const { connect } = projectReactorToConnect(reactor);\n const structural = isStructuralMultiReactor(reactor);\n if (!connect.reactor && !connect.instance && !connect.app && !structural) {\n // `base` IS host.config when the host has one; a host without a config\n // block still carries its composition and drives (set on `base` above).\n // With none of the three, there is no override: a classic build.\n return host.config !== undefined || composition || declaredDefaults\n ? base\n : undefined;\n }\n const drives = structural\n ? projectDrivesIntoConnect({\n createdDriveUrls: remoteBackendUrls(reactor),\n configuredDefaultDrives: base.drives?.defaultDrives,\n }).drives\n : base.drives;\n // When the host DECLARES backends, instance facts derive from them and win\n // over config defaults (declaring `kind: \"worker\"` is more explicit intent\n // than a scaffold's `reactorWorker: false`); without backends the P2 rule\n // stands — an explicit connect.* value wins over descriptive projection.\n const declaresBackends = Object.keys(reactor?.backends ?? {}).length > 0;\n const instance = declaresBackends\n ? {\n ...base.instance,\n ...connect.instance,\n ...(structural ? { multiReactor: true } : {}),\n }\n : { ...connect.instance, ...base.instance };\n return {\n ...base,\n reactor: { ...connect.reactor, ...base.reactor },\n instance: instance as never,\n app: { ...connect.app, ...base.app },\n ...(drives ? { drives: { ...base.drives, ...drives } } : {}),\n };\n}\n\n/**\n * Start a server; under a supervising compound (`ctx.parent`), drop the\n * process-exiting signal listeners it installed (vite's dev and preview\n * servers exit on SIGTERM): the compound owns the exit and stops members in\n * reverse dependency order through their handles.\n */\nasync function startUnderSupervisor<T>(\n ctx: RunnerContext,\n start: () => Promise<T>,\n): Promise<T> {\n if (!ctx.parent) return start();\n const signals = [\"SIGINT\", \"SIGTERM\"] as const;\n const before = new Map(\n signals.map((signal) => [signal, new Set(process.listeners(signal))]),\n );\n try {\n return await start();\n } finally {\n for (const signal of signals) {\n for (const listener of process.listeners(signal)) {\n if (!before.get(signal)?.has(listener)) {\n process.off(signal, listener);\n }\n }\n }\n }\n}\n\n/** Fail at `ph run`, naming the plugin and key, when a composed Connect\n * plugin's entry config does not match its schema. */\nasync function validateComposition(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<void> {\n const { validateConnectPluginConfigs } =\n await import(\"./connect-plugin-configs.js\");\n await validateConnectPluginConfigs(\n ctx.projectRoot,\n host.runner.plugins,\n ctx.verb,\n `hosts/${host.name}/host.js`,\n );\n}\n\n/** A project file the build resolved: the built dist has it (as icon.ico or\n * a data URI); served, its path would mean nothing. */\nfunction isBuiltImage(ref: unknown): boolean {\n const src =\n typeof ref === \"object\" && ref !== null && \"src\" in ref ? ref.src : ref;\n return typeof src === \"string\" && !isPassthroughImageRef(src);\n}\n\n// The served config keeps the build's images: the favicon and any branding\n// image given as a project path were resolved into the dist, and merged over\n// it a path would replace the built data URI with a URL that 404s.\nexport function withoutBuiltImages(config: PHConnectRuntimeConfig | undefined) {\n const branding = config?.branding;\n if (!branding) return config;\n const { favicon: _, ...served } = branding;\n if (isBuiltImage(served.icon)) delete served.icon;\n if (isBuiltImage(served.loader)) delete served.loader;\n return { ...config, branding: served };\n}\n\n// Per host: Studio and other hosts' dev servers run side by side in one project.\nconst viteCacheOf = (host: ConnectHostParsed, ctx: RunnerContext) =>\n join(\n ctx.projectRoot,\n \"node_modules\",\n `.vite-${host.name.replace(/[^\\w.-]/g, \"_\")}`,\n );\n\nexport async function dev(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<RunnerHandle<ConnectOutputs>> {\n await validateComposition(host, ctx);\n const { runConnectStudio } = await import(\"../services/connect-studio.js\");\n const args = toStudioArgs(host);\n const server = await startUnderSupervisor(ctx, () =>\n runConnectStudio(args, undefined, callerOverride(host, ctx, ctx.verb), {\n routes: host.runner.routes,\n cacheDir: viteCacheOf(host, ctx),\n }),\n );\n // vite's dev server binds its default host (\"localhost\") here.\n return connectHandle(server, { host: \"localhost\", port: args.port });\n}\n\n/** `run` is dev-studio until the plugin phases give hosts a production\n * runtime; `serve` (below) is the static production server. */\nexport const run = dev;\n\n/** P3.3 — `build`: the SAME service as classic `ph connect build`. */\nexport async function build(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<void> {\n await validateComposition(host, ctx);\n const { runConnectBuild } = await import(\"../services/connect-build.js\");\n const args: Partial<ConnectBuildArgs> = {\n // Classic `ph connect`'s default: `dist/` is the package `ph build` writes.\n outDir: host.runner.outDir ?? DEFAULT_CONNECT_OUTDIR,\n };\n // The host's config bakes in: its title, favicon, manifest, base path and loading shell.\n await runConnectBuild(\n args as ConnectBuildArgs,\n callerOverride(host, ctx, ctx.verb),\n { routes: host.runner.routes },\n );\n}\n\n/** P3.3 — `serve`: the SAME vite preview server as classic\n * `ph connect preview` (static serve of a built Connect; run `build` first).\n * The host's connect config (including a supervising compound's projected\n * drives and the reactor projection) rides a serve override: the baked\n * powerhouse.config.json merges with it at request time, and\n * `runner.cspRegistrySync` (set by the compound's wiring) patches the baked\n * CSP's script-src for the runtime registry — together these replace the\n * ph-win-desktop sidecar's hand-rolled static server (desktop shape). */\nexport async function serve(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<RunnerHandle<ConnectOutputs>> {\n await validateComposition(host, ctx);\n const { runConnectPreview } = await import(\"../services/connect-preview.js\");\n const runner = host.runner;\n const port = runner.port ?? DEFAULT_CONNECT_STUDIO_PORT;\n const bind = runner.host ?? \"127.0.0.1\";\n const args: Partial<ConnectPreviewArgs> = {\n port,\n outDir: runner.outDir ?? DEFAULT_CONNECT_OUTDIR,\n open: runner.openBrowser === true,\n strictPort: runner.strictPort === true,\n cors: true,\n printUrls: true,\n bindCLIShortcuts: false,\n // Explicit IPv4 loopback (runner.host overrides): vite's default\n // \"localhost\" can bind ::1 only on Windows, and a supervising shell\n // (ph-win) probes 127.0.0.1 — the sidecar this replaces bound 127.0.0.1.\n host: bind,\n };\n const override = withoutBuiltImages(callerOverride(host, ctx, ctx.verb));\n const server = await startUnderSupervisor(ctx, () =>\n runConnectPreview(args as ConnectPreviewArgs, {\n connect: override,\n cspRegistrySync: runner.cspRegistrySync === true,\n }),\n );\n return connectHandle(server, { host: bind, port });\n}\n"],"names":["z.boolean","z.string","z.union","z.literal","z.strictObject","z.url"],"mappings":";;;;;;;;;;;;;;;;AAwCA,MAAa,OAAO;;;;;;;;;AAUpB,MAAM,UAAU,mBAAmB,MACjC,EAAE,kBAAkB,OAAO;CACzB,QAAQ,EAAE,iBACP,OAAO;;EAEN,aAAaA,QAAU,CAAC,CAAC,SAAS;;EAElC,YAAYA,QAAU,CAAC,CAAC,SAAS;;EAEjC,QAAQC,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;;EAGnC,iBAAiBD,QAAU,CAAC,CAAC,SAAS;;;EAGtC,QAAQE,MAAQ,CAACD,OAAS,GAAGE,QAAU,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS;CAC3D,CAAC,CAAC,CACD,OAAO;CACV,QAAQ,wBAAwB,EAAE,SAAS,CAAC,CAAC,SAAS;AACxD,CAAC,CACH;AACA,MAAa,qBAAqB,QAAQ;AAC1C,MAAa,aAAa,QAAQ;;;AASlC,MAAa,gBAAgBC,aAAe;CAC1C,QAAQC,IAAM;CACd,WAAWD,aAAe,EAAE,SAASC,IAAM,EAAE,CAAC;AAChD,CAAC;;;;AAqBD,SAAS,cACP,QACA,WAC8B;CAC9B,MAAM,WAAW,UAAU,UAAU,KAAK,GAAG,UAAU,KAAK;CAC5D,MAAM,MAAM,OAAO,cAAc,MAAM,MAAM;CAC7C,IAAI;CACJ,OAAO;EACL,SAAS,cAAc,MAAM;GAC3B,QAAQ,IAAI,IAAI,GAAG,CAAC,CAAC;GACrB,WAAW,EAAE,SAAS,IAAI;EAC5B,CAAC;EACD,OAAO,QAAQ,QAAQ;EACvB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e;EAClC,MAAM;EACN,WAAW;EACX,kBAAkB;EAIlB,MAAM;CACR;CACA,MAAM,WAAW,mBAAmB,eAAe,MAAM,KAAK,IAAI,IAAI,CAAC;CAOvE,OAAO,cAAc,MANA,qBAAqB,WACxC,kBAAkB,MAA4B;EAC5C,SAAS;EACT,iBAAiB,OAAO,oBAAoB;CAC9C,CAAC,CACH,GAC6B;EAAE,MAAM;EAAM;CAAK,CAAC;AACnD","debug_id":"7cd9d76a-0126-553f-ac1f-1cdb2d9cc69e"}
1
+ {"version":3,"file":"connect.mjs","sources":["../../src/runners/connect.ts"],"sourcesContent":["import {\n DEFAULT_CONNECT_OUTDIR,\n DEFAULT_CONNECT_STUDIO_PORT,\n type PHConnectCompositionEntry,\n type PHConnectDefaultDrive,\n type PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport { connectConfigSchemaWith } from \"@powerhousedao/shared/connect/connect-config-schema\";\nimport { isPassthroughImageRef } from \"@powerhousedao/shared/connect/image-ref\";\nimport {\n defineHostSchemas,\n entryActiveForVerb,\n findDeadConnectConfig,\n isStructuralMultiReactor,\n mergeDefaultDrives,\n normalizePluginEntries,\n resolveDriveDeclaration,\n type DriveDeclaration,\n projectDrivesIntoConnect,\n projectReactorToConnect,\n remoteBackendUrls,\n type ReactorConfig,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\nimport type {\n ConnectBuildArgs,\n ConnectPreviewArgs,\n ConnectStudioArgs,\n} from \"../types.js\";\n\n/**\n * BRIDGE runner for Connect hosts (uniform-runners phase 0): maps a\n * hosts/connect/host.js definition onto the SAME service the classic\n * `ph connect studio` (dev/run), `ph connect build` and `ph connect preview`\n * (serve) commands call — no forked behavior.\n */\n\nexport const kind = \"reactor\";\n\n/** The connect host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails), and\n * `config` typed by Connect's own zod schema (the authored `connect` block),\n * whose URL fields that name another host's outputs\n * (`drives.defaultDrives[].url`, `renown.switchboardUrl`) are token-able.\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.extend({\n runner: s.runnerBaseSchema\n .extend({\n /** Open a browser tab once listening (dev/serve). */\n openBrowser: z.boolean().optional(),\n /** Fail instead of moving to the next free port when `port` is taken. */\n strictPort: z.boolean().optional(),\n /** The Connect build output dir (`build` writes it, `serve` serves it). */\n outDir: z.string().min(1).optional(),\n /** Patch the baked CSP for the runtime registry (`serve`); a\n * compound's wiring sets it on its connect member. */\n cspRegistrySync: z.boolean().optional(),\n /** The host's routes folder, project-relative; false for none.\n * Default: hosts/connect/routes. */\n routes: z.union([z.string(), z.literal(false)]).optional(),\n })\n .strict(),\n config: connectConfigSchemaWith(s.tokenable).optional(),\n }),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a connect host.js author writes. */\nexport type ConnectHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type ConnectHostParsed = z.output<typeof hostSchema>;\n\n/** What a started Connect (`dev`/`run`/`serve`) produces: the origin it\n * actually listens on and the app URL (origin plus base path). */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({ connect: z.url() }),\n});\nexport type ConnectOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/connect\": {\n host: ConnectHost;\n outputs: ConnectOutputs;\n };\n }\n}\n\n/** The slice of a vite dev/preview server a handle needs. */\ninterface ListeningServer {\n resolvedUrls: { local: string[] } | null;\n close(): Promise<void>;\n}\n\n/** A started Connect as a runner handle. vite has already listened when the\n * service returns, so `ready` is settled; the outputs carry the URL vite\n * resolved (the port it actually bound), falling back to the requested one. */\nfunction connectHandle(\n server: ListeningServer,\n requested: { host: string; port: number },\n): RunnerHandle<ConnectOutputs> {\n const fallback = `http://${requested.host}:${requested.port}/`;\n const app = server.resolvedUrls?.local[0] ?? fallback;\n let closing: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin: new URL(app).origin,\n endpoints: { connect: app },\n }),\n ready: Promise.resolve(),\n shutdown: () => (closing ??= server.close()),\n };\n}\n\n/** The studio arg surface is wide (commonArgs + server args); the service only\n * reads a known subset, and the repo's own tests build these objects the same\n * way (Partial + cast — see connect-build.test.ts `mk()`). */\nfunction toStudioArgs(host: ConnectHostParsed): ConnectStudioArgs {\n const runner = host.runner;\n const args: Partial<ConnectStudioArgs> = {\n port: runner.port ?? DEFAULT_CONNECT_STUDIO_PORT,\n // The bind address (runnerBaseSchema `host`); unset keeps vite's default.\n ...(runner.host ? { host: runner.host } : {}),\n open: runner.openBrowser === true,\n strictPort: runner.strictPort === true,\n printUrls: true,\n bindCLIShortcuts: false,\n };\n return args as ConnectStudioArgs;\n}\n\n/** Merge the reactor-block projection (protocol → connect.reactor,\n * backend kind → instance.reactorWorker, workflows → app.workflowsEnabled)\n * into the host's connect config, which rides the studio caller-override.\n * The host config wins on conflict (an explicit connect.* value is intent) —\n * EXCEPT structural multi-reactor (P4.2): declaring a remote backend next to\n * a local one IS the intent, so it beats a scaffold-default\n * instance.multiReactor: false, and the remote's drive url merges FIRST into\n * drives.defaultDrives (the first url entry is what the routing client dials). */\n/** host.js reactor.drives -> the served drives.defaultDrives shapes: locals\n * carry id/name/icon and the preferredEditor under its Connect alias `app`;\n * remotes carry their URL. */\nfunction declaredDrivesToDefaults(\n projectRoot: string,\n declarations: readonly DriveDeclaration[],\n): PHConnectDefaultDrive[] {\n return declarations.map((declaration) => {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n if (drive.kind === \"remote\") {\n return {\n url: drive.remoteUrl!,\n name: drive.name,\n icon: drive.icon ?? null,\n };\n }\n return {\n local: true as const,\n id: drive.id,\n name: drive.name,\n icon: drive.icon ?? null,\n ...(drive.preferredEditor ? { app: drive.preferredEditor } : {}),\n };\n });\n}\n\nfunction callerOverride(\n host: ConnectHostParsed,\n ctx?: RunnerContext,\n verb = \"dev\",\n): PHConnectRuntimeConfig | undefined {\n // A copy: the projection below adds served-only keys (composition, …).\n const base: PHConnectRuntimeConfig = { ...host.config };\n const reactor: ReactorConfig | undefined = host.reactor;\n\n // R3: the composition (verb-filtered, projected as DATA — the browser\n // pipeline resolves and runs the entries), declared drives, and the\n // reactor-core identity/namespace keys.\n const entries = host.runner.plugins;\n const composition: PHConnectCompositionEntry[] | undefined =\n entries === undefined\n ? undefined\n : normalizePluginEntries(entries, `hosts/${host.name}/host.js`)\n .filter((entry) => entryActiveForVerb(entry, verb))\n .map((entry) => ({ module: entry.module, config: entry.config }));\n // Entry configs arrive RESOLVED: output tokens (e.g. the workflows\n // plugin's `drive: switchboard.drives.workflows.url`) were replaced by\n // `ph run` (standalone: the producer's run record; in a compound: the\n // member's live outputs) before validateHost let this verb run.\n if (entries !== undefined) {\n // Change 2: show the composition plan on the `ph run connect` terminal.\n // The pipeline itself runs in the browser (hook execution logs to the\n // browser console); here we report WHAT will be served and for which verb.\n const all = normalizePluginEntries(entries, `hosts/${host.name}/host.js`);\n console.log(\n `[connect] composition plan (verb=${verb}): ${composition?.length ?? 0} active of ${all.length} declared`,\n );\n for (const entry of all) {\n const active = entryActiveForVerb(entry, verb);\n const scope =\n entry.verbs === \"*\" ? \"\" : ` verbs=[${entry.verbs.join(\",\")}]`;\n const cfg = Object.keys(entry.config);\n console.log(\n `[connect] ${active ? \"•\" : \"○\"} ${entry.module}${scope}` +\n (cfg.length ? ` config: {${cfg.join(\", \")}}` : \"\") +\n (active ? \"\" : \" (inactive for this verb)\"),\n );\n }\n }\n // Config a Connect plugin owns, set on the host while that plugin is not\n // composed for this verb: Connect serves the plugin-absent value instead.\n for (const warning of findDeadConnectConfig(\n host.config,\n entries,\n verb,\n `hosts/${host.name}/host.js`,\n )) {\n console.warn(warning.message);\n }\n const declared = reactor?.drives;\n const declaredDefaults =\n declared && ctx\n ? declaredDrivesToDefaults(ctx.projectRoot, declared)\n : undefined;\n const reactorRenown = reactor?.renown;\n const reactorNamespace = reactor?.namespace;\n base.drives = declaredDefaults\n ? {\n ...base.drives,\n defaultDrives: mergeDefaultDrives(\n declaredDefaults,\n base.drives?.defaultDrives ?? [],\n ),\n preserveStrategy: base.drives?.preserveStrategy ?? \"preserve-all\",\n }\n : base.drives;\n if (composition) base.composition = composition;\n if (reactorRenown) base.renown = { ...reactorRenown, ...base.renown };\n if (reactorNamespace !== undefined)\n base.instance = {\n ...base.instance,\n namespace: base.instance?.namespace ?? reactorNamespace,\n } as typeof base.instance;\n const { connect } = projectReactorToConnect(reactor);\n const structural = isStructuralMultiReactor(reactor);\n if (!connect.reactor && !connect.instance && !connect.app && !structural) {\n // `base` IS host.config when the host has one; a host without a config\n // block still carries its composition and drives (set on `base` above).\n // With none of the three, there is no override: a classic build.\n return host.config !== undefined || composition || declaredDefaults\n ? base\n : undefined;\n }\n const drives = structural\n ? projectDrivesIntoConnect({\n createdDriveUrls: remoteBackendUrls(reactor),\n configuredDefaultDrives: base.drives?.defaultDrives,\n }).drives\n : base.drives;\n // When the host DECLARES backends, instance facts derive from them and win\n // over config defaults (declaring `kind: \"worker\"` is more explicit intent\n // than a scaffold's `reactorWorker: false`); without backends the P2 rule\n // stands — an explicit connect.* value wins over descriptive projection.\n const declaresBackends = Object.keys(reactor?.backends ?? {}).length > 0;\n const instance = declaresBackends\n ? {\n ...base.instance,\n ...connect.instance,\n ...(structural ? { multiReactor: true } : {}),\n }\n : { ...connect.instance, ...base.instance };\n return {\n ...base,\n reactor: { ...connect.reactor, ...base.reactor },\n instance: instance as never,\n app: { ...connect.app, ...base.app },\n ...(drives ? { drives: { ...base.drives, ...drives } } : {}),\n };\n}\n\n/**\n * Start a server; under a supervising compound (`ctx.parent`), drop the\n * process-exiting signal listeners it installed (vite's dev and preview\n * servers exit on SIGTERM): the compound owns the exit and stops members in\n * reverse dependency order through their handles.\n */\nasync function startUnderSupervisor<T>(\n ctx: RunnerContext,\n start: () => Promise<T>,\n): Promise<T> {\n if (!ctx.parent) return start();\n const signals = [\"SIGINT\", \"SIGTERM\"] as const;\n const before = new Map(\n signals.map((signal) => [signal, new Set(process.listeners(signal))]),\n );\n try {\n return await start();\n } finally {\n for (const signal of signals) {\n for (const listener of process.listeners(signal)) {\n if (!before.get(signal)?.has(listener)) {\n process.off(signal, listener);\n }\n }\n }\n }\n}\n\n/** Fail at `ph run`, naming the plugin and key, when a composed Connect\n * plugin's entry config does not match its schema. */\nasync function validateComposition(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<void> {\n const { validateConnectPluginConfigs } =\n await import(\"./connect-plugin-configs.js\");\n await validateConnectPluginConfigs(\n ctx.projectRoot,\n host.runner.plugins,\n ctx.verb,\n `hosts/${host.name}/host.js`,\n );\n}\n\n/** A project file the build resolved: the built dist has it (as icon.ico or\n * a data URI); served, its path would mean nothing. */\nfunction isBuiltImage(ref: unknown): boolean {\n const src =\n typeof ref === \"object\" && ref !== null && \"src\" in ref ? ref.src : ref;\n return typeof src === \"string\" && !isPassthroughImageRef(src);\n}\n\n// The served config keeps the build's images: the favicon and any branding\n// image given as a project path were resolved into the dist, and merged over\n// it a path would replace the built data URI with a URL that 404s.\nexport function withoutBuiltImages(config: PHConnectRuntimeConfig | undefined) {\n const branding = config?.branding;\n if (!branding) return config;\n const { favicon: _, ...served } = branding;\n if (isBuiltImage(served.icon)) delete served.icon;\n if (isBuiltImage(served.loader)) delete served.loader;\n return { ...config, branding: served };\n}\n\n// Per host: Studio and other hosts' dev servers run side by side in one project.\nconst viteCacheOf = (host: ConnectHostParsed, ctx: RunnerContext) =>\n join(\n ctx.projectRoot,\n \"node_modules\",\n `.vite-${host.name.replace(/[^\\w.-]/g, \"_\")}`,\n );\n\nexport async function dev(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<RunnerHandle<ConnectOutputs>> {\n await validateComposition(host, ctx);\n const { runConnectStudio } = await import(\"../services/connect-studio.js\");\n const args = toStudioArgs(host);\n const server = await startUnderSupervisor(ctx, () =>\n runConnectStudio(args, undefined, callerOverride(host, ctx, ctx.verb), {\n routes: host.runner.routes,\n cacheDir: viteCacheOf(host, ctx),\n }),\n );\n // vite's dev server binds its default host (\"localhost\") here.\n return connectHandle(server, { host: \"localhost\", port: args.port });\n}\n\n/** `run` is dev-studio until the plugin phases give hosts a production\n * runtime; `serve` (below) is the static production server. */\nexport const run = dev;\n\n/** P3.3 — `build`: the SAME service as classic `ph connect build`. */\nexport async function build(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<void> {\n await validateComposition(host, ctx);\n const { runConnectBuild } = await import(\"../services/connect-build.js\");\n const args: Partial<ConnectBuildArgs> = {\n // Classic `ph connect`'s default: `dist/` is the package `ph build` writes.\n outDir: host.runner.outDir ?? DEFAULT_CONNECT_OUTDIR,\n };\n // The host's config bakes in: its title, favicon, manifest, base path and loading shell.\n await runConnectBuild(\n args as ConnectBuildArgs,\n callerOverride(host, ctx, ctx.verb),\n { routes: host.runner.routes },\n );\n}\n\n/** P3.3 — `serve`: the SAME vite preview server as classic\n * `ph connect preview` (static serve of a built Connect; run `build` first).\n * The host's connect config (including a supervising compound's projected\n * drives and the reactor projection) rides a serve override: the baked\n * powerhouse.config.json merges with it at request time, and\n * `runner.cspRegistrySync` (set by the compound's wiring) patches the baked\n * CSP's script-src for the runtime registry — together these replace the\n * ph-win-desktop sidecar's hand-rolled static server (desktop shape). */\nexport async function serve(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<RunnerHandle<ConnectOutputs>> {\n await validateComposition(host, ctx);\n const { runConnectPreview } = await import(\"../services/connect-preview.js\");\n const runner = host.runner;\n const port = runner.port ?? DEFAULT_CONNECT_STUDIO_PORT;\n const bind = runner.host ?? \"127.0.0.1\";\n const args: Partial<ConnectPreviewArgs> = {\n port,\n outDir: runner.outDir ?? DEFAULT_CONNECT_OUTDIR,\n open: runner.openBrowser === true,\n strictPort: runner.strictPort === true,\n cors: true,\n printUrls: true,\n bindCLIShortcuts: false,\n // Explicit IPv4 loopback (runner.host overrides): vite's default\n // \"localhost\" can bind ::1 only on Windows, and a supervising shell\n // (ph-win) probes 127.0.0.1 — the sidecar this replaces bound 127.0.0.1.\n host: bind,\n };\n const override = withoutBuiltImages(callerOverride(host, ctx, ctx.verb));\n const server = await startUnderSupervisor(ctx, () =>\n runConnectPreview(args as ConnectPreviewArgs, {\n connect: override,\n cspRegistrySync: runner.cspRegistrySync === true,\n }),\n );\n return connectHandle(server, { host: bind, port });\n}\n"],"names":["z.boolean","z.string","z.union","z.literal","z.strictObject","z.url"],"mappings":";;;;;;;;;;;;;;;;AAwCA,MAAa,OAAO;;;;;;;;;AAUpB,MAAM,UAAU,mBAAmB,MACjC,EAAE,kBAAkB,OAAO;CACzB,QAAQ,EAAE,iBACP,OAAO;;EAEN,aAAaA,QAAU,CAAC,CAAC,SAAS;;EAElC,YAAYA,QAAU,CAAC,CAAC,SAAS;;EAEjC,QAAQC,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;;EAGnC,iBAAiBD,QAAU,CAAC,CAAC,SAAS;;;EAGtC,QAAQE,MAAQ,CAACD,OAAS,GAAGE,QAAU,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS;CAC3D,CAAC,CAAC,CACD,OAAO;CACV,QAAQ,wBAAwB,EAAE,SAAS,CAAC,CAAC,SAAS;AACxD,CAAC,CACH;AACA,MAAa,qBAAqB,QAAQ;AAC1C,MAAa,aAAa,QAAQ;;;AASlC,MAAa,gBAAgBC,aAAe;CAC1C,QAAQC,IAAM;CACd,WAAWD,aAAe,EAAE,SAASC,IAAM,EAAE,CAAC;AAChD,CAAC;;;;AAqBD,SAAS,cACP,QACA,WAC8B;CAC9B,MAAM,WAAW,UAAU,UAAU,KAAK,GAAG,UAAU,KAAK;CAC5D,MAAM,MAAM,OAAO,cAAc,MAAM,MAAM;C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ACnC,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,MAAM,SAAS,KAAK;CACpB,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,OAAoC;EACxC;EACA,QAAQ,OAAO,UAAU;EACzB,MAAM,OAAO,gBAAgB;EAC7B,YAAY,OAAO,eAAe;EAClC,MAAM;EACN,WAAW;EACX,kBAAkB;EAIlB,MAAM;CACR;CACA,MAAM,WAAW,mBAAmB,eAAe,MAAM,KAAK,IAAI,IAAI,CAAC;CAOvE,OAAO,cAAc,MANA,qBAAqB,WACxC,kBAAkB,MAA4B;EAC5C,SAAS;EACT,iBAAiB,OAAO,oBAAoB;CAC9C,CAAC,CACH,GAC6B;EAAE,MAAM;EAAM;CAAK,CAAC;AACnD","debug_id":"bc999a09-5124-54df-901c-a561fbab3730"}
@@ -1,5 +1,5 @@
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]="884205e8-ae13-5449-b01d-d57c825d71ce")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5f04123a-704e-5014-a89f-94def3c07880")}catch(e){}}();
3
3
  import { c as strictObject, f as url, l as string$1, m as prettifyError, r as boolean$1, s as record } from "../schemas-D5N5U_Mf.mjs";
4
4
  import { G as resolveHostPlugins, f as defineHostSchemas, m as drivesSchema } from "../compound-Gjt5rBfF-BmSW1XPB.mjs";
5
5
  import { d as protocolConflicts, h as seedDrives, m as resolveDriveDeclaration, o as mergeDrivePlan, s as primaryBackend, t as assertProtocolConsistency, u as projectReactorToSwitchboard } from "../dist-BVqNlv1z.mjs";
@@ -119,6 +119,11 @@ function renderPriority(priority) {
119
119
  const why = priority.mode === "dynamic" ? `dynamic, ${priority.reason}` : "fixed";
120
120
  return `catch-up priority ${priority.level} (${why})`;
121
121
  }
122
+ /** The console width the bars are sized for: a reported width, else 80. */
123
+ function widthOf(stream) {
124
+ const columns = stream.columns;
125
+ return typeof columns === "number" && columns > 0 ? columns : 80;
126
+ }
122
127
  const DEFAULT_POLL_MS = 1e3;
123
128
  const DEFAULT_LINE_MS = 1e4;
124
129
  const MIN_BAR = 10;
@@ -131,18 +136,27 @@ function percent(row) {
131
136
  function fit(label, width) {
132
137
  return label.length <= width ? label.padEnd(width) : `…${label.slice(label.length - width + 1)}`;
133
138
  }
134
- /** The bar block, one line per row, sized to `columns`, under the priority when known. */
139
+ /**
140
+ * The bar block, one line per row, under the priority when known. Every line
141
+ * stays short of the terminal's last column: a line that fills it wraps on
142
+ * xterm-based terminals (VS Code, Windows Terminal), and the erase would then
143
+ * lift fewer lines than are on screen, leaving old bars behind. On a narrow
144
+ * terminal the label gives way before the bar.
145
+ */
135
146
  function renderBars(rows, columns, priority) {
136
- const labelWidth = Math.min(MAX_LABEL, Math.max(...rows.map((row) => row.label.length), 0));
137
- const barWidth = Math.max(MIN_BAR, columns - labelWidth - 12);
147
+ const width = Math.max(columns - 1, 1);
148
+ const fixed = 9;
149
+ const longest = Math.max(...rows.map((row) => row.label.length), 0);
150
+ const labelWidth = Math.max(1, Math.min(MAX_LABEL, longest, width - fixed - MIN_BAR));
151
+ const barWidth = Math.max(MIN_BAR, width - labelWidth - fixed);
138
152
  const bars = rows.map((row) => {
139
153
  const fraction = row.state === "done" ? 1 : row.fraction;
140
154
  const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);
141
155
  const bar = "█".repeat(filled) + "░".repeat(barWidth - filled);
142
- return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`;
156
+ return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`.slice(0, width);
143
157
  });
144
158
  if (!priority) return bars;
145
- return [renderPriority(priority).slice(0, Math.max(columns - 1, 1)), ...bars];
159
+ return [renderPriority(priority).slice(0, width), ...bars];
146
160
  }
147
161
  /** One line for a log without a TTY, listing only what is still catching up. */
148
162
  function renderLine(rows, priority) {
@@ -177,7 +191,7 @@ function startProgressDisplay(source, options) {
177
191
  };
178
192
  const draw = () => {
179
193
  if (!tty || stopped || !atLineStart || !busy(rows)) return;
180
- const lines = renderBars(rows, stdout.columns ?? 80, priority);
194
+ const lines = renderBars(rows, widthOf(stdout), priority);
181
195
  originalOut(`${lines.join("\n")}\n`);
182
196
  drawn = lines.length;
183
197
  };
@@ -189,9 +203,15 @@ function startProgressDisplay(source, options) {
189
203
  draw();
190
204
  return result;
191
205
  };
206
+ const onResize = () => {
207
+ if (stopped) return;
208
+ erase();
209
+ draw();
210
+ };
192
211
  if (tty) {
193
212
  stdout.write = above(originalOut);
194
213
  stderr.write = above(originalErr);
214
+ stdout.on?.("resize", onResize);
195
215
  }
196
216
  const tick = async () => {
197
217
  if (reading || stopped) return;
@@ -222,6 +242,7 @@ function startProgressDisplay(source, options) {
222
242
  clearInterval(timer);
223
243
  erase();
224
244
  if (tty) {
245
+ stdout.off?.("resize", onResize);
225
246
  stdout.write = restoreOut;
226
247
  stderr.write = restoreErr;
227
248
  }
@@ -496,4 +517,4 @@ async function build(host, _ctx) {
496
517
  export { build, checkBoot, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, switchboardDriveOutputSchema };
497
518
 
498
519
  //# sourceMappingURL=switchboard.mjs.map
499
- //# debugId=884205e8-ae13-5449-b01d-d57c825d71ce
520
+ //# debugId=5f04123a-704e-5014-a89f-94def3c07880
@@ -1 +1 @@
1
- {"version":3,"file":"switchboard.mjs","sources":["../../src/runners/reactor-env.ts","../../src/services/classic-args.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n assertProtocolConsistency,\n primaryBackend,\n projectReactorToSwitchboard,\n type ReactorConfig,\n} from \"@powerhousedao/host-core\";\n\n/** The reactor block as the switchboard boots with it: the vars `env` leaves unset, and dbPath. */\nexport function switchboardBootProjection(\n reactor: ReactorConfig | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): { env: Record<string, string>; dbPath?: string } {\n const { env: projected, options } = projectReactorToSwitchboard(reactor);\n const unset: Record<string, string> = {};\n for (const [name, value] of Object.entries(projected) as [\n string,\n unknown,\n ][]) {\n // A deferred $output token is not a value yet.\n if (env[name] === undefined && typeof value === \"string\")\n unset[name] = value;\n }\n return {\n env: unset,\n ...(options.dbPath !== undefined ? { dbPath: options.dbPath } : {}),\n };\n}\n\n/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */\nexport function switchboardDevMode(\n devVerb: boolean,\n runner: { dev?: boolean },\n): boolean {\n return devVerb || runner.dev === true;\n}\n\n/**\n * Apply a host's reactor block to the CURRENT process env, the way the\n * in-process switchboard server reads it at boot (D2.c: env derivation\n * immediately before the member starts; sequential boots make this safe).\n * Single-sourcing teeth first: a pre-set env contradicting the protocol block\n * fails loudly. Then set-if-absent, so an operator's explicit (agreeing) env\n * still wins during the transition. Returns the non-env options (dbPath).\n *\n * Lives OUTSIDE the runner modules on purpose: every export of a runner\n * module reads as a dispatchable verb, and this is not one.\n */\nexport function applyReactorEnvProjection(\n reactor: ReactorConfig | undefined,\n hostFileLabel: string,\n): { dbPath?: string } {\n assertProtocolConsistency(reactor?.protocol, process.env, hostFileLabel);\n const projection = switchboardBootProjection(reactor, process.env);\n Object.assign(process.env, projection.env);\n // A path-storage data dir must exist before the server boots — its own\n // mkdir is not recursive (the ph-win sidecar did this too).\n const storage = primaryBackend(reactor)?.storage;\n if (storage?.kind === \"path\" && storage.dataDir) {\n // `ph run` resolves `$env` and the `${userData}` sugar before the verb;\n // an unresolved one here would mkdir a literal \"${userData}\" folder.\n if (/\\$\\{(userData|projectRoot)\\}/.test(storage.dataDir)) {\n throw new Error(\n `${hostFileLabel}: storage.dataDir \"${storage.dataDir}\" was not resolved; resolve the host (resolveHostOutputs) before starting it.`,\n );\n }\n fs.mkdirSync(storage.dataDir, { recursive: true });\n }\n return projection.dbPath !== undefined ? { dbPath: projection.dbPath } : {};\n}\n","import { switchboardArgs } from \"@powerhousedao/shared/clis/args\";\nimport { command, runSafely } from \"cmd-ts\";\nimport type { SwitchboardArgs } from \"../types.js\";\n\n/**\n * The classic `ph switchboard` argument shape, produced by the SAME cmd-ts\n * definitions the classic command parses — not re-derived by hand. A runner\n * starts from this object and overlays only the keys its host file owns, so\n * every key the classic command carries (including the ones it carries as\n * `undefined`, e.g. `dbPath`) reaches the service exactly as it does on the\n * classic path. The uniform-runners switchboard runner once hand-built a\n * partial object that omitted `dbPath`; the service's then-default\n * `.ph/read-model.db` became both the reactor and the read-model PGlite dir —\n * two instances on one PGDATA (see uniform-runners-plan/legacy-parity-rectification.md).\n */\nconst classicSwitchboard = command({\n name: \"switchboard\",\n args: switchboardArgs,\n handler: (args) => args,\n});\n\nexport async function classicSwitchboardArgs(\n argv: string[] = [],\n): Promise<SwitchboardArgs> {\n const result = await runSafely(classicSwitchboard, argv);\n if (result._tag === \"error\") {\n throw new Error(\n `classic switchboard args did not parse: ${result.error.config.message}`,\n );\n }\n return result.value;\n}\n","import {\n computeProgress,\n type CatchUpPriorityState,\n type IInspector,\n type ReactorProgress,\n} from \"@powerhousedao/reactor\";\n\n/** One bar: a processor factory or a read model, and how far its catch-up has got. */\nexport type ProgressRow = {\n readonly label: string;\n /** 0..1 of the current run. */\n readonly fraction: number;\n readonly state: \"catching-up\" | \"done\" | \"errored\";\n};\n\n/** The catch-up priority as the progress display states it. */\nexport type ProgressPriority = {\n readonly mode: CatchUpPriorityState[\"mode\"];\n readonly level: number;\n readonly reason: string;\n};\n\n/** What one read of the source shows: the bars, and the priority when known. */\nexport type ProgressSnapshot = {\n readonly rows: readonly ProgressRow[];\n readonly priority: ProgressPriority | undefined;\n};\n\n/** Reads the current rows; rejects while the reactor cannot answer. */\nexport type ProgressSource = () => Promise<ProgressSnapshot>;\n\nfunction withDrives(label: string, driveCount: number): string {\n return `${label} (${driveCount} ${driveCount === 1 ? \"drive\" : \"drives\"})`;\n}\n\n/** One row per processor factory, then one per reactor read model. */\nexport function progressRows(progress: ReactorProgress): ProgressRow[] {\n const factories = progress.factories.map((factory): ProgressRow => ({\n label: withDrives(factory.label, factory.driveCount),\n fraction: factory.fraction,\n state:\n factory.phase === \"errored\"\n ? \"errored\"\n : factory.phase === \"catching-up\"\n ? \"catching-up\"\n : \"done\",\n }));\n const readModels = progress.readModels.map((model): ProgressRow => ({\n label: model.consumerId,\n fraction: model.fraction,\n state: model.blocked ? \"errored\" : model.complete ? \"done\" : \"catching-up\",\n }));\n return [...factories, ...readModels];\n}\n\n/** Rows from a reactor's inspector: its processors, catch-up status and priority. */\nexport function inspectorProgressSource(inspector: IInspector): ProgressSource {\n return async () => {\n const processors = await inspector.getProcessors();\n let catchUp:\n | Awaited<ReturnType<IInspector[\"getCatchUpStatus\"]>>\n | undefined;\n try {\n catchUp = await inspector.getCatchUpStatus();\n } catch {\n catchUp = undefined;\n }\n let priority: ProgressPriority | undefined;\n try {\n const state = await inspector.getCatchUpPriority();\n priority = { mode: state.mode, level: state.level, reason: state.reason };\n } catch {\n priority = undefined;\n }\n return {\n rows: progressRows(computeProgress(processors, catchUp)),\n priority,\n };\n };\n}\n\n/** `catch-up priority 6 (dynamic, idle 14 s)`, or `catch-up priority 3 (fixed)`. */\nexport function renderPriority(priority: ProgressPriority): string {\n const why =\n priority.mode === \"dynamic\" ? `dynamic, ${priority.reason}` : \"fixed\";\n return `catch-up priority ${priority.level} (${why})`;\n}\n\n/** The slice of a TTY stream the display writes to and intercepts. */\nexport type ProgressStream = {\n write: NodeJS.WriteStream[\"write\"];\n readonly isTTY?: boolean;\n readonly columns?: number;\n};\n\nexport type ProgressDisplayOptions = {\n readonly stdout: ProgressStream;\n readonly stderr: ProgressStream;\n /** How often the source is read. */\n readonly pollMs?: number;\n /** Without a TTY: how often a progress line is printed while catching up. */\n readonly lineMs?: number;\n};\n\nexport type ProgressDisplay = {\n /** Stops polling, removes the bars and restores the streams. */\n stop(): void;\n};\n\nconst DEFAULT_POLL_MS = 1_000;\nconst DEFAULT_LINE_MS = 10_000;\nconst MIN_BAR = 10;\nconst MAX_LABEL = 32;\n\nfunction percent(row: ProgressRow): string {\n if (row.state === \"errored\") return \"errored\";\n if (row.state === \"done\") return \"done\";\n return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;\n}\n\nfunction fit(label: string, width: number): string {\n return label.length <= width\n ? label.padEnd(width)\n : `…${label.slice(label.length - width + 1)}`;\n}\n\n/** The bar block, one line per row, sized to `columns`, under the priority when known. */\nexport function renderBars(\n rows: readonly ProgressRow[],\n columns: number,\n priority?: ProgressPriority,\n): string[] {\n const labelWidth = Math.min(\n MAX_LABEL,\n Math.max(...rows.map((row) => row.label.length), 0),\n );\n const barWidth = Math.max(MIN_BAR, columns - labelWidth - 12);\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)}`;\n });\n if (!priority) return bars;\n // Short of the last column, so a full line never wraps.\n return [renderPriority(priority).slice(0, Math.max(columns - 1, 1)), ...bars];\n}\n\n/** One line for a log without a TTY, listing only what is still catching up. */\nexport function renderLine(\n rows: readonly ProgressRow[],\n priority?: ProgressPriority,\n): string {\n const busy = rows.filter((row) => row.state !== \"done\");\n const line = `catch-up: ${busy.map((row) => `${row.label} ${percent(row)}`).join(\" · \")}`;\n return priority\n ? `${line} · priority ${priority.level} ${priority.mode}`\n : line;\n}\n\nfunction busy(rows: readonly ProgressRow[]): boolean {\n return rows.some((row) => row.state !== \"done\");\n}\n\n/**\n * Shows catch-up progress while any row is not done. In a terminal the bars\n * sit below the output and every other write is printed above them; without\n * one, a progress line is printed every `lineMs`.\n */\nexport function startProgressDisplay(\n source: ProgressSource,\n options: ProgressDisplayOptions,\n): ProgressDisplay {\n const { stdout, stderr } = options;\n const tty = stdout.isTTY === true;\n let rows: readonly ProgressRow[] = [];\n let priority: ProgressPriority | undefined;\n let drawn = 0;\n let atLineStart = true;\n let lastLine = 0;\n let stopped = false;\n let reading = false;\n\n const restoreOut = stdout.write;\n const restoreErr = stderr.write;\n const originalOut = restoreOut.bind(stdout);\n const originalErr = restoreErr.bind(stderr);\n\n const erase = () => {\n if (drawn > 0) originalOut(`\\x1b[${drawn}A\\r\\x1b[0J`);\n drawn = 0;\n };\n const draw = () => {\n if (!tty || stopped || !atLineStart || !busy(rows)) return;\n const lines = renderBars(rows, stdout.columns ?? 80, priority);\n originalOut(`${lines.join(\"\\n\")}\\n`);\n drawn = lines.length;\n };\n\n // Every other write goes above the bars: lift them, write, put them back.\n const above =\n (write: (chunk: string | Uint8Array, ...rest: never[]) => boolean) =>\n (chunk: string | Uint8Array, ...rest: never[]): boolean => {\n erase();\n const result = write(chunk, ...rest);\n const text =\n typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n if (text.length > 0) atLineStart = text.endsWith(\"\\n\");\n draw();\n return result;\n };\n 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 }\n\n const tick = async () => {\n if (reading || stopped) return;\n reading = true;\n try {\n ({ rows, priority } = await source());\n } catch {\n // The reactor did not answer; keep the last rows until it does.\n } finally {\n reading = false;\n }\n if (stopped) return;\n if (tty) {\n erase();\n draw();\n return;\n }\n const now = Date.now();\n if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {\n originalOut(`${renderLine(rows, priority)}\\n`);\n lastLine = now;\n }\n };\n\n const timer = setInterval(\n () => void tick(),\n options.pollMs ?? DEFAULT_POLL_MS,\n );\n (timer as { unref?: () => void }).unref?.();\n void tick();\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n erase();\n if (tty) {\n stdout.write = restoreOut;\n stderr.write = restoreErr;\n }\n },\n };\n}\n","import {\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 applyReactorEnvProjection,\n switchboardBootProjection,\n switchboardDevMode,\n} from \"./reactor-env.js\";\nimport { z } from \"zod\";\nimport { classicSwitchboardArgs } from \"../services/classic-args.js\";\nimport {\n inspectorProgressSource,\n startProgressDisplay,\n} from \"../services/run/catch-up-progress.js\";\nimport type { BuildArgs, SwitchboardArgs } from \"../types.js\";\n\n/**\n * BRIDGE runner for Switchboard hosts (uniform-runners phase 0): maps a\n * hosts/switchboard/host.js definition onto the SAME `startSwitchboard`\n * service the classic command calls. `run` = production loaders, `dev` =\n * Vite package loader (worker pools refused by the server, as always).\n */\n\nexport const kind = \"reactor\";\n\n/** The switchboard host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails). The\n * runner reads nothing from `config`, so only an empty one is accepted.\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.extend({\n runner: s.runnerBaseSchema\n .extend({\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.strictObject({}).optional(),\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 dbPath: string | undefined,\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 // The host file's readModel.url. Absent, the key stays present and\n // undefined exactly as the classic command carries it, so the server's\n // own split defaults (.ph/reactor-storage + .ph/read-storage) apply.\n // Omitting the key resurrected a dead service default and put the\n // reactor and the read model on ONE PGlite dir (two writers, one PGDATA).\n dbPath: dbPath ?? classic.dbPath,\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). */\nasync function waitForDrive(url: string, timeoutMs: number): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n const res = await fetch(url, { signal: AbortSignal.timeout(3000) });\n if (res.ok) 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 seededIds.set(drive.slug, drive.id);\n const { addDefaultDrive } =\n await import(\"@powerhousedao/switchboard/utils\");\n await addDefaultDrive(\n reactor as Parameters<typeof addDefaultDrive>[0],\n {\n id: drive.id,\n slug: drive.slug,\n global: { name: drive.name, icon: drive.icon },\n ...(drive.preferredEditor\n ? { preferredEditor: drive.preferredEditor }\n : {}),\n local: {\n availableOffline: drive.availableOffline,\n listeners: [],\n sharingType: drive.sharingType,\n triggers: [],\n },\n } as Parameters<typeof addDefaultDrive>[1],\n port,\n );\n },\n attachRemoteDrive: () => Promise.resolve(), // remotes ride options.remoteDrives\n };\n}\n\nasync function start(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n devMode: boolean,\n): Promise<SwitchboardHandle> {\n const options = applyReactorEnvProjection(\n host.reactor,\n `hosts/${host.name}/host.js`,\n );\n const { startSwitchboard } = await import(\"../services/switchboard.js\");\n const entries = host.runner.plugins;\n const entriesDeclared = entries !== undefined;\n const args = await toSwitchboardArgs(\n host,\n devMode,\n options.dbPath,\n entriesDeclared,\n );\n\n // R2 step 2: a declared composition activates the plugin pipeline — the\n // runner resolves the entries against the PROJECT dependency tree and the\n // flag drives server-side activation. No plugins key = classic path.\n let pluginComposition;\n if (entries !== undefined) {\n process.env.FEATURE_PLUGIN_HOST_ENABLED = \"1\";\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 const switchboard = await startSwitchboard(serverArgs);\n // Bars for processor and read-model catch-up, below the server's output;\n // PH_CATCH_UP_PROGRESS=false leaves the output as it was.\n const progress =\n switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== \"false\"\n ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {\n stdout: process.stdout,\n stderr: process.stderr,\n })\n : undefined;\n // The port the server actually bound (it may move off a taken one).\n const port = switchboard.port;\n const origin = `http://localhost:${port}`;\n const driveUrlOf = (slug: string) => `${origin}/d/${slug}`;\n\n const seededIds = new Map<string, string>();\n const localPlanned = planned.filter((p) => p.drive.kind === \"local\");\n if (localPlanned.length > 0) {\n await seedDrives(\n seederClient(switchboard.reactor, port, seededIds),\n localPlanned.map((p) => p.drive),\n );\n }\n\n const drives: SwitchboardOutputs[\"drives\"] = {};\n // The server creates its implicit default drive only when nothing replaces\n // it: no host declaration and no remote drive (services/switchboard.ts).\n const localHostDrives = hostDrives.filter((d) => d.drive.kind === \"local\");\n const defaultSlug = defaultDriveSlug(switchboard.defaultDriveUrl);\n if (hostDrives.length === 0 && remoteDrives.length === 0) {\n drives[defaultSlug] = { id: defaultSlug, url: driveUrlOf(defaultSlug) };\n }\n for (const { declaredSlug, drive } of localPlanned) {\n drives[declaredSlug] = {\n id: seededIds.get(drive.slug) ?? drive.id,\n url: driveUrlOf(drive.slug),\n };\n }\n\n const slug =\n localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;\n const driveUrl = driveUrlOf(slug);\n\n // No composition declared (the deprecated `reactor.workflows` switch): the\n // workflows flag still seeds the SAME project-hashed drive the classic\n // vetra path seeds. With a composition the workflows PLUGIN declares that\n // drive (contributions.drives above), so nothing implicit happens here.\n if (entries === undefined && switchboard.workflowsEnabled) {\n const { seedWorkflowsDrive } = await import(\"../services/vetra.js\");\n const { generateProjectDriveId } = await import(\"../utils.js\");\n const url = await seedWorkflowsDrive(switchboard.reactor, port);\n if (url)\n drives.workflows = { id: generateProjectDriveId(\"workflows\"), url };\n }\n\n const ready = waitForDrive(driveUrl, 180_000);\n // A supervisor awaits `ready` and sees the rejection; an unsupervised caller\n // (or a test with the service mocked) must not die of an unhandled one.\n ready.catch(() => undefined);\n const graphql = `${origin}/graphql`;\n // Stops the reactor the server owns, then drains the HTTP server (freeing\n // the port), GraphQL, MCP, attachments, the plugins' onShutdown and the\n // read-model db, then closes the reactor database. SwitchboardReactor\n // memoizes it; standalone, SIGINT/SIGTERM run the same teardown, so a\n // shutdown() during or after a signal joins it instead of draining twice.\n let stopping: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin,\n endpoints: {\n graphql,\n ...(switchboard.mcpEnabled ? { mcp: `${origin}/mcp` } : {}),\n },\n drives,\n }),\n ready,\n shutdown: () => {\n progress?.stop();\n return (stopping ??= switchboard.shutdown());\n },\n };\n}\n\n// The four verbs are orthogonal: each does ONE job.\n// - `run`/`serve`: START the server in production mode (serves the built\n// project package). `serve` is run's alias — a server IS its served stack,\n// and it lets the compound forward one `serve` verb to every member.\n// - `dev`: START the server in dev mode (watch / the Vite package loader).\n// - `build`: PRODUCE the project package this switchboard serves, and start\n// NOTHING. The analog of `ph connect build` on the server side: legacy\n// `ph switchboard build` never existed, but the project still has a build.\n// `build` is what lets a compound forward a single `build` verb to all members\n// (desktop/cli) without the switchboard member failing on an unknown verb.\n\nexport async function run(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, false);\n}\n\nexport const serve = run;\n\nexport async function dev(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, true);\n}\n\n/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */\nexport async function checkBoot(\n host: SwitchboardHostParsed,\n ctx: BootCheckContext,\n): Promise<BootIssue[]> {\n const issues: BootIssue[] = protocolConflicts(\n host.reactor?.protocol,\n ctx.env,\n ctx.file,\n ).map((message) => ({ path: \"reactor.protocol\", message }));\n const { getConfig } = await import(\"@powerhousedao/config/node\");\n const { switchboardBootFactsFromEnv, switchboardBootIssues } =\n await import(\"@powerhousedao/switchboard/boot\");\n const projection = switchboardBootProjection(host.reactor, ctx.env);\n const { facts, issues: parseIssues } = await switchboardBootFactsFromEnv(\n { ...ctx.env, ...projection.env },\n {\n // As the `dev` verb starts it.\n dev: switchboardDevMode(ctx.verb === \"dev\", host.runner),\n ...(projection.dbPath !== undefined ? { dbPath: projection.dbPath } : {}),\n configuredRenown: getConfig(\n path.join(ctx.projectRoot, \"powerhouse.config.json\"),\n ).auth?.renown,\n },\n );\n for (const message of [...parseIssues, ...switchboardBootIssues(facts)]) {\n issues.push({ path: \"\", message });\n }\n return issues;\n}\n\n/** Build the project's reactor package (the SAME service as `ph build`) — what\n * this switchboard serves. Starts no server; orthogonal to run/serve/dev. */\nexport async function build(\n host: SwitchboardHostParsed,\n _ctx: RunnerContext,\n): Promise<void> {\n const { runBuild } = await import(\"../services/build.js\");\n const args: Partial<BuildArgs> = {\n outDir: host.runner.outDir ?? \"dist\",\n };\n await runBuild(args as BuildArgs);\n}\n"],"names":["z.boolean","z.string","z.strictObject","z.url","z.record","z.prettifyError"],"mappings":";;;;;;;;;;;;AASA,SAAgB,0BACd,S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Q;AAErB,eAAsB,IACpB,MACA,KAC4B;CAC5B,OAAO,MAAM,MAAM,KAAK,IAAI;AAC9B;;AAGA,eAAsB,UACpB,MACA,KACsB;CACtB,MAAM,SAAsB,kBAC1B,KAAK,SAAS,UACd,IAAI,KACJ,IAAI,IACN,CAAC,CAAC,KAAK,aAAa;EAAE,MAAM;EAAoB;CAAQ,EAAE;CAC1D,MAAM,EAAE,cAAc,MAAM,OAAO;CACnC,MAAM,EAAE,6BAA6B,0BACnC,MAAM,OAAO;CACf,MAAM,aAAa,0BAA0B,KAAK,SAAS,IAAI,GAAG;CAClE,MAAM,EAAE,OAAO,QAAQ,gBAAgB,MAAM,4BAC3C;EAAE,GAAG,IAAI;EAAK,GAAG,WAAW;CAAI,GAChC;EAEE,KAAK,mBAAmB,IAAI,SAAS,OAAO,KAAK,MAAM;EACvD,GAAI,WAAW,WAAW,KAAA,IAAY,EAAE,QAAQ,WAAW,OAAO,IAAI,CAAC;EACvE,kBAAkB,UAChB,KAAK,KAAK,IAAI,aAAa,wBAAwB,CACrD,CAAC,CAAC,MAAM;CACV,CACF;CACA,KAAK,MAAM,WAAW,CAAC,GAAG,aAAa,GAAG,sBAAsB,KAAK,CAAC,GACpE,OAAO,KAAK;EAAE,MAAM;EAAI;CAAQ,CAAC;CAEnC,OAAO;AACT;;;AAIA,eAAsB,MACpB,MACA,MACe;CACf,MAAM,EAAE,aAAa,MAAM,OAAO;CAIlC,MAAM,SAAS,EAFb,QAAQ,KAAK,OAAO,UAAU,OAEd,CAAc;AAClC","debug_id":"884205e8-ae13-5449-b01d-d57c825d71ce"}
1
+ {"version":3,"file":"switchboard.mjs","sources":["../../src/runners/reactor-env.ts","../../src/services/classic-args.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n assertProtocolConsistency,\n primaryBackend,\n projectReactorToSwitchboard,\n type ReactorConfig,\n} from \"@powerhousedao/host-core\";\n\n/** The reactor block as the switchboard boots with it: the vars `env` leaves unset, and dbPath. */\nexport function switchboardBootProjection(\n reactor: ReactorConfig | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): { env: Record<string, string>; dbPath?: string } {\n const { env: projected, options } = projectReactorToSwitchboard(reactor);\n const unset: Record<string, string> = {};\n for (const [name, value] of Object.entries(projected) as [\n string,\n unknown,\n ][]) {\n // A deferred $output token is not a value yet.\n if (env[name] === undefined && typeof value === \"string\")\n unset[name] = value;\n }\n return {\n env: unset,\n ...(options.dbPath !== undefined ? { dbPath: options.dbPath } : {}),\n };\n}\n\n/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */\nexport function switchboardDevMode(\n devVerb: boolean,\n runner: { dev?: boolean },\n): boolean {\n return devVerb || runner.dev === true;\n}\n\n/**\n * Apply a host's reactor block to the CURRENT process env, the way the\n * in-process switchboard server reads it at boot (D2.c: env derivation\n * immediately before the member starts; sequential boots make this safe).\n * Single-sourcing teeth first: a pre-set env contradicting the protocol block\n * fails loudly. Then set-if-absent, so an operator's explicit (agreeing) env\n * still wins during the transition. Returns the non-env options (dbPath).\n *\n * Lives OUTSIDE the runner modules on purpose: every export of a runner\n * module reads as a dispatchable verb, and this is not one.\n */\nexport function applyReactorEnvProjection(\n reactor: ReactorConfig | undefined,\n hostFileLabel: string,\n): { dbPath?: string } {\n assertProtocolConsistency(reactor?.protocol, process.env, hostFileLabel);\n const projection = switchboardBootProjection(reactor, process.env);\n Object.assign(process.env, projection.env);\n // A path-storage data dir must exist before the server boots — its own\n // mkdir is not recursive (the ph-win sidecar did this too).\n const storage = primaryBackend(reactor)?.storage;\n if (storage?.kind === \"path\" && storage.dataDir) {\n // `ph run` resolves `$env` and the `${userData}` sugar before the verb;\n // an unresolved one here would mkdir a literal \"${userData}\" folder.\n if (/\\$\\{(userData|projectRoot)\\}/.test(storage.dataDir)) {\n throw new Error(\n `${hostFileLabel}: storage.dataDir \"${storage.dataDir}\" was not resolved; resolve the host (resolveHostOutputs) before starting it.`,\n );\n }\n fs.mkdirSync(storage.dataDir, { recursive: true });\n }\n return projection.dbPath !== undefined ? { dbPath: projection.dbPath } : {};\n}\n","import { switchboardArgs } from \"@powerhousedao/shared/clis/args\";\nimport { command, runSafely } from \"cmd-ts\";\nimport type { SwitchboardArgs } from \"../types.js\";\n\n/**\n * The classic `ph switchboard` argument shape, produced by the SAME cmd-ts\n * definitions the classic command parses — not re-derived by hand. A runner\n * starts from this object and overlays only the keys its host file owns, so\n * every key the classic command carries (including the ones it carries as\n * `undefined`, e.g. `dbPath`) reaches the service exactly as it does on the\n * classic path. The uniform-runners switchboard runner once hand-built a\n * partial object that omitted `dbPath`; the service's then-default\n * `.ph/read-model.db` became both the reactor and the read-model PGlite dir —\n * two instances on one PGDATA (see uniform-runners-plan/legacy-parity-rectification.md).\n */\nconst classicSwitchboard = command({\n name: \"switchboard\",\n args: switchboardArgs,\n handler: (args) => args,\n});\n\nexport async function classicSwitchboardArgs(\n argv: string[] = [],\n): Promise<SwitchboardArgs> {\n const result = await runSafely(classicSwitchboard, argv);\n if (result._tag === \"error\") {\n throw new Error(\n `classic switchboard args did not parse: ${result.error.config.message}`,\n );\n }\n return result.value;\n}\n","import {\n computeProgress,\n type CatchUpPriorityState,\n type IInspector,\n type ReactorProgress,\n} from \"@powerhousedao/reactor\";\n\n/** One bar: a processor factory or a read model, and how far its catch-up has got. */\nexport type ProgressRow = {\n readonly label: string;\n /** 0..1 of the current run. */\n readonly fraction: number;\n readonly state: \"catching-up\" | \"done\" | \"errored\";\n};\n\n/** The catch-up priority as the progress display states it. */\nexport type ProgressPriority = {\n readonly mode: CatchUpPriorityState[\"mode\"];\n readonly level: number;\n readonly reason: string;\n};\n\n/** What one read of the source shows: the bars, and the priority when known. */\nexport type ProgressSnapshot = {\n readonly rows: readonly ProgressRow[];\n readonly priority: ProgressPriority | undefined;\n};\n\n/** Reads the current rows; rejects while the reactor cannot answer. */\nexport type ProgressSource = () => Promise<ProgressSnapshot>;\n\nfunction withDrives(label: string, driveCount: number): string {\n return `${label} (${driveCount} ${driveCount === 1 ? \"drive\" : \"drives\"})`;\n}\n\n/** One row per processor factory, then one per reactor read model. */\nexport function progressRows(progress: ReactorProgress): ProgressRow[] {\n const factories = progress.factories.map((factory): ProgressRow => ({\n label: withDrives(factory.label, factory.driveCount),\n fraction: factory.fraction,\n state:\n factory.phase === \"errored\"\n ? \"errored\"\n : factory.phase === \"catching-up\"\n ? \"catching-up\"\n : \"done\",\n }));\n const readModels = progress.readModels.map((model): ProgressRow => ({\n label: model.consumerId,\n fraction: model.fraction,\n state: model.blocked ? \"errored\" : model.complete ? \"done\" : \"catching-up\",\n }));\n return [...factories, ...readModels];\n}\n\n/** Rows from a reactor's inspector: its processors, catch-up status and priority. */\nexport function inspectorProgressSource(inspector: IInspector): ProgressSource {\n return async () => {\n const processors = await inspector.getProcessors();\n let catchUp:\n | Awaited<ReturnType<IInspector[\"getCatchUpStatus\"]>>\n | undefined;\n try {\n catchUp = await inspector.getCatchUpStatus();\n } catch {\n catchUp = undefined;\n }\n let priority: ProgressPriority | undefined;\n try {\n const state = await inspector.getCatchUpPriority();\n priority = { mode: state.mode, level: state.level, reason: state.reason };\n } catch {\n priority = undefined;\n }\n return {\n rows: progressRows(computeProgress(processors, catchUp)),\n priority,\n };\n };\n}\n\n/** `catch-up priority 6 (dynamic, idle 14 s)`, or `catch-up priority 3 (fixed)`. */\nexport function renderPriority(priority: ProgressPriority): string {\n const why =\n priority.mode === \"dynamic\" ? `dynamic, ${priority.reason}` : \"fixed\";\n return `catch-up priority ${priority.level} (${why})`;\n}\n\n/** The slice of a TTY stream the display writes to and intercepts. */\nexport type ProgressStream = {\n write: NodeJS.WriteStream[\"write\"];\n readonly isTTY?: boolean;\n readonly columns?: number;\n /** A TTY stream emits \"resize\" when the terminal's size changes. */\n on?(event: \"resize\", listener: () => void): unknown;\n off?(event: \"resize\", listener: () => void): unknown;\n};\n\n/** The console width the bars are sized for: a reported width, else 80. */\nfunction widthOf(stream: ProgressStream): number {\n const columns = stream.columns;\n return typeof columns === \"number\" && columns > 0 ? columns : 80;\n}\n\nexport type ProgressDisplayOptions = {\n readonly stdout: ProgressStream;\n readonly stderr: ProgressStream;\n /** How often the source is read. */\n readonly pollMs?: number;\n /** Without a TTY: how often a progress line is printed while catching up. */\n readonly lineMs?: number;\n};\n\nexport type ProgressDisplay = {\n /** Stops polling, removes the bars and restores the streams. */\n stop(): void;\n};\n\nconst DEFAULT_POLL_MS = 1_000;\nconst DEFAULT_LINE_MS = 10_000;\nconst MIN_BAR = 10;\nconst MAX_LABEL = 32;\n\nfunction percent(row: ProgressRow): string {\n if (row.state === \"errored\") return \"errored\";\n if (row.state === \"done\") return \"done\";\n return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;\n}\n\nfunction fit(label: string, width: number): string {\n return label.length <= width\n ? label.padEnd(width)\n : `…${label.slice(label.length - width + 1)}`;\n}\n\n/**\n * The bar block, one line per row, under the priority when known. Every line\n * stays short of the terminal's last column: a line that fills it wraps on\n * xterm-based terminals (VS Code, Windows Terminal), and the erase would then\n * lift fewer lines than are on screen, leaving old bars behind. On a narrow\n * terminal the label gives way before the bar.\n */\nexport function renderBars(\n rows: readonly ProgressRow[],\n columns: number,\n priority?: ProgressPriority,\n): string[] {\n const width = Math.max(columns - 1, 1);\n // label, space, bar, space, 7 for \"errored\" / \"100%\"\n const fixed = 9;\n const longest = Math.max(...rows.map((row) => row.label.length), 0);\n const labelWidth = Math.max(\n 1,\n Math.min(MAX_LABEL, longest, width - fixed - MIN_BAR),\n );\n const barWidth = Math.max(MIN_BAR, width - labelWidth - fixed);\n const bars = rows.map((row) => {\n const fraction = row.state === \"done\" ? 1 : row.fraction;\n const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);\n const bar = \"█\".repeat(filled) + \"░\".repeat(barWidth - filled);\n return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`.slice(\n 0,\n width,\n );\n });\n if (!priority) return bars;\n return [renderPriority(priority).slice(0, width), ...bars];\n}\n\n/** One line for a log without a TTY, listing only what is still catching up. */\nexport function renderLine(\n rows: readonly ProgressRow[],\n priority?: ProgressPriority,\n): string {\n const busy = rows.filter((row) => row.state !== \"done\");\n const line = `catch-up: ${busy.map((row) => `${row.label} ${percent(row)}`).join(\" · \")}`;\n return priority\n ? `${line} · priority ${priority.level} ${priority.mode}`\n : line;\n}\n\nfunction busy(rows: readonly ProgressRow[]): boolean {\n return rows.some((row) => row.state !== \"done\");\n}\n\n/**\n * Shows catch-up progress while any row is not done. In a terminal the bars\n * sit below the output and every other write is printed above them; without\n * one, a progress line is printed every `lineMs`.\n */\nexport function startProgressDisplay(\n source: ProgressSource,\n options: ProgressDisplayOptions,\n): ProgressDisplay {\n const { stdout, stderr } = options;\n const tty = stdout.isTTY === true;\n let rows: readonly ProgressRow[] = [];\n let priority: ProgressPriority | undefined;\n let drawn = 0;\n let atLineStart = true;\n let lastLine = 0;\n let stopped = false;\n let reading = false;\n\n const restoreOut = stdout.write;\n const restoreErr = stderr.write;\n const originalOut = restoreOut.bind(stdout);\n const originalErr = restoreErr.bind(stderr);\n\n const erase = () => {\n if (drawn > 0) originalOut(`\\x1b[${drawn}A\\r\\x1b[0J`);\n drawn = 0;\n };\n const draw = () => {\n if (!tty || stopped || !atLineStart || !busy(rows)) return;\n const lines = renderBars(rows, widthOf(stdout), priority);\n originalOut(`${lines.join(\"\\n\")}\\n`);\n drawn = lines.length;\n };\n\n // Every other write goes above the bars: lift them, write, put them back.\n const above =\n (write: (chunk: string | Uint8Array, ...rest: never[]) => boolean) =>\n (chunk: string | Uint8Array, ...rest: never[]): boolean => {\n erase();\n const result = write(chunk, ...rest);\n const text =\n typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n if (text.length > 0) atLineStart = text.endsWith(\"\\n\");\n draw();\n return result;\n };\n // A resized terminal has already reflowed the drawn lines; redraw for the\n // new width right away rather than at the next poll.\n const onResize = () => {\n if (stopped) return;\n erase();\n draw();\n };\n if (tty) {\n stdout.write = above(originalOut as never) as NodeJS.WriteStream[\"write\"];\n stderr.write = above(originalErr as never) as NodeJS.WriteStream[\"write\"];\n stdout.on?.(\"resize\", onResize);\n }\n\n const tick = async () => {\n if (reading || stopped) return;\n reading = true;\n try {\n ({ rows, priority } = await source());\n } catch {\n // The reactor did not answer; keep the last rows until it does.\n } finally {\n reading = false;\n }\n if (stopped) return;\n if (tty) {\n erase();\n draw();\n return;\n }\n const now = Date.now();\n if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {\n originalOut(`${renderLine(rows, priority)}\\n`);\n lastLine = now;\n }\n };\n\n const timer = setInterval(\n () => void tick(),\n options.pollMs ?? DEFAULT_POLL_MS,\n );\n (timer as { unref?: () => void }).unref?.();\n void tick();\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n erase();\n if (tty) {\n stdout.off?.(\"resize\", onResize);\n stdout.write = restoreOut;\n stderr.write = restoreErr;\n }\n },\n };\n}\n","import {\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 applyReactorEnvProjection,\n switchboardBootProjection,\n switchboardDevMode,\n} from \"./reactor-env.js\";\nimport { z } from \"zod\";\nimport { classicSwitchboardArgs } from \"../services/classic-args.js\";\nimport {\n inspectorProgressSource,\n startProgressDisplay,\n} from \"../services/run/catch-up-progress.js\";\nimport type { BuildArgs, SwitchboardArgs } from \"../types.js\";\n\n/**\n * BRIDGE runner for Switchboard hosts (uniform-runners phase 0): maps a\n * hosts/switchboard/host.js definition onto the SAME `startSwitchboard`\n * service the classic command calls. `run` = production loaders, `dev` =\n * Vite package loader (worker pools refused by the server, as always).\n */\n\nexport const kind = \"reactor\";\n\n/** The switchboard host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails). The\n * runner reads nothing from `config`, so only an empty one is accepted.\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.extend({\n runner: s.runnerBaseSchema\n .extend({\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.strictObject({}).optional(),\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 dbPath: string | undefined,\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 // The host file's readModel.url. Absent, the key stays present and\n // undefined exactly as the classic command carries it, so the server's\n // own split defaults (.ph/reactor-storage + .ph/read-storage) apply.\n // Omitting the key resurrected a dead service default and put the\n // reactor and the read model on ONE PGlite dir (two writers, one PGDATA).\n dbPath: dbPath ?? classic.dbPath,\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). */\nasync function waitForDrive(url: string, timeoutMs: number): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n const res = await fetch(url, { signal: AbortSignal.timeout(3000) });\n if (res.ok) 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 seededIds.set(drive.slug, drive.id);\n const { addDefaultDrive } =\n await import(\"@powerhousedao/switchboard/utils\");\n await addDefaultDrive(\n reactor as Parameters<typeof addDefaultDrive>[0],\n {\n id: drive.id,\n slug: drive.slug,\n global: { name: drive.name, icon: drive.icon },\n ...(drive.preferredEditor\n ? { preferredEditor: drive.preferredEditor }\n : {}),\n local: {\n availableOffline: drive.availableOffline,\n listeners: [],\n sharingType: drive.sharingType,\n triggers: [],\n },\n } as Parameters<typeof addDefaultDrive>[1],\n port,\n );\n },\n attachRemoteDrive: () => Promise.resolve(), // remotes ride options.remoteDrives\n };\n}\n\nasync function start(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n devMode: boolean,\n): Promise<SwitchboardHandle> {\n const options = applyReactorEnvProjection(\n host.reactor,\n `hosts/${host.name}/host.js`,\n );\n const { startSwitchboard } = await import(\"../services/switchboard.js\");\n const entries = host.runner.plugins;\n const entriesDeclared = entries !== undefined;\n const args = await toSwitchboardArgs(\n host,\n devMode,\n options.dbPath,\n entriesDeclared,\n );\n\n // R2 step 2: a declared composition activates the plugin pipeline — the\n // runner resolves the entries against the PROJECT dependency tree and the\n // flag drives server-side activation. No plugins key = classic path.\n let pluginComposition;\n if (entries !== undefined) {\n process.env.FEATURE_PLUGIN_HOST_ENABLED = \"1\";\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 const switchboard = await startSwitchboard(serverArgs);\n // Bars for processor and read-model catch-up, below the server's output;\n // PH_CATCH_UP_PROGRESS=false leaves the output as it was.\n const progress =\n switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== \"false\"\n ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {\n stdout: process.stdout,\n stderr: process.stderr,\n })\n : undefined;\n // The port the server actually bound (it may move off a taken one).\n const port = switchboard.port;\n const origin = `http://localhost:${port}`;\n const driveUrlOf = (slug: string) => `${origin}/d/${slug}`;\n\n const seededIds = new Map<string, string>();\n const localPlanned = planned.filter((p) => p.drive.kind === \"local\");\n if (localPlanned.length > 0) {\n await seedDrives(\n seederClient(switchboard.reactor, port, seededIds),\n localPlanned.map((p) => p.drive),\n );\n }\n\n const drives: SwitchboardOutputs[\"drives\"] = {};\n // The server creates its implicit default drive only when nothing replaces\n // it: no host declaration and no remote drive (services/switchboard.ts).\n const localHostDrives = hostDrives.filter((d) => d.drive.kind === \"local\");\n const defaultSlug = defaultDriveSlug(switchboard.defaultDriveUrl);\n if (hostDrives.length === 0 && remoteDrives.length === 0) {\n drives[defaultSlug] = { id: defaultSlug, url: driveUrlOf(defaultSlug) };\n }\n for (const { declaredSlug, drive } of localPlanned) {\n drives[declaredSlug] = {\n id: seededIds.get(drive.slug) ?? drive.id,\n url: driveUrlOf(drive.slug),\n };\n }\n\n const slug =\n localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;\n const driveUrl = driveUrlOf(slug);\n\n // No composition declared (the deprecated `reactor.workflows` switch): the\n // workflows flag still seeds the SAME project-hashed drive the classic\n // vetra path seeds. With a composition the workflows PLUGIN declares that\n // drive (contributions.drives above), so nothing implicit happens here.\n if (entries === undefined && switchboard.workflowsEnabled) {\n const { seedWorkflowsDrive } = await import(\"../services/vetra.js\");\n const { generateProjectDriveId } = await import(\"../utils.js\");\n const url = await seedWorkflowsDrive(switchboard.reactor, port);\n if (url)\n drives.workflows = { id: generateProjectDriveId(\"workflows\"), url };\n }\n\n const ready = waitForDrive(driveUrl, 180_000);\n // A supervisor awaits `ready` and sees the rejection; an unsupervised caller\n // (or a test with the service mocked) must not die of an unhandled one.\n ready.catch(() => undefined);\n const graphql = `${origin}/graphql`;\n // Stops the reactor the server owns, then drains the HTTP server (freeing\n // the port), GraphQL, MCP, attachments, the plugins' onShutdown and the\n // read-model db, then closes the reactor database. SwitchboardReactor\n // memoizes it; standalone, SIGINT/SIGTERM run the same teardown, so a\n // shutdown() during or after a signal joins it instead of draining twice.\n let stopping: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin,\n endpoints: {\n graphql,\n ...(switchboard.mcpEnabled ? { mcp: `${origin}/mcp` } : {}),\n },\n drives,\n }),\n ready,\n shutdown: () => {\n progress?.stop();\n return (stopping ??= switchboard.shutdown());\n },\n };\n}\n\n// The four verbs are orthogonal: each does ONE job.\n// - `run`/`serve`: START the server in production mode (serves the built\n// project package). `serve` is run's alias — a server IS its served stack,\n// and it lets the compound forward one `serve` verb to every member.\n// - `dev`: START the server in dev mode (watch / the Vite package loader).\n// - `build`: PRODUCE the project package this switchboard serves, and start\n// NOTHING. The analog of `ph connect build` on the server side: legacy\n// `ph switchboard build` never existed, but the project still has a build.\n// `build` is what lets a compound forward a single `build` verb to all members\n// (desktop/cli) without the switchboard member failing on an unknown verb.\n\nexport async function run(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, false);\n}\n\nexport const serve = run;\n\nexport async function dev(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, true);\n}\n\n/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */\nexport async function checkBoot(\n host: SwitchboardHostParsed,\n ctx: BootCheckContext,\n): Promise<BootIssue[]> {\n const issues: BootIssue[] = protocolConflicts(\n host.reactor?.protocol,\n ctx.env,\n ctx.file,\n ).map((message) => ({ path: \"reactor.protocol\", message }));\n const { getConfig } = await import(\"@powerhousedao/config/node\");\n const { switchboardBootFactsFromEnv, switchboardBootIssues } =\n await import(\"@powerhousedao/switchboard/boot\");\n const projection = switchboardBootProjection(host.reactor, ctx.env);\n const { facts, issues: parseIssues } = await switchboardBootFactsFromEnv(\n { ...ctx.env, ...projection.env },\n {\n // As the `dev` verb starts it.\n dev: switchboardDevMode(ctx.verb === \"dev\", host.runner),\n ...(projection.dbPath !== undefined ? { dbPath: projection.dbPath } : {}),\n configuredRenown: getConfig(\n path.join(ctx.projectRoot, \"powerhouse.config.json\"),\n ).auth?.renown,\n },\n );\n for (const message of [...parseIssues, ...switchboardBootIssues(facts)]) {\n issues.push({ path: \"\", message });\n }\n return issues;\n}\n\n/** Build the project's reactor package (the SAME service as `ph build`) — what\n * this switchboard serves. Starts no server; orthogonal to run/serve/dev. */\nexport async function build(\n host: SwitchboardHostParsed,\n _ctx: RunnerContext,\n): Promise<void> {\n const { runBuild } = await import(\"../services/build.js\");\n const args: Partial<BuildArgs> = {\n outDir: host.runner.outDir ?? \"dist\",\n };\n await runBuild(args as BuildArgs);\n}\n"],"names":["z.boolean","z.string","z.strictObject","z.url","z.record","z.prettifyError"],"mappings":";;;;;;;;;;;;AASA,SAAgB,0BACd,SACA,KACkD;CAClD,MAAM,EAAE,KAAK,WAAW,YAAY,4BAA4B,OAAO;CACvE,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,SAAS,GAKlD,IAAI,IAAI,UAAU,KAAA,KAAa,OAAO,UAAU,UAC9C,MAAM,QAAQ;CAElB,OAAO;EACL,KAAK;EACL,GAAI,QAAQ,WAAW,KAAA,IAAY,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;CACnE;AACF;;AAGA,SAAgB,mBACd,SACA,QACS;CACT,OAAO,WAAW,OAAO,QAAQ;AACnC;;;;;;;;;;;;AAaA,SAAgB,0BACd,SACA,eACqB;CACrB,0BAA0B,SAAS,UAAU,QAAQ,KAAK,aAAa;CACvE,MAAM,aAAa,0BAA0B,SAAS,QAAQ,GAAG;CACjE,OAAO,OAAO,QAAQ,KAAK,WAAW,GAAG;CAGzC,MAAM,UAAU,eAAe,OAAO,CAAC,EAAE;CACzC,IAAI,SAAS,SAAS,UAAU,QAAQ,SAAS;EAG/C,IAAI,+BAA+B,KAAK,QAAQ,OAAO,GACrD,MAAM,IAAI,MACR,GAAG,cAAc,qBAAqB,QAAQ,QAAQ,8EACxD;EAEF,GAAG,UAAU,QA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AC3C;EAAE,GAAG,IAAI;EAAK,GAAG,WAAW;CAAI,GAChC;EAEE,KAAK,mBAAmB,IAAI,SAAS,OAAO,KAAK,MAAM;EACvD,GAAI,WAAW,WAAW,KAAA,IAAY,EAAE,QAAQ,WAAW,OAAO,IAAI,CAAC;EACvE,kBAAkB,UAChB,KAAK,KAAK,IAAI,aAAa,wBAAwB,CACrD,CAAC,CAAC,MAAM;CACV,CACF;CACA,KAAK,MAAM,WAAW,CAAC,GAAG,aAAa,GAAG,sBAAsB,KAAK,CAAC,GACpE,OAAO,KAAK;EAAE,MAAM;EAAI;CAAQ,CAAC;CAEnC,OAAO;AACT;;;AAIA,eAAsB,MACpB,MACA,MACe;CACf,MAAM,EAAE,aAAa,MAAM,OAAO;CAIlC,MAAM,SAAS,EAFb,QAAQ,KAAK,OAAO,UAAU,OAEd,CAAc;AAClC","debug_id":"5f04123a-704e-5014-a89f-94def3c07880"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/ph-cli",
3
- "version": "6.2.3-dev.76",
3
+ "version": "6.2.3-dev.77",
4
4
  "description": "",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -38,15 +38,15 @@
38
38
  "keywords": [],
39
39
  "author": "",
40
40
  "dependencies": {
41
- "@powerhousedao/builder-tools": "6.2.3-dev.76",
42
- "@powerhousedao/codegen": "6.2.3-dev.76",
43
- "@powerhousedao/common": "6.2.3-dev.76",
44
- "@powerhousedao/config": "6.2.3-dev.76",
45
- "@powerhousedao/reactor": "6.2.3-dev.76",
46
- "@powerhousedao/shared": "6.2.3-dev.76",
47
- "@powerhousedao/switchboard": "6.2.3-dev.76",
48
- "@powerhousedao/vetra": "6.2.3-dev.76",
49
- "@renown/sdk": "6.2.3-dev.76",
41
+ "@powerhousedao/builder-tools": "6.2.3-dev.77",
42
+ "@powerhousedao/codegen": "6.2.3-dev.77",
43
+ "@powerhousedao/common": "6.2.3-dev.77",
44
+ "@powerhousedao/config": "6.2.3-dev.77",
45
+ "@powerhousedao/reactor": "6.2.3-dev.77",
46
+ "@powerhousedao/shared": "6.2.3-dev.77",
47
+ "@powerhousedao/switchboard": "6.2.3-dev.77",
48
+ "@powerhousedao/vetra": "6.2.3-dev.77",
49
+ "@renown/sdk": "6.2.3-dev.77",
50
50
  "@sentry/node-core": "^10.52.0",
51
51
  "@tsdown/css": "0.23.0",
52
52
  "@vercel/nft": "^1.11.0",
@@ -55,7 +55,7 @@
55
55
  "change-case": "5.4.4",
56
56
  "cmd-ts": "0.15.0",
57
57
  "colorette": "2.0.20",
58
- "document-model": "6.2.3-dev.76",
58
+ "document-model": "6.2.3-dev.77",
59
59
  "dotenv": "16.4.7",
60
60
  "enquirer": "2.4.1",
61
61
  "kysely": "0.28.16",
@@ -77,8 +77,8 @@
77
77
  "ts-morph": "27.0.2",
78
78
  "write-package": "7.2.0",
79
79
  "zod": "^4.5.4",
80
- "@powerhousedao/desktop": "6.2.3-dev.76",
81
- "@powerhousedao/host-core": "6.2.3-dev.76"
80
+ "@powerhousedao/desktop": "6.2.3-dev.77",
81
+ "@powerhousedao/host-core": "6.2.3-dev.77"
82
82
  },
83
83
  "scripts": {
84
84
  "tsc": "tsc",