@powerhousedao/ph-cli 6.2.3-dev.73 → 6.2.3-dev.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/check-9KDSF1Wj.mjs +53 -0
  2. package/dist/check-9KDSF1Wj.mjs.map +1 -0
  3. package/dist/{cli-connect-override-CEJhQWRX.mjs → cli-connect-override-BrS-X8Rs.mjs} +4 -4
  4. package/dist/{cli-connect-override-CEJhQWRX.mjs.map → cli-connect-override-BrS-X8Rs.mjs.map} +1 -1
  5. package/dist/cli.mjs +11 -7
  6. package/dist/cli.mjs.map +1 -1
  7. package/dist/{compound-B6RZMA0Y-Cv3XMQ3Y.mjs → compound-Gjt5rBfF-BmSW1XPB.mjs} +178 -43
  8. package/dist/compound-Gjt5rBfF-BmSW1XPB.mjs.map +1 -0
  9. package/dist/{connect-build-BfhOGbha.mjs → connect-build-B5nYqlLc.mjs} +4 -4
  10. package/dist/{connect-build-BfhOGbha.mjs.map → connect-build-B5nYqlLc.mjs.map} +1 -1
  11. package/dist/{connect-config-DblqJgxR.mjs → connect-config-Bi95JhNG.mjs} +4 -4
  12. package/dist/{connect-config-DblqJgxR.mjs.map → connect-config-Bi95JhNG.mjs.map} +1 -1
  13. package/dist/{connect-plugin-configs-D2fwYpMw.mjs → connect-plugin-configs-BwYEbQSY.mjs} +4 -4
  14. package/dist/{connect-plugin-configs-D2fwYpMw.mjs.map → connect-plugin-configs-BwYEbQSY.mjs.map} +1 -1
  15. package/dist/{connect-studio-BS26pchr.mjs → connect-studio-Co_UNyEC.mjs} +3 -3
  16. package/dist/{connect-studio-B1_4TNEb.mjs → connect-studio-DGWUidCV.mjs} +4 -4
  17. package/dist/{connect-studio-B1_4TNEb.mjs.map → connect-studio-DGWUidCV.mjs.map} +1 -1
  18. package/dist/{dist-CCLkwpTS.mjs → dist-BVqNlv1z.mjs} +243 -14
  19. package/dist/dist-BVqNlv1z.mjs.map +1 -0
  20. package/dist/{explain-DUXbB9jf.mjs → explain-CPD1tzoV.mjs} +5 -5
  21. package/dist/{explain-DUXbB9jf.mjs.map → explain-CPD1tzoV.mjs.map} +1 -1
  22. package/dist/{generate-all-Dgyy_kT-.mjs → generate-all-CaAHbviS.mjs} +4 -4
  23. package/dist/{generate-all-Dgyy_kT-.mjs.map → generate-all-CaAHbviS.mjs.map} +1 -1
  24. package/dist/{generate-subgraph-BeGR9Y_k.mjs → generate-subgraph-DRrInOOv.mjs} +13 -6
  25. package/dist/generate-subgraph-DRrInOOv.mjs.map +1 -0
  26. package/dist/{index-BIbx17vt.d.mts → index-7hbcAZpm.d.mts} +17 -3
  27. package/dist/{index-BIbx17vt.d.mts.map → index-7hbcAZpm.d.mts.map} +1 -1
  28. package/dist/migrate-b38W7NH_.mjs +177 -0
  29. package/dist/migrate-b38W7NH_.mjs.map +1 -0
  30. package/dist/ph-cli-commands-D4y7NPxI.mjs +4 -0
  31. package/dist/{ph-cli-commands-CpHLMDM3.mjs → ph-cli-commands-kLUOOYuy.mjs} +35 -16
  32. package/dist/ph-cli-commands-kLUOOYuy.mjs.map +1 -0
  33. package/dist/{run-sugar-Ns53R6lU.mjs → run-sugar-BJxPKwlM.mjs} +4 -4
  34. package/dist/{run-sugar-Ns53R6lU.mjs.map → run-sugar-BJxPKwlM.mjs.map} +1 -1
  35. package/dist/runners/connect.d.mts +1 -1
  36. package/dist/runners/connect.mjs +5 -5
  37. package/dist/runners/switchboard.d.mts +3 -1
  38. package/dist/runners/switchboard.d.mts.map +1 -1
  39. package/dist/runners/switchboard.mjs +48 -10
  40. package/dist/runners/switchboard.mjs.map +1 -1
  41. package/dist/{start-run-BIaYSpHh.mjs → start-run-CDZ3YAr9.mjs} +4 -4
  42. package/dist/{start-run-BIaYSpHh.mjs.map → start-run-CDZ3YAr9.mjs.map} +1 -1
  43. package/dist/{vetra-UQsfYM_Q.mjs → vetra-DO5eUgAo.mjs} +6 -6
  44. package/dist/{vetra-UQsfYM_Q.mjs.map → vetra-DO5eUgAo.mjs.map} +1 -1
  45. package/package.json +14 -13
  46. package/dist/compound-B6RZMA0Y-Cv3XMQ3Y.mjs.map +0 -1
  47. package/dist/dist-CCLkwpTS.mjs.map +0 -1
  48. package/dist/generate-subgraph-BeGR9Y_k.mjs.map +0 -1
  49. package/dist/migrate-DK4HK7Dn.mjs +0 -83
  50. package/dist/migrate-DK4HK7Dn.mjs.map +0 -1
  51. package/dist/ph-cli-commands-CpHLMDM3.mjs.map +0 -1
  52. package/dist/ph-cli-commands-rrEBvLx4.mjs +0 -4
@@ -1 +1 @@
1
- {"version":3,"file":"switchboard.mjs","sources":["../../src/runners/reactor-env.ts","../../src/services/classic-args.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/**\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 const { env, options } = projectReactorToSwitchboard(reactor);\n assertProtocolConsistency(reactor?.protocol, process.env, hostFileLabel);\n for (const [name, value] of Object.entries(env)) {\n if (process.env[name] === undefined) process.env[name] = value;\n }\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 options;\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 defineHostSchemas,\n drivesSchema,\n mergeDrivePlan,\n resolveDriveDeclaration,\n resolveHostPlugins,\n seedDrives,\n type DriveSeederClient,\n type ResolvedDrive,\n type ResolvedPlugin,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { applyReactorEnvProjection } from \"./reactor-env.js\";\nimport { z } from \"zod\";\nimport { classicSwitchboardArgs } from \"../services/classic-args.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 // The verb owns dev mode; `runner.dev` is the host-file spelling of it.\n dev: devMode || runner.dev === true ? 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 // 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: () => (stopping ??= switchboard.shutdown()),\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/** 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":";;;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,0BACd,SACA,eACqB;CACrB,MAAM,EAAE,KAAK,YAAY,4BAA4B,OAAO;CAC5D,0BAA0B,SAAS,UAAU,QAAQ,KAAK,aAAa;CACvE,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,GAAG,GAC5C,IAAI,QAAQ,IAAI,UAAU,KAAA,GAAW,QAAQ,IAAI,QAAQ;CAI3D,MAAM,UAAU,eAAe,OAAO,CAAC,EAAE;CACzC,IAAI,SAAS,SAAS,UAAU,QAAQ,SAAS;EAG/C,IAAI,+BAA+B,KAA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IlC,MAAM,SAAS,EAFb,QAAQ,KAAK,OAAO,UAAU,OAEd,CAAc;AAClC","debug_id":"8604c920-467f-5ac7-b870-1d3fd5a160e6"}
1
+ {"version":3,"file":"switchboard.mjs","sources":["../../src/runners/reactor-env.ts","../../src/services/classic-args.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 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 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 // 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: () => (stopping ??= switchboard.shutdown()),\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,SAA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AC5B,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":"8f16679e-6120-5f1c-9f61-849b5d2b0b26"}
@@ -1,6 +1,6 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="9f2cd400-8719-5008-b948-dce162fc9198")}catch(e){}}();
3
- import { A as readProjectName, B as validateDeclaredHost, D as processResolveEnv, E as probeRun, H as writeRunRecord, I as resolveRunnerModule, L as runRecordOutputSource, N as resolveHostOutputs, O as producerOutputsSchemas, S as outputRefsOf, V as validateHost, g as isSchemaLike, h as getVerb, i as clearRunRecord, j as readRunRecord, n as ONE_SHOT_VERBS, v as loadHost, y as loadProducers, z as toStartedHandle } from "./compound-B6RZMA0Y-Cv3XMQ3Y.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="54c0e687-1b61-5f73-a4a3-9270d07b362c")}catch(e){}}();
3
+ import { D as loadHost, H as readRunRecord, J as runRecordOutputSource, L as probeRun, M as outputRefsOf, O as loadProducers, Q as toStartedHandle, R as processResolveEnv, V as readProjectName, W as resolveHostOutputs, b as getVerb, et as validateDeclaredHost, n as ONE_SHOT_VERBS, nt as writeRunRecord, q as resolveRunnerModule, s as clearRunRecord, tt as validateHost, w as isSchemaLike, z as producerOutputsSchemas } from "./compound-Gjt5rBfF-BmSW1XPB.mjs";
4
4
  //#region src/services/run/start-run.ts
5
5
  /**
6
6
  * `ph run <host> [verb]`: dispatch the verb (default `run`) of the host's
@@ -120,5 +120,5 @@ async function publishOutputs(runner, result, target) {
120
120
  //#endregion
121
121
  export { startRun };
122
122
 
123
- //# sourceMappingURL=start-run-BIaYSpHh.mjs.map
124
- //# debugId=9f2cd400-8719-5008-b948-dce162fc9198
123
+ //# sourceMappingURL=start-run-CDZ3YAr9.mjs.map
124
+ //# debugId=54c0e687-1b61-5f73-a4a3-9270d07b362c
@@ -1 +1 @@
1
- {"version":3,"file":"start-run-BIaYSpHh.mjs","sources":["../src/services/run/start-run.ts"],"sourcesContent":["import {\n clearRunRecord,\n getVerb,\n isSchemaLike,\n loadHost,\n loadProducers,\n ONE_SHOT_VERBS,\n outputRefsOf,\n probeRun,\n processResolveEnv,\n producerOutputsSchemas,\n readProjectName,\n readRunRecord,\n resolveHostOutputs,\n resolveRunnerModule,\n runRecordOutputSource,\n toStartedHandle,\n validateDeclaredHost,\n validateHost,\n writeRunRecord,\n type RunnerModule,\n} from \"@powerhousedao/host-core\";\n\nexport interface StartRunArgs {\n host: string;\n verb?: string;\n projectRoot?: string;\n debug?: boolean;\n}\n\n/**\n * `ph run <host> [verb]`: dispatch the verb (default `run`) of the host's\n * declared runner. There is deliberately no type→runner registry — what a\n * host does is written in its own file.\n *\n * The pipeline (typed-host-configs 3.5): declared validation (token shapes,\n * `$output` paths against the producers' outputsSchemas, the runner's\n * declaredHostSchema), the live-instance lock, resolution (`$output` from\n * the producers' live run records, `$env` from this process, the\n * `${userData}` sugar), resolved validation, then the verb with the parsed\n * host. A compound runner gets its declared host: its members resolve their\n * own tokens as they start.\n *\n * A reactor runner that exports `outputsSchema` has its handle's outputs\n * published in a v2 `.ph/run/<name>.json` record once ready; this is the only\n * standalone writer (mastra included). Compounds write their own record with\n * the members in it; one-shot verbs (`build`) return nothing and write none.\n */\nexport async function startRun(args: StartRunArgs): Promise<unknown> {\n const projectRoot = args.projectRoot ?? process.cwd();\n const loaded = await loadHost(projectRoot, args.host);\n const { warnSupersededConfigKeys } = await import(\"./superseded-config.js\");\n warnSupersededConfigKeys(projectRoot);\n const specifier = loaded.host.runner.module;\n const runner = await resolveRunnerModule(projectRoot, specifier);\n const verb = args.verb ?? \"run\";\n const fn = getVerb(runner, specifier, verb);\n const file = loaded.file;\n if (args.debug) {\n console.log({ host: loaded.host.name, runner: specifier, verb });\n }\n\n if (runner.kind === \"compound\") {\n validateDeclaredHost(runner, specifier, loaded.host, file);\n const host = validateHost(runner, specifier, loaded.host, file, {\n tokens: \"allow\",\n });\n return fn(host, { projectRoot, verb, env: process.env });\n }\n\n const projectName = readProjectName(projectRoot);\n const producers = await loadProducers(projectRoot, outputRefsOf(loaded.host));\n validateDeclaredHost(runner, specifier, loaded.host, file, {\n outputsSchemaOf: producerOutputsSchemas(producers),\n });\n const oneShot = ONE_SHOT_VERBS.has(verb);\n if (oneShot) {\n // `build` reads no other host's outputs: no producer needs to run.\n const host = validateHost(runner, specifier, loaded.host, file, {\n tokens: \"allow\",\n });\n return fn(host, { projectRoot, verb, env: process.env });\n }\n const publishes = isSchemaLike(runner.outputsSchema);\n // Before the verb starts anything: a second live instance would take\n // over the first one's record (and clear it on exit).\n if (publishes) assertNotRunning(projectRoot, loaded.host.name, projectName);\n const resolved = resolveHostOutputs(loaded.host, {\n outputs: runRecordOutputSource(projectRoot, {\n consumer: args.host,\n producers,\n projectName,\n }),\n ...processResolveEnv(projectRoot),\n where: `hosts/${args.host}/host.js`,\n });\n const host = validateHost(runner, specifier, resolved, file);\n const result = await fn(host, { projectRoot, verb, env: process.env });\n if (publishes && result !== undefined && result !== null) {\n await publishOutputs(runner, result, {\n projectRoot,\n projectName,\n hostName: loaded.host.name,\n specifier,\n verb,\n });\n }\n return result;\n}\n\nfunction assertNotRunning(\n projectRoot: string,\n hostName: string,\n projectName: string,\n): void {\n const probe = probeRun(projectRoot, hostName, projectName);\n if (probe.status === \"live\" && probe.record.pid !== process.pid) {\n throw new Error(\n `${hostName} is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`,\n );\n }\n if (probe.status === \"foreign\") {\n throw new Error(\n `.ph/run/${hostName}.json describes a live \"${probe.record.projectName}\", but this project is \"${projectName}\". Refusing to start a second instance.`,\n );\n }\n}\n\ninterface PublishTarget {\n projectRoot: string;\n projectName: string;\n hostName: string;\n specifier: string;\n verb: string;\n}\n\n/** Await `ready`, validate the outputs, write the v2 record and clear it on\n * exit. A handle that never gets ready or reports invalid outputs is shut\n * down before the error propagates. */\nasync function publishOutputs(\n runner: RunnerModule,\n result: unknown,\n target: PublishTarget,\n): Promise<void> {\n const where = `${target.specifier} ${target.verb}`;\n const handle = toStartedHandle(result, where);\n const name = target.projectName;\n let outputs: unknown;\n try {\n if (!isSchemaLike(runner.outputsSchema)) return;\n // Checked again after the start: an instance that started meanwhile.\n assertNotRunning(target.projectRoot, target.hostName, name);\n if (handle.ready) await handle.ready;\n const parsed = runner.outputsSchema.safeParse(handle.outputs);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map(\n (issue) =>\n ` - ${issue.path.map(String).join(\".\") || \"<root>\"}: ${issue.message}`,\n )\n .join(\"\\n\");\n throw new Error(\n `${where} reported outputs that fail its outputsSchema:\\n${issues}`,\n );\n }\n outputs = parsed.data;\n } catch (error) {\n await handle.shutdown?.();\n throw error;\n }\n\n writeRunRecord(target.projectRoot, {\n version: 2,\n host: target.hostName,\n projectName: name,\n kind: \"reactor\",\n verb: target.verb,\n pid: process.pid,\n startedAt: new Date().toISOString(),\n outputs: outputs as Record<string, unknown>,\n });\n // No SIGINT/SIGTERM handler: the switchboard reactor's own handler kills\n // the reactor before draining the api, and a parallel shutdown() would\n // break that order. Without an exit event the record keeps a dead pid,\n // which probeRun reports as stale.\n process.on(\"exit\", () => {\n if (readRunRecord(target.projectRoot, target.hostName)?.pid === process.pid)\n clearRunRecord(target.projectRoot, target.hostName);\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgDA,eAAsB,SAAS,MAAsC;CACnE,MAAM,cAAc,KAAK,eAAe,QAAQ,IAAI;CACpD,MAAM,SAAS,MAAM,SAAS,aAAa,KAAK,IAAI;CACpD,MAAM,EAAE,6BAA6B,MAAM,OAAO;CAClD,yBAAyB,WAAW;CACpC,MAAM,YAAY,OAAO,KAAK,OAAO;CACrC,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;CAC/D,MAAM,OAAO,KAAK,QAAQ;CAC1B,MAAM,KAAK,QAAQ,QAAQ,WAAW,IAAI;CAC1C,MAAM,OAAO,OAAO;CACpB,IAAI,KAAK,OACP,QAAQ,IAAI;EAAE,MAAM,OAAO,KAAK;EAAM,QAAQ;EAAW;CAAK,CAAC;CAGjE,IAAI,OAAO,SAAS,YAAY;EAC9B,qBAAqB,QAAQ,WAAW,OAAO,MAAM,IAAI;EAI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AAM,IAAI,MACR,WAAW,SAAS,0BAA0B,MAAM,OAAO,YAAY,0BAA0B,YAAY,wCAC/G;AAEJ;;;;AAaA,eAAe,eACb,QACA,QACA,QACe;CACf,MAAM,QAAQ,GAAG,OAAO,UAAU,GAAG,OAAO;CAC5C,MAAM,SAAS,gBAAgB,QAAQ,KAAK;CAC5C,MAAM,OAAO,OAAO;CACpB,IAAI;CACJ,IAAI;EACF,IAAI,CAAC,aAAa,OAAO,aAAa,GAAG;EAEzC,iBAAiB,OAAO,aAAa,OAAO,UAAU,IAAI;EAC1D,IAAI,OAAO,OAAO,MAAM,OAAO;EAC/B,MAAM,SAAS,OAAO,cAAc,UAAU,OAAO,OAAO;EAC5D,IAAI,CAAC,OAAO,SAAS;GACnB,MAAM,SAAS,OAAO,MAAM,OACzB,KACE,UACC,OAAO,MAAM,KAAK,IAAI,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,SAAS,IAAI,MAAM,SAClE,CAAC,CACA,KAAK,IAAI;GACZ,MAAM,IAAI,MACR,GAAG,MAAM,kDAAkD,QAC7D;EACF;EACA,UAAU,OAAO;CACnB,SAAS,OAAO;EACd,MAAM,OAAO,WAAW;EACxB,MAAM;CACR;CAEA,eAAe,OAAO,aAAa;EACjC,SAAS;EACT,MAAM,OAAO;EACb,aAAa;EACb,MAAM;EACN,MAAM,OAAO;EACb,KAAK,QAAQ;EACb,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;EACzB;CACX,CAAC;CAKD,QAAQ,GAAG,cAAc;EACvB,IAAI,cAAc,OAAO,aAAa,OAAO,QAAQ,CAAC,EAAE,QAAQ,QAAQ,KACtE,eAAe,OAAO,aAAa,OAAO,QAAQ;CACtD,CAAC;AACH","debug_id":"9f2cd400-8719-5008-b948-dce162fc9198"}
1
+ {"version":3,"file":"start-run-CDZ3YAr9.mjs","sources":["../src/services/run/start-run.ts"],"sourcesContent":["import {\n clearRunRecord,\n getVerb,\n isSchemaLike,\n loadHost,\n loadProducers,\n ONE_SHOT_VERBS,\n outputRefsOf,\n probeRun,\n processResolveEnv,\n producerOutputsSchemas,\n readProjectName,\n readRunRecord,\n resolveHostOutputs,\n resolveRunnerModule,\n runRecordOutputSource,\n toStartedHandle,\n validateDeclaredHost,\n validateHost,\n writeRunRecord,\n type RunnerModule,\n} from \"@powerhousedao/host-core\";\n\nexport interface StartRunArgs {\n host: string;\n verb?: string;\n projectRoot?: string;\n debug?: boolean;\n}\n\n/**\n * `ph run <host> [verb]`: dispatch the verb (default `run`) of the host's\n * declared runner. There is deliberately no type→runner registry — what a\n * host does is written in its own file.\n *\n * The pipeline (typed-host-configs 3.5): declared validation (token shapes,\n * `$output` paths against the producers' outputsSchemas, the runner's\n * declaredHostSchema), the live-instance lock, resolution (`$output` from\n * the producers' live run records, `$env` from this process, the\n * `${userData}` sugar), resolved validation, then the verb with the parsed\n * host. A compound runner gets its declared host: its members resolve their\n * own tokens as they start.\n *\n * A reactor runner that exports `outputsSchema` has its handle's outputs\n * published in a v2 `.ph/run/<name>.json` record once ready; this is the only\n * standalone writer (mastra included). Compounds write their own record with\n * the members in it; one-shot verbs (`build`) return nothing and write none.\n */\nexport async function startRun(args: StartRunArgs): Promise<unknown> {\n const projectRoot = args.projectRoot ?? process.cwd();\n const loaded = await loadHost(projectRoot, args.host);\n const { warnSupersededConfigKeys } = await import(\"./superseded-config.js\");\n warnSupersededConfigKeys(projectRoot);\n const specifier = loaded.host.runner.module;\n const runner = await resolveRunnerModule(projectRoot, specifier);\n const verb = args.verb ?? \"run\";\n const fn = getVerb(runner, specifier, verb);\n const file = loaded.file;\n if (args.debug) {\n console.log({ host: loaded.host.name, runner: specifier, verb });\n }\n\n if (runner.kind === \"compound\") {\n validateDeclaredHost(runner, specifier, loaded.host, file);\n const host = validateHost(runner, specifier, loaded.host, file, {\n tokens: \"allow\",\n });\n return fn(host, { projectRoot, verb, env: process.env });\n }\n\n const projectName = readProjectName(projectRoot);\n const producers = await loadProducers(projectRoot, outputRefsOf(loaded.host));\n validateDeclaredHost(runner, specifier, loaded.host, file, {\n outputsSchemaOf: producerOutputsSchemas(producers),\n });\n const oneShot = ONE_SHOT_VERBS.has(verb);\n if (oneShot) {\n // `build` reads no other host's outputs: no producer needs to run.\n const host = validateHost(runner, specifier, loaded.host, file, {\n tokens: \"allow\",\n });\n return fn(host, { projectRoot, verb, env: process.env });\n }\n const publishes = isSchemaLike(runner.outputsSchema);\n // Before the verb starts anything: a second live instance would take\n // over the first one's record (and clear it on exit).\n if (publishes) assertNotRunning(projectRoot, loaded.host.name, projectName);\n const resolved = resolveHostOutputs(loaded.host, {\n outputs: runRecordOutputSource(projectRoot, {\n consumer: args.host,\n producers,\n projectName,\n }),\n ...processResolveEnv(projectRoot),\n where: `hosts/${args.host}/host.js`,\n });\n const host = validateHost(runner, specifier, resolved, file);\n const result = await fn(host, { projectRoot, verb, env: process.env });\n if (publishes && result !== undefined && result !== null) {\n await publishOutputs(runner, result, {\n projectRoot,\n projectName,\n hostName: loaded.host.name,\n specifier,\n verb,\n });\n }\n return result;\n}\n\nfunction assertNotRunning(\n projectRoot: string,\n hostName: string,\n projectName: string,\n): void {\n const probe = probeRun(projectRoot, hostName, projectName);\n if (probe.status === \"live\" && probe.record.pid !== process.pid) {\n throw new Error(\n `${hostName} is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`,\n );\n }\n if (probe.status === \"foreign\") {\n throw new Error(\n `.ph/run/${hostName}.json describes a live \"${probe.record.projectName}\", but this project is \"${projectName}\". Refusing to start a second instance.`,\n );\n }\n}\n\ninterface PublishTarget {\n projectRoot: string;\n projectName: string;\n hostName: string;\n specifier: string;\n verb: string;\n}\n\n/** Await `ready`, validate the outputs, write the v2 record and clear it on\n * exit. A handle that never gets ready or reports invalid outputs is shut\n * down before the error propagates. */\nasync function publishOutputs(\n runner: RunnerModule,\n result: unknown,\n target: PublishTarget,\n): Promise<void> {\n const where = `${target.specifier} ${target.verb}`;\n const handle = toStartedHandle(result, where);\n const name = target.projectName;\n let outputs: unknown;\n try {\n if (!isSchemaLike(runner.outputsSchema)) return;\n // Checked again after the start: an instance that started meanwhile.\n assertNotRunning(target.projectRoot, target.hostName, name);\n if (handle.ready) await handle.ready;\n const parsed = runner.outputsSchema.safeParse(handle.outputs);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map(\n (issue) =>\n ` - ${issue.path.map(String).join(\".\") || \"<root>\"}: ${issue.message}`,\n )\n .join(\"\\n\");\n throw new Error(\n `${where} reported outputs that fail its outputsSchema:\\n${issues}`,\n );\n }\n outputs = parsed.data;\n } catch (error) {\n await handle.shutdown?.();\n throw error;\n }\n\n writeRunRecord(target.projectRoot, {\n version: 2,\n host: target.hostName,\n projectName: name,\n kind: \"reactor\",\n verb: target.verb,\n pid: process.pid,\n startedAt: new Date().toISOString(),\n outputs: outputs as Record<string, unknown>,\n });\n // No SIGINT/SIGTERM handler: the switchboard reactor's own handler kills\n // the reactor before draining the api, and a parallel shutdown() would\n // break that order. Without an exit event the record keeps a dead pid,\n // which probeRun reports as stale.\n process.on(\"exit\", () => {\n if (readRunRecord(target.projectRoot, target.hostName)?.pid === process.pid)\n clearRunRecord(target.projectRoot, target.hostName);\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgDA,eAAsB,SAAS,MAAsC;CACnE,MAAM,cAAc,KAAK,eAAe,QAAQ,IAAI;CACpD,MAAM,SAAS,MAAM,SAAS,aAAa,KAAK,IAAI;CACpD,MAAM,EAAE,6BAA6B,MAAM,OAAO;CAClD,yBAAyB,WAAW;CACpC,MAAM,YAAY,OAAO,KAAK,OAAO;CACrC,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;CAC/D,MAAM,OAAO,KAAK,QAAQ;CAC1B,MAAM,KAAK,QAAQ,QAAQ,WAAW,IAAI;CAC1C,MAAM,OAAO,OAAO;CACpB,IAAI,KAAK,OACP,QAAQ,IAAI;EAAE,MAAM,OAAO,KAAK;EAAM,QAAQ;EAAW;CAAK,CAAC;CAGjE,IAAI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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]="22037c38-3549-5922-bd54-945c55ee7c8d")}catch(e){}}();
3
- import { i as mergeDefaultDrives, u as rebaseDriveUrl } from "./dist-CCLkwpTS.mjs";
4
- import { a as parseDefaultDrivesUrl, i as wasFlagExplicitlyPassed } from "./cli-connect-override-CEJhQWRX.mjs";
5
- import { t as runConnectStudio } from "./connect-studio-B1_4TNEb.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="12c43cde-3e39-53ed-9bf3-2ffd6518b05f")}catch(e){}}();
3
+ import { a as mergeDefaultDrives, f as rebaseDriveUrl } from "./dist-BVqNlv1z.mjs";
4
+ import { a as parseDefaultDrivesUrl, i as wasFlagExplicitlyPassed } from "./cli-connect-override-BrS-X8Rs.mjs";
5
+ import { t as runConnectStudio } from "./connect-studio-DGWUidCV.mjs";
6
6
  import { a as generateProjectDriveId } from "./utils-9KyRM0mf.mjs";
7
7
  import { i as POWERHOUSE_DRIVE_ICON, r as startSwitchboard$1 } from "./switchboard-h4-XgP1h.mjs";
8
8
  import fs from "node:fs";
@@ -610,5 +610,5 @@ async function startVetra(args) {
610
610
  //#endregion
611
611
  export { seedWorkflowsDrive, startVetra };
612
612
 
613
- //# sourceMappingURL=vetra-UQsfYM_Q.mjs.map
614
- //# debugId=22037c38-3549-5922-bd54-945c55ee7c8d
613
+ //# sourceMappingURL=vetra-DO5eUgAo.mjs.map
614
+ //# debugId=12c43cde-3e39-53ed-9bf3-2ffd6518b05f
@@ -1 +1 @@
1
- {"version":3,"file":"vetra-UQsfYM_Q.mjs","sources":["../src/utils/configure-vetra-github-url.ts","../src/utils/resolve-switchboard-port.ts","../src/utils/vetra-runtime.ts","../src/services/vetra.ts"],"sourcesContent":["import {\n createVetraDocument,\n getVetraDocuments,\n setPackageGithubUrl,\n} from \"@powerhousedao/common/utils\";\nimport { red } from \"colorette\";\nimport { execSync } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\n\n/**\n * Get git remote URL (origin)\n * @returns Git remote URL or null if not configured\n */\nfunction getGitRemoteUrl(): string | null {\n try {\n const url = execSync(\"git remote get-url origin\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim();\n return url || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Prompt user to enter a custom GitHub URL\n */\nasync function promptForCustomUrl(): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(\"\\nEnter GitHub URL (or press Enter to skip): \");\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const url = answer.trim();\n resolve(url || null);\n });\n });\n}\n\n/**\n * Prompt yes/no question\n */\nasync function promptYesNo(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(`\\n${question} (y/n): `);\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const response = answer.trim().toLowerCase();\n resolve(response === \"y\" || response === \"yes\");\n });\n });\n}\n\n/**\n * Prompt user to select or enter GitHub URL\n * @param gitRemoteUrl - Git remote URL if available\n * @returns Selected URL or null if skipped\n */\nasync function promptForGithubUrl(\n gitRemoteUrl: string | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log(\"\\n\" + \"=\".repeat(50));\n console.log(\"🔍 Vetra Package Configuration\");\n console.log(\"=\".repeat(50));\n console.log(\n \"\\nWe detected a Vetra package document in your remote drive without a GitHub URL configured.\",\n );\n console.log(\"\\nWould you like to configure the GitHub URL now?\");\n\n if (gitRemoteUrl) {\n console.log(`\\nGit remote URL detected: ${gitRemoteUrl}`);\n console.log(\"\\nOptions:\");\n console.log(\"1. Use detected URL\");\n console.log(\"2. Enter a different URL\");\n console.log(\"3. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-3): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n resolve(gitRemoteUrl);\n } else if (choice === \"2\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"3\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-3): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n } else {\n console.log(\"\\nNo git remote URL detected.\");\n console.log(\"\\nOptions:\");\n console.log(\"1. Enter GitHub URL manually\");\n console.log(\"2. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-2): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"2\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-2): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n }\n });\n}\n\n/**\n * Set git remote URL (origin)\n */\nfunction setGitRemoteUrl(url: string): void {\n try {\n execSync(`git remote add origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin set to: ${url}`);\n } catch {\n try {\n execSync(`git remote set-url origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin updated to: ${url}`);\n } catch {\n console.error(red(`❌ Failed to set git remote URL`));\n }\n }\n}\n\n/**\n * Validates documents and returns the target document to use\n * Warns if multiple documents found\n */\nfunction validateAndSelectDocument<T>(documents: T[]): T | null {\n if (documents.length === 0) {\n return null;\n }\n\n if (documents.length > 1) {\n console.warn(\n `⚠️ Warning: Multiple Vetra documents found (${documents.length}). Using first document.`,\n );\n }\n\n return documents[0];\n}\n\nasync function applyGithubUrlConfiguration(\n graphqlEndpoint: string,\n vetraDriveId: string,\n documentId: string,\n selectedUrl: string,\n shouldSetRemote: boolean,\n): Promise<void> {\n // Set package GitHub URL\n await setPackageGithubUrl(\n graphqlEndpoint,\n vetraDriveId,\n documentId,\n selectedUrl,\n );\n\n console.log(`✅ GitHub URL configured: ${selectedUrl}`);\n\n // Set git remote URL if requested\n if (shouldSetRemote) {\n setGitRemoteUrl(selectedUrl);\n }\n}\n\nfunction logVerbose(message: string, verbose?: boolean): void {\n if (verbose) {\n console.log(message);\n }\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Configure GitHub URL for Vetra documents\n * @param switchboardPort - Port where switchboard is running\n * @param vetraDriveUrl - Remote drive URL\n * @param verbose - Enable verbose logging\n */\nexport async function configureVetraGithubUrl(\n switchboardPort: number,\n vetraDriveUrl: string,\n verbose?: boolean,\n): Promise<void> {\n logVerbose(\"Checking GitHub URL configuration...\", verbose);\n\n try {\n const graphqlEndpoint = `http://localhost:${switchboardPort}/graphql`;\n const vetraDriveId = vetraDriveUrl.split(\"/\").pop();\n if (!vetraDriveId) {\n throw new Error(\"Invalid vetraDriveUrl: unable to extract drive ID\");\n }\n\n const documents = await getVetraDocuments(graphqlEndpoint, vetraDriveId);\n\n // Skip if already configured\n if (documents.some((doc) => doc.githubUrl)) {\n logVerbose(\"GitHub URL already configured, skipping setup\", verbose);\n return;\n }\n\n // Get or create target document\n let targetDocumentId: string;\n const targetDocument = validateAndSelectDocument(documents);\n\n // Collect user input\n const gitRemoteUrl = getGitRemoteUrl();\n const selectedUrl = await promptForGithubUrl(gitRemoteUrl);\n\n if (!selectedUrl) {\n logVerbose(\"GitHub URL configuration skipped\", verbose);\n return;\n }\n\n let shouldSetRemote = false;\n if (selectedUrl !== gitRemoteUrl && !gitRemoteUrl) {\n shouldSetRemote = await promptYesNo(\"Set this as your git remote URL?\");\n }\n\n if (!targetDocument) {\n logVerbose(\"No Vetra documents found, creating new document...\", verbose);\n\n targetDocumentId = await createVetraDocument(\n graphqlEndpoint,\n vetraDriveId,\n \"vetra-package\",\n );\n\n logVerbose(`Created new document: ${targetDocumentId}`, verbose);\n } else {\n targetDocumentId = targetDocument.id;\n }\n\n await applyGithubUrlConfiguration(\n graphqlEndpoint,\n vetraDriveId,\n targetDocumentId,\n selectedUrl,\n shouldSetRemote,\n );\n } catch (error) {\n console.error(\n red(\n `⚠️ GitHub URL configuration failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n logVerbose(String(error), verbose);\n }\n}\n","import { isPortAvailable } from \"@powerhousedao/switchboard/server\";\nimport { yellow } from \"colorette\";\n\nconst MAX_FALLBACK_ATTEMPTS = 20;\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function findFreePort(start: number): Promise<number | null> {\n for (let i = 0; i < MAX_FALLBACK_ATTEMPTS; i++) {\n const candidate = start + i;\n if (await isPortAvailable(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Resolve the port switchboard should bind to. If the requested port is free,\n * returns it unchanged. If it's in use, walks forward for the next free port\n * and — in an interactive terminal — asks the user to confirm the fallback.\n * In CI / piped contexts the fallback is applied automatically so scripts\n * don't hang on an unanswered prompt.\n *\n * Throws a process.exit(1) when the user declines the prompt or when no free\n * port is available in the search window.\n */\nexport async function resolveSwitchboardPort(\n requested: number,\n): Promise<number> {\n if (await isPortAvailable(requested)) return requested;\n\n const candidate = await findFreePort(requested + 1);\n if (candidate === null) {\n console.error(\n `Port ${requested} is in use and no free port was found in the range ${requested}-${requested + MAX_FALLBACK_ATTEMPTS - 1}.`,\n );\n process.exit(1);\n }\n\n if (!isInteractive()) {\n console.log(\n yellow(\n `Port ${requested} is in use. Falling back to port ${candidate} (non-interactive; skipping confirmation).`,\n ),\n );\n return candidate;\n }\n\n const enquirer = await import(\"enquirer\");\n\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `Port ${requested} is in use. Use port ${candidate} instead?`,\n initial: true,\n });\n confirmed = answer.confirmed;\n } catch {\n // user aborted the prompt (Ctrl-C); treat as decline\n confirmed = false;\n }\n\n if (!confirmed) {\n console.error(\n `Aborted. Free port ${requested} or pass --switchboard-port <port> to choose a different port.`,\n );\n process.exit(1);\n }\n\n return candidate;\n}\n","import { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport type VetraRuntimeRecord = {\n pid: number;\n projectName: string;\n switchboardPort: number;\n connectPort: number;\n mcpUrl: string;\n startedAt: string;\n};\n\nexport type VetraProbe =\n | { status: \"none\" }\n | { status: \"stale\" }\n | { status: \"live\"; record: VetraRuntimeRecord }\n | { status: \"foreign\"; record: VetraRuntimeRecord };\n\nconst READY_TIMEOUT_MS = 2000;\n\n// Under the project's .ph tree — relocated with it by PH_USER_DATA_DIR.\nconst recordPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra-runtime.json\");\n\nexport function readVetraRuntime(\n projectDir: string,\n): VetraRuntimeRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(recordPath(projectDir), \"utf8\"),\n ) as VetraRuntimeRecord;\n } catch {\n // Missing or corrupt: either way there is no usable record.\n return undefined;\n }\n}\n\nexport function writeVetraRuntime(\n projectDir: string,\n record: VetraRuntimeRecord,\n): void {\n const target = recordPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\\n`);\n}\n\nexport function clearVetraRuntime(projectDir: string): void {\n try {\n fs.rmSync(recordPath(projectDir));\n } catch {\n // Already gone.\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nasync function isReady(port: number): Promise<boolean> {\n try {\n const response = await fetch(`http://localhost:${port}/ready`, {\n signal: AbortSignal.timeout(READY_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Decide whether the recorded instance is actually serving this project.\n *\n * All three checks are load-bearing. A pid can be reused by an unrelated\n * process, so a live pid proves nothing on its own. Another project's\n * switchboard would answer `/ready` on its own port, so a healthy `/ready`\n * proves nothing either. And the recorded `projectName` is what separates\n * \"my instance\" from \"someone else's instance that happens to hold this\n * port\" — which is precisely the confusion that let an agent write document\n * models into a different project's drive.\n *\n * A stale record is deleted so the next start is unblocked. A foreign one is\n * left alone: it describes something that is alive.\n */\nexport async function probeVetraRuntime(\n projectDir: string,\n projectName: string,\n): Promise<VetraProbe> {\n const record = readVetraRuntime(projectDir);\n if (!record) return { status: \"none\" };\n\n if (!isPidAlive(record.pid) || !(await isReady(record.switchboardPort))) {\n clearVetraRuntime(projectDir);\n return { status: \"stale\" };\n }\n\n if (record.projectName !== projectName) {\n return { status: \"foreign\", record };\n }\n return { status: \"live\", record };\n}\n\nconst MCP_FILES = [\".mcp.json\", path.join(\".cursor\", \"mcp.json\")];\n\n/**\n * Point every generated MCP config at `port`, returning the files changed.\n *\n * An MCP client resolves these files at session start and cannot read the\n * project config or `.env`, so when an override moves the port the literal\n * has to be corrected on disk. Rewrites in place rather than regenerating,\n * so any other servers or hand-added keys survive.\n */\nexport function syncMcpPort(projectDir: string, port: number): string[] {\n const changed: string[] = [];\n for (const rel of MCP_FILES) {\n const target = path.join(projectDir, rel);\n if (!fs.existsSync(target)) continue;\n\n let parsed: { mcpServers?: Record<string, { url?: string }> };\n try {\n parsed = JSON.parse(fs.readFileSync(target, \"utf8\")) as typeof parsed;\n } catch {\n // Hand-broken JSON is the author's to fix; don't clobber it.\n continue;\n }\n\n const server = parsed.mcpServers?.[\"reactor-mcp\"];\n if (!server?.url) continue;\n\n const wanted = `http://localhost:${port}/mcp`;\n if (server.url === wanted) continue;\n\n server.url = wanted;\n fs.writeFileSync(target, `${JSON.stringify(parsed, null, 2)}\\n`);\n changed.push(rel);\n }\n return changed;\n}\n","import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport { join } from \"node:path\";\nimport { blue, green, red, yellow, type Color } from \"colorette\";\nimport type { ILogger } from \"document-model\";\nimport { childLogger, setLogLevel } from \"document-model\";\nimport { createLogger } from \"vite\";\nimport type { VetraArgs } from \"../types.js\";\nimport { generateProjectDriveId, POWERHOUSE_CONFIG_FILE } from \"../utils.js\";\nimport { wasFlagExplicitlyPassed } from \"../utils/cli-connect-override.js\";\nimport {\n configureVetraGithubUrl,\n sleep,\n} from \"../utils/configure-vetra-github-url.js\";\nimport { POWERHOUSE_DRIVE_ICON } from \"../utils/drive-icons.js\";\nimport { mergeDefaultDrives, rebaseDriveUrl } from \"@powerhousedao/host-core\";\nimport { parseDefaultDrivesUrl } from \"../utils/parse-default-drives.js\";\nimport { resolveSwitchboardPort } from \"../utils/resolve-switchboard-port.js\";\nimport {\n clearVetraRuntime,\n probeVetraRuntime,\n syncMcpPort,\n writeVetraRuntime,\n} from \"../utils/vetra-runtime.js\";\nimport { runConnectStudio } from \"./connect-studio.js\";\nimport { startSwitchboard } from \"./switchboard.js\";\n\nconst VETRA_DRIVE_NAME = \"vetra\";\n\nconst getDefaultVetraUrl = (port: number) =>\n `http://localhost:${port}/d/${generateProjectDriveId(VETRA_DRIVE_NAME)}`;\n\nconst getDriveId = (driveUrl: string | undefined): string =>\n driveUrl?.split(\"/\").pop() ?? generateProjectDriveId(VETRA_DRIVE_NAME);\n\n// rebaseDriveUrl moved to @powerhousedao/host-core (uniform-runners P1.4) —\n// one implementation shared by this classic path and the generic compound.\n\nfunction createViteLogger(color: Color) {\n const customLogger = createLogger(\"info\");\n const loggerInfo = customLogger.info.bind(customLogger);\n customLogger.info = (msg, options) => {\n loggerInfo(color(msg), options);\n };\n const loggerWarn = customLogger.warn.bind(customLogger);\n customLogger.warn = (msg, options) => {\n loggerWarn(yellow(msg), options);\n };\n const loggerError = customLogger.error.bind(customLogger);\n customLogger.error = (msg, options) => {\n loggerError(red(msg), options);\n };\n\n const loggerWarnOnce = customLogger.warnOnce.bind(customLogger);\n customLogger.warnOnce = (msg, options) => {\n loggerWarnOnce(yellow(msg), options);\n };\n return customLogger;\n}\n\nasync function startVetraPreviewDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n): Promise<string | null> {\n const previewDriveId = generateProjectDriveId(\"preview\");\n\n const previewDrive = {\n id: previewDriveId,\n slug: previewDriveId,\n global: {\n name: \"Vetra Preview\",\n icon: POWERHOUSE_DRIVE_ICON,\n nodes: [],\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(reactor, previewDrive, port);\n\n if (verbose && driveUrl) {\n console.log(blue(`Vetra Switchboard: Preview drive: ${driveUrl}`));\n }\n return driveUrl ?? null;\n}\n\n// Opens in Workflow Studio; only seeded when the switchboard runs workflows.\n// Exported for the switchboard bridge runner: a hosts project with\n// reactor.workflows enabled seeds the SAME project-hashed drive this vetra\n// path does, until drive provisioning becomes a plugin contribution.\nexport async function seedWorkflowsDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n): Promise<string | null> {\n const workflowsDrive = {\n id: generateProjectDriveId(\"workflows\"),\n slug: \"workflows\",\n global: { name: \"Workflows\" },\n preferredEditor: \"workflow-studio\",\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(reactor, workflowsDrive, port);\n\n if (verbose && driveUrl) {\n console.log(blue(`Vetra Switchboard: Workflows drive: ${driveUrl}`));\n }\n return driveUrl ?? null;\n}\nasync function startLocalVetraSwitchboard(args: VetraArgs, logger?: ILogger) {\n const {\n connectPort,\n switchboardPort,\n dev,\n packages,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n remoteDrive,\n interactive,\n watch,\n verbose,\n } = args;\n\n // Convert single remote drive to array if provided\n const remoteDrives = remoteDrive ? [remoteDrive] : [];\n\n const vetraProcessorConfig: VetraProcessorConfigType = {\n interactive,\n driveUrl: remoteDrive ?? getDefaultVetraUrl(connectPort),\n driveId: getDriveId(remoteDrive),\n };\n\n const processorConfig = new Map<string, unknown>();\n processorConfig.set(VETRA_PROCESSOR_CONFIG_KEY, vetraProcessorConfig);\n\n const vetraDriveId = generateProjectDriveId(VETRA_DRIVE_NAME);\n\n // When the user didn't opt into strict-port semantics, check for a port\n // conflict up front and ask for confirmation before binding a fallback.\n // Doing this in the CLI layer keeps the interactive prompt out of the\n // switchboard server package and aligns with the existing prerelease-tag\n // confirmation flow in `ph publish`.\n const resolvedSwitchboardPort = args.strictPort\n ? switchboardPort\n : await resolveSwitchboardPort(switchboardPort);\n\n try {\n const switchboard = await startSwitchboard(\n {\n ...args,\n useVetraDrive: true, // Use Vetra drive instead of Powerhouse drive\n mcp: true,\n port: resolvedSwitchboardPort,\n // We've already probed and (when interactive) confirmed the port with\n // the user, so keep the server from running its own fallback on top.\n strictPort: true,\n dev,\n packages,\n remoteDrives,\n vetraDriveId,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n processorConfig,\n basePath: undefined,\n keypairPath: undefined,\n dbPath: args.dbPath,\n useIdentity: undefined,\n migrate: undefined,\n migrateStatus: undefined,\n reset: undefined,\n yes: undefined,\n requireIdentity: undefined,\n },\n logger,\n );\n\n const actualSwitchboardPort = switchboard.port;\n\n // Add preview drive (only in watch mode)\n let previewDriveUrl: string | null = null;\n if (watch) {\n try {\n previewDriveUrl = await startVetraPreviewDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n let workflowsDriveUrl: string | null = null;\n if (switchboard.workflowsEnabled) {\n try {\n workflowsDriveUrl = await seedWorkflowsDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Started successfully`));\n if (remoteDrive) {\n console.log(\n blue(`Vetra Switchboard: Syncing with remote drive: ${remoteDrive}`),\n );\n }\n } else {\n console.log();\n console.log(\n blue(\n `Vetra Switchboard: http://localhost:${actualSwitchboardPort}/graphql`,\n ),\n );\n console.log(blue(` ➜ Drive URL: ${switchboard.defaultDriveUrl}`));\n if (previewDriveUrl) {\n console.log(blue(` ➜ Preview Drive URL: ${previewDriveUrl}`));\n }\n if (workflowsDriveUrl) {\n console.log(blue(` ➜ Workflows Drive URL: ${workflowsDriveUrl}`));\n }\n }\n return {\n driveUrl: switchboard.defaultDriveUrl || \"\",\n previewDriveUrl: previewDriveUrl,\n workflowsDriveUrl,\n switchboardPort: actualSwitchboardPort,\n };\n } catch (error) {\n console.error(\n red(\n `Vetra Switchboard: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n\nexport async function startVetra(args: VetraArgs) {\n const {\n connectPort,\n verbose,\n remoteDrive,\n disableConnect,\n debug,\n httpsCertFile,\n httpsKeyFile,\n disableLocalPackages,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n watchTimeout,\n } = args;\n\n const switchboardLogger = childLogger([\"vetra\", \"switchboard\"]);\n\n // One Vetra per project. Two instances over one working tree would contend\n // for the same `.ph/read-model.db` and `.ph/reactor-storage`, and leave the\n // project with two drives that diverge.\n const projectDir = process.cwd();\n const { readPackageSync } = await import(\"read-pkg\");\n const projectName = readPackageSync({ cwd: projectDir }).name;\n const probe = await probeVetraRuntime(projectDir, projectName);\n\n if (probe.status === \"live\") {\n console.log();\n console.log(green(\"Vetra is already running for this project.\"));\n console.log(\n green(` ➜ Connect: http://localhost:${probe.record.connectPort}`),\n );\n console.log(\n green(\n ` ➜ Switchboard: http://localhost:${probe.record.switchboardPort}/graphql`,\n ),\n );\n console.log(\n `Stop that instance (pid ${probe.record.pid}) if you need to restart it.`,\n );\n return;\n }\n\n if (probe.status === \"foreign\") {\n console.error(\n red(\n `.ph/vetra-runtime.json describes a live Vetra for \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance. ` +\n `Delete .ph/vetra-runtime.json if that record is wrong.`,\n ),\n );\n process.exit(1);\n }\n\n try {\n // Set default log level to info if not already specified\n if (!process.env.LOG_LEVEL) {\n setLogLevel(\"info\");\n }\n\n if (verbose) {\n switchboardLogger.info(\"Starting Vetra Switchboard...\");\n if (remoteDrive) {\n const source = remoteDrive\n ? \"command line argument\"\n : \"powerhouse.config.json\";\n switchboardLogger.info(`Using vetraUrl from ${source}: ${remoteDrive}`);\n }\n }\n const switchboardResult = await startLocalVetraSwitchboard(\n {\n ...args,\n dev: true, // Vetra always runs in dev mode to load local packages\n httpsKeyFile,\n httpsCertFile,\n disableLocalPackages,\n debug,\n },\n switchboardLogger,\n );\n const driveUrl: string = switchboardResult.driveUrl || remoteDrive || \"\";\n const previewDriveUrl = switchboardResult.previewDriveUrl;\n const workflowsDriveUrl = switchboardResult.workflowsDriveUrl;\n const actualSwitchboardPort = switchboardResult.switchboardPort;\n\n // Record what we actually bound, so a second `ph vetra` can tell a live\n // instance from a stale file, and so an agent can see the real ports.\n writeVetraRuntime(projectDir, {\n pid: process.pid,\n projectName,\n switchboardPort: actualSwitchboardPort,\n connectPort,\n mcpUrl: `http://localhost:${actualSwitchboardPort}/mcp`,\n startedAt: new Date().toISOString(),\n });\n const releaseRuntimeRecord = () => clearVetraRuntime(projectDir);\n process.on(\"exit\", releaseRuntimeRecord);\n process.on(\"SIGINT\", () => {\n releaseRuntimeRecord();\n process.exit(130);\n });\n process.on(\"SIGTERM\", () => {\n releaseRuntimeRecord();\n process.exit(143);\n });\n\n // An MCP client resolved `.mcp.json` before this process started and\n // cannot re-read it, so a drifted literal means the agent is pointed at\n // the wrong port — possibly another project's reactor. Correct the file\n // and say so plainly; we cannot fix the already-open client ourselves.\n const driftedMcpFiles = syncMcpPort(projectDir, actualSwitchboardPort);\n if (driftedMcpFiles.length > 0) {\n console.log(\n yellow(\n `Updated ${driftedMcpFiles.join(\" and \")} to port ${actualSwitchboardPort}. ` +\n `Reconnect your MCP client (/mcp) to pick it up. ` +\n `This edit is local — do not commit it.`,\n ),\n );\n }\n\n // Configure GitHub URL if remote drive is set\n if (remoteDrive) {\n // give some time for the drive to process initial strands\n await sleep(3000);\n\n await configureVetraGithubUrl(\n actualSwitchboardPort,\n remoteDrive,\n verbose,\n );\n\n // give some time for the user to read log messages\n await sleep(2000);\n }\n\n if (verbose) {\n console.log(\"Starting Codegen Reactor...\");\n }\n\n // Start Connect pointing to the drive (unless disabled)\n if (!disableConnect) {\n // --drives-public-base: advertise proxy-reachable drive URLs to the\n // browser instead of the switchboard's localhost origin.\n const publicBase = args.drivesPublicBase;\n const browserDriveUrl = publicBase\n ? rebaseDriveUrl(driveUrl, publicBase)\n : driveUrl;\n const browserPreviewDriveUrl =\n previewDriveUrl && publicBase\n ? rebaseDriveUrl(previewDriveUrl, publicBase)\n : previewDriveUrl;\n const browserWorkflowsDriveUrl =\n workflowsDriveUrl && publicBase\n ? rebaseDriveUrl(workflowsDriveUrl, publicBase)\n : workflowsDriveUrl;\n\n // The resolved default-drive list: vetra's own drives first (the\n // Vetra drive, the preview drive in watch mode, and the Workflows\n // drive when workflows are on), then the\n // project's configured `connect.drives.defaultDrives` from\n // powerhouse.config.json (issue #3023). A drive vetra also starts is\n // listed only once. An explicit `--default-drives-url` is appended on\n // top of this list by buildStudioConnectOverride — it never replaces\n // the vetra drives.\n const vetraDriveEntries = [\n ...(browserDriveUrl\n ? [{ url: browserDriveUrl, name: null, icon: null }]\n : []),\n ...(browserPreviewDriveUrl\n ? [{ url: browserPreviewDriveUrl, name: null, icon: null }]\n : []),\n ...(browserWorkflowsDriveUrl\n ? [{ url: browserWorkflowsDriveUrl, name: null, icon: null }]\n : []),\n ];\n const configuredDefaultDrives =\n getConfig(join(projectDir, POWERHOUSE_CONFIG_FILE)).connect?.drives\n ?.defaultDrives ?? [];\n const resolvedDefaultDrives = mergeDefaultDrives(\n vetraDriveEntries,\n configuredDefaultDrives,\n );\n\n if (verbose) {\n console.log(\"Starting Connect...\");\n // Mirror buildStudioConnectOverride: an explicit\n // --default-drives-url is appended to the resolved list.\n const flagDefaultDrives = wasFlagExplicitlyPassed(\"default-drives-url\")\n ? parseDefaultDrivesUrl(args.defaultDrivesUrl ?? \"\")\n : [];\n const printedDefaultDrives = mergeDefaultDrives(\n resolvedDefaultDrives,\n flagDefaultDrives,\n );\n console.log(\n ` ➜ Connect will use default drives: ${printedDefaultDrives\n .map((d) => (\"url\" in d ? d.url : `local:${d.id}`))\n .join(\", \")}`,\n );\n }\n console.log();\n console.log(green(`Vetra Connect: http://localhost:${connectPort}`));\n\n const customViteLogger = createViteLogger(green);\n\n // Programmatic override forwarded to the Connect runtime config —\n // vetra always sets these regardless of what the user typed on the\n // command line. We pass it as the explicit third arg to\n // runConnectStudio so it survives the `wasFlagExplicitlyPassed`\n // gating (the user didn't pass --default-drives-url; vetra is setting\n // it itself).\n const vetraDrivesOverride = {\n drives: {\n defaultDrives: resolvedDefaultDrives,\n preserveStrategy: \"preserve-all\" as const,\n },\n };\n\n await runConnectStudio(\n {\n ...args,\n port: connectPort,\n disableLocalPackages,\n debug,\n host: host,\n open: open,\n cors: cors,\n strictPort: strictPort,\n printUrls: printUrls,\n bindCLIShortcuts: bindCLIShortcuts,\n watchTimeout: watchTimeout,\n },\n customViteLogger,\n vetraDrivesOverride,\n );\n }\n } catch (error) {\n console.error(error);\n }\n}\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M,0BACJ,UAAU,KAAK,YAAA,wBAAkC,CAAC,CAAC,CAAC,SAAS,QACzD,iBAAiB,CAAC;GACxB,MAAM,wBAAwB,mBAC5B,mBACA,uBACF;GAEA,IAAI,SAAS;IACX,QAAQ,IAAI,qBAAqB;IAGjC,MAAM,oBAAoB,wBAAwB,oBAAoB,IAClE,sBAAsB,KAAK,oBAAoB,EAAE,IACjD,CAAC;IACL,MAAM,uBAAuB,mBAC3B,uBACA,iBACF;IACA,QAAQ,IACN,yCAAyC,qBACtC,KAAK,MAAO,SAAS,IAAI,EAAE,MAAM,SAAS,EAAE,IAAK,CAAC,CAClD,KAAK,IAAI,GACd;GACF;GACA,QAAQ,IAAI;GACZ,QAAQ,IAAI,MAAM,mCAAmC,aAAa,CAAC;GAEnE,MAAM,mBAAmB,iBAAiB,KAAK;GAQ/C,MAAM,sBAAsB,EAC1B,QAAQ;IACN,eAAe;IACf,kBAAkB;GACpB,EACF;GAEA,MAAM,iBACJ;IACE,GAAG;IACH,MAAM;IACN;IACA;IACM;IACA;IACA;IACM;IACD;IACO;IACJ;GAChB,GACA,kBACA,mBACF;EACF;CACF,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AACF","debug_id":"22037c38-3549-5922-bd54-945c55ee7c8d"}
1
+ {"version":3,"file":"vetra-DO5eUgAo.mjs","sources":["../src/utils/configure-vetra-github-url.ts","../src/utils/resolve-switchboard-port.ts","../src/utils/vetra-runtime.ts","../src/services/vetra.ts"],"sourcesContent":["import {\n createVetraDocument,\n getVetraDocuments,\n setPackageGithubUrl,\n} from \"@powerhousedao/common/utils\";\nimport { red } from \"colorette\";\nimport { execSync } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\n\n/**\n * Get git remote URL (origin)\n * @returns Git remote URL or null if not configured\n */\nfunction getGitRemoteUrl(): string | null {\n try {\n const url = execSync(\"git remote get-url origin\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim();\n return url || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Prompt user to enter a custom GitHub URL\n */\nasync function promptForCustomUrl(): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(\"\\nEnter GitHub URL (or press Enter to skip): \");\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const url = answer.trim();\n resolve(url || null);\n });\n });\n}\n\n/**\n * Prompt yes/no question\n */\nasync function promptYesNo(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(`\\n${question} (y/n): `);\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const response = answer.trim().toLowerCase();\n resolve(response === \"y\" || response === \"yes\");\n });\n });\n}\n\n/**\n * Prompt user to select or enter GitHub URL\n * @param gitRemoteUrl - Git remote URL if available\n * @returns Selected URL or null if skipped\n */\nasync function promptForGithubUrl(\n gitRemoteUrl: string | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log(\"\\n\" + \"=\".repeat(50));\n console.log(\"🔍 Vetra Package Configuration\");\n console.log(\"=\".repeat(50));\n console.log(\n \"\\nWe detected a Vetra package document in your remote drive without a GitHub URL configured.\",\n );\n console.log(\"\\nWould you like to configure the GitHub URL now?\");\n\n if (gitRemoteUrl) {\n console.log(`\\nGit remote URL detected: ${gitRemoteUrl}`);\n console.log(\"\\nOptions:\");\n console.log(\"1. Use detected URL\");\n console.log(\"2. Enter a different URL\");\n console.log(\"3. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-3): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n resolve(gitRemoteUrl);\n } else if (choice === \"2\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"3\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-3): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n } else {\n console.log(\"\\nNo git remote URL detected.\");\n console.log(\"\\nOptions:\");\n console.log(\"1. Enter GitHub URL manually\");\n console.log(\"2. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-2): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"2\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-2): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n }\n });\n}\n\n/**\n * Set git remote URL (origin)\n */\nfunction setGitRemoteUrl(url: string): void {\n try {\n execSync(`git remote add origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin set to: ${url}`);\n } catch {\n try {\n execSync(`git remote set-url origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin updated to: ${url}`);\n } catch {\n console.error(red(`❌ Failed to set git remote URL`));\n }\n }\n}\n\n/**\n * Validates documents and returns the target document to use\n * Warns if multiple documents found\n */\nfunction validateAndSelectDocument<T>(documents: T[]): T | null {\n if (documents.length === 0) {\n return null;\n }\n\n if (documents.length > 1) {\n console.warn(\n `⚠️ Warning: Multiple Vetra documents found (${documents.length}). Using first document.`,\n );\n }\n\n return documents[0];\n}\n\nasync function applyGithubUrlConfiguration(\n graphqlEndpoint: string,\n vetraDriveId: string,\n documentId: string,\n selectedUrl: string,\n shouldSetRemote: boolean,\n): Promise<void> {\n // Set package GitHub URL\n await setPackageGithubUrl(\n graphqlEndpoint,\n vetraDriveId,\n documentId,\n selectedUrl,\n );\n\n console.log(`✅ GitHub URL configured: ${selectedUrl}`);\n\n // Set git remote URL if requested\n if (shouldSetRemote) {\n setGitRemoteUrl(selectedUrl);\n }\n}\n\nfunction logVerbose(message: string, verbose?: boolean): void {\n if (verbose) {\n console.log(message);\n }\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Configure GitHub URL for Vetra documents\n * @param switchboardPort - Port where switchboard is running\n * @param vetraDriveUrl - Remote drive URL\n * @param verbose - Enable verbose logging\n */\nexport async function configureVetraGithubUrl(\n switchboardPort: number,\n vetraDriveUrl: string,\n verbose?: boolean,\n): Promise<void> {\n logVerbose(\"Checking GitHub URL configuration...\", verbose);\n\n try {\n const graphqlEndpoint = `http://localhost:${switchboardPort}/graphql`;\n const vetraDriveId = vetraDriveUrl.split(\"/\").pop();\n if (!vetraDriveId) {\n throw new Error(\"Invalid vetraDriveUrl: unable to extract drive ID\");\n }\n\n const documents = await getVetraDocuments(graphqlEndpoint, vetraDriveId);\n\n // Skip if already configured\n if (documents.some((doc) => doc.githubUrl)) {\n logVerbose(\"GitHub URL already configured, skipping setup\", verbose);\n return;\n }\n\n // Get or create target document\n let targetDocumentId: string;\n const targetDocument = validateAndSelectDocument(documents);\n\n // Collect user input\n const gitRemoteUrl = getGitRemoteUrl();\n const selectedUrl = await promptForGithubUrl(gitRemoteUrl);\n\n if (!selectedUrl) {\n logVerbose(\"GitHub URL configuration skipped\", verbose);\n return;\n }\n\n let shouldSetRemote = false;\n if (selectedUrl !== gitRemoteUrl && !gitRemoteUrl) {\n shouldSetRemote = await promptYesNo(\"Set this as your git remote URL?\");\n }\n\n if (!targetDocument) {\n logVerbose(\"No Vetra documents found, creating new document...\", verbose);\n\n targetDocumentId = await createVetraDocument(\n graphqlEndpoint,\n vetraDriveId,\n \"vetra-package\",\n );\n\n logVerbose(`Created new document: ${targetDocumentId}`, verbose);\n } else {\n targetDocumentId = targetDocument.id;\n }\n\n await applyGithubUrlConfiguration(\n graphqlEndpoint,\n vetraDriveId,\n targetDocumentId,\n selectedUrl,\n shouldSetRemote,\n );\n } catch (error) {\n console.error(\n red(\n `⚠️ GitHub URL configuration failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n logVerbose(String(error), verbose);\n }\n}\n","import { isPortAvailable } from \"@powerhousedao/switchboard/server\";\nimport { yellow } from \"colorette\";\n\nconst MAX_FALLBACK_ATTEMPTS = 20;\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function findFreePort(start: number): Promise<number | null> {\n for (let i = 0; i < MAX_FALLBACK_ATTEMPTS; i++) {\n const candidate = start + i;\n if (await isPortAvailable(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Resolve the port switchboard should bind to. If the requested port is free,\n * returns it unchanged. If it's in use, walks forward for the next free port\n * and — in an interactive terminal — asks the user to confirm the fallback.\n * In CI / piped contexts the fallback is applied automatically so scripts\n * don't hang on an unanswered prompt.\n *\n * Throws a process.exit(1) when the user declines the prompt or when no free\n * port is available in the search window.\n */\nexport async function resolveSwitchboardPort(\n requested: number,\n): Promise<number> {\n if (await isPortAvailable(requested)) return requested;\n\n const candidate = await findFreePort(requested + 1);\n if (candidate === null) {\n console.error(\n `Port ${requested} is in use and no free port was found in the range ${requested}-${requested + MAX_FALLBACK_ATTEMPTS - 1}.`,\n );\n process.exit(1);\n }\n\n if (!isInteractive()) {\n console.log(\n yellow(\n `Port ${requested} is in use. Falling back to port ${candidate} (non-interactive; skipping confirmation).`,\n ),\n );\n return candidate;\n }\n\n const enquirer = await import(\"enquirer\");\n\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `Port ${requested} is in use. Use port ${candidate} instead?`,\n initial: true,\n });\n confirmed = answer.confirmed;\n } catch {\n // user aborted the prompt (Ctrl-C); treat as decline\n confirmed = false;\n }\n\n if (!confirmed) {\n console.error(\n `Aborted. Free port ${requested} or pass --switchboard-port <port> to choose a different port.`,\n );\n process.exit(1);\n }\n\n return candidate;\n}\n","import { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport type VetraRuntimeRecord = {\n pid: number;\n projectName: string;\n switchboardPort: number;\n connectPort: number;\n mcpUrl: string;\n startedAt: string;\n};\n\nexport type VetraProbe =\n | { status: \"none\" }\n | { status: \"stale\" }\n | { status: \"live\"; record: VetraRuntimeRecord }\n | { status: \"foreign\"; record: VetraRuntimeRecord };\n\nconst READY_TIMEOUT_MS = 2000;\n\n// Under the project's .ph tree — relocated with it by PH_USER_DATA_DIR.\nconst recordPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra-runtime.json\");\n\nexport function readVetraRuntime(\n projectDir: string,\n): VetraRuntimeRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(recordPath(projectDir), \"utf8\"),\n ) as VetraRuntimeRecord;\n } catch {\n // Missing or corrupt: either way there is no usable record.\n return undefined;\n }\n}\n\nexport function writeVetraRuntime(\n projectDir: string,\n record: VetraRuntimeRecord,\n): void {\n const target = recordPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\\n`);\n}\n\nexport function clearVetraRuntime(projectDir: string): void {\n try {\n fs.rmSync(recordPath(projectDir));\n } catch {\n // Already gone.\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nasync function isReady(port: number): Promise<boolean> {\n try {\n const response = await fetch(`http://localhost:${port}/ready`, {\n signal: AbortSignal.timeout(READY_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Decide whether the recorded instance is actually serving this project.\n *\n * All three checks are load-bearing. A pid can be reused by an unrelated\n * process, so a live pid proves nothing on its own. Another project's\n * switchboard would answer `/ready` on its own port, so a healthy `/ready`\n * proves nothing either. And the recorded `projectName` is what separates\n * \"my instance\" from \"someone else's instance that happens to hold this\n * port\" — which is precisely the confusion that let an agent write document\n * models into a different project's drive.\n *\n * A stale record is deleted so the next start is unblocked. A foreign one is\n * left alone: it describes something that is alive.\n */\nexport async function probeVetraRuntime(\n projectDir: string,\n projectName: string,\n): Promise<VetraProbe> {\n const record = readVetraRuntime(projectDir);\n if (!record) return { status: \"none\" };\n\n if (!isPidAlive(record.pid) || !(await isReady(record.switchboardPort))) {\n clearVetraRuntime(projectDir);\n return { status: \"stale\" };\n }\n\n if (record.projectName !== projectName) {\n return { status: \"foreign\", record };\n }\n return { status: \"live\", record };\n}\n\nconst MCP_FILES = [\".mcp.json\", path.join(\".cursor\", \"mcp.json\")];\n\n/**\n * Point every generated MCP config at `port`, returning the files changed.\n *\n * An MCP client resolves these files at session start and cannot read the\n * project config or `.env`, so when an override moves the port the literal\n * has to be corrected on disk. Rewrites in place rather than regenerating,\n * so any other servers or hand-added keys survive.\n */\nexport function syncMcpPort(projectDir: string, port: number): string[] {\n const changed: string[] = [];\n for (const rel of MCP_FILES) {\n const target = path.join(projectDir, rel);\n if (!fs.existsSync(target)) continue;\n\n let parsed: { mcpServers?: Record<string, { url?: string }> };\n try {\n parsed = JSON.parse(fs.readFileSync(target, \"utf8\")) as typeof parsed;\n } catch {\n // Hand-broken JSON is the author's to fix; don't clobber it.\n continue;\n }\n\n const server = parsed.mcpServers?.[\"reactor-mcp\"];\n if (!server?.url) continue;\n\n const wanted = `http://localhost:${port}/mcp`;\n if (server.url === wanted) continue;\n\n server.url = wanted;\n fs.writeFileSync(target, `${JSON.stringify(parsed, null, 2)}\\n`);\n changed.push(rel);\n }\n return changed;\n}\n","import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport { join } from \"node:path\";\nimport { blue, green, red, yellow, type Color } from \"colorette\";\nimport type { ILogger } from \"document-model\";\nimport { childLogger, setLogLevel } from \"document-model\";\nimport { createLogger } from \"vite\";\nimport type { VetraArgs } from \"../types.js\";\nimport { generateProjectDriveId, POWERHOUSE_CONFIG_FILE } from \"../utils.js\";\nimport { wasFlagExplicitlyPassed } from \"../utils/cli-connect-override.js\";\nimport {\n configureVetraGithubUrl,\n sleep,\n} from \"../utils/configure-vetra-github-url.js\";\nimport { POWERHOUSE_DRIVE_ICON } from \"../utils/drive-icons.js\";\nimport { mergeDefaultDrives, rebaseDriveUrl } from \"@powerhousedao/host-core\";\nimport { parseDefaultDrivesUrl } from \"../utils/parse-default-drives.js\";\nimport { resolveSwitchboardPort } from \"../utils/resolve-switchboard-port.js\";\nimport {\n clearVetraRuntime,\n probeVetraRuntime,\n syncMcpPort,\n writeVetraRuntime,\n} from \"../utils/vetra-runtime.js\";\nimport { runConnectStudio } from \"./connect-studio.js\";\nimport { startSwitchboard } from \"./switchboard.js\";\n\nconst VETRA_DRIVE_NAME = \"vetra\";\n\nconst getDefaultVetraUrl = (port: number) =>\n `http://localhost:${port}/d/${generateProjectDriveId(VETRA_DRIVE_NAME)}`;\n\nconst getDriveId = (driveUrl: string | undefined): string =>\n driveUrl?.split(\"/\").pop() ?? generateProjectDriveId(VETRA_DRIVE_NAME);\n\n// rebaseDriveUrl moved to @powerhousedao/host-core (uniform-runners P1.4) —\n// one implementation shared by this classic path and the generic compound.\n\nfunction createViteLogger(color: Color) {\n const customLogger = createLogger(\"info\");\n const loggerInfo = customLogger.info.bind(customLogger);\n customLogger.info = (msg, options) => {\n loggerInfo(color(msg), options);\n };\n const loggerWarn = customLogger.warn.bind(customLogger);\n customLogger.warn = (msg, options) => {\n loggerWarn(yellow(msg), options);\n };\n const loggerError = customLogger.error.bind(customLogger);\n customLogger.error = (msg, options) => {\n loggerError(red(msg), options);\n };\n\n const loggerWarnOnce = customLogger.warnOnce.bind(customLogger);\n customLogger.warnOnce = (msg, options) => {\n loggerWarnOnce(yellow(msg), options);\n };\n return customLogger;\n}\n\nasync function startVetraPreviewDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n): Promise<string | null> {\n const previewDriveId = generateProjectDriveId(\"preview\");\n\n const previewDrive = {\n id: previewDriveId,\n slug: previewDriveId,\n global: {\n name: \"Vetra Preview\",\n icon: POWERHOUSE_DRIVE_ICON,\n nodes: [],\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(reactor, previewDrive, port);\n\n if (verbose && driveUrl) {\n console.log(blue(`Vetra Switchboard: Preview drive: ${driveUrl}`));\n }\n return driveUrl ?? null;\n}\n\n// Opens in Workflow Studio; only seeded when the switchboard runs workflows.\n// Exported for the switchboard bridge runner: a hosts project with\n// reactor.workflows enabled seeds the SAME project-hashed drive this vetra\n// path does, until drive provisioning becomes a plugin contribution.\nexport async function seedWorkflowsDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n): Promise<string | null> {\n const workflowsDrive = {\n id: generateProjectDriveId(\"workflows\"),\n slug: \"workflows\",\n global: { name: \"Workflows\" },\n preferredEditor: \"workflow-studio\",\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(reactor, workflowsDrive, port);\n\n if (verbose && driveUrl) {\n console.log(blue(`Vetra Switchboard: Workflows drive: ${driveUrl}`));\n }\n return driveUrl ?? null;\n}\nasync function startLocalVetraSwitchboard(args: VetraArgs, logger?: ILogger) {\n const {\n connectPort,\n switchboardPort,\n dev,\n packages,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n remoteDrive,\n interactive,\n watch,\n verbose,\n } = args;\n\n // Convert single remote drive to array if provided\n const remoteDrives = remoteDrive ? [remoteDrive] : [];\n\n const vetraProcessorConfig: VetraProcessorConfigType = {\n interactive,\n driveUrl: remoteDrive ?? getDefaultVetraUrl(connectPort),\n driveId: getDriveId(remoteDrive),\n };\n\n const processorConfig = new Map<string, unknown>();\n processorConfig.set(VETRA_PROCESSOR_CONFIG_KEY, vetraProcessorConfig);\n\n const vetraDriveId = generateProjectDriveId(VETRA_DRIVE_NAME);\n\n // When the user didn't opt into strict-port semantics, check for a port\n // conflict up front and ask for confirmation before binding a fallback.\n // Doing this in the CLI layer keeps the interactive prompt out of the\n // switchboard server package and aligns with the existing prerelease-tag\n // confirmation flow in `ph publish`.\n const resolvedSwitchboardPort = args.strictPort\n ? switchboardPort\n : await resolveSwitchboardPort(switchboardPort);\n\n try {\n const switchboard = await startSwitchboard(\n {\n ...args,\n useVetraDrive: true, // Use Vetra drive instead of Powerhouse drive\n mcp: true,\n port: resolvedSwitchboardPort,\n // We've already probed and (when interactive) confirmed the port with\n // the user, so keep the server from running its own fallback on top.\n strictPort: true,\n dev,\n packages,\n remoteDrives,\n vetraDriveId,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n processorConfig,\n basePath: undefined,\n keypairPath: undefined,\n dbPath: args.dbPath,\n useIdentity: undefined,\n migrate: undefined,\n migrateStatus: undefined,\n reset: undefined,\n yes: undefined,\n requireIdentity: undefined,\n },\n logger,\n );\n\n const actualSwitchboardPort = switchboard.port;\n\n // Add preview drive (only in watch mode)\n let previewDriveUrl: string | null = null;\n if (watch) {\n try {\n previewDriveUrl = await startVetraPreviewDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n let workflowsDriveUrl: string | null = null;\n if (switchboard.workflowsEnabled) {\n try {\n workflowsDriveUrl = await seedWorkflowsDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Started successfully`));\n if (remoteDrive) {\n console.log(\n blue(`Vetra Switchboard: Syncing with remote drive: ${remoteDrive}`),\n );\n }\n } else {\n console.log();\n console.log(\n blue(\n `Vetra Switchboard: http://localhost:${actualSwitchboardPort}/graphql`,\n ),\n );\n console.log(blue(` ➜ Drive URL: ${switchboard.defaultDriveUrl}`));\n if (previewDriveUrl) {\n console.log(blue(` ➜ Preview Drive URL: ${previewDriveUrl}`));\n }\n if (workflowsDriveUrl) {\n console.log(blue(` ➜ Workflows Drive URL: ${workflowsDriveUrl}`));\n }\n }\n return {\n driveUrl: switchboard.defaultDriveUrl || \"\",\n previewDriveUrl: previewDriveUrl,\n workflowsDriveUrl,\n switchboardPort: actualSwitchboardPort,\n };\n } catch (error) {\n console.error(\n red(\n `Vetra Switchboard: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n\nexport async function startVetra(args: VetraArgs) {\n const {\n connectPort,\n verbose,\n remoteDrive,\n disableConnect,\n debug,\n httpsCertFile,\n httpsKeyFile,\n disableLocalPackages,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n watchTimeout,\n } = args;\n\n const switchboardLogger = childLogger([\"vetra\", \"switchboard\"]);\n\n // One Vetra per project. Two instances over one working tree would contend\n // for the same `.ph/read-model.db` and `.ph/reactor-storage`, and leave the\n // project with two drives that diverge.\n const projectDir = process.cwd();\n const { readPackageSync } = await import(\"read-pkg\");\n const projectName = readPackageSync({ cwd: projectDir }).name;\n const probe = await probeVetraRuntime(projectDir, projectName);\n\n if (probe.status === \"live\") {\n console.log();\n console.log(green(\"Vetra is already running for this project.\"));\n console.log(\n green(` ➜ Connect: http://localhost:${probe.record.connectPort}`),\n );\n console.log(\n green(\n ` ➜ Switchboard: http://localhost:${probe.record.switchboardPort}/graphql`,\n ),\n );\n console.log(\n `Stop that instance (pid ${probe.record.pid}) if you need to restart it.`,\n );\n return;\n }\n\n if (probe.status === \"foreign\") {\n console.error(\n red(\n `.ph/vetra-runtime.json describes a live Vetra for \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance. ` +\n `Delete .ph/vetra-runtime.json if that record is wrong.`,\n ),\n );\n process.exit(1);\n }\n\n try {\n // Set default log level to info if not already specified\n if (!process.env.LOG_LEVEL) {\n setLogLevel(\"info\");\n }\n\n if (verbose) {\n switchboardLogger.info(\"Starting Vetra Switchboard...\");\n if (remoteDrive) {\n const source = remoteDrive\n ? \"command line argument\"\n : \"powerhouse.config.json\";\n switchboardLogger.info(`Using vetraUrl from ${source}: ${remoteDrive}`);\n }\n }\n const switchboardResult = await startLocalVetraSwitchboard(\n {\n ...args,\n dev: true, // Vetra always runs in dev mode to load local packages\n httpsKeyFile,\n httpsCertFile,\n disableLocalPackages,\n debug,\n },\n switchboardLogger,\n );\n const driveUrl: string = switchboardResult.driveUrl || remoteDrive || \"\";\n const previewDriveUrl = switchboardResult.previewDriveUrl;\n const workflowsDriveUrl = switchboardResult.workflowsDriveUrl;\n const actualSwitchboardPort = switchboardResult.switchboardPort;\n\n // Record what we actually bound, so a second `ph vetra` can tell a live\n // instance from a stale file, and so an agent can see the real ports.\n writeVetraRuntime(projectDir, {\n pid: process.pid,\n projectName,\n switchboardPort: actualSwitchboardPort,\n connectPort,\n mcpUrl: `http://localhost:${actualSwitchboardPort}/mcp`,\n startedAt: new Date().toISOString(),\n });\n const releaseRuntimeRecord = () => clearVetraRuntime(projectDir);\n process.on(\"exit\", releaseRuntimeRecord);\n process.on(\"SIGINT\", () => {\n releaseRuntimeRecord();\n process.exit(130);\n });\n process.on(\"SIGTERM\", () => {\n releaseRuntimeRecord();\n process.exit(143);\n });\n\n // An MCP client resolved `.mcp.json` before this process started and\n // cannot re-read it, so a drifted literal means the agent is pointed at\n // the wrong port — possibly another project's reactor. Correct the file\n // and say so plainly; we cannot fix the already-open client ourselves.\n const driftedMcpFiles = syncMcpPort(projectDir, actualSwitchboardPort);\n if (driftedMcpFiles.length > 0) {\n console.log(\n yellow(\n `Updated ${driftedMcpFiles.join(\" and \")} to port ${actualSwitchboardPort}. ` +\n `Reconnect your MCP client (/mcp) to pick it up. ` +\n `This edit is local — do not commit it.`,\n ),\n );\n }\n\n // Configure GitHub URL if remote drive is set\n if (remoteDrive) {\n // give some time for the drive to process initial strands\n await sleep(3000);\n\n await configureVetraGithubUrl(\n actualSwitchboardPort,\n remoteDrive,\n verbose,\n );\n\n // give some time for the user to read log messages\n await sleep(2000);\n }\n\n if (verbose) {\n console.log(\"Starting Codegen Reactor...\");\n }\n\n // Start Connect pointing to the drive (unless disabled)\n if (!disableConnect) {\n // --drives-public-base: advertise proxy-reachable drive URLs to the\n // browser instead of the switchboard's localhost origin.\n const publicBase = args.drivesPublicBase;\n const browserDriveUrl = publicBase\n ? rebaseDriveUrl(driveUrl, publicBase)\n : driveUrl;\n const browserPreviewDriveUrl =\n previewDriveUrl && publicBase\n ? rebaseDriveUrl(previewDriveUrl, publicBase)\n : previewDriveUrl;\n const browserWorkflowsDriveUrl =\n workflowsDriveUrl && publicBase\n ? rebaseDriveUrl(workflowsDriveUrl, publicBase)\n : workflowsDriveUrl;\n\n // The resolved default-drive list: vetra's own drives first (the\n // Vetra drive, the preview drive in watch mode, and the Workflows\n // drive when workflows are on), then the\n // project's configured `connect.drives.defaultDrives` from\n // powerhouse.config.json (issue #3023). A drive vetra also starts is\n // listed only once. An explicit `--default-drives-url` is appended on\n // top of this list by buildStudioConnectOverride — it never replaces\n // the vetra drives.\n const vetraDriveEntries = [\n ...(browserDriveUrl\n ? [{ url: browserDriveUrl, name: null, icon: null }]\n : []),\n ...(browserPreviewDriveUrl\n ? [{ url: browserPreviewDriveUrl, name: null, icon: null }]\n : []),\n ...(browserWorkflowsDriveUrl\n ? [{ url: browserWorkflowsDriveUrl, name: null, icon: null }]\n : []),\n ];\n const configuredDefaultDrives =\n getConfig(join(projectDir, POWERHOUSE_CONFIG_FILE)).connect?.drives\n ?.defaultDrives ?? [];\n const resolvedDefaultDrives = mergeDefaultDrives(\n vetraDriveEntries,\n configuredDefaultDrives,\n );\n\n if (verbose) {\n console.log(\"Starting Connect...\");\n // Mirror buildStudioConnectOverride: an explicit\n // --default-drives-url is appended to the resolved list.\n const flagDefaultDrives = wasFlagExplicitlyPassed(\"default-drives-url\")\n ? parseDefaultDrivesUrl(args.defaultDrivesUrl ?? \"\")\n : [];\n const printedDefaultDrives = mergeDefaultDrives(\n resolvedDefaultDrives,\n flagDefaultDrives,\n );\n console.log(\n ` ➜ Connect will use default drives: ${printedDefaultDrives\n .map((d) => (\"url\" in d ? d.url : `local:${d.id}`))\n .join(\", \")}`,\n );\n }\n console.log();\n console.log(green(`Vetra Connect: http://localhost:${connectPort}`));\n\n const customViteLogger = createViteLogger(green);\n\n // Programmatic override forwarded to the Connect runtime config —\n // vetra always sets these regardless of what the user typed on the\n // command line. We pass it as the explicit third arg to\n // runConnectStudio so it survives the `wasFlagExplicitlyPassed`\n // gating (the user didn't pass --default-drives-url; vetra is setting\n // it itself).\n const vetraDrivesOverride = {\n drives: {\n defaultDrives: resolvedDefaultDrives,\n preserveStrategy: \"preserve-all\" as const,\n },\n };\n\n await runConnectStudio(\n {\n ...args,\n port: connectPort,\n disableLocalPackages,\n debug,\n host: host,\n open: open,\n cors: cors,\n strictPort: strictPort,\n printUrls: printUrls,\n bindCLIShortcuts: bindCLIShortcuts,\n watchTimeout: watchTimeout,\n },\n customViteLogger,\n vetraDrivesOverride,\n );\n }\n } catch (error) {\n console.error(error);\n }\n}\n"],"names":["startSwitchboard"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,kBAAiC;CACxC,IAAI;EAKF,OAJY,SAAS,6BAA6B;GAChD,UAAU;GACV,OAAO;IAAC;IAAQ;IAAQ;GAAM;EAChC,CAAC,CAAC,CAAC,KACM,KAAK;CAChB,QAAQ;EACN,OAAO;CACT;AACF;;;;AAKA,eAAe,qBAA6C;CAC1D,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,KAAK,gBAAgB;GACzB,OAAO,QAAQ;GACf,QAAQ,QAAQ;EAClB,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SAAS,EAAE,IAAK,CAAC,CAClD,KAAK,IAAI,GACd;GACF;GACA,QAAQ,IAAI;GACZ,QAAQ,IAAI,MAAM,mCAAmC,aAAa,CAAC;GAEnE,MAAM,mBAAmB,iBAAiB,KAAK;GAQ/C,MAAM,sBAAsB,EAC1B,QAAQ;IACN,eAAe;IACf,kBAAkB;GACpB,EACF;GAEA,MAAM,iBACJ;IACE,GAAG;IACH,MAAM;IACN;IACA;IACM;IACA;IACA;IACM;IACD;IACO;IACJ;GAChB,GACA,kBACA,mBACF;EACF;CACF,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AACF","debug_id":"12c43cde-3e39-53ed-9bf3-2ffd6518b05f"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/ph-cli",
3
- "version": "6.2.3-dev.73",
3
+ "version": "6.2.3-dev.74",
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.73",
42
- "@powerhousedao/codegen": "6.2.3-dev.73",
43
- "@powerhousedao/common": "6.2.3-dev.73",
44
- "@powerhousedao/config": "6.2.3-dev.73",
45
- "@powerhousedao/reactor": "6.2.3-dev.73",
46
- "@powerhousedao/shared": "6.2.3-dev.73",
47
- "@powerhousedao/switchboard": "6.2.3-dev.73",
48
- "@powerhousedao/vetra": "6.2.3-dev.73",
49
- "@renown/sdk": "6.2.3-dev.73",
41
+ "@powerhousedao/builder-tools": "6.2.3-dev.74",
42
+ "@powerhousedao/codegen": "6.2.3-dev.74",
43
+ "@powerhousedao/common": "6.2.3-dev.74",
44
+ "@powerhousedao/config": "6.2.3-dev.74",
45
+ "@powerhousedao/reactor": "6.2.3-dev.74",
46
+ "@powerhousedao/shared": "6.2.3-dev.74",
47
+ "@powerhousedao/switchboard": "6.2.3-dev.74",
48
+ "@powerhousedao/vetra": "6.2.3-dev.74",
49
+ "@renown/sdk": "6.2.3-dev.74",
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,8 @@
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.73",
58
+ "document-model": "6.2.3-dev.74",
59
+ "dotenv": "16.4.7",
59
60
  "enquirer": "2.4.1",
60
61
  "kysely": "0.28.16",
61
62
  "package-manager-detector": "1.6.0",
@@ -76,8 +77,8 @@
76
77
  "ts-morph": "27.0.2",
77
78
  "write-package": "7.2.0",
78
79
  "zod": "^4.5.4",
79
- "@powerhousedao/desktop": "6.2.3-dev.73",
80
- "@powerhousedao/host-core": "6.2.3-dev.73"
80
+ "@powerhousedao/desktop": "6.2.3-dev.74",
81
+ "@powerhousedao/host-core": "6.2.3-dev.74"
81
82
  },
82
83
  "scripts": {
83
84
  "tsc": "tsc",