@powerhousedao/ph-cli 6.2.3-dev.78 → 6.2.3-dev.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-Dj8qfSSe.mjs → build-DUzhIPb7.mjs} +8 -55
- package/dist/build-DUzhIPb7.mjs.map +1 -0
- package/dist/build-FoZl36TM.mjs +4 -0
- package/dist/{check-KEXBwJXM.mjs → check-DDy1o6Vr.mjs} +10 -7
- package/dist/check-DDy1o6Vr.mjs.map +1 -0
- package/dist/{cli-connect-override-C65On7dE.mjs → cli-connect-override-By7u9IVR.mjs} +4 -4
- package/dist/{cli-connect-override-C65On7dE.mjs.map → cli-connect-override-By7u9IVR.mjs.map} +1 -1
- package/dist/cli.mjs +5 -9
- package/dist/cli.mjs.map +1 -1
- package/dist/{connect-build-B9jwzQlf.mjs → connect-build-BBAZuqpo.mjs} +5 -5
- package/dist/{connect-build-B9jwzQlf.mjs.map → connect-build-BBAZuqpo.mjs.map} +1 -1
- package/dist/{connect-config-D5SHcBf1.mjs → connect-config-ghJlOd-x.mjs} +4 -4
- package/dist/{connect-config-D5SHcBf1.mjs.map → connect-config-ghJlOd-x.mjs.map} +1 -1
- package/dist/connect-studio-BaVeuul3.mjs +78 -0
- package/dist/connect-studio-BaVeuul3.mjs.map +1 -0
- package/dist/{connect-studio-CYETzL2c.mjs → connect-studio-CfggUldW.mjs} +3 -3
- package/dist/{dist-CSn_YRdB.mjs → dist-Bd6sSt7Y.mjs} +19 -19
- package/dist/dist-Bd6sSt7Y.mjs.map +1 -0
- package/dist/{explain-BsZw-WrZ.mjs → explain-C9zER5xn.mjs} +4 -4
- package/dist/{explain-BsZw-WrZ.mjs.map → explain-C9zER5xn.mjs.map} +1 -1
- package/dist/{export-BGJVYlCK.mjs → export-CrIz2spe.mjs} +4 -4
- package/dist/{export-BGJVYlCK.mjs.map → export-CrIz2spe.mjs.map} +1 -1
- package/dist/generate-migration-file-yK8uA70U.mjs +20 -0
- package/dist/generate-migration-file-yK8uA70U.mjs.map +1 -0
- package/dist/{generate-piece-U3tP-Sex.mjs → generate-piece-C6ymlErL.mjs} +6 -6
- package/dist/{generate-piece-U3tP-Sex.mjs.map → generate-piece-C6ymlErL.mjs.map} +1 -1
- package/dist/{generate-piece-action-DbxrzfKY.mjs → generate-piece-action-uYRdKtQA.mjs} +5 -5
- package/dist/{generate-piece-action-DbxrzfKY.mjs.map → generate-piece-action-uYRdKtQA.mjs.map} +1 -1
- package/dist/{generate-piece-trigger-CqVOcL9g.mjs → generate-piece-trigger-CZaDD-cc.mjs} +5 -5
- package/dist/{generate-piece-trigger-CqVOcL9g.mjs.map → generate-piece-trigger-CZaDD-cc.mjs.map} +1 -1
- package/dist/{generate-processor-B9Umgjy9.mjs → generate-processor-BVjOsfjJ.mjs} +5 -5
- package/dist/{generate-processor-B9Umgjy9.mjs.map → generate-processor-BVjOsfjJ.mjs.map} +1 -1
- package/dist/{generate-subgraph-DRrInOOv.mjs → generate-subgraph-CrHbYK91.mjs} +5 -5
- package/dist/{generate-subgraph-DRrInOOv.mjs.map → generate-subgraph-CrHbYK91.mjs.map} +1 -1
- package/dist/get-version-_coBX13A.mjs +11 -0
- package/dist/get-version-_coBX13A.mjs.map +1 -0
- package/dist/{index-DHHaYrj2.d.mts → index-DdpGYzN0.d.mts} +2 -2
- package/dist/{index-DHHaYrj2.d.mts.map → index-DdpGYzN0.d.mts.map} +1 -1
- package/dist/{init-ScuT3z7P.mjs → init-Ch1rCksS.mjs} +12 -10
- package/dist/{init-ScuT3z7P.mjs.map → init-Ch1rCksS.mjs.map} +1 -1
- package/dist/install-added-dependencies-DnZFR3aE.mjs +18 -0
- package/dist/install-added-dependencies-DnZFR3aE.mjs.map +1 -0
- package/dist/mcp-CZ02pj76.mjs +262 -0
- package/dist/mcp-CZ02pj76.mjs.map +1 -0
- package/dist/member-config-8Vwys-4O.mjs +154 -0
- package/dist/member-config-8Vwys-4O.mjs.map +1 -0
- package/dist/{migrate-b38W7NH_.mjs → migrate-CIJaE3iZ.mjs} +4 -4
- package/dist/{migrate-b38W7NH_.mjs.map → migrate-CIJaE3iZ.mjs.map} +1 -1
- package/dist/offered-routes-imports-CQInWI6y.mjs +4 -0
- package/dist/offered-routes-imports-CalXK9dh.mjs +96 -0
- package/dist/offered-routes-imports-CalXK9dh.mjs.map +1 -0
- package/dist/{ph-cli-commands-DJYB9BDl.mjs → ph-cli-commands-B37zr8uN.mjs} +102 -35
- package/dist/ph-cli-commands-B37zr8uN.mjs.map +1 -0
- package/dist/ph-cli-commands-S3ArIR8q.mjs +4 -0
- package/dist/runners/connect.d.mts +5 -1
- package/dist/runners/connect.d.mts.map +1 -1
- package/dist/runners/connect.mjs +3 -3
- package/dist/runners/switchboard.d.mts +1159 -3
- package/dist/runners/switchboard.d.mts.map +1 -1
- package/dist/runners/switchboard.mjs +48 -67
- package/dist/runners/switchboard.mjs.map +1 -1
- package/dist/scripts/generate-commands-docs.ts +4 -0
- package/dist/{switchboard-h4-XgP1h.mjs → switchboard-BI35F5H7.mjs} +40 -8
- package/dist/switchboard-BI35F5H7.mjs.map +1 -0
- package/dist/switchboard-DohZ1tbp.mjs +4 -0
- package/dist/sync-connect-routes-BtAsFPXN.mjs +4 -0
- package/dist/sync-connect-routes-t0Slg-P6.mjs +25 -0
- package/dist/sync-connect-routes-t0Slg-P6.mjs.map +1 -0
- package/dist/{vetra-C4ri3YLH.mjs → vetra-C9fsChId.mjs} +75 -127
- package/dist/vetra-C9fsChId.mjs.map +1 -0
- package/dist/vetra-launch-DQDZxGTV.mjs +343 -0
- package/dist/vetra-launch-DQDZxGTV.mjs.map +1 -0
- package/package.json +15 -13
- package/dist/build-C78yPntL.mjs +0 -4
- package/dist/build-Dj8qfSSe.mjs.map +0 -1
- package/dist/check-KEXBwJXM.mjs.map +0 -1
- package/dist/connect-studio-CEpyVlJ_.mjs +0 -39
- package/dist/connect-studio-CEpyVlJ_.mjs.map +0 -1
- package/dist/dist-CSn_YRdB.mjs.map +0 -1
- package/dist/install-added-dependencies-DVSbzler.mjs +0 -33
- package/dist/install-added-dependencies-DVSbzler.mjs.map +0 -1
- package/dist/ph-cli-commands-DJYB9BDl.mjs.map +0 -1
- package/dist/ph-cli-commands-JBUwDL2d.mjs +0 -4
- package/dist/switchboard-C5zgkRl2.mjs +0 -4
- package/dist/switchboard-h4-XgP1h.mjs.map +0 -1
- package/dist/vetra-C4ri3YLH.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard.d.mts","names":[],"sources":["../../src/commands/switchboard.ts","../../src/types.ts","../../src/runners/switchboard.ts"],"mappings":";;;cAGa,aAAW,+CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"switchboard.d.mts","names":[],"sources":["../../src/commands/switchboard.ts","../../src/types.ts","../../src/runners/switchboard.ts"],"mappings":";;;cAGa,aAAW,+CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA6CtB,6CAAA,iDAAA,mDAAA;;;KCkBU,kBAAkB,uBAAuB;;;;;;;;;qBCzBxC;qBAoCA,oBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;GAGvC;;;;;;;qBAQW,eAAa;;;;;;;;;;GAOxB;YACU,qBAAqB,gBAAe;QAExC;YACI;IACR;MACE,MAAM;MACN,SAAS;;;;;YAMH,wBAAwB,KAAK;EACvC;;;YAgHU,oBAAoB,aAAa;wBA0OvB,IACpB,MAAM,uBACN,KAAK,gBACJ,QAAQ;qBAIE,cAAK;wBAEI,IACpB,MAAM,uBACN,KAAK,gBACJ,QAAQ;;wBAKW,UACpB,MAAM,uBACN,KAAK,mBACJ,QAAQ;;;wBA+CW,MACpB,MAAM,uBACN,MAAM,gBACL"}
|
|
@@ -1,51 +1,13 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="1819c7f8-3860-5090-85e5-aa961b217309")}catch(e){}}();
|
|
3
3
|
import { c as record, h as prettifyError, l as strictObject, p as url, r as boolean$1, s as number, u as string$1 } from "../schemas-Cnv5AnQT.mjs";
|
|
4
4
|
import { g as drivesSchema, m as defineHostSchemas, q as resolveHostPlugins } from "../compound-Cfqa5Jal-B5rkCmIj.mjs";
|
|
5
|
-
import {
|
|
5
|
+
import { _ as seedDrives, d as protocolConflicts, g as resolveDriveDeclaration, s as mergeDrivePlan } from "../dist-Bd6sSt7Y.mjs";
|
|
6
|
+
import { a as reactorBlockConflicts, c as switchboardDevMode, i as prepareMemberStorage, n as memberSwitchboardConfig, o as readModelAsReactorStore, r as memberSwitchboardConfigSchema, t as memberEnvOf } from "../member-config-8Vwys-4O.mjs";
|
|
6
7
|
import { command, runSafely } from "cmd-ts";
|
|
7
8
|
import { switchboardArgs } from "@powerhousedao/shared/clis/args";
|
|
8
|
-
import fs from "node:fs";
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import { computeProgress } from "@powerhousedao/reactor";
|
|
11
|
-
//#region src/runners/reactor-env.ts
|
|
12
|
-
/** The reactor block as the switchboard boots with it: the vars `env` leaves unset, and dbPath. */
|
|
13
|
-
function switchboardBootProjection(reactor, env) {
|
|
14
|
-
const { env: projected, options } = projectReactorToSwitchboard(reactor);
|
|
15
|
-
const unset = {};
|
|
16
|
-
for (const [name, value] of Object.entries(projected)) if (env[name] === void 0 && typeof value === "string") unset[name] = value;
|
|
17
|
-
return {
|
|
18
|
-
env: unset,
|
|
19
|
-
...options.dbPath !== void 0 ? { dbPath: options.dbPath } : {}
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */
|
|
23
|
-
function switchboardDevMode(devVerb, runner) {
|
|
24
|
-
return devVerb || runner.dev === true;
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Apply a host's reactor block to the CURRENT process env, the way the
|
|
28
|
-
* in-process switchboard server reads it at boot (D2.c: env derivation
|
|
29
|
-
* immediately before the member starts; sequential boots make this safe).
|
|
30
|
-
* Single-sourcing teeth first: a pre-set env contradicting the protocol block
|
|
31
|
-
* fails loudly. Then set-if-absent, so an operator's explicit (agreeing) env
|
|
32
|
-
* still wins during the transition. Returns the non-env options (dbPath).
|
|
33
|
-
*
|
|
34
|
-
* Lives OUTSIDE the runner modules on purpose: every export of a runner
|
|
35
|
-
* module reads as a dispatchable verb, and this is not one.
|
|
36
|
-
*/
|
|
37
|
-
function applyReactorEnvProjection(reactor, hostFileLabel) {
|
|
38
|
-
assertProtocolConsistency(reactor?.protocol, process.env, hostFileLabel);
|
|
39
|
-
const projection = switchboardBootProjection(reactor, process.env);
|
|
40
|
-
Object.assign(process.env, projection.env);
|
|
41
|
-
const storage = primaryBackend(reactor)?.storage;
|
|
42
|
-
if (storage?.kind === "path" && storage.dataDir) {
|
|
43
|
-
if (/\$\{(userData|projectRoot)\}/.test(storage.dataDir)) throw new Error(`${hostFileLabel}: storage.dataDir "${storage.dataDir}" was not resolved; resolve the host (resolveHostOutputs) before starting it.`);
|
|
44
|
-
fs.mkdirSync(storage.dataDir, { recursive: true });
|
|
45
|
-
}
|
|
46
|
-
return projection.dbPath !== void 0 ? { dbPath: projection.dbPath } : {};
|
|
47
|
-
}
|
|
48
|
-
//#endregion
|
|
49
11
|
//#region src/services/classic-args.ts
|
|
50
12
|
/**
|
|
51
13
|
* The classic `ph switchboard` argument shape, produced by the SAME cmd-ts
|
|
@@ -258,8 +220,9 @@ function startProgressDisplay(source, options) {
|
|
|
258
220
|
*/
|
|
259
221
|
const kind = "reactor";
|
|
260
222
|
/** The switchboard host: the host-core reactor host with every runner option
|
|
261
|
-
* this module reads declared (strict: an unknown runner key fails).
|
|
262
|
-
*
|
|
223
|
+
* this module reads declared (strict: an unknown runner key fails).
|
|
224
|
+
* `config.switchboard` is this member's own switchboard config (auth,
|
|
225
|
+
* inspection, workers, ...); a key the reactor block also sets is refused.
|
|
263
226
|
* One definition, two schemas: `declaredHostSchema` (token-able fields take
|
|
264
227
|
* output tokens; types host files) and `hostSchema` (resolved; checked
|
|
265
228
|
* right before the verb). */
|
|
@@ -272,7 +235,13 @@ const schemas = defineHostSchemas((s) => s.reactorHostSchema.extend({
|
|
|
272
235
|
/** The project package output dir `build` writes (default "dist"). */
|
|
273
236
|
outDir: string$1().min(1).optional()
|
|
274
237
|
}).strict(),
|
|
275
|
-
config: strictObject({}).optional()
|
|
238
|
+
config: strictObject({ switchboard: memberSwitchboardConfigSchema.optional() }).optional()
|
|
239
|
+
}).superRefine((host, ctx) => {
|
|
240
|
+
for (const message of reactorBlockConflicts(host)) ctx.addIssue({
|
|
241
|
+
code: "custom",
|
|
242
|
+
path: ["config", "switchboard"],
|
|
243
|
+
message
|
|
244
|
+
});
|
|
276
245
|
}));
|
|
277
246
|
const declaredHostSchema = schemas.declaredHostSchema;
|
|
278
247
|
const hostSchema = schemas.hostSchema;
|
|
@@ -302,15 +271,14 @@ const outputsSchema = strictObject({
|
|
|
302
271
|
* such as `dbPath` — reaches the service exactly as on the classic path. No
|
|
303
272
|
* cast: a key the classic shape has and this object lacks is a type error.
|
|
304
273
|
*/
|
|
305
|
-
async function toSwitchboardArgs(host, devMode,
|
|
274
|
+
async function toSwitchboardArgs(host, devMode, composed) {
|
|
306
275
|
const classic = await classicSwitchboardArgs();
|
|
307
276
|
const runner = host.runner;
|
|
308
277
|
return {
|
|
309
278
|
...classic,
|
|
310
279
|
port: runner.port ?? classic.port,
|
|
311
280
|
dev: switchboardDevMode(devMode, runner) ? true : classic.dev,
|
|
312
|
-
mcp: composed ? void 0 : classic.mcp
|
|
313
|
-
dbPath: dbPath ?? classic.dbPath
|
|
281
|
+
mcp: composed ? void 0 : classic.mcp
|
|
314
282
|
};
|
|
315
283
|
}
|
|
316
284
|
/** The drive the switchboard service creates by default
|
|
@@ -404,16 +372,18 @@ function seederClient(reactor, port, seededIds) {
|
|
|
404
372
|
};
|
|
405
373
|
}
|
|
406
374
|
async function start(host, ctx, devMode) {
|
|
407
|
-
const
|
|
408
|
-
const
|
|
375
|
+
const hostFile = `hosts/${host.name}/host.js`;
|
|
376
|
+
const env = memberEnvOf(ctx.env);
|
|
377
|
+
prepareMemberStorage(host.reactor, env.shell, hostFile);
|
|
378
|
+
const legacyStore = readModelAsReactorStore(host.reactor, env.shell, hostFile);
|
|
379
|
+
if (legacyStore) console.warn(legacyStore.warning);
|
|
380
|
+
const { startSwitchboard } = await import("../switchboard-DohZ1tbp.mjs");
|
|
409
381
|
const entries = host.runner.plugins;
|
|
410
382
|
const entriesDeclared = entries !== void 0;
|
|
411
|
-
const args = await toSwitchboardArgs(host, devMode,
|
|
383
|
+
const args = await toSwitchboardArgs(host, devMode, entriesDeclared);
|
|
384
|
+
const memberConfig = await memberSwitchboardConfig(host, env, { pluginHost: entriesDeclared });
|
|
412
385
|
let pluginComposition;
|
|
413
|
-
if (entries !== void 0) {
|
|
414
|
-
process.env.FEATURE_PLUGIN_HOST_ENABLED = "1";
|
|
415
|
-
pluginComposition = await resolveHostPlugins(ctx.projectRoot, "switchboard", ctx.verb, entries, `hosts/${host.name}/host.js`);
|
|
416
|
-
}
|
|
386
|
+
if (entries !== void 0) pluginComposition = await resolveHostPlugins(ctx.projectRoot, "switchboard", ctx.verb, entries, `hosts/${host.name}/host.js`);
|
|
417
387
|
const hostDrives = (host.reactor?.drives ?? []).map((declaration) => ({
|
|
418
388
|
declaredSlug: declaration.slug,
|
|
419
389
|
drive: resolveDriveDeclaration(ctx.projectRoot, declaration)
|
|
@@ -427,7 +397,7 @@ async function start(host, ctx, devMode) {
|
|
|
427
397
|
...hostDrives.length > 0 ? { drive: void 0 } : {},
|
|
428
398
|
...remoteDrives.length > 0 ? { remoteDrives } : {},
|
|
429
399
|
...ctx.parent ? { signalHandlers: false } : {}
|
|
430
|
-
});
|
|
400
|
+
}, void 0, memberConfig);
|
|
431
401
|
const progress = switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== "false" ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {
|
|
432
402
|
stdout: process.stdout,
|
|
433
403
|
stderr: process.stderr
|
|
@@ -451,7 +421,7 @@ async function start(host, ctx, devMode) {
|
|
|
451
421
|
};
|
|
452
422
|
const driveUrl = driveUrlOf(localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug);
|
|
453
423
|
if (entries === void 0 && switchboard.workflowsEnabled) {
|
|
454
|
-
const { seedWorkflowsDrive } = await import("../vetra-
|
|
424
|
+
const { seedWorkflowsDrive } = await import("../vetra-C9fsChId.mjs");
|
|
455
425
|
const { generateProjectDriveId } = await import("../utils-DAux4Ga7.mjs");
|
|
456
426
|
const url = await seedWorkflowsDrive(switchboard.reactor, port);
|
|
457
427
|
if (url) drives.workflows = {
|
|
@@ -488,22 +458,33 @@ async function dev(host, ctx) {
|
|
|
488
458
|
}
|
|
489
459
|
/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */
|
|
490
460
|
async function checkBoot(host, ctx) {
|
|
491
|
-
const
|
|
461
|
+
const env = memberEnvOf(ctx.env, ctx.projectRoot);
|
|
462
|
+
const issues = protocolConflicts(host.reactor?.protocol, env.shell, ctx.file).map((message) => ({
|
|
492
463
|
path: "reactor.protocol",
|
|
493
464
|
message
|
|
494
465
|
}));
|
|
466
|
+
const legacyStore = readModelAsReactorStore(host.reactor, env.shell, ctx.file);
|
|
467
|
+
if (legacyStore) issues.push({
|
|
468
|
+
path: "reactor.backends",
|
|
469
|
+
message: legacyStore.warning
|
|
470
|
+
});
|
|
495
471
|
const { getConfig } = await import("@powerhousedao/config/node");
|
|
496
|
-
const {
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
472
|
+
const { switchboardBootFactsOf, switchboardBootIssues } = await import("@powerhousedao/switchboard/boot");
|
|
473
|
+
let config;
|
|
474
|
+
try {
|
|
475
|
+
config = await memberSwitchboardConfig(host, env, { pluginHost: host.runner.plugins !== void 0 });
|
|
476
|
+
} catch (error) {
|
|
477
|
+
issues.push({
|
|
478
|
+
path: "",
|
|
479
|
+
message: error instanceof Error ? error.message : String(error)
|
|
480
|
+
});
|
|
481
|
+
return issues;
|
|
482
|
+
}
|
|
483
|
+
const facts = await switchboardBootFactsOf(config, {
|
|
502
484
|
dev: switchboardDevMode(ctx.verb === "dev", host.runner),
|
|
503
|
-
...projection.dbPath !== void 0 ? { dbPath: projection.dbPath } : {},
|
|
504
485
|
configuredRenown: getConfig(path.join(ctx.projectRoot, "powerhouse.config.json")).auth?.renown
|
|
505
486
|
});
|
|
506
|
-
for (const message of
|
|
487
|
+
for (const message of switchboardBootIssues(facts)) issues.push({
|
|
507
488
|
path: "",
|
|
508
489
|
message
|
|
509
490
|
});
|
|
@@ -512,11 +493,11 @@ async function checkBoot(host, ctx) {
|
|
|
512
493
|
/** Build the project's reactor package (the SAME service as `ph build`) — what
|
|
513
494
|
* this switchboard serves. Starts no server; orthogonal to run/serve/dev. */
|
|
514
495
|
async function build(host, _ctx) {
|
|
515
|
-
const { runBuild } = await import("../build-
|
|
496
|
+
const { runBuild } = await import("../build-FoZl36TM.mjs");
|
|
516
497
|
await runBuild({ outDir: host.runner.outDir ?? "dist" });
|
|
517
498
|
}
|
|
518
499
|
//#endregion
|
|
519
500
|
export { build, checkBoot, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, switchboardDriveOutputSchema };
|
|
520
501
|
|
|
521
502
|
//# sourceMappingURL=switchboard.mjs.map
|
|
522
|
-
//# debugId=
|
|
503
|
+
//# debugId=1819c7f8-3860-5090-85e5-aa961b217309
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard.mjs","sources":["../../src/runners/reactor-env.ts","../../src/services/classic-args.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n assertProtocolConsistency,\n primaryBackend,\n projectReactorToSwitchboard,\n type ReactorConfig,\n} from \"@powerhousedao/host-core\";\n\n/** The reactor block as the switchboard boots with it: the vars `env` leaves unset, and dbPath. */\nexport function switchboardBootProjection(\n reactor: ReactorConfig | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): { env: Record<string, string>; dbPath?: string } {\n const { env: projected, options } = projectReactorToSwitchboard(reactor);\n const unset: Record<string, string> = {};\n for (const [name, value] of Object.entries(projected) as [\n string,\n unknown,\n ][]) {\n // A deferred $output token is not a value yet.\n if (env[name] === undefined && typeof value === \"string\")\n unset[name] = value;\n }\n return {\n env: unset,\n ...(options.dbPath !== undefined ? { dbPath: options.dbPath } : {}),\n };\n}\n\n/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */\nexport function switchboardDevMode(\n devVerb: boolean,\n runner: { dev?: boolean },\n): boolean {\n return devVerb || runner.dev === true;\n}\n\n/**\n * Apply a host's reactor block to the CURRENT process env, the way the\n * in-process switchboard server reads it at boot (D2.c: env derivation\n * immediately before the member starts; sequential boots make this safe).\n * Single-sourcing teeth first: a pre-set env contradicting the protocol block\n * fails loudly. Then set-if-absent, so an operator's explicit (agreeing) env\n * still wins during the transition. Returns the non-env options (dbPath).\n *\n * Lives OUTSIDE the runner modules on purpose: every export of a runner\n * module reads as a dispatchable verb, and this is not one.\n */\nexport function applyReactorEnvProjection(\n reactor: ReactorConfig | undefined,\n hostFileLabel: string,\n): { dbPath?: string } {\n assertProtocolConsistency(reactor?.protocol, process.env, hostFileLabel);\n const projection = switchboardBootProjection(reactor, process.env);\n Object.assign(process.env, projection.env);\n // A path-storage data dir must exist before the server boots — its own\n // mkdir is not recursive (the ph-win sidecar did this too).\n const storage = primaryBackend(reactor)?.storage;\n if (storage?.kind === \"path\" && storage.dataDir) {\n // `ph run` resolves `$env` and the `${userData}` sugar before the verb;\n // an unresolved one here would mkdir a literal \"${userData}\" folder.\n if (/\\$\\{(userData|projectRoot)\\}/.test(storage.dataDir)) {\n throw new Error(\n `${hostFileLabel}: storage.dataDir \"${storage.dataDir}\" was not resolved; resolve the host (resolveHostOutputs) before starting it.`,\n );\n }\n fs.mkdirSync(storage.dataDir, { recursive: true });\n }\n return projection.dbPath !== undefined ? { dbPath: projection.dbPath } : {};\n}\n","import { switchboardArgs } from \"@powerhousedao/shared/clis/args\";\nimport { command, runSafely } from \"cmd-ts\";\nimport type { SwitchboardArgs } from \"../types.js\";\n\n/**\n * The classic `ph switchboard` argument shape, produced by the SAME cmd-ts\n * definitions the classic command parses — not re-derived by hand. A runner\n * starts from this object and overlays only the keys its host file owns, so\n * every key the classic command carries (including the ones it carries as\n * `undefined`, e.g. `dbPath`) reaches the service exactly as it does on the\n * classic path. The uniform-runners switchboard runner once hand-built a\n * partial object that omitted `dbPath`; the service's then-default\n * `.ph/read-model.db` became both the reactor and the read-model PGlite dir —\n * two instances on one PGDATA (see uniform-runners-plan/legacy-parity-rectification.md).\n */\nconst classicSwitchboard = command({\n name: \"switchboard\",\n args: switchboardArgs,\n handler: (args) => args,\n});\n\nexport async function classicSwitchboardArgs(\n argv: string[] = [],\n): Promise<SwitchboardArgs> {\n const result = await runSafely(classicSwitchboard, argv);\n if (result._tag === \"error\") {\n throw new Error(\n `classic switchboard args did not parse: ${result.error.config.message}`,\n );\n }\n return result.value;\n}\n","import {\n computeProgress,\n type CatchUpPriorityState,\n type IInspector,\n type ReactorProgress,\n} from \"@powerhousedao/reactor\";\n\n/** One bar: a processor factory or a read model, and how far its catch-up has got. */\nexport type ProgressRow = {\n readonly label: string;\n /** 0..1 of the current run. */\n readonly fraction: number;\n readonly state: \"catching-up\" | \"done\" | \"errored\";\n};\n\n/** The catch-up priority as the progress display states it. */\nexport type ProgressPriority = {\n readonly mode: CatchUpPriorityState[\"mode\"];\n readonly level: number;\n readonly reason: string;\n};\n\n/** What one read of the source shows: the bars, and the priority when known. */\nexport type ProgressSnapshot = {\n readonly rows: readonly ProgressRow[];\n readonly priority: ProgressPriority | undefined;\n};\n\n/** Reads the current rows; rejects while the reactor cannot answer. */\nexport type ProgressSource = () => Promise<ProgressSnapshot>;\n\nfunction withDrives(label: string, driveCount: number): string {\n return `${label} (${driveCount} ${driveCount === 1 ? \"drive\" : \"drives\"})`;\n}\n\n/** One row per processor factory, then one per reactor read model. */\nexport function progressRows(progress: ReactorProgress): ProgressRow[] {\n const factories = progress.factories.map((factory): ProgressRow => ({\n label: withDrives(factory.label, factory.driveCount),\n fraction: factory.fraction,\n state:\n factory.phase === \"errored\"\n ? \"errored\"\n : factory.phase === \"catching-up\"\n ? \"catching-up\"\n : \"done\",\n }));\n const readModels = progress.readModels.map((model): ProgressRow => ({\n label: model.consumerId,\n fraction: model.fraction,\n state: model.blocked ? \"errored\" : model.complete ? \"done\" : \"catching-up\",\n }));\n return [...factories, ...readModels];\n}\n\n/** Rows from a reactor's inspector: its processors, catch-up status and priority. */\nexport function inspectorProgressSource(inspector: IInspector): ProgressSource {\n return async () => {\n const processors = await inspector.getProcessors();\n let catchUp:\n | Awaited<ReturnType<IInspector[\"getCatchUpStatus\"]>>\n | undefined;\n try {\n catchUp = await inspector.getCatchUpStatus();\n } catch {\n catchUp = undefined;\n }\n let priority: ProgressPriority | undefined;\n try {\n const state = await inspector.getCatchUpPriority();\n priority = { mode: state.mode, level: state.level, reason: state.reason };\n } catch {\n priority = undefined;\n }\n return {\n rows: progressRows(computeProgress(processors, catchUp)),\n priority,\n };\n };\n}\n\n/** `catch-up priority 6 (dynamic, idle 14 s)`, or `catch-up priority 3 (fixed)`. */\nexport function renderPriority(priority: ProgressPriority): string {\n const why =\n priority.mode === \"dynamic\" ? `dynamic, ${priority.reason}` : \"fixed\";\n return `catch-up priority ${priority.level} (${why})`;\n}\n\n/** The slice of a TTY stream the display writes to and intercepts. */\nexport type ProgressStream = {\n write: NodeJS.WriteStream[\"write\"];\n readonly isTTY?: boolean;\n readonly columns?: number;\n /** A TTY stream emits \"resize\" when the terminal's size changes. */\n on?(event: \"resize\", listener: () => void): unknown;\n off?(event: \"resize\", listener: () => void): unknown;\n};\n\n/** The console width the bars are sized for: a reported width, else 80. */\nfunction widthOf(stream: ProgressStream): number {\n const columns = stream.columns;\n return typeof columns === \"number\" && columns > 0 ? columns : 80;\n}\n\nexport type ProgressDisplayOptions = {\n readonly stdout: ProgressStream;\n readonly stderr: ProgressStream;\n /** How often the source is read. */\n readonly pollMs?: number;\n /** Without a TTY: how often a progress line is printed while catching up. */\n readonly lineMs?: number;\n};\n\nexport type ProgressDisplay = {\n /** Stops polling, removes the bars and restores the streams. */\n stop(): void;\n};\n\nconst DEFAULT_POLL_MS = 1_000;\nconst DEFAULT_LINE_MS = 10_000;\nconst MIN_BAR = 10;\nconst MAX_LABEL = 32;\n\nfunction percent(row: ProgressRow): string {\n if (row.state === \"errored\") return \"errored\";\n if (row.state === \"done\") return \"done\";\n return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;\n}\n\nfunction fit(label: string, width: number): string {\n return label.length <= width\n ? label.padEnd(width)\n : `…${label.slice(label.length - width + 1)}`;\n}\n\n/**\n * The bar block, one line per row, under the priority when known. Every line\n * stays short of the terminal's last column: a line that fills it wraps on\n * xterm-based terminals (VS Code, Windows Terminal), and the erase would then\n * lift fewer lines than are on screen, leaving old bars behind. On a narrow\n * terminal the label gives way before the bar.\n */\nexport function renderBars(\n rows: readonly ProgressRow[],\n columns: number,\n priority?: ProgressPriority,\n): string[] {\n const width = Math.max(columns - 1, 1);\n // label, space, bar, space, 7 for \"errored\" / \"100%\"\n const fixed = 9;\n const longest = Math.max(...rows.map((row) => row.label.length), 0);\n const labelWidth = Math.max(\n 1,\n Math.min(MAX_LABEL, longest, width - fixed - MIN_BAR),\n );\n const barWidth = Math.max(MIN_BAR, width - labelWidth - fixed);\n const bars = rows.map((row) => {\n const fraction = row.state === \"done\" ? 1 : row.fraction;\n const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);\n const bar = \"█\".repeat(filled) + \"░\".repeat(barWidth - filled);\n return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`.slice(\n 0,\n width,\n );\n });\n if (!priority) return bars;\n return [renderPriority(priority).slice(0, width), ...bars];\n}\n\n/** One line for a log without a TTY, listing only what is still catching up. */\nexport function renderLine(\n rows: readonly ProgressRow[],\n priority?: ProgressPriority,\n): string {\n const busy = rows.filter((row) => row.state !== \"done\");\n const line = `catch-up: ${busy.map((row) => `${row.label} ${percent(row)}`).join(\" · \")}`;\n return priority\n ? `${line} · priority ${priority.level} ${priority.mode}`\n : line;\n}\n\nfunction busy(rows: readonly ProgressRow[]): boolean {\n return rows.some((row) => row.state !== \"done\");\n}\n\n/**\n * Shows catch-up progress while any row is not done. In a terminal the bars\n * sit below the output and every other write is printed above them; without\n * one, a progress line is printed every `lineMs`.\n */\nexport function startProgressDisplay(\n source: ProgressSource,\n options: ProgressDisplayOptions,\n): ProgressDisplay {\n const { stdout, stderr } = options;\n const tty = stdout.isTTY === true;\n let rows: readonly ProgressRow[] = [];\n let priority: ProgressPriority | undefined;\n let drawn = 0;\n let atLineStart = true;\n let lastLine = 0;\n let stopped = false;\n let reading = false;\n\n const restoreOut = stdout.write;\n const restoreErr = stderr.write;\n const originalOut = restoreOut.bind(stdout);\n const originalErr = restoreErr.bind(stderr);\n\n const erase = () => {\n if (drawn > 0) originalOut(`\\x1b[${drawn}A\\r\\x1b[0J`);\n drawn = 0;\n };\n const draw = () => {\n if (!tty || stopped || !atLineStart || !busy(rows)) return;\n const lines = renderBars(rows, widthOf(stdout), priority);\n originalOut(`${lines.join(\"\\n\")}\\n`);\n drawn = lines.length;\n };\n\n // Every other write goes above the bars: lift them, write, put them back.\n const above =\n (write: (chunk: string | Uint8Array, ...rest: never[]) => boolean) =>\n (chunk: string | Uint8Array, ...rest: never[]): boolean => {\n erase();\n const result = write(chunk, ...rest);\n const text =\n typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n if (text.length > 0) atLineStart = text.endsWith(\"\\n\");\n draw();\n return result;\n };\n // A resized terminal has already reflowed the drawn lines; redraw for the\n // new width right away rather than at the next poll.\n const onResize = () => {\n if (stopped) return;\n erase();\n draw();\n };\n if (tty) {\n stdout.write = above(originalOut as never) as NodeJS.WriteStream[\"write\"];\n stderr.write = above(originalErr as never) as NodeJS.WriteStream[\"write\"];\n stdout.on?.(\"resize\", onResize);\n }\n\n const tick = async () => {\n if (reading || stopped) return;\n reading = true;\n try {\n ({ rows, priority } = await source());\n } catch {\n // The reactor did not answer; keep the last rows until it does.\n } finally {\n reading = false;\n }\n if (stopped) return;\n if (tty) {\n erase();\n draw();\n return;\n }\n const now = Date.now();\n if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {\n originalOut(`${renderLine(rows, priority)}\\n`);\n lastLine = now;\n }\n };\n\n const timer = setInterval(\n () => void tick(),\n options.pollMs ?? DEFAULT_POLL_MS,\n );\n (timer as { unref?: () => void }).unref?.();\n void tick();\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n erase();\n if (tty) {\n stdout.off?.(\"resize\", onResize);\n stdout.write = restoreOut;\n stderr.write = restoreErr;\n }\n },\n };\n}\n","import {\n defineHostSchemas,\n drivesSchema,\n mergeDrivePlan,\n protocolConflicts,\n resolveDriveDeclaration,\n resolveHostPlugins,\n seedDrives,\n type BootCheckContext,\n type BootIssue,\n type DriveSeederClient,\n type ResolvedDrive,\n type ResolvedPlugin,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport path from \"node:path\";\nimport {\n applyReactorEnvProjection,\n switchboardBootProjection,\n switchboardDevMode,\n} from \"./reactor-env.js\";\nimport { z } from \"zod\";\nimport { classicSwitchboardArgs } from \"../services/classic-args.js\";\nimport {\n inspectorProgressSource,\n startProgressDisplay,\n} from \"../services/run/catch-up-progress.js\";\nimport type { BuildArgs, SwitchboardArgs } from \"../types.js\";\n\n/**\n * BRIDGE runner for Switchboard hosts (uniform-runners phase 0): maps a\n * hosts/switchboard/host.js definition onto the SAME `startSwitchboard`\n * service the classic command calls. `run` = production loaders, `dev` =\n * Vite package loader (worker pools refused by the server, as always).\n */\n\nexport const kind = \"reactor\";\n\n/** The switchboard host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails). The\n * runner reads nothing from `config`, so only an empty one is accepted.\n * One definition, two schemas: `declaredHostSchema` (token-able fields take\n * output tokens; types host files) and `hostSchema` (resolved; checked\n * right before the verb). */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema.extend({\n runner: s.runnerBaseSchema\n .extend({\n /** 0 binds a port the OS picks; `origin` reports it. */\n port: z.number().int().min(0).max(65535).optional(),\n /** Dev mode without the `dev` verb (the Vite package loader). */\n dev: z.boolean().optional(),\n /** The project package output dir `build` writes (default \"dist\"). */\n outDir: z.string().min(1).optional(),\n })\n .strict(),\n config: z.strictObject({}).optional(),\n }),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a switchboard host.js author writes. */\nexport type SwitchboardHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type SwitchboardHostParsed = z.output<typeof hostSchema>;\n\n/** One drive the switchboard serves: its document id and its URL. */\nexport const switchboardDriveOutputSchema = z.strictObject({\n id: z.string().min(1),\n url: z.url(),\n});\n\n/** What a started switchboard produces. `origin` carries the port the server\n * actually bound. `drives` is keyed by the DECLARED slug (a `projectHash:\n * true` drive is reachable as `vetra`, its URL uses the hashed slug it is\n * served under) and includes plugin-created drives (e.g. `workflows`) and\n * the server's implicit default drive. `endpoints.mcp` is present when MCP\n * is mounted. */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({\n graphql: z.url(),\n mcp: z.url().optional(),\n }),\n drives: z.record(z.string(), switchboardDriveOutputSchema),\n});\nexport type SwitchboardOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/switchboard\": {\n host: SwitchboardHost;\n outputs: SwitchboardOutputs;\n };\n }\n}\n\n/** The classic arg shape with the one switch a composition may leave unset. */\nexport type SwitchboardRunnerArgs = Omit<SwitchboardArgs, \"mcp\"> & {\n mcp: boolean | undefined;\n};\n\n/**\n * Start from the classic `ph switchboard` args (parsed by the classic\n * definitions, no flags) and overlay ONLY the keys the host file owns. Every\n * other key — including the ones the classic command carries as `undefined`,\n * such as `dbPath` — reaches the service exactly as on the classic path. No\n * cast: a key the classic shape has and this object lacks is a type error.\n */\nasync function toSwitchboardArgs(\n host: SwitchboardHostParsed,\n devMode: boolean,\n dbPath: string | undefined,\n composed: boolean,\n): Promise<SwitchboardRunnerArgs> {\n const classic = await classicSwitchboardArgs();\n const runner = host.runner;\n return {\n ...classic,\n port: runner.port ?? classic.port,\n dev: switchboardDevMode(devMode, runner) ? true : classic.dev,\n // A declared composition owns the carved switches (R2): the mcp plugin's\n // presence sets it, its absence must deactivate. Classic path: classic.\n mcp: composed ? undefined : classic.mcp,\n // The host file's readModel.url. Absent, the key stays present and\n // undefined exactly as the classic command carries it, so the server's\n // own split defaults (.ph/reactor-storage + .ph/read-storage) apply.\n // Omitting the key resurrected a dead service default and put the\n // reactor and the read model on ONE PGlite dir (two writers, one PGDATA).\n dbPath: dbPath ?? classic.dbPath,\n };\n}\n\n/** The drive the switchboard service creates by default\n * (services/switchboard.ts `defaultSwitchboardOptions.drive`). */\nconst DEFAULT_DRIVE_SLUG = \"powerhouse\";\n\n/** The `<slug>` of the server-reported `…/d/<slug>` default drive URL. */\nfunction defaultDriveSlug(url: string | undefined): string {\n const match = url ? /\\/d\\/([^/?#]+)\\/?$/.exec(url) : null;\n return match ? decodeURIComponent(match[1]) : DEFAULT_DRIVE_SLUG;\n}\n\n/** A drive in the plan with the slug its declaration used (a `projectHash:\n * true` drive is served under its hashed slug; outputs key it by this one). */\ninterface PlannedDrive {\n declaredSlug: string;\n drive: ResolvedDrive;\n}\n\n/**\n * The drives the composition's plugins contribute, resolved and in plan\n * order, minus the slugs the host declares itself (mergeDrivePlan: the host\n * file wins). A contribution that is not a valid drive declaration fails the\n * boot naming the plugin.\n */\nfunction pluginDrives(\n projectRoot: string,\n hostDrives: readonly PlannedDrive[],\n composition: readonly ResolvedPlugin[] | undefined,\n where: string,\n): PlannedDrive[] {\n if (!composition) return [];\n const contributed = composition.flatMap((resolved) => {\n const drives = resolved.plugin.contributions?.drives ?? [];\n if (drives.length === 0) return [];\n const parsed = drivesSchema.safeParse(drives);\n if (!parsed.success) {\n throw new Error(\n `${where}: plugin \"${resolved.plugin.name}\" contributes an invalid drive declaration:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n return parsed.data.map((declaration) => ({\n declaration,\n source: resolved.plugin.name,\n }));\n });\n if (contributed.length === 0) return [];\n // served slug -> declared slug, for the outputs' keys\n const declaredSlugs = new Map(\n contributed.map(({ declaration }) => [\n resolveDriveDeclaration(projectRoot, declaration).slug,\n declaration.slug,\n ]),\n );\n const hostSlugs = new Set(hostDrives.map((d) => d.drive.slug));\n return mergeDrivePlan(projectRoot, [], contributed)\n .map((entry) => entry.drive)\n .filter((drive) => !hostSlugs.has(drive.slug))\n .map((drive) => ({\n declaredSlug: declaredSlugs.get(drive.slug) ?? drive.slug,\n drive,\n }));\n}\n\n/** Poll the default drive endpoint until the server answers — the compound's\n * readiness gate: Connect auto-connects the drive on first load, so the drive\n * must answer before the connect member serves (the sidecar's\n * waitForSwitchboard, moved behind the handle contract). */\nasync function waitForDrive(url: string, timeoutMs: number): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n const res = await fetch(url, { signal: AbortSignal.timeout(3000) });\n if (res.ok) return;\n } catch {\n // not listening yet\n }\n if (Date.now() > deadline) {\n throw new Error(\n `Switchboard drive ${url} did not answer within ${timeoutMs}ms.`,\n );\n }\n await new Promise((resolve) => setTimeout(resolve, 400));\n }\n}\n\n/** What a started switchboard returns. */\nexport type SwitchboardHandle = RunnerHandle<SwitchboardOutputs>;\n\n/** The slice of the switchboard's reactor client (IReactorClient) the seeder\n * reads: id-or-slug resolution against the read model (live documents). */\ninterface SlugLookupClient {\n resolveIdOrSlug(identifier: string): Promise<string | undefined>;\n}\n\n/**\n * Adapter from the switchboard's reactor client onto the host-core seeder.\n * Seeding is SLUG-keyed: a live drive that already serves the slug — under\n * whatever id (a store from a run that hashed the project path differently,\n * or a hand-made drive) — is the drive, and nothing is created. addDefaultDrive\n * alone only knows ids: with a different id it would try to create a second\n * drive for the slug, and against a deleted document with that id the create\n * fails on every boot.\n */\nfunction seederClient(\n reactor: unknown,\n port: number,\n seededIds: Map<string, string>,\n): DriveSeederClient {\n return {\n findDriveBySlug: async (slug: string) => {\n try {\n const id = await (reactor as SlugLookupClient).resolveIdOrSlug(slug);\n if (id) seededIds.set(slug, id);\n return id || undefined;\n } catch {\n // not found (or ambiguous): seed as declared\n return undefined;\n }\n },\n createDrive: async (drive: ResolvedDrive) => {\n seededIds.set(drive.slug, drive.id);\n const { addDefaultDrive } =\n await import(\"@powerhousedao/switchboard/utils\");\n await addDefaultDrive(\n reactor as Parameters<typeof addDefaultDrive>[0],\n {\n id: drive.id,\n slug: drive.slug,\n global: { name: drive.name, icon: drive.icon },\n ...(drive.preferredEditor\n ? { preferredEditor: drive.preferredEditor }\n : {}),\n local: {\n availableOffline: drive.availableOffline,\n listeners: [],\n sharingType: drive.sharingType,\n triggers: [],\n },\n } as Parameters<typeof addDefaultDrive>[1],\n port,\n );\n },\n attachRemoteDrive: () => Promise.resolve(), // remotes ride options.remoteDrives\n };\n}\n\nasync function start(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n devMode: boolean,\n): Promise<SwitchboardHandle> {\n const options = applyReactorEnvProjection(\n host.reactor,\n `hosts/${host.name}/host.js`,\n );\n const { startSwitchboard } = await import(\"../services/switchboard.js\");\n const entries = host.runner.plugins;\n const entriesDeclared = entries !== undefined;\n const args = await toSwitchboardArgs(\n host,\n devMode,\n options.dbPath,\n entriesDeclared,\n );\n\n // R2 step 2: a declared composition activates the plugin pipeline — the\n // runner resolves the entries against the PROJECT dependency tree and the\n // flag drives server-side activation. No plugins key = classic path.\n let pluginComposition;\n if (entries !== undefined) {\n process.env.FEATURE_PLUGIN_HOST_ENABLED = \"1\";\n pluginComposition = await resolveHostPlugins(\n ctx.projectRoot,\n \"switchboard\",\n ctx.verb,\n entries,\n `hosts/${host.name}/host.js`,\n );\n }\n\n // Core drive declarations (reactor.drives): locals seed after boot via the\n // host-core seeder; remotes ride the existing remoteDrives option; the\n // implicit default powerhouse drive is replaced by the declared set.\n const hostDrives: PlannedDrive[] = (host.reactor?.drives ?? []).map(\n (declaration) => ({\n declaredSlug: declaration.slug,\n drive: resolveDriveDeclaration(ctx.projectRoot, declaration),\n }),\n );\n // Plugin-contributed drives (e.g. the workflows plugin's Workflows drive)\n // join the plan after the host's own: a host declaration with the same slug\n // wins, and the host's drives stay first (the first local one is the\n // readiness gate and the compound's primary drive).\n const contributedDrives = pluginDrives(\n ctx.projectRoot,\n hostDrives,\n pluginComposition,\n `hosts/${host.name}/host.js`,\n );\n const planned = [...hostDrives, ...contributedDrives];\n const resolvedDrives = planned.map((p) => p.drive);\n const remoteDrives = resolvedDrives.flatMap((d) =>\n d.kind === \"remote\" && d.remoteUrl ? [d.remoteUrl] : [],\n );\n const serverArgs = {\n ...args,\n ...(pluginComposition ? { pluginComposition } : {}),\n // Only the HOST's declarations replace the implicit default drive; a\n // contribution adds to whatever the host serves.\n ...(hostDrives.length > 0 ? { drive: undefined } : {}),\n ...(remoteDrives.length > 0 ? { remoteDrives } : {}),\n // A compound member: the compound owns SIGINT/SIGTERM and the exit, and\n // stops this reactor through the handle's shutdown().\n ...(ctx.parent ? { signalHandlers: false } : {}),\n };\n\n const switchboard = await startSwitchboard(serverArgs);\n // Bars for processor and read-model catch-up, below the server's output;\n // PH_CATCH_UP_PROGRESS=false leaves the output as it was.\n const progress =\n switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== \"false\"\n ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {\n stdout: process.stdout,\n stderr: process.stderr,\n })\n : undefined;\n // The port the server actually bound (it may move off a taken one).\n const port = switchboard.port;\n const origin = `http://localhost:${port}`;\n const driveUrlOf = (slug: string) => `${origin}/d/${slug}`;\n\n const seededIds = new Map<string, string>();\n const localPlanned = planned.filter((p) => p.drive.kind === \"local\");\n if (localPlanned.length > 0) {\n await seedDrives(\n seederClient(switchboard.reactor, port, seededIds),\n localPlanned.map((p) => p.drive),\n );\n }\n\n const drives: SwitchboardOutputs[\"drives\"] = {};\n // The server creates its implicit default drive only when nothing replaces\n // it: no host declaration and no remote drive (services/switchboard.ts).\n const localHostDrives = hostDrives.filter((d) => d.drive.kind === \"local\");\n const defaultSlug = defaultDriveSlug(switchboard.defaultDriveUrl);\n if (hostDrives.length === 0 && remoteDrives.length === 0) {\n drives[defaultSlug] = { id: defaultSlug, url: driveUrlOf(defaultSlug) };\n }\n for (const { declaredSlug, drive } of localPlanned) {\n drives[declaredSlug] = {\n id: seededIds.get(drive.slug) ?? drive.id,\n url: driveUrlOf(drive.slug),\n };\n }\n\n const slug =\n localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;\n const driveUrl = driveUrlOf(slug);\n\n // No composition declared (the deprecated `reactor.workflows` switch): the\n // workflows flag still seeds the SAME project-hashed drive the classic\n // vetra path seeds. With a composition the workflows PLUGIN declares that\n // drive (contributions.drives above), so nothing implicit happens here.\n if (entries === undefined && switchboard.workflowsEnabled) {\n const { seedWorkflowsDrive } = await import(\"../services/vetra.js\");\n const { generateProjectDriveId } = await import(\"../utils.js\");\n const url = await seedWorkflowsDrive(switchboard.reactor, port);\n if (url)\n drives.workflows = { id: generateProjectDriveId(\"workflows\"), url };\n }\n\n const ready = waitForDrive(driveUrl, 180_000);\n // A supervisor awaits `ready` and sees the rejection; an unsupervised caller\n // (or a test with the service mocked) must not die of an unhandled one.\n ready.catch(() => undefined);\n const graphql = `${origin}/graphql`;\n // Stops the reactor the server owns, then drains the HTTP server (freeing\n // the port), GraphQL, MCP, attachments, the plugins' onShutdown and the\n // read-model db, then closes the reactor database. SwitchboardReactor\n // memoizes it; standalone, SIGINT/SIGTERM run the same teardown, so a\n // shutdown() during or after a signal joins it instead of draining twice.\n let stopping: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin,\n endpoints: {\n graphql,\n ...(switchboard.mcpEnabled ? { mcp: `${origin}/mcp` } : {}),\n },\n drives,\n }),\n ready,\n shutdown: () => {\n progress?.stop();\n return (stopping ??= switchboard.shutdown());\n },\n };\n}\n\n// The four verbs are orthogonal: each does ONE job.\n// - `run`/`serve`: START the server in production mode (serves the built\n// project package). `serve` is run's alias — a server IS its served stack,\n// and it lets the compound forward one `serve` verb to every member.\n// - `dev`: START the server in dev mode (watch / the Vite package loader).\n// - `build`: PRODUCE the project package this switchboard serves, and start\n// NOTHING. The analog of `ph connect build` on the server side: legacy\n// `ph switchboard build` never existed, but the project still has a build.\n// `build` is what lets a compound forward a single `build` verb to all members\n// (desktop/cli) without the switchboard member failing on an unknown verb.\n\nexport async function run(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, false);\n}\n\nexport const serve = run;\n\nexport async function dev(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, true);\n}\n\n/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */\nexport async function checkBoot(\n host: SwitchboardHostParsed,\n ctx: BootCheckContext,\n): Promise<BootIssue[]> {\n const issues: BootIssue[] = protocolConflicts(\n host.reactor?.protocol,\n ctx.env,\n ctx.file,\n ).map((message) => ({ path: \"reactor.protocol\", message }));\n const { getConfig } = await import(\"@powerhousedao/config/node\");\n const { switchboardBootFactsFromEnv, switchboardBootIssues } =\n await import(\"@powerhousedao/switchboard/boot\");\n const projection = switchboardBootProjection(host.reactor, ctx.env);\n const { facts, issues: parseIssues } = await switchboardBootFactsFromEnv(\n { ...ctx.env, ...projection.env },\n {\n // As the `dev` verb starts it.\n dev: switchboardDevMode(ctx.verb === \"dev\", host.runner),\n ...(projection.dbPath !== undefined ? { dbPath: projection.dbPath } : {}),\n configuredRenown: getConfig(\n path.join(ctx.projectRoot, \"powerhouse.config.json\"),\n ).auth?.renown,\n },\n );\n for (const message of [...parseIssues, ...switchboardBootIssues(facts)]) {\n issues.push({ path: \"\", message });\n }\n return issues;\n}\n\n/** Build the project's reactor package (the SAME service as `ph build`) — what\n * this switchboard serves. Starts no server; orthogonal to run/serve/dev. */\nexport async function build(\n host: SwitchboardHostParsed,\n _ctx: RunnerContext,\n): Promise<void> {\n const { runBuild } = await import(\"../services/build.js\");\n const args: Partial<BuildArgs> = {\n outDir: host.runner.outDir ?? \"dist\",\n };\n await runBuild(args as BuildArgs);\n}\n"],"names":["z.number","z.boolean","z.string","z.strictObject","z.url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AAG,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":"e27b13de-cbd8-5537-989f-0ef2c8b775f4"}
|
|
1
|
+
{"version":3,"file":"switchboard.mjs","sources":["../../src/services/classic-args.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["import { switchboardArgs } from \"@powerhousedao/shared/clis/args\";\nimport { command, runSafely } from \"cmd-ts\";\nimport type { SwitchboardArgs } from \"../types.js\";\n\n/**\n * The classic `ph switchboard` argument shape, produced by the SAME cmd-ts\n * definitions the classic command parses — not re-derived by hand. A runner\n * starts from this object and overlays only the keys its host file owns, so\n * every key the classic command carries (including the ones it carries as\n * `undefined`, e.g. `dbPath`) reaches the service exactly as it does on the\n * classic path. The uniform-runners switchboard runner once hand-built a\n * partial object that omitted `dbPath`; the service's then-default\n * `.ph/read-model.db` became both the reactor and the read-model PGlite dir —\n * two instances on one PGDATA (see uniform-runners-plan/legacy-parity-rectification.md).\n */\nconst classicSwitchboard = command({\n name: \"switchboard\",\n args: switchboardArgs,\n handler: (args) => args,\n});\n\nexport async function classicSwitchboardArgs(\n argv: string[] = [],\n): Promise<SwitchboardArgs> {\n const result = await runSafely(classicSwitchboard, argv);\n if (result._tag === \"error\") {\n throw new Error(\n `classic switchboard args did not parse: ${result.error.config.message}`,\n );\n }\n return result.value;\n}\n","import {\n computeProgress,\n type CatchUpPriorityState,\n type IInspector,\n type ReactorProgress,\n} from \"@powerhousedao/reactor\";\n\n/** One bar: a processor factory or a read model, and how far its catch-up has got. */\nexport type ProgressRow = {\n readonly label: string;\n /** 0..1 of the current run. */\n readonly fraction: number;\n readonly state: \"catching-up\" | \"done\" | \"errored\";\n};\n\n/** The catch-up priority as the progress display states it. */\nexport type ProgressPriority = {\n readonly mode: CatchUpPriorityState[\"mode\"];\n readonly level: number;\n readonly reason: string;\n};\n\n/** What one read of the source shows: the bars, and the priority when known. */\nexport type ProgressSnapshot = {\n readonly rows: readonly ProgressRow[];\n readonly priority: ProgressPriority | undefined;\n};\n\n/** Reads the current rows; rejects while the reactor cannot answer. */\nexport type ProgressSource = () => Promise<ProgressSnapshot>;\n\nfunction withDrives(label: string, driveCount: number): string {\n return `${label} (${driveCount} ${driveCount === 1 ? \"drive\" : \"drives\"})`;\n}\n\n/** One row per processor factory, then one per reactor read model. */\nexport function progressRows(progress: ReactorProgress): ProgressRow[] {\n const factories = progress.factories.map((factory): ProgressRow => ({\n label: withDrives(factory.label, factory.driveCount),\n fraction: factory.fraction,\n state:\n factory.phase === \"errored\"\n ? \"errored\"\n : factory.phase === \"catching-up\"\n ? \"catching-up\"\n : \"done\",\n }));\n const readModels = progress.readModels.map((model): ProgressRow => ({\n label: model.consumerId,\n fraction: model.fraction,\n state: model.blocked ? \"errored\" : model.complete ? \"done\" : \"catching-up\",\n }));\n return [...factories, ...readModels];\n}\n\n/** Rows from a reactor's inspector: its processors, catch-up status and priority. */\nexport function inspectorProgressSource(inspector: IInspector): ProgressSource {\n return async () => {\n const processors = await inspector.getProcessors();\n let catchUp:\n | Awaited<ReturnType<IInspector[\"getCatchUpStatus\"]>>\n | undefined;\n try {\n catchUp = await inspector.getCatchUpStatus();\n } catch {\n catchUp = undefined;\n }\n let priority: ProgressPriority | undefined;\n try {\n const state = await inspector.getCatchUpPriority();\n priority = { mode: state.mode, level: state.level, reason: state.reason };\n } catch {\n priority = undefined;\n }\n return {\n rows: progressRows(computeProgress(processors, catchUp)),\n priority,\n };\n };\n}\n\n/** `catch-up priority 6 (dynamic, idle 14 s)`, or `catch-up priority 3 (fixed)`. */\nexport function renderPriority(priority: ProgressPriority): string {\n const why =\n priority.mode === \"dynamic\" ? `dynamic, ${priority.reason}` : \"fixed\";\n return `catch-up priority ${priority.level} (${why})`;\n}\n\n/** The slice of a TTY stream the display writes to and intercepts. */\nexport type ProgressStream = {\n write: NodeJS.WriteStream[\"write\"];\n readonly isTTY?: boolean;\n readonly columns?: number;\n /** A TTY stream emits \"resize\" when the terminal's size changes. */\n on?(event: \"resize\", listener: () => void): unknown;\n off?(event: \"resize\", listener: () => void): unknown;\n};\n\n/** The console width the bars are sized for: a reported width, else 80. */\nfunction widthOf(stream: ProgressStream): number {\n const columns = stream.columns;\n return typeof columns === \"number\" && columns > 0 ? columns : 80;\n}\n\nexport type ProgressDisplayOptions = {\n readonly stdout: ProgressStream;\n readonly stderr: ProgressStream;\n /** How often the source is read. */\n readonly pollMs?: number;\n /** Without a TTY: how often a progress line is printed while catching up. */\n readonly lineMs?: number;\n};\n\nexport type ProgressDisplay = {\n /** Stops polling, removes the bars and restores the streams. */\n stop(): void;\n};\n\nconst DEFAULT_POLL_MS = 1_000;\nconst DEFAULT_LINE_MS = 10_000;\nconst MIN_BAR = 10;\nconst MAX_LABEL = 32;\n\nfunction percent(row: ProgressRow): string {\n if (row.state === \"errored\") return \"errored\";\n if (row.state === \"done\") return \"done\";\n return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;\n}\n\nfunction fit(label: string, width: number): string {\n return label.length <= width\n ? label.padEnd(width)\n : `…${label.slice(label.length - width + 1)}`;\n}\n\n/**\n * The bar block, one line per row, under the priority when known. Every line\n * stays short of the terminal's last column: a line that fills it wraps on\n * xterm-based terminals (VS Code, Windows Terminal), and the erase would then\n * lift fewer lines than are on screen, leaving old bars behind. On a narrow\n * terminal the label gives way before the bar.\n */\nexport function renderBars(\n rows: readonly ProgressRow[],\n columns: number,\n priority?: ProgressPriority,\n): string[] {\n const width = Math.max(columns - 1, 1);\n // label, space, bar, space, 7 for \"errored\" / \"100%\"\n const fixed = 9;\n const longest = Math.max(...rows.map((row) => row.label.length), 0);\n const labelWidth = Math.max(\n 1,\n Math.min(MAX_LABEL, longest, width - fixed - MIN_BAR),\n );\n const barWidth = Math.max(MIN_BAR, width - labelWidth - fixed);\n const bars = rows.map((row) => {\n const fraction = row.state === \"done\" ? 1 : row.fraction;\n const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);\n const bar = \"█\".repeat(filled) + \"░\".repeat(barWidth - filled);\n return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`.slice(\n 0,\n width,\n );\n });\n if (!priority) return bars;\n return [renderPriority(priority).slice(0, width), ...bars];\n}\n\n/** One line for a log without a TTY, listing only what is still catching up. */\nexport function renderLine(\n rows: readonly ProgressRow[],\n priority?: ProgressPriority,\n): string {\n const busy = rows.filter((row) => row.state !== \"done\");\n const line = `catch-up: ${busy.map((row) => `${row.label} ${percent(row)}`).join(\" · \")}`;\n return priority\n ? `${line} · priority ${priority.level} ${priority.mode}`\n : line;\n}\n\nfunction busy(rows: readonly ProgressRow[]): boolean {\n return rows.some((row) => row.state !== \"done\");\n}\n\n/**\n * Shows catch-up progress while any row is not done. In a terminal the bars\n * sit below the output and every other write is printed above them; without\n * one, a progress line is printed every `lineMs`.\n */\nexport function startProgressDisplay(\n source: ProgressSource,\n options: ProgressDisplayOptions,\n): ProgressDisplay {\n const { stdout, stderr } = options;\n const tty = stdout.isTTY === true;\n let rows: readonly ProgressRow[] = [];\n let priority: ProgressPriority | undefined;\n let drawn = 0;\n let atLineStart = true;\n let lastLine = 0;\n let stopped = false;\n let reading = false;\n\n const restoreOut = stdout.write;\n const restoreErr = stderr.write;\n const originalOut = restoreOut.bind(stdout);\n const originalErr = restoreErr.bind(stderr);\n\n const erase = () => {\n if (drawn > 0) originalOut(`\\x1b[${drawn}A\\r\\x1b[0J`);\n drawn = 0;\n };\n const draw = () => {\n if (!tty || stopped || !atLineStart || !busy(rows)) return;\n const lines = renderBars(rows, widthOf(stdout), priority);\n originalOut(`${lines.join(\"\\n\")}\\n`);\n drawn = lines.length;\n };\n\n // Every other write goes above the bars: lift them, write, put them back.\n const above =\n (write: (chunk: string | Uint8Array, ...rest: never[]) => boolean) =>\n (chunk: string | Uint8Array, ...rest: never[]): boolean => {\n erase();\n const result = write(chunk, ...rest);\n const text =\n typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n if (text.length > 0) atLineStart = text.endsWith(\"\\n\");\n draw();\n return result;\n };\n // A resized terminal has already reflowed the drawn lines; redraw for the\n // new width right away rather than at the next poll.\n const onResize = () => {\n if (stopped) return;\n erase();\n draw();\n };\n if (tty) {\n stdout.write = above(originalOut as never) as NodeJS.WriteStream[\"write\"];\n stderr.write = above(originalErr as never) as NodeJS.WriteStream[\"write\"];\n stdout.on?.(\"resize\", onResize);\n }\n\n const tick = async () => {\n if (reading || stopped) return;\n reading = true;\n try {\n ({ rows, priority } = await source());\n } catch {\n // The reactor did not answer; keep the last rows until it does.\n } finally {\n reading = false;\n }\n if (stopped) return;\n if (tty) {\n erase();\n draw();\n return;\n }\n const now = Date.now();\n if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {\n originalOut(`${renderLine(rows, priority)}\\n`);\n lastLine = now;\n }\n };\n\n const timer = setInterval(\n () => void tick(),\n options.pollMs ?? DEFAULT_POLL_MS,\n );\n (timer as { unref?: () => void }).unref?.();\n void tick();\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n erase();\n if (tty) {\n stdout.off?.(\"resize\", onResize);\n stdout.write = restoreOut;\n stderr.write = restoreErr;\n }\n },\n };\n}\n","import {\n defineHostSchemas,\n drivesSchema,\n mergeDrivePlan,\n protocolConflicts,\n resolveDriveDeclaration,\n resolveHostPlugins,\n seedDrives,\n type BootCheckContext,\n type BootIssue,\n type DriveSeederClient,\n type ResolvedDrive,\n type ResolvedPlugin,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport path from \"node:path\";\nimport {\n memberEnvOf,\n memberSwitchboardConfig,\n memberSwitchboardConfigSchema,\n prepareMemberStorage,\n reactorBlockConflicts,\n readModelAsReactorStore,\n switchboardDevMode,\n} from \"./member-config.js\";\nimport { z } from \"zod\";\nimport { classicSwitchboardArgs } from \"../services/classic-args.js\";\nimport {\n inspectorProgressSource,\n startProgressDisplay,\n} from \"../services/run/catch-up-progress.js\";\nimport type { BuildArgs, SwitchboardArgs } from \"../types.js\";\n\n/**\n * BRIDGE runner for Switchboard hosts (uniform-runners phase 0): maps a\n * hosts/switchboard/host.js definition onto the SAME `startSwitchboard`\n * service the classic command calls. `run` = production loaders, `dev` =\n * Vite package loader (worker pools refused by the server, as always).\n */\n\nexport const kind = \"reactor\";\n\n/** The switchboard host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails).\n * `config.switchboard` is this member's own switchboard config (auth,\n * inspection, workers, ...); a key the reactor block also sets is refused.\n * One definition, two schemas: `declaredHostSchema` (token-able fields take\n * output tokens; types host files) and `hostSchema` (resolved; checked\n * right before the verb). */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema\n .extend({\n runner: s.runnerBaseSchema\n .extend({\n /** 0 binds a port the OS picks; `origin` reports it. */\n port: z.number().int().min(0).max(65535).optional(),\n /** Dev mode without the `dev` verb (the Vite package loader). */\n dev: z.boolean().optional(),\n /** The project package output dir `build` writes (default \"dist\"). */\n outDir: z.string().min(1).optional(),\n })\n .strict(),\n config: z\n .strictObject({ switchboard: memberSwitchboardConfigSchema.optional() })\n .optional(),\n })\n .superRefine((host, ctx) => {\n for (const message of reactorBlockConflicts(host)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"switchboard\"],\n message,\n });\n }\n }),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a switchboard host.js author writes. */\nexport type SwitchboardHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type SwitchboardHostParsed = z.output<typeof hostSchema>;\n\n/** One drive the switchboard serves: its document id and its URL. */\nexport const switchboardDriveOutputSchema = z.strictObject({\n id: z.string().min(1),\n url: z.url(),\n});\n\n/** What a started switchboard produces. `origin` carries the port the server\n * actually bound. `drives` is keyed by the DECLARED slug (a `projectHash:\n * true` drive is reachable as `vetra`, its URL uses the hashed slug it is\n * served under) and includes plugin-created drives (e.g. `workflows`) and\n * the server's implicit default drive. `endpoints.mcp` is present when MCP\n * is mounted. */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({\n graphql: z.url(),\n mcp: z.url().optional(),\n }),\n drives: z.record(z.string(), switchboardDriveOutputSchema),\n});\nexport type SwitchboardOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/switchboard\": {\n host: SwitchboardHost;\n outputs: SwitchboardOutputs;\n };\n }\n}\n\n/** The classic arg shape with the one switch a composition may leave unset. */\nexport type SwitchboardRunnerArgs = Omit<SwitchboardArgs, \"mcp\"> & {\n mcp: boolean | undefined;\n};\n\n/**\n * Start from the classic `ph switchboard` args (parsed by the classic\n * definitions, no flags) and overlay ONLY the keys the host file owns. Every\n * other key — including the ones the classic command carries as `undefined`,\n * such as `dbPath` — reaches the service exactly as on the classic path. No\n * cast: a key the classic shape has and this object lacks is a type error.\n */\nasync function toSwitchboardArgs(\n host: SwitchboardHostParsed,\n devMode: boolean,\n composed: boolean,\n): Promise<SwitchboardRunnerArgs> {\n const classic = await classicSwitchboardArgs();\n const runner = host.runner;\n return {\n ...classic,\n port: runner.port ?? classic.port,\n dev: switchboardDevMode(devMode, runner) ? true : classic.dev,\n // A declared composition owns the carved switches (R2): the mcp plugin's\n // presence sets it, its absence must deactivate. Classic path: classic.\n mcp: composed ? undefined : classic.mcp,\n };\n}\n\n/** The drive the switchboard service creates by default\n * (services/switchboard.ts `defaultSwitchboardOptions.drive`). */\nconst DEFAULT_DRIVE_SLUG = \"powerhouse\";\n\n/** The `<slug>` of the server-reported `…/d/<slug>` default drive URL. */\nfunction defaultDriveSlug(url: string | undefined): string {\n const match = url ? /\\/d\\/([^/?#]+)\\/?$/.exec(url) : null;\n return match ? decodeURIComponent(match[1]) : DEFAULT_DRIVE_SLUG;\n}\n\n/** A drive in the plan with the slug its declaration used (a `projectHash:\n * true` drive is served under its hashed slug; outputs key it by this one). */\ninterface PlannedDrive {\n declaredSlug: string;\n drive: ResolvedDrive;\n}\n\n/**\n * The drives the composition's plugins contribute, resolved and in plan\n * order, minus the slugs the host declares itself (mergeDrivePlan: the host\n * file wins). A contribution that is not a valid drive declaration fails the\n * boot naming the plugin.\n */\nfunction pluginDrives(\n projectRoot: string,\n hostDrives: readonly PlannedDrive[],\n composition: readonly ResolvedPlugin[] | undefined,\n where: string,\n): PlannedDrive[] {\n if (!composition) return [];\n const contributed = composition.flatMap((resolved) => {\n const drives = resolved.plugin.contributions?.drives ?? [];\n if (drives.length === 0) return [];\n const parsed = drivesSchema.safeParse(drives);\n if (!parsed.success) {\n throw new Error(\n `${where}: plugin \"${resolved.plugin.name}\" contributes an invalid drive declaration:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n return parsed.data.map((declaration) => ({\n declaration,\n source: resolved.plugin.name,\n }));\n });\n if (contributed.length === 0) return [];\n // served slug -> declared slug, for the outputs' keys\n const declaredSlugs = new Map(\n contributed.map(({ declaration }) => [\n resolveDriveDeclaration(projectRoot, declaration).slug,\n declaration.slug,\n ]),\n );\n const hostSlugs = new Set(hostDrives.map((d) => d.drive.slug));\n return mergeDrivePlan(projectRoot, [], contributed)\n .map((entry) => entry.drive)\n .filter((drive) => !hostSlugs.has(drive.slug))\n .map((drive) => ({\n declaredSlug: declaredSlugs.get(drive.slug) ?? drive.slug,\n drive,\n }));\n}\n\n/** Poll the default drive endpoint until the server answers — the compound's\n * readiness gate: Connect auto-connects the drive on first load, so the drive\n * must answer before the connect member serves (the sidecar's\n * waitForSwitchboard, moved behind the handle contract). */\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 hostFile = `hosts/${host.name}/host.js`;\n // Split before the server import loads the project .env into the env.\n const env = memberEnvOf(ctx.env);\n prepareMemberStorage(host.reactor, env.shell, hostFile);\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n hostFile,\n );\n if (legacyStore) console.warn(legacyStore.warning);\n const { startSwitchboard } = await import(\"../services/switchboard.js\");\n const entries = host.runner.plugins;\n const entriesDeclared = entries !== undefined;\n const args = await toSwitchboardArgs(host, devMode, entriesDeclared);\n // This member's own config, under the args: nothing is written to the\n // process env, so compound members do not see each other's settings.\n const memberConfig = await memberSwitchboardConfig(host, env, {\n pluginHost: entriesDeclared,\n });\n\n // R2 step 2: a declared composition activates the plugin pipeline — the\n // runner resolves the entries against the PROJECT dependency tree and\n // `features.pluginHost` drives server-side activation. No plugins key =\n // classic path.\n let pluginComposition;\n if (entries !== undefined) {\n pluginComposition = await resolveHostPlugins(\n ctx.projectRoot,\n \"switchboard\",\n ctx.verb,\n entries,\n `hosts/${host.name}/host.js`,\n );\n }\n\n // Core drive declarations (reactor.drives): locals seed after boot via the\n // host-core seeder; remotes ride the existing remoteDrives option; the\n // implicit default powerhouse drive is replaced by the declared set.\n const hostDrives: PlannedDrive[] = (host.reactor?.drives ?? []).map(\n (declaration) => ({\n declaredSlug: declaration.slug,\n drive: resolveDriveDeclaration(ctx.projectRoot, declaration),\n }),\n );\n // Plugin-contributed drives (e.g. the workflows plugin's Workflows drive)\n // join the plan after the host's own: a host declaration with the same slug\n // wins, and the host's drives stay first (the first local one is the\n // readiness gate and the compound's primary drive).\n const contributedDrives = pluginDrives(\n ctx.projectRoot,\n hostDrives,\n pluginComposition,\n `hosts/${host.name}/host.js`,\n );\n const planned = [...hostDrives, ...contributedDrives];\n const resolvedDrives = planned.map((p) => p.drive);\n const remoteDrives = resolvedDrives.flatMap((d) =>\n d.kind === \"remote\" && d.remoteUrl ? [d.remoteUrl] : [],\n );\n const serverArgs = {\n ...args,\n ...(pluginComposition ? { pluginComposition } : {}),\n // Only the HOST's declarations replace the implicit default drive; a\n // contribution adds to whatever the host serves.\n ...(hostDrives.length > 0 ? { drive: undefined } : {}),\n ...(remoteDrives.length > 0 ? { remoteDrives } : {}),\n // A compound member: the compound owns SIGINT/SIGTERM and the exit, and\n // stops this reactor through the handle's shutdown().\n ...(ctx.parent ? { signalHandlers: false } : {}),\n };\n\n const switchboard = await startSwitchboard(\n serverArgs,\n undefined,\n memberConfig,\n );\n // Bars for processor and read-model catch-up, below the server's output;\n // PH_CATCH_UP_PROGRESS=false leaves the output as it was.\n const progress =\n switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== \"false\"\n ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {\n stdout: process.stdout,\n stderr: process.stderr,\n })\n : undefined;\n // The port the server actually bound (it may move off a taken one).\n const port = switchboard.port;\n const origin = `http://localhost:${port}`;\n const driveUrlOf = (slug: string) => `${origin}/d/${slug}`;\n\n const seededIds = new Map<string, string>();\n const localPlanned = planned.filter((p) => p.drive.kind === \"local\");\n if (localPlanned.length > 0) {\n await seedDrives(\n seederClient(switchboard.reactor, port, seededIds),\n localPlanned.map((p) => p.drive),\n );\n }\n\n const drives: SwitchboardOutputs[\"drives\"] = {};\n // The server creates its implicit default drive only when nothing replaces\n // it: no host declaration and no remote drive (services/switchboard.ts).\n const localHostDrives = hostDrives.filter((d) => d.drive.kind === \"local\");\n const defaultSlug = defaultDriveSlug(switchboard.defaultDriveUrl);\n if (hostDrives.length === 0 && remoteDrives.length === 0) {\n drives[defaultSlug] = { id: defaultSlug, url: driveUrlOf(defaultSlug) };\n }\n for (const { declaredSlug, drive } of localPlanned) {\n drives[declaredSlug] = {\n id: seededIds.get(drive.slug) ?? drive.id,\n url: driveUrlOf(drive.slug),\n };\n }\n\n const slug =\n localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;\n const driveUrl = driveUrlOf(slug);\n\n // No composition declared (the deprecated `reactor.workflows` switch): the\n // workflows flag still seeds the SAME project-hashed drive the classic\n // vetra path seeds. With a composition the workflows PLUGIN declares that\n // drive (contributions.drives above), so nothing implicit happens here.\n if (entries === undefined && switchboard.workflowsEnabled) {\n const { seedWorkflowsDrive } = await import(\"../services/vetra.js\");\n const { generateProjectDriveId } = await import(\"../utils.js\");\n const url = await seedWorkflowsDrive(switchboard.reactor, port);\n if (url)\n drives.workflows = { id: generateProjectDriveId(\"workflows\"), url };\n }\n\n const ready = waitForDrive(driveUrl, 180_000);\n // A supervisor awaits `ready` and sees the rejection; an unsupervised caller\n // (or a test with the service mocked) must not die of an unhandled one.\n ready.catch(() => undefined);\n const graphql = `${origin}/graphql`;\n // Stops the reactor the server owns, then drains the HTTP server (freeing\n // the port), GraphQL, MCP, attachments, the plugins' onShutdown and the\n // read-model db, then closes the reactor database. SwitchboardReactor\n // memoizes it; standalone, SIGINT/SIGTERM run the same teardown, so a\n // shutdown() during or after a signal joins it instead of draining twice.\n let stopping: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin,\n endpoints: {\n graphql,\n ...(switchboard.mcpEnabled ? { mcp: `${origin}/mcp` } : {}),\n },\n drives,\n }),\n ready,\n shutdown: () => {\n progress?.stop();\n return (stopping ??= switchboard.shutdown());\n },\n };\n}\n\n// The four verbs are orthogonal: each does ONE job.\n// - `run`/`serve`: START the server in production mode (serves the built\n// project package). `serve` is run's alias — a server IS its served stack,\n// and it lets the compound forward one `serve` verb to every member.\n// - `dev`: START the server in dev mode (watch / the Vite package loader).\n// - `build`: PRODUCE the project package this switchboard serves, and start\n// NOTHING. The analog of `ph connect build` on the server side: legacy\n// `ph switchboard build` never existed, but the project still has a build.\n// `build` is what lets a compound forward a single `build` verb to all members\n// (desktop/cli) without the switchboard member failing on an unknown verb.\n\nexport async function run(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, false);\n}\n\nexport const serve = run;\n\nexport async function dev(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, true);\n}\n\n/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */\nexport async function checkBoot(\n host: SwitchboardHostParsed,\n ctx: BootCheckContext,\n): Promise<BootIssue[]> {\n // As `start` splits it: the project .env sits under the host file.\n const env = memberEnvOf(ctx.env, ctx.projectRoot);\n const issues: BootIssue[] = protocolConflicts(\n host.reactor?.protocol,\n env.shell,\n ctx.file,\n ).map((message) => ({ path: \"reactor.protocol\", message }));\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n ctx.file,\n );\n if (legacyStore) {\n issues.push({ path: \"reactor.backends\", message: legacyStore.warning });\n }\n const { getConfig } = await import(\"@powerhousedao/config/node\");\n const { switchboardBootFactsOf, switchboardBootIssues } =\n await import(\"@powerhousedao/switchboard/boot\");\n let config;\n try {\n // As `start` builds it; an env parse error becomes the issue.\n config = await memberSwitchboardConfig(host, env, {\n pluginHost: host.runner.plugins !== undefined,\n });\n } catch (error) {\n issues.push({\n path: \"\",\n message: error instanceof Error ? error.message : String(error),\n });\n return issues;\n }\n const facts = await switchboardBootFactsOf(config, {\n // As the `dev` verb starts it.\n dev: switchboardDevMode(ctx.verb === \"dev\", host.runner),\n configuredRenown: getConfig(\n path.join(ctx.projectRoot, \"powerhouse.config.json\"),\n ).auth?.renown,\n });\n for (const message of switchboardBootIssues(facts)) {\n issues.push({ path: \"\", message });\n }\n return issues;\n}\n\n/** Build the project's reactor package (the SAME service as `ph build`) — what\n * this switchboard serves. Starts no server; orthogonal to run/serve/dev. */\nexport async function build(\n host: SwitchboardHostParsed,\n _ctx: RunnerContext,\n): Promise<void> {\n const { runBuild } = await import(\"../services/build.js\");\n const args: Partial<BuildArgs> = {\n outDir: host.runner.outDir ?? \"dist\",\n };\n await runBuild(args as BuildArgs);\n}\n"],"names":["z.number","z.boolean","z.string","z\n .strictObject","z.strictObject","z.url","z.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KAAK,IAAI;AAC9B;;AAGA,eAAsB,UACpB,MACA,KACsB;CAEtB,MAAM,MAAM,YAAY,IAAI,KAAK,IAAI,WAAW;CAChD,MAAM,SAAsB,kBAC1B,KAAK,SAAS,UACd,IAAI,OACJ,IAAI,IACN,CAAC,CAAC,KAAK,aAAa;EAAE,MAAM;EAAoB;CAAQ,EAAE;CAC1D,MAAM,cAAc,wBAClB,KAAK,SACL,IAAI,OACJ,IAAI,IACN;CACA,IAAI,aACF,OAAO,KAAK;EAAE,MAAM;EAAoB,SAAS,YAAY;CAAQ,CAAC;CAExE,MAAM,EAAE,cAAc,MAAM,OAAO;CACnC,MAAM,EAAE,wBAAwB,0BAC9B,MAAM,OAAO;CACf,IAAI;CACJ,IAAI;EAEF,SAAS,MAAM,wBAAwB,MAAM,KAAK,EAChD,YAAY,KAAK,OAAO,YAAY,KAAA,EACtC,CAAC;CACH,SAAS,OAAO;EACd,OAAO,KAAK;GACV,MAAM;GACN,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAChE,CAAC;EACD,OAAO;CACT;CACA,MAAM,QAAQ,MAAM,uBAAuB,QAAQ;EAEjD,KAAK,mBAAmB,IAAI,SAAS,OAAO,KAAK,MAAM;EACvD,kBAAkB,UAChB,KAAK,KAAK,IAAI,aAAa,wBAAwB,CACrD,CAAC,CAAC,MAAM;CACV,CAAC;CACD,KAAK,MAAM,WAAW,sBAAsB,KAAK,GAC/C,OAAO,KAAK;EAAE,MAAM;EAAI;CAAQ,CAAC;CAEnC,OAAO;AACT;;;AAIA,eAAsB,MACpB,MACA,MACe;CACf,MAAM,EAAE,aAAa,MAAM,OAAO;CAIlC,MAAM,SAAS,EAFb,QAAQ,KAAK,OAAO,UAAU,OAEd,CAAc;AAClC","debug_id":"1819c7f8-3860-5090-85e5-aa961b217309"}
|
|
@@ -4,6 +4,7 @@ import { build as buildCmd } from "../src/commands/build.js";
|
|
|
4
4
|
import { build, connect, preview, studio } from "../src/commands/connect.js";
|
|
5
5
|
import { generateAllCmd } from "../src/commands/generate-all.js";
|
|
6
6
|
import { generateAppCmd } from "../src/commands/generate-app.js";
|
|
7
|
+
import { generateConnectRoutesCmd } from "../src/commands/generate-connect-routes.js";
|
|
7
8
|
import { generateDocumentModelCmd } from "../src/commands/generate-document-model.js";
|
|
8
9
|
import { generateEditorCmd } from "../src/commands/generate-editor.js";
|
|
9
10
|
import { generateMigrationFileCmd } from "../src/commands/generate-migration-file.js";
|
|
@@ -17,6 +18,7 @@ import { inspect } from "../src/commands/inspect.js";
|
|
|
17
18
|
import { install } from "../src/commands/install.js";
|
|
18
19
|
import { list } from "../src/commands/list.js";
|
|
19
20
|
import { login } from "../src/commands/login.js";
|
|
21
|
+
import { mcp } from "../src/commands/mcp.js";
|
|
20
22
|
import { migrate } from "../src/commands/migrate.js";
|
|
21
23
|
import { phCli } from "../src/commands/ph-cli.js";
|
|
22
24
|
import { switchboard } from "../src/commands/switchboard.js";
|
|
@@ -35,6 +37,7 @@ const commands = [
|
|
|
35
37
|
{ name: "piece-action", command: generatePieceActionCmd },
|
|
36
38
|
{ name: "piece-trigger", command: generatePieceTriggerCmd },
|
|
37
39
|
{ name: "migration-file", command: generateMigrationFileCmd },
|
|
40
|
+
{ name: "connect-routes", command: generateConnectRoutesCmd },
|
|
38
41
|
{ name: "vetra", command: vetra },
|
|
39
42
|
{ name: "build", command: buildCmd },
|
|
40
43
|
{ name: "connect", command: connect },
|
|
@@ -44,6 +47,7 @@ const commands = [
|
|
|
44
47
|
{ name: "access token", command: accessToken },
|
|
45
48
|
{ name: "inspect", command: inspect },
|
|
46
49
|
{ name: "list", command: list },
|
|
50
|
+
{ name: "mcp", command: mcp },
|
|
47
51
|
{ name: "migrate", command: migrate },
|
|
48
52
|
{ name: "switchboard", command: switchboard },
|
|
49
53
|
{ name: "login", command: login },
|
|
@@ -1,7 +1,9 @@
|
|
|
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]="
|
|
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]="6bba431d-54b0-507a-884b-e7c2f95ffa5c")}catch(e){}}();
|
|
3
3
|
import { DEFAULT_DRIVE_ICON } from "@powerhousedao/shared/clis";
|
|
4
|
-
import {
|
|
4
|
+
import { callerOverEnv } from "@powerhousedao/switchboard/config";
|
|
5
|
+
import { switchboardConfigFromEnv } from "@powerhousedao/switchboard/config/env";
|
|
6
|
+
import { initSwitchboardProcess, startSwitchboard } from "@powerhousedao/switchboard/server";
|
|
5
7
|
//#region src/utils/drive-icons.ts
|
|
6
8
|
/**
|
|
7
9
|
* Icon for the drives ph-cli creates, inlined as a data URI.
|
|
@@ -92,8 +94,8 @@ function getDefaultVetraSwitchboardOptions(vetraDriveId) {
|
|
|
92
94
|
}
|
|
93
95
|
};
|
|
94
96
|
}
|
|
95
|
-
async function startSwitchboard$1(options, logger) {
|
|
96
|
-
const { packages: packagesString, remoteDrives, useVetraDrive, vetraDriveId, useIdentity, keypairPath, requireIdentity, ...serverOptions } = options;
|
|
97
|
+
async function startSwitchboard$1(options, logger, base) {
|
|
98
|
+
const { packages: packagesString, remoteDrives, useVetraDrive, vetraDriveId, useIdentity, keypairPath, requireIdentity, basePath, ...serverOptions } = options;
|
|
97
99
|
if (useVetraDrive || serverOptions.dev) allowLocalhostEgress();
|
|
98
100
|
const defaultOptions = useVetraDrive ? getDefaultVetraSwitchboardOptions(vetraDriveId) : defaultSwitchboardOptions;
|
|
99
101
|
const identity = useIdentity || keypairPath || requireIdentity ? {
|
|
@@ -117,13 +119,43 @@ async function startSwitchboard$1(options, logger) {
|
|
|
117
119
|
packages,
|
|
118
120
|
logger
|
|
119
121
|
};
|
|
120
|
-
|
|
121
|
-
|
|
122
|
+
const config = callerOverEnv(base ?? switchboardConfigFromEnv(process.env, { logger }), configLayerOf(finalOptions, basePath));
|
|
123
|
+
initSwitchboardProcess(config);
|
|
124
|
+
return await startSwitchboard(config, {
|
|
125
|
+
logger,
|
|
126
|
+
pluginComposition: finalOptions.pluginComposition,
|
|
127
|
+
signalHandlers: finalOptions.signalHandlers,
|
|
122
128
|
fatalErrorShutdown: true
|
|
123
129
|
});
|
|
124
130
|
}
|
|
131
|
+
/** The keys of the server's options view this command sets, as a config layer. */
|
|
132
|
+
function configLayerOf(options, basePath) {
|
|
133
|
+
const dbPath = options.dbPath || void 0;
|
|
134
|
+
return {
|
|
135
|
+
server: {
|
|
136
|
+
basePath: basePath || void 0,
|
|
137
|
+
port: options.port,
|
|
138
|
+
strictPort: options.strictPort,
|
|
139
|
+
dev: options.dev,
|
|
140
|
+
https: options.https
|
|
141
|
+
},
|
|
142
|
+
storage: {
|
|
143
|
+
readModel: { url: dbPath },
|
|
144
|
+
reactor: { url: dbPath }
|
|
145
|
+
},
|
|
146
|
+
features: { mcp: options.mcp },
|
|
147
|
+
packages: {
|
|
148
|
+
list: options.packages,
|
|
149
|
+
disableLocal: options.disableLocalPackages
|
|
150
|
+
},
|
|
151
|
+
identity: options.identity,
|
|
152
|
+
drive: options.drive,
|
|
153
|
+
remoteDrives: options.remoteDrives,
|
|
154
|
+
processorConfig: options.processorConfig
|
|
155
|
+
};
|
|
156
|
+
}
|
|
125
157
|
//#endregion
|
|
126
158
|
export { POWERHOUSE_DRIVE_ICON as i, defaultSwitchboardOptions as n, startSwitchboard$1 as r, allowLocalhostEgress as t };
|
|
127
159
|
|
|
128
|
-
//# sourceMappingURL=switchboard-
|
|
129
|
-
//# debugId=
|
|
160
|
+
//# sourceMappingURL=switchboard-BI35F5H7.mjs.map
|
|
161
|
+
//# debugId=6bba431d-54b0-507a-884b-e7c2f95ffa5c
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"switchboard-BI35F5H7.mjs","sources":["../src/utils/drive-icons.ts","../src/services/switchboard.ts"],"sourcesContent":["/**\n * Icon for the drives ph-cli creates, inlined as a data URI.\n *\n * This used to be an IPFS URL on a private gateway, which now answers 403 -\n * and a drive stores its icon as a plain URL in document state, so the moment\n * that URL rots every client renders a broken image, for as long as the drive\n * exists. A public gateway would only move the problem: IPFS gateways are\n * frequently overloaded, and a drive icon must not depend on the network at\n * all.\n *\n * A data URI keeps the asset inside this package and inside the drive: no\n * fetch, no gateway, no deploy-base or cross-origin question, and nothing to\n * 404. A few hundred bytes - the size of the string below is the entire cost,\n * paid once in the drive's state.\n *\n * Kept URL-encoded rather than base64 so the markup stays readable and\n * reviewable (`#` must be `%23`; `<`, `>`, `\"` and the CSS braces are legal\n * enough in a data URI but are encoded so the value is also safe to paste\n * into markup).\n */\n\n/** Encodes an SVG for use in a `data:` URI, smaller than base64 and readable. */\nfunction svgDataUri(svg: string): string {\n const compact = svg.replace(/\\s+/g, \" \").trim();\n return `data:image/svg+xml,${compact\n .replace(/%/g, \"%25\")\n .replace(/#/g, \"%23\")\n .replace(/</g, \"%3C\")\n .replace(/>/g, \"%3E\")\n .replace(/\"/g, \"%22\")\n .replace(/\\{/g, \"%7B\")\n .replace(/\\}/g, \"%7D\")}`;\n}\n\n// The Powerhouse mark: four petals on a 64 grid, each a square with one\n// quarter-circle bite taken out of its inner corner.\nconst PETALS = [\n \"M0 4.6C0 2.1 2.1 0 4.6 0h21.2c2.5 0 4.6 2.1 4.6 4.6v2.8c0 12.7-10.3 23-23 23H4.6C2.1 30.4 0 28.4 0 25.8V4.6Z\",\n \"M33.6 56.6c0-12.7 10.3-23 23-23h2.8c2.5 0 4.6 2.1 4.6 4.6v21.2c0 2.5-2.1 4.6-4.6 4.6H38.2c-2.5 0-4.6-2.1-4.6-4.6v-2.8Z\",\n \"M0 38.2c0-2.5 2.1-4.6 4.6-4.6h2.8c12.7 0 23 10.3 23 23v2.8c0 2.5-2.1 4.6-4.6 4.6H4.6C2.1 64 0 61.9 0 59.4V38.2Z\",\n \"M33.6 4.6C33.6 2.1 35.6 0 38.2 0h21.2C61.9 0 64 2.1 64 4.6v21.2c0 2.5-2.1 4.6-4.6 4.6h-2.8c-12.7 0-23-10.3-23-23V4.6Z\",\n];\n\n/** The mark in the light theme's grey. */\nconst LIGHT_FILL = \"#404345\";\n\n/** The mark in the dark theme's grey. */\nconst DARK_FILL = \"#F3F5F7\";\n\n// Drawn in one grey that follows the theme, so the icon sits in the sidebar\n// beside the single-tone `currentcolor` glyphs of the other drives instead of\n// competing with them.\n//\n// A data URI rendered through an `<img>` is its own document and cannot see\n// the host page's `.dark` class, so the theme is read from the embedded\n// document's own color scheme. That is the OS preference by default; the\n// renderer propagates an explicit in-app theme choice by setting\n// `color-scheme` on the `<img>`, which overrides it where the browser\n// supports the propagation.\nconst MARK_SVG = `\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\" width=\"32\" height=\"32\">\n <style>\n path { fill: ${LIGHT_FILL} }\n @media (prefers-color-scheme: dark) { path { fill: ${DARK_FILL} } }\n </style>\n <path d=\"${PETALS[0]}\"/>\n <path d=\"${PETALS[1]}\"/>\n <path d=\"${PETALS[2]}\"/>\n <path d=\"${PETALS[3]}\"/>\n</svg>`;\n\n/** Icon for the drives ph-cli creates. */\nexport const POWERHOUSE_DRIVE_ICON = svgDataUri(MARK_SVG);\n","import type { ResolvedPlugin } from \"@powerhousedao/host-core\";\nimport { DEFAULT_DRIVE_ICON } from \"@powerhousedao/shared/clis\";\nimport {\n callerOverEnv,\n type SwitchboardConfigInput,\n} from \"@powerhousedao/switchboard/config\";\nimport { switchboardConfigFromEnv } from \"@powerhousedao/switchboard/config/env\";\nimport {\n initSwitchboardProcess,\n startSwitchboard as startSwitchboardServer,\n type IdentityOptions,\n type StartServerOptions,\n} from \"@powerhousedao/switchboard/server\";\nimport type { ILogger } from \"document-model\";\nimport type { SwitchboardArgs } from \"../types.js\";\nimport { POWERHOUSE_DRIVE_ICON } from \"../utils/drive-icons.js\";\n\nconst EGRESS_ALLOW_ENV = \"PH_WORKFLOWS_EGRESS_ALLOW_ADDRESSES\";\nconst LOCALHOST_ADDRESSES = [\"127.0.0.1/32\", \"::1/128\"];\n\n// Lets pieces reach services on this machine, keeping any addresses already set\nexport function allowLocalhostEgress(env: NodeJS.ProcessEnv = process.env) {\n const current = (env[EGRESS_ALLOW_ENV] ?? \"\")\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\");\n const missing = LOCALHOST_ADDRESSES.filter(\n (address) => !current.includes(address),\n );\n if (missing.length > 0)\n env[EGRESS_ALLOW_ENV] = [...current, ...missing].join(\",\");\n}\n\n// No `dbPath` default here: the classic commands always carry the parsed\n// `dbPath` key (undefined without --db-path) and so always overrode it — the\n// server's own split defaults (`.ph/reactor-storage` for the reactor,\n// `.ph/read-storage` for the read model) are the legacy layout. A default\n// here resurfaces for any caller that omits the key and then names ONE dir\n// for both PGlite stores (two writers on one PGDATA).\nexport const defaultSwitchboardOptions = {\n port: 4001,\n drive: {\n id: \"powerhouse\",\n slug: \"powerhouse\",\n global: {\n name: \"Powerhouse\",\n icon: DEFAULT_DRIVE_ICON,\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\",\n triggers: [],\n },\n },\n mcp: true,\n} satisfies StartServerOptions;\n\nfunction getDefaultVetraSwitchboardOptions(\n vetraDriveId: string,\n): Partial<StartServerOptions> {\n return {\n port: 4001,\n drive: {\n id: vetraDriveId,\n slug: vetraDriveId,\n global: {\n name: \"Vetra\",\n icon: POWERHOUSE_DRIVE_ICON,\n },\n preferredEditor: \"vetra-drive-app\",\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\",\n triggers: [],\n },\n },\n };\n}\n\nexport async function startSwitchboard(\n options: Omit<SwitchboardArgs, \"mcp\"> & {\n /** A declared composition (R2) leaves this unset: the mcp plugin's presence sets it. */\n mcp?: boolean;\n /** `undefined` suppresses the default drive (declared drives replace it). */\n drive?: StartServerOptions[\"drive\"];\n strictPort?: boolean;\n processorConfig?: Map<string, unknown>;\n /** False under a supervising compound, which owns SIGINT/SIGTERM. */\n signalHandlers?: boolean;\n /** A declared composition (R2), resolved by the runner. */\n pluginComposition?: ResolvedPlugin[];\n },\n logger?: ILogger,\n /** The layer under the command's options; default: this process's env. */\n base?: SwitchboardConfigInput,\n) {\n const {\n packages: packagesString,\n remoteDrives,\n useVetraDrive,\n vetraDriveId,\n useIdentity,\n keypairPath,\n requireIdentity,\n basePath,\n ...serverOptions\n } = options;\n\n // Vetra and dev mode run against local services\n if (useVetraDrive || serverOptions.dev) allowLocalhostEgress();\n\n // Choose the appropriate default configuration\n const defaultOptions = useVetraDrive\n ? getDefaultVetraSwitchboardOptions(vetraDriveId)\n : defaultSwitchboardOptions;\n\n // Build identity options if enabled\n const identity: IdentityOptions | undefined =\n useIdentity || keypairPath || requireIdentity\n ? {\n keypairPath,\n requireExisting: requireIdentity,\n }\n : undefined;\n\n const packages = packagesString?.split(\",\");\n\n // Only include the default drive if no remote drives are provided\n const finalOptions =\n remoteDrives.length > 0\n ? {\n ...defaultOptions,\n drive: undefined, // Don't create default drive when syncing with remote\n ...serverOptions,\n remoteDrives,\n identity,\n packages,\n logger,\n }\n : {\n ...defaultOptions,\n ...serverOptions,\n remoteDrives,\n identity,\n packages,\n logger,\n };\n\n // The env (or the caller's base) under the command's own options.\n const config = callerOverEnv(\n base ?? switchboardConfigFromEnv(process.env, { logger }),\n configLayerOf(finalOptions, basePath),\n );\n initSwitchboardProcess(config);\n const reactor = await startSwitchboardServer(config, {\n logger,\n pluginComposition: finalOptions.pluginComposition,\n signalHandlers: finalOptions.signalHandlers,\n fatalErrorShutdown: true,\n });\n\n return reactor;\n}\n\n/** The keys of the server's options view this command sets, as a config layer. */\nfunction configLayerOf(\n options: StartServerOptions,\n basePath: string | undefined,\n): SwitchboardConfigInput {\n const dbPath = options.dbPath || undefined;\n return {\n server: {\n basePath: basePath || undefined,\n port: options.port,\n strictPort: options.strictPort,\n dev: options.dev,\n https: options.https,\n },\n storage: {\n // `dbPath` names both stores, over the env, as it did as an option.\n readModel: { url: dbPath },\n reactor: { url: dbPath },\n },\n features: { mcp: options.mcp },\n packages: {\n list: options.packages,\n disableLocal: options.disableLocalPackages,\n },\n identity: options.identity,\n drive: options.drive,\n remoteDrives: options.remoteDrives,\n processorConfig: options.processorConfig,\n };\n}\n"],"names":["startSwitchboard","startSwitchboardServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,WAAW,KAAqB;CAEvC,OAAO,sBADS,IAAI,QAAQ,QAAQ,GAAG,CAAC,CAAC,KACN,CAAC,CACjC,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,OAAO,KAAK,CAAC,CACrB,QAAQ,OAAO,KAAK;AACzB;AAIA,MAAM,SAAS;CACb;CACA;CACA;CACA;AACF;;AA+BA,MAAa,wBAAwB,WAAW;;;;;;aAPnC,OAAO,GAAG;aACV,OAAO,GAAG;aACV,OAAO,GAAG;aACV,OAAO,GAAG;OAIiC;;;ACvDxD,MAAM,mBAAmB;AACzB,MAAM,sBAAsB,CAAC,gBAAgB,SAAS;AAGtD,SAAgB,qBAAqB,MAAyB,QAAQ,KAAK;CACzE,MAAM,WAAW,IAAI,qBAAqB,GAAA,CACvC,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,QAAQ,UAAU,UAAU,EAAE;CACjC,MAAM,UAAU,oBAAoB,QACjC,YAAY,CAAC,QAAQ,SAAS,OAAO,CACxC;CACA,IAAI,QAAQ,SAAS,GACnB,IAAI,oBAAoB,CAAC,GAAG,SAAS,GAAG,OAAO,C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ACjC,OAAO;EACL,QAAQ;GACN,UAAU,YAAY,KAAA;GACtB,MAAM,QAAQ;GACd,YAAY,QAAQ;GACpB,KAAK,QAAQ;GACb,OAAO,QAAQ;EACjB;EACA,SAAS;GAEP,WAAW,EAAE,KAAK,OAAO;GACzB,SAAS,EAAE,KAAK,OAAO;EACzB;EACA,UAAU,EAAE,KAAK,QAAQ,IAAI;EAC7B,UAAU;GACR,MAAM,QAAQ;GACd,cAAc,QAAQ;EACxB;EACA,UAAU,QAAQ;EAClB,OAAO,QAAQ;EACf,cAAc,QAAQ;EACtB,iBAAiB,QAAQ;CAC3B;AACF","debug_id":"6bba431d-54b0-507a-884b-e7c2f95ffa5c"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { r as startSwitchboard } from "./switchboard-BI35F5H7.mjs";
|
|
2
|
+
export { startSwitchboard };
|
|
3
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a09bf2eb-cf3c-5735-8e3c-20f8ce5a6c1c")}catch(e){}}();
|
|
4
|
+
//# debugId=a09bf2eb-cf3c-5735-8e3c-20f8ce5a6c1c
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { r as syncProjectConnectRoutes } from "./sync-connect-routes-t0Slg-P6.mjs";
|
|
2
|
+
export { syncProjectConnectRoutes };
|
|
3
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a0e16059-68ca-5115-9c0e-68e1b5113d9c")}catch(e){}}();
|
|
4
|
+
//# debugId=a0e16059-68ca-5115-9c0e-68e1b5113d9c
|
|
@@ -0,0 +1,25 @@
|
|
|
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]="635b041c-5cc1-56f7-aac5-714511c1dd4c")}catch(e){}}();
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
//#region src/utils/sync-connect-routes.ts
|
|
6
|
+
const OFFERED_ROUTES_MODULE = ".ph/connect-routes.package.ts";
|
|
7
|
+
const HOST_ROUTES_DIR = "hosts/connect/routes";
|
|
8
|
+
const CONNECT_ROUTES_GEN = ".ph/connect-routes.gen.ts";
|
|
9
|
+
/** Writes the tree hosts/connect/routes/ type-checks against; without the
|
|
10
|
+
* folder, a tree there keeps Connect's routes only. Loads builder-tools only
|
|
11
|
+
* for a project with routes or a tree. */
|
|
12
|
+
async function syncProjectConnectRoutes(projectRoot) {
|
|
13
|
+
if (![
|
|
14
|
+
"hosts/connect/routes",
|
|
15
|
+
CONNECT_ROUTES_GEN,
|
|
16
|
+
".ph/connect-routes.package.ts"
|
|
17
|
+
].some((p) => existsSync(join(projectRoot, p)))) return;
|
|
18
|
+
const { resolveConnectRoutesDir, syncConnectRoutes } = await import("@powerhousedao/builder-tools");
|
|
19
|
+
await syncConnectRoutes(projectRoot, resolveConnectRoutesDir(projectRoot));
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
export { OFFERED_ROUTES_MODULE as n, syncProjectConnectRoutes as r, HOST_ROUTES_DIR as t };
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=sync-connect-routes-t0Slg-P6.mjs.map
|
|
25
|
+
//# debugId=635b041c-5cc1-56f7-aac5-714511c1dd4c
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sync-connect-routes-t0Slg-P6.mjs","sources":["../src/utils/sync-connect-routes.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n// builder-tools' PACKAGE_ROUTES_MODULE and HOST_ROUTES_DIR, without loading it\n// for packages with no routes.\nexport const OFFERED_ROUTES_MODULE = \".ph/connect-routes.package.ts\";\nexport const HOST_ROUTES_DIR = \"hosts/connect/routes\";\nconst CONNECT_ROUTES_GEN = \".ph/connect-routes.gen.ts\";\n\n/** Writes the tree hosts/connect/routes/ type-checks against; without the\n * folder, a tree there keeps Connect's routes only. Loads builder-tools only\n * for a project with routes or a tree. */\nexport async function syncProjectConnectRoutes(projectRoot: string) {\n const probes = [HOST_ROUTES_DIR, CONNECT_ROUTES_GEN, OFFERED_ROUTES_MODULE];\n if (!probes.some((p) => existsSync(join(projectRoot, p)))) return;\n const { resolveConnectRoutesDir, syncConnectRoutes } =\n await import(\"@powerhousedao/builder-tools\");\n await syncConnectRoutes(projectRoot, resolveConnectRoutesDir(projectRoot));\n}\n"],"names":[],"mappings":";;;;;AAKA,MAAa,wBAAwB;AACrC,MAAa,kBAAkB;AAC/B,MAAM,qBAAqB;;;;AAK3B,eAAsB,yBAAyB,aAAqB;CAElE,IAAI,CAAC;;EAD4B;;CACvB,CAAC,CAAC,MAAM,MAAM,WAAW,KAAK,aAAa,CAAC,CAAC,CAAC,GAAG;CAC3D,MAAM,EAAE,yBAAyB,sBAC/B,MAAM,OAAO;CACf,MAAM,kBAAkB,aAAa,wBAAwB,WAAW,CAAC;AAC3E","debug_id":"635b041c-5cc1-56f7-aac5-714511c1dd4c"}
|