@powerhousedao/switchboard 6.2.3-dev.58 → 6.2.3-dev.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  2. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  3. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  4. package/CHANGELOG.md +22 -0
  5. package/dist/index.mjs +1 -1
  6. package/dist/mcp-cNWW82NH.mjs +27 -0
  7. package/dist/mcp-cNWW82NH.mjs.map +1 -0
  8. package/dist/plugin-host-CGO4XZzK.d.mts +38 -0
  9. package/dist/plugin-host-CGO4XZzK.d.mts.map +1 -0
  10. package/dist/plugins/attachments.d.mts +23 -0
  11. package/dist/plugins/attachments.d.mts.map +1 -0
  12. package/dist/plugins/attachments.mjs +4 -0
  13. package/dist/plugins/mcp.d.mts +21 -0
  14. package/dist/plugins/mcp.d.mts.map +1 -0
  15. package/dist/plugins/mcp.mjs +4 -0
  16. package/dist/plugins/privacy.d.mts +12 -0
  17. package/dist/plugins/privacy.d.mts.map +1 -0
  18. package/dist/plugins/privacy.mjs +4 -0
  19. package/dist/plugins/workflows.d.mts +36 -0
  20. package/dist/plugins/workflows.d.mts.map +1 -0
  21. package/dist/plugins/workflows.mjs +4 -0
  22. package/dist/privacy-C8KVimKF.mjs +113 -0
  23. package/dist/privacy-C8KVimKF.mjs.map +1 -0
  24. package/dist/{server-Cw2WnaCA.mjs → server-Ncv91CrC.mjs} +187 -1359
  25. package/dist/server-Ncv91CrC.mjs.map +1 -0
  26. package/dist/server.d.mts +12 -14
  27. package/dist/server.d.mts.map +1 -1
  28. package/dist/server.mjs +3 -3
  29. package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
  30. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
  31. package/dist/workflows-qKtqZhn3.mjs +1338 -0
  32. package/dist/workflows-qKtqZhn3.mjs.map +1 -0
  33. package/package.json +42 -17
  34. package/test/boot-mcp-enabled.test.ts +10 -1
  35. package/test/plugin-presence.test.ts +269 -0
  36. package/tsconfig.json +3 -0
  37. package/tsdown.config.ts +6 -0
  38. package/dist/server-Cw2WnaCA.mjs.map +0 -1
@@ -1,5 +1,8 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="99cead54-dc11-5711-a454-9efc98498890")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="686b0a5d-6f56-5f96-8277-8dcb19167510")}catch(e){}}();
3
+ import { a as composeWorkflowRuntime, c as resolveWorkflowsEnabled, d as installFatalErrorShutdown, f as triggerFatalShutdown, i as assertWorkflowPackageLoadable, l as retryWorkflowSingleton, n as WORKFLOW_PACKAGE_NAME, o as isWorkflowSingletonConflict, r as WORKFLOW_TELEMETRY_SCOPE, s as modelManifestSource, t as workflowsPlugin, u as workflowSingletonLossHandler } from "./workflows-qKtqZhn3.mjs";
4
+ import { n as resolvePrivacy, r as startPrivacy, t as privacyPlugin } from "./privacy-C8KVimKF.mjs";
5
+ import { t as mcpPlugin } from "./mcp-cNWW82NH.mjs";
3
6
  import { n as addDefaultReactorDrive, r as isPostgresUrl, t as addDefaultDrive } from "./utils-uaBlzyjS.mjs";
4
7
  import { createRequire, register } from "node:module";
5
8
  import { metrics, trace } from "@opentelemetry/api";
@@ -12,9 +15,9 @@ import { existsSync, promises, realpathSync } from "node:fs";
12
15
  import path, { resolve } from "node:path";
13
16
  import { createDurableNodeFs, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteFsync, syncTree } from "@powerhousedao/reactor-api/pglite-node";
14
17
  import { ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
15
- import { AuthorizationPolicy, BaseSubgraph, ForbiddenError, HttpPackageLoader, ImportPackageLoader, PGLITE_UTC_PARSERS, PackageManagementService, PackagesSubgraph, PrivacyPermissionAdapter, baseDocumentModels, callerSubject, createCanonicalDocumentIdResolver, getUniqueDocumentModels, initializeAndStartAPI, reportFailure, resolveRenownConfig, runDetached } from "@powerhousedao/reactor-api";
18
+ import { HttpPackageLoader, ImportPackageLoader, PGLITE_UTC_PARSERS, PackageManagementService, PackagesSubgraph, baseDocumentModels, getUniqueDocumentModels, initializeAndStartAPI, reportFailure, resolveRenownConfig, runDetached } from "@powerhousedao/reactor-api";
16
19
  import { httpsHooksPath } from "@powerhousedao/reactor-api/https-hooks";
17
- import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, parseRef, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
20
+ import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
18
21
  import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
19
22
  import { DriveNodeView, NodeProcessor, REACTOR_DRIVE_SUBGRAPH_NAME, ReactorDriveClient, createReactorDriveResolvers, reactorDriveSubgraphTypeDefs } from "@powerhousedao/reactor-drive";
20
23
  import { DEFAULT_KEYPAIR_PATH, DEFAULT_RENOWN_URL, NodeKeyStorage, RENOWN_READ_MODEL_SUBGRAPH, RenownBuilder, RenownCryptoBuilder, createLocalCredentialVerifier, createRenownTrustPolicy, resolveSwitchboardEndpoint } from "@renown/sdk/node";
@@ -24,15 +27,13 @@ import path$1 from "path";
24
27
  import { Pool } from "pg";
25
28
  import { Readable } from "node:stream";
26
29
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
27
- import { DisclosureService, MIN_DEPLOYMENT_SECRET_BYTES, createModuleErasure, createPrivacySubgraph, registerSubjectDocumentsReadModel } from "@powerhousedao/reactor-privacy";
30
+ import { mergeContributions, resolveOrder, runObserveHook, runObserveHookSequential, runTransformHook } from "@powerhousedao/host-core";
28
31
  import { DEFAULT_SIGNATURE_POLICY, isSignaturePolicy } from "@powerhousedao/shared/document-model";
29
32
  import { readFile } from "node:fs/promises";
30
33
  import os from "node:os";
31
34
  import { fileURLToPath, pathToFileURL } from "node:url";
32
35
  import { EnvVarProvider } from "@openfeature/env-var-provider";
33
36
  import { OpenFeature } from "@openfeature/server-sdk";
34
- import { GraphQLError, Kind } from "graphql";
35
- import { gql } from "graphql-tag";
36
37
  //#region src/pglite-version.ts
37
38
  const SUPPORTED_PG_MAJORS = [16, 17];
38
39
  async function readPgVersionFile(dataDir) {
@@ -862,142 +863,6 @@ async function registerAttachmentReferenceReadModelOnModule(clientModule, attach
862
863
  return { status: "available" };
863
864
  }
864
865
  //#endregion
865
- //#region src/fatal-shutdown.mts
866
- const FORCED_EXIT_MS = 15e3;
867
- const fatalHandlers = /* @__PURE__ */ new WeakMap();
868
- /**
869
- * Sends an uncaught exception or unhandled rejection through the SIGTERM
870
- * shutdown that `withSignalHandlers()` installs, so the reactor and read-model
871
- * PGlite stores close with a shutdown checkpoint before the process exits
872
- * with code 1. Node's default is to exit at once, which leaves both stores
873
- * to WAL recovery on the next open. A store whose wasm runtime aborted
874
- * (ENOSPC) rejects its close; the builder logs that and still exits. A
875
- * shutdown that hangs is cut off after FORCED_EXIT_MS.
876
- *
877
- * A rejection is fatal only when this is its sole listener: Node exits on an
878
- * unhandled rejection only when nothing listens for it, and Sentry's
879
- * listener deliberately keeps the process running.
880
- */
881
- function installFatalErrorShutdown(logger, proc = process) {
882
- if (fatalHandlers.has(proc)) return;
883
- const realExit = proc.exit.bind(proc);
884
- let shuttingDown = false;
885
- /**
886
- * Logs without ever throwing. onFatal runs inside the uncaughtException
887
- * handler, so a logger whose transport is gone (EPIPE on a closed stdout)
888
- * would otherwise throw from the handler that reports throws, killing the
889
- * process before the shutdown it is supposed to run. A logging failure is
890
- * swallowed: there is nowhere left to report it.
891
- */
892
- const logFatal = (message, err) => {
893
- try {
894
- if (err === void 0) logger.error(message);
895
- else logger.error(message, err);
896
- } catch {}
897
- };
898
- const onFatal = (kind, err) => {
899
- logFatal(`${kind}: @error`, err);
900
- if (shuttingDown) return;
901
- shuttingDown = true;
902
- proc.exitCode = 1;
903
- setTimeout(() => {
904
- logFatal("Shutdown after fatal error timed out; exiting");
905
- realExit(1);
906
- }, FORCED_EXIT_MS).unref();
907
- proc.kill(proc.pid, "SIGTERM");
908
- };
909
- fatalHandlers.set(proc, onFatal);
910
- proc.on("uncaughtException", (err) => onFatal("Uncaught exception", err));
911
- proc.on("unhandledRejection", (reason) => {
912
- if (proc.listenerCount("unhandledRejection") > 1) return;
913
- onFatal("Unhandled rejection", reason);
914
- });
915
- }
916
- /**
917
- * Routes a fatal condition the caller detected through the same shutdown as an
918
- * uncaught error. Returns false, and does nothing, when
919
- * `installFatalErrorShutdown` has not run for `proc`.
920
- */
921
- function triggerFatalShutdown(kind, err, proc = process) {
922
- const onFatal = fatalHandlers.get(proc);
923
- if (!onFatal) return false;
924
- onFatal(kind, err);
925
- return true;
926
- }
927
- //#endregion
928
- //#region src/privacy.mts
929
- const DAY_MS = 864e5;
930
- /** Enabling privacy on a switchboard that cannot run it safely. */
931
- var PrivacyBootError = class extends Error {
932
- constructor(message) {
933
- super(message);
934
- this.name = "PrivacyBootError";
935
- }
936
- };
937
- function positive(env, name, unitMs) {
938
- const raw = env[name];
939
- if (raw === void 0 || raw.trim() === "") return void 0;
940
- const value = Number(raw);
941
- if (!Number.isFinite(value) || value <= 0) throw new PrivacyBootError(`${name} must be a positive number, got "${raw}"`);
942
- return value * unitMs;
943
- }
944
- function resolvePrivacy(options, env) {
945
- if (!(options?.enabled ?? env.PH_PRIVACY_ENABLED === "true")) return { enabled: false };
946
- const deploymentSecret = options?.deploymentSecret ?? env.PH_PRIVACY_DEPLOYMENT_SECRET;
947
- if (!deploymentSecret || Buffer.byteLength(deploymentSecret, "utf8") < MIN_DEPLOYMENT_SECRET_BYTES) throw new PrivacyBootError(`PH_PRIVACY_ENABLED needs PH_PRIVACY_DEPLOYMENT_SECRET of at least ${MIN_DEPLOYMENT_SECRET_BYTES} bytes`);
948
- return {
949
- enabled: true,
950
- deploymentSecret,
951
- intervalMs: positive(env, "PH_PRIVACY_INTERVAL_MS", 1),
952
- deadlineMs: positive(env, "PH_PRIVACY_DEADLINE_DAYS", DAY_MS),
953
- markerGraceMs: positive(env, "PH_PRIVACY_MARKER_GRACE_DAYS", DAY_MS),
954
- purgeTimeoutMs: positive(env, "PH_PRIVACY_PURGE_TIMEOUT_MINUTES", 6e4)
955
- };
956
- }
957
- /** Subject index, erasure scheduler and admin subgraph on a built reactor. */
958
- async function startPrivacy(deps) {
959
- const { config, reactorModule, authorizationService } = deps;
960
- if (authorizationService.config.policy === AuthorizationPolicy.OPEN) throw new PrivacyBootError("PH_PRIVACY_ENABLED is refused under the OPEN authorization policy: every caller, anonymous included, would administer erasure. Enable authentication (AUTH_ENABLED=true with ADMINS) first.");
961
- if (!reactorModule) throw new PrivacyBootError("PH_PRIVACY_ENABLED needs an in-process reactor module");
962
- if (!deps.signer?.app?.key) throw new PrivacyBootError("PH_PRIVACY_ENABLED needs a reactor signer (a Renown identity): every receiver refuses an unsigned purge marker");
963
- const permissions = deps.documentPermissionService ? new PrivacyPermissionAdapter(deps.documentPermissionService) : void 0;
964
- const { service, scheduler } = createModuleErasure(reactorModule, {
965
- deploymentSecret: config.deploymentSecret,
966
- signer: deps.signer,
967
- permissions,
968
- intervalMs: config.intervalMs,
969
- deadlineMs: config.deadlineMs,
970
- markerGraceMs: config.markerGraceMs,
971
- purgeTimeoutMs: config.purgeTimeoutMs,
972
- logger: deps.logger
973
- });
974
- const disclosure = new DisclosureService(reactorModule.database, config.deploymentSecret, permissions);
975
- let subgraph;
976
- try {
977
- subgraph = createPrivacySubgraph({
978
- authorizationService,
979
- erasure: service,
980
- disclosure
981
- });
982
- } catch (error) {
983
- throw new PrivacyBootError(error instanceof Error ? error.message : String(error));
984
- }
985
- await registerSubjectDocumentsReadModel(reactorModule, { deploymentSecret: config.deploymentSecret });
986
- await deps.graphqlManager.registerSubgraphInstance({
987
- ...subgraph,
988
- path: deps.graphqlManager.getBasePath(),
989
- reactorClient: deps.reactorClient,
990
- relationalDb: void 0
991
- }, "graphql", false);
992
- scheduler.start();
993
- deps.logger.info("Privacy add-on started: subject index, erasure scheduler");
994
- return {
995
- erasure: service,
996
- scheduler,
997
- stop: () => scheduler.stop()
998
- };
999
- }
1000
- //#endregion
1001
866
  //#region src/builder-defaults.mts
1002
867
  /**
1003
868
  * Apply switchboard's standard configuration to a reactor + client builder
@@ -1035,6 +900,115 @@ function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options
1035
900
  if (trust?.trustPolicy) reactorBuilder.withTrustPolicy(trust.trustPolicy, trust.workerTrustPolicy);
1036
901
  }
1037
902
  //#endregion
903
+ //#region src/plugins/attachments.mts
904
+ /**
905
+ * R2.3 — the attachments subsystem as a built-in plugin: the six /attachments
906
+ * routes mount at onHttpMounting and the remote attachment service is created
907
+ * for the returned handle. Presence is activation — removed from the
908
+ * composition, the routes and service do not exist. NOT yet carved: the
909
+ * attachment-reference read model registered inside reactor construction
910
+ * (carve map: server.mts initializeClient) — it follows with the
911
+ * onReadModelsRegistering step in R2 step 2; until then it registers on both
912
+ * paths (a dormant read model when the plugin is absent, harmless).
913
+ *
914
+ * Inputs (carve map): api (routes), options.attachmentServiceUrl /
915
+ * PH_SWITCHBOARD_PUBLIC_URL / https + serverPort + renown (service config).
916
+ */
917
+ const attachmentsPlugin = {
918
+ name: "switchboard-attachments",
919
+ appliesTo: "switchboard",
920
+ hooks: { onHttpMounting: (ctx) => {
921
+ registerAttachmentRoutes(ctx.api);
922
+ ctx.attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(ctx.options, ctx.serverPort, ctx.renown));
923
+ } }
924
+ };
925
+ //#endregion
926
+ //#region src/plugin-host.mts
927
+ /**
928
+ * R2 — SwitchboardCore's plugin pipeline (rewire plan, carve map:
929
+ * uniform-runners-plan/rewire/r2-carve-map.md). Behind
930
+ * FEATURE_PLUGIN_HOST_ENABLED: flag off, startSwitchboard runs the existing
931
+ * inline path byte-identically; flag on, the five subsystems run as built-in
932
+ * plugins through these hook moments. Subsystems carve one per commit; until
933
+ * a subsystem is carved, its inline code runs on BOTH paths and its plugin
934
+ * twin does not exist.
935
+ *
936
+ * Hook vocabulary (SwitchboardHooks), anchored to the boot spine:
937
+ * - transformServerOptions — after option/flag resolution, before anything opens
938
+ * - onReadModelsRegistering — inside reactor construction (build-time read models)
939
+ * - onHttpMounting — api exists; routes mount here
940
+ * - onSubgraphsRegistering — push into lateSubgraphs before the drain
941
+ * - onReactorReady — client + graphqlManager destructured
942
+ * - onDrivesReady — after core drive seeding / remote attachment
943
+ * - onShutdown — first in the subsystem-ordered teardown
944
+ */
945
+ const PLUGIN_HOST_FLAG = "FEATURE_PLUGIN_HOST_ENABLED";
946
+ function isPluginHostEnabled(env = process.env) {
947
+ const value = env[PLUGIN_HOST_FLAG]?.trim().toLowerCase();
948
+ return value === "1" || value === "true";
949
+ }
950
+ /** Built-in plugins, pre-listed (the default composition until host.js
951
+ * entries map in R2 step 2). Subsystems join as R2 carves them. */
952
+ function builtinSwitchboardPlugins() {
953
+ const entry = {
954
+ enabled: true,
955
+ verbs: "*",
956
+ config: {}
957
+ };
958
+ return [
959
+ {
960
+ plugin: mcpPlugin,
961
+ provenance: "built-in",
962
+ entry: {
963
+ ...entry,
964
+ module: "@powerhousedao/switchboard/plugins/mcp"
965
+ }
966
+ },
967
+ {
968
+ plugin: attachmentsPlugin,
969
+ provenance: "built-in",
970
+ entry: {
971
+ ...entry,
972
+ module: "@powerhousedao/switchboard/plugins/attachments"
973
+ }
974
+ },
975
+ {
976
+ plugin: privacyPlugin,
977
+ provenance: "built-in",
978
+ entry: {
979
+ ...entry,
980
+ module: "@powerhousedao/switchboard/plugins/privacy"
981
+ }
982
+ },
983
+ {
984
+ plugin: workflowsPlugin,
985
+ provenance: "built-in",
986
+ entry: {
987
+ ...entry,
988
+ module: "@powerhousedao/switchboard/plugins/workflows"
989
+ }
990
+ }
991
+ ];
992
+ }
993
+ function createSwitchboardPluginHost(ctx, resolved) {
994
+ resolved ??= builtinSwitchboardPlugins();
995
+ const ordered = resolveOrder(resolved.map((r) => r.plugin));
996
+ const contributions = mergeContributions(resolved.map((r) => ({
997
+ plugin: r.plugin,
998
+ provenance: r.provenance
999
+ })));
1000
+ const fullCtx = {
1001
+ ...ctx,
1002
+ contributions
1003
+ };
1004
+ return {
1005
+ plugins: ordered,
1006
+ ctx: fullCtx,
1007
+ transformOptions: (seed) => runTransformHook("transformServerOptions", ordered, fullCtx, seed),
1008
+ observe: (hook) => hook === "onShutdown" ? runObserveHookSequential(hook, ordered, fullCtx) : runObserveHook(hook, ordered, fullCtx)
1009
+ };
1010
+ }
1011
+ //#endregion
1038
1012
  //#region src/env.mts
1039
1013
  function parseNonNegativeInt(raw, name) {
1040
1014
  if (raw === void 0 || raw.trim() === "") return;
@@ -1338,1201 +1312,6 @@ async function resolveMcpEnabled({ featureFlags, option }) {
1338
1312
  return featureFlags.getBooleanValue(MCP_ENABLED, true);
1339
1313
  }
1340
1314
  //#endregion
1341
- //#region src/workflow/oauth-callback.ts
1342
- const OAUTH_CALLBACK_PATH = "oauth/callback";
1343
- function escapeHtml(text) {
1344
- return text.replace(/[&<>"']/g, (char) => ({
1345
- "&": "&amp;",
1346
- "<": "&lt;",
1347
- ">": "&gt;",
1348
- "\"": "&quot;",
1349
- "'": "&#39;"
1350
- })[char]);
1351
- }
1352
- function resultPage(ok, detail) {
1353
- const title = ok ? "Connected" : "Sign-in failed";
1354
- return `<!doctype html>
1355
- <html><head><meta charset="utf-8"><title>${title}</title>
1356
- <meta name="viewport" content="width=device-width, initial-scale=1">
1357
- <style>body{font:15px system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#222}main{max-width:28rem;padding:1.5rem;text-align:center}h1{font-size:1.1rem}</style>
1358
- </head><body><main><h1>${title}</h1><p>${ok ? "You can close this window." : escapeHtml(detail ?? "The sign-in did not finish.")}</p></main>
1359
- ${ok ? "<script>setTimeout(function(){window.close()},600)<\/script>" : ""}
1360
- </body></html>`;
1361
- }
1362
- function registerOAuthCallback(http, runtime) {
1363
- return http.get(OAUTH_CALLBACK_PATH, { auth: "public" }, async (request) => {
1364
- const params = new URL(request.url).searchParams;
1365
- const state = params.get("state");
1366
- const result = state ? await runtime.completeOAuth({
1367
- state,
1368
- code: params.get("code") ?? void 0,
1369
- error: params.get("error") ?? void 0,
1370
- errorDescription: params.get("error_description") ?? void 0
1371
- }) : {
1372
- ok: false,
1373
- detail: "The provider sent no state",
1374
- returnUrl: null
1375
- };
1376
- if (result.returnUrl && state) {
1377
- const back = new URL(result.returnUrl);
1378
- back.searchParams.set("ph_oauth", state);
1379
- return new Response(null, {
1380
- status: 303,
1381
- headers: {
1382
- location: back.href,
1383
- "cache-control": "no-store"
1384
- }
1385
- });
1386
- }
1387
- return new Response(resultPage(result.ok, result.detail), {
1388
- status: result.ok ? 200 : 400,
1389
- headers: {
1390
- "content-type": "text/html; charset=utf-8",
1391
- "cache-control": "no-store",
1392
- "referrer-policy": "no-referrer"
1393
- }
1394
- });
1395
- });
1396
- }
1397
- function callbackUrlOf(http) {
1398
- return `${http.baseUrl.replace(/\/+$/, "")}/${OAUTH_CALLBACK_PATH}`;
1399
- }
1400
- //#endregion
1401
- //#region src/workflow/resolvers.ts
1402
- const PIECE_SOURCES = [
1403
- "local",
1404
- "registry",
1405
- "activepieces"
1406
- ];
1407
- function isPieceSource(value) {
1408
- return PIECE_SOURCES.includes(value);
1409
- }
1410
- function blockRef(input) {
1411
- if (input.kind !== "action" && input.kind !== "trigger") throw new GraphQLError(`A block's kind is "action" or "trigger", got "${input.kind}"`);
1412
- return {
1413
- pieceName: input.pieceName,
1414
- pieceVersion: input.pieceVersion,
1415
- name: input.name,
1416
- kind: input.kind
1417
- };
1418
- }
1419
- async function cursorAware(call) {
1420
- try {
1421
- return await call();
1422
- } catch (error) {
1423
- if (error instanceof Error && error.name === "InvalidRunCursorError") throw new GraphQLError(error.message, { extensions: { code: "BAD_USER_INPUT" } });
1424
- throw error;
1425
- }
1426
- }
1427
- function selectsStepData(selections, path) {
1428
- let level = selections;
1429
- for (const name of [...path, "steps"]) {
1430
- const next = [];
1431
- for (const set of level) for (const selection of set.selections) {
1432
- if (selection.kind !== Kind.FIELD) return true;
1433
- if (selection.name.value === name && selection.selectionSet) next.push(selection.selectionSet);
1434
- }
1435
- if (next.length === 0) return false;
1436
- level = next;
1437
- }
1438
- return level.some((set) => set.selections.some((selection) => selection.kind !== Kind.FIELD || selection.name.value === "input" || selection.name.value === "output"));
1439
- }
1440
- function readsStepData(info, path) {
1441
- if (!info) return true;
1442
- return selectsStepData(info.fieldNodes.flatMap((node) => node.selectionSet ? [node.selectionSet] : []), path);
1443
- }
1444
- function requireAdmin(authorizationService, ctx) {
1445
- if (!authorizationService.isSupremeAdmin(ctx.user?.address)) throw new GraphQLError("Admin access required");
1446
- }
1447
- async function syncAware(call) {
1448
- try {
1449
- return await call();
1450
- } catch (error) {
1451
- if (error instanceof Error && error.name === "WorkflowSyncingError") throw new GraphQLError(error.message, { extensions: {
1452
- code: "WORKFLOW_SYNCING",
1453
- retryable: true
1454
- } });
1455
- throw error;
1456
- }
1457
- }
1458
- function parseJson(value) {
1459
- if (value === null) return null;
1460
- try {
1461
- return JSON.parse(value);
1462
- } catch {
1463
- return value;
1464
- }
1465
- }
1466
- function toStepRecord(row) {
1467
- return {
1468
- stepId: row.step_id,
1469
- stepKey: row.step_key,
1470
- pieceName: row.piece_name,
1471
- blockName: row.block_name,
1472
- status: row.status,
1473
- input: parseJson(row.input),
1474
- output: parseJson(row.output),
1475
- port: row.port,
1476
- error: row.error,
1477
- errorName: row.error_name,
1478
- startedAt: row.started_at,
1479
- endedAt: row.ended_at,
1480
- pieceVersion: row.piece_version,
1481
- pieceSource: row.piece_source,
1482
- versionMatch: row.version_match,
1483
- versionNote: row.version_note
1484
- };
1485
- }
1486
- function toRunRecord(row, steps) {
1487
- return {
1488
- id: row.id,
1489
- workflowId: row.workflow_id,
1490
- workflowName: row.workflow_name,
1491
- workflowVersion: row.workflow_version,
1492
- triggerKind: row.trigger_kind,
1493
- triggerPayload: parseJson(row.trigger_payload),
1494
- status: row.status,
1495
- error: row.error,
1496
- errorName: row.error_name,
1497
- startedAt: row.started_at,
1498
- endedAt: row.ended_at,
1499
- rerunOf: row.rerun_of,
1500
- warnings: row.warnings,
1501
- warningNotes: parseJson(row.warning_notes) ?? [],
1502
- steps: steps.map(toStepRecord)
1503
- };
1504
- }
1505
- const UNKNOWN_ACCESS = {
1506
- authEnforcement: true,
1507
- authConditions: false,
1508
- identity: null
1509
- };
1510
- function signedIn(ctx) {
1511
- return Boolean(ctx.user?.address);
1512
- }
1513
- function isAbsolute(url) {
1514
- return /^https?:\/\//i.test(url);
1515
- }
1516
- function redirectUriFor(routing, requested) {
1517
- if (!routing) throw new GraphQLError("This host serves no OAuth2 callback");
1518
- if (isAbsolute(routing.callbackUrl)) return routing.callbackUrl;
1519
- if (!requested) throw new GraphQLError("This host does not know its public URL; pass redirectUri");
1520
- let url;
1521
- try {
1522
- url = new URL(requested);
1523
- } catch {
1524
- throw new GraphQLError(`"${requested}" is not a URL`);
1525
- }
1526
- if (url.protocol !== "https:" && url.protocol !== "http:" || url.pathname !== routing.callbackUrl || url.search !== "" || url.hash !== "") throw new GraphQLError(`redirectUri must be this host's ${routing.callbackUrl}`);
1527
- return url.href;
1528
- }
1529
- function returnUrlFor(requested, ctx) {
1530
- if (!requested) return void 0;
1531
- const origin = ctx.headers.origin;
1532
- let url;
1533
- try {
1534
- url = new URL(requested);
1535
- } catch {
1536
- url = void 0;
1537
- }
1538
- if (!url || !origin || url.origin !== origin) throw new GraphQLError("returnUrl must be on the requesting page's origin");
1539
- return url.href;
1540
- }
1541
- const getResolvers = (runtime, authorizationService, oauth, access = UNKNOWN_ACCESS, assertCanRead) => {
1542
- return {
1543
- Query: { workflowRuntime: () => ({}) },
1544
- WorkflowRuntimeQueries: {
1545
- health: () => "ok",
1546
- authEnforcement: () => access.authEnforcement,
1547
- reactorIdentity: (_parent, _args, ctx) => signedIn(ctx) ? access.identity : null,
1548
- authConditions: (_parent, _args, ctx) => signedIn(ctx) ? access.authConditions : null,
1549
- reactorAccessDenial: async (_parent, args, ctx) => {
1550
- if (!assertCanRead) throw new GraphQLError("No read check configured");
1551
- await assertCanRead(args.workflowId, ctx);
1552
- return runtime.reactorAccessDenial(args.workflowId) ?? null;
1553
- },
1554
- blockDescriptor: (_parent, args) => runtime.blockDescriptor(blockRef(args.block)),
1555
- blockOptions: (_parent, args, ctx) => runtime.blockOptions(blockRef(args.block), args.propName, args.input, args.connectionId ?? void 0, ctx, args.searchValue ?? void 0, args.reactorConnectionId ?? void 0),
1556
- pieceCatalog: () => runtime.pieceCatalog(),
1557
- pieceActions: (_parent, args) => runtime.pieceActions(args.packageName, args.version ?? void 0),
1558
- pieceTriggers: (_parent, args) => runtime.pieceTriggers(args.packageName, args.version ?? void 0),
1559
- blockOutputTree: (_parent, args) => runtime.blockOutputTree(blockRef(args.block), args.config),
1560
- stepOutputTree: (_parent, args, ctx) => runtime.stepOutputTree(args.workflowId, args.stepId, ctx),
1561
- blockResolutions: (_parent, args, ctx) => runtime.blockResolutions(args.workflowId, ctx),
1562
- pieceDetail: (_parent, args) => runtime.pieceDetail(args.packageName, args.version ?? void 0),
1563
- searchPieces: (_parent, args) => {
1564
- if (args.kind !== "action" && args.kind !== "trigger") throw new GraphQLError(`A search's kind is "action" or "trigger", got "${args.kind}"`);
1565
- const unknown = (args.sources ?? []).filter((source) => !isPieceSource(source));
1566
- if (unknown.length > 0) throw new GraphQLError(`A search's sources are ${PIECE_SOURCES.join(", ")}, got ${unknown.join(", ")}`);
1567
- return runtime.searchPieces(args.query, {
1568
- kind: args.kind,
1569
- sources: (args.sources ?? []).filter(isPieceSource),
1570
- categories: args.categories ?? void 0,
1571
- limit: args.limit ?? void 0
1572
- });
1573
- },
1574
- connections: (_parent, _args, ctx) => runtime.connections(ctx),
1575
- webhookEndpoint: (_parent, args, ctx) => syncAware(() => runtime.webhookEndpoint(args.workflowId, ctx, { driveId: args.driveId ?? void 0 })),
1576
- secret: async (_parent, args) => {
1577
- try {
1578
- return await (await runtime.secrets()).stat(args.ref);
1579
- } catch {
1580
- return null;
1581
- }
1582
- },
1583
- secrets: async () => (await runtime.secrets()).list(),
1584
- oauthRedirectUri: () => oauth?.callbackUrl ?? null,
1585
- oauthAttempt: (_parent, args, ctx) => runtime.oauthAttempt(args.state, ctx),
1586
- triggerStates: async (_parent, _args, ctx) => (await runtime.triggerStates(ctx)).map((row) => ({
1587
- workflowId: row.workflow_id,
1588
- pieceName: row.piece_name,
1589
- triggerName: row.trigger_name,
1590
- status: row.status,
1591
- intervalMs: row.interval_ms,
1592
- nextPollAt: row.next_poll_at,
1593
- lastPollAt: row.last_poll_at,
1594
- lastError: row.last_error,
1595
- consecutiveFailures: row.consecutive_failures,
1596
- nextRenewAt: row.next_renew_at,
1597
- renewError: row.renew_error,
1598
- renewFailures: row.renew_failures,
1599
- pieceVersion: row.piece_version,
1600
- pieceSource: row.piece_source,
1601
- versionMatch: row.version_match,
1602
- versionNote: row.version_note
1603
- })),
1604
- runs: async (_parent, args, ctx, info) => (await runtime.runs({
1605
- ...args,
1606
- withStepData: readsStepData(info, [])
1607
- }, ctx)).map((record) => toRunRecord(record.row, record.steps)),
1608
- runsPage: async (_parent, args, ctx, info) => {
1609
- const { paging, ...scope } = args;
1610
- const page = await cursorAware(() => runtime.runsPage({
1611
- ...scope,
1612
- limit: paging?.limit ?? void 0,
1613
- cursor: paging?.cursor ?? null,
1614
- withStepData: readsStepData(info, ["items"])
1615
- }, ctx));
1616
- return {
1617
- items: page.records.map((record) => toRunRecord(record.row, record.steps)),
1618
- hasNextPage: page.hasNextPage,
1619
- hasPreviousPage: Boolean(paging?.cursor),
1620
- cursor: page.cursor
1621
- };
1622
- },
1623
- run: async (_parent, args, ctx) => {
1624
- const record = await runtime.run(args.id, ctx);
1625
- return record ? toRunRecord(record.row, record.steps) : null;
1626
- }
1627
- },
1628
- Mutation: { workflowRuntime: () => ({}) },
1629
- WorkflowRuntimeMutations: {
1630
- fire: (_parent, args, ctx) => runtime.fire(args.workflowId, args.payload, "manual", void 0, ctx),
1631
- testTrigger: (_parent, args, ctx) => syncAware(() => runtime.testTrigger(args.workflowId, ctx, {
1632
- ...args.payload !== void 0 ? { payload: args.payload } : {},
1633
- ...typeof args.timeoutSeconds === "number" ? { timeoutMs: args.timeoutSeconds * 1e3 } : {},
1634
- driveId: args.driveId ?? void 0
1635
- })),
1636
- cancelTriggerTest: (_parent, args, ctx) => runtime.cancelTriggerTestFor(args.workflowId, ctx),
1637
- testStep: (_parent, args, ctx) => syncAware(() => runtime.testStep(args.workflowId, args.stepId, ctx, { driveId: args.driveId ?? void 0 })),
1638
- rerun: (_parent, args, ctx) => runtime.rerun(args.runId, ctx),
1639
- createSecret: async (_parent, args, ctx) => {
1640
- requireAdmin(authorizationService, ctx);
1641
- return (await runtime.secrets()).create({
1642
- value: args.value,
1643
- label: args.label ?? void 0
1644
- });
1645
- },
1646
- rotateSecret: async (_parent, args, ctx) => {
1647
- requireAdmin(authorizationService, ctx);
1648
- return (await runtime.secrets()).rotate(args.ref, args.value);
1649
- },
1650
- deleteSecret: async (_parent, args, ctx) => {
1651
- requireAdmin(authorizationService, ctx);
1652
- await (await runtime.secrets()).delete(args.ref);
1653
- return true;
1654
- },
1655
- checkConnection: (_parent, args, ctx) => runtime.checkConnection(args.connectionId, ctx),
1656
- startOAuth: (_parent, args, ctx) => {
1657
- requireAdmin(authorizationService, ctx);
1658
- const returnUrl = returnUrlFor(args.returnUrl, ctx);
1659
- return runtime.startOAuth(args.connectionId, ctx, {
1660
- redirectUri: redirectUriFor(oauth, args.redirectUri),
1661
- ...returnUrl ? { returnUrl } : {}
1662
- });
1663
- }
1664
- }
1665
- };
1666
- };
1667
- //#endregion
1668
- //#region src/workflow/schema.ts
1669
- const schema = gql`
1670
- """
1671
- WorkflowRuntime Queries
1672
- """
1673
- type WorkflowRuntimeQueries {
1674
- health: String!
1675
- """
1676
- Whether this reactor enforces document auth (REACTOR_AUTH_ENFORCEMENT).
1677
- On, a workflow needs a signed publish, and the host grants, to reach
1678
- documents. Answered to any caller.
1679
- """
1680
- authEnforcement: Boolean!
1681
- """
1682
- Who this host signs as: grant it on each document a step writes. Null for
1683
- a caller who is not signed in, or a host with no signer.
1684
- """
1685
- reactorIdentity: ReactorIdentity
1686
- """
1687
- REACTOR_AUTH_CONDITIONS. True: grant the host by key, with
1688
- { match: subject.key == key }; false: by address. Null for a caller who
1689
- is not signed in.
1690
- """
1691
- authConditions: Boolean
1692
- """
1693
- Why the workflow's last publish or enable got no reactor access, naming
1694
- the publisher and the connection; null when the check passed.
1695
- """
1696
- reactorAccessDenial(workflowId: String!): String
1697
- """
1698
- Persisted runs, newest first. Scope them to one workflow, or to every
1699
- workflow a drive holds; workflowId wins when both are given.
1700
- """
1701
- runs(
1702
- workflowId: String
1703
- driveId: String
1704
- limit: Int
1705
- "Trigger kinds to leave out, e.g. test."
1706
- excludeTriggerKinds: [String!]
1707
- ): [WorkflowRunRecord!]!
1708
- """
1709
- The same listing a page at a time, newest journaled first. Pass a page's
1710
- cursor back in paging to read the next; a page is short only when
1711
- hasNextPage is false, or when the caller could read none of a long
1712
- stretch of runs. A run that starts between pages keeps its place.
1713
- """
1714
- runsPage(
1715
- workflowId: String
1716
- driveId: String
1717
- excludeTriggerKinds: [String!]
1718
- paging: WorkflowRunsPagingInput
1719
- ): WorkflowRunResultPage!
1720
- run(id: String!): WorkflowRunRecord
1721
- """
1722
- The descriptor (props, auth, ports) of one action or trigger, as the
1723
- version that runs it describes it; triggers come back under "trigger".
1724
- """
1725
- blockDescriptor(block: BlockInput!): Unknown
1726
- """
1727
- Resolves a dynamic prop against the current config values: a DROPDOWN
1728
- yields { options, placeholder, disabled }, a DYNAMIC prop yields the
1729
- resolved sub-property descriptor list.
1730
- """
1731
- blockOptions(
1732
- block: BlockInput!
1733
- propName: String!
1734
- input: Unknown
1735
- connectionId: String
1736
- "What the author typed, for a DROPDOWN declared with refreshOnSearch."
1737
- searchValue: String
1738
- "The step's reactor connection; its filter narrows what the resolver reads."
1739
- reactorConnectionId: String
1740
- ): Unknown
1741
- """
1742
- Every piece this reactor offers: the core piece, its package pieces, and
1743
- the pieces the registry and Activepieces publish.
1744
- """
1745
- pieceCatalog: Unknown
1746
- """
1747
- A piece's actions at one version; pin a step to that version.
1748
- """
1749
- pieceActions(
1750
- packageName: String!
1751
- "That version; the installed or latest one when omitted."
1752
- version: String
1753
- ): Unknown
1754
- """
1755
- A piece's triggers at one version; pin a trigger to that version.
1756
- """
1757
- pieceTriggers(
1758
- packageName: String!
1759
- "That version; the installed or latest one when omitted."
1760
- version: String
1761
- ): Unknown
1762
- """
1763
- Full piece detail (PieceMetadataModel-shaped), verbatim from the cloud API.
1764
- """
1765
- pieceDetail(
1766
- packageName: String!
1767
- "That version; the installed or latest one when omitted."
1768
- version: String
1769
- ): Unknown
1770
- """
1771
- Piece and block search across the catalog, grouped by piece. The index
1772
- builds lazily on first use; poll while status is "indexing".
1773
- """
1774
- searchPieces(
1775
- query: String!
1776
- "action | trigger"
1777
- kind: String!
1778
- "local | registry | activepieces; all when omitted."
1779
- sources: [String!]
1780
- "Category ids, any of; all when omitted."
1781
- categories: [String!]
1782
- "Pieces returned."
1783
- limit: Int
1784
- ): PieceSearchResult!
1785
- """
1786
- Health of every registered piece trigger (poll schedule, errors).
1787
- """
1788
- triggerStates: [TriggerStateRecord!]!
1789
- """
1790
- Authored output shape of a block (SDL / outputSchema / sampleData).
1791
- """
1792
- blockOutputTree(block: BlockInput!, config: Unknown): Unknown
1793
- """
1794
- Output shape of a draft step or trigger: its latest test output
1795
- (source "test", with sample and testedAt) when tested, else as blockOutputTree.
1796
- """
1797
- stepOutputTree(workflowId: String!, stepId: String!): Unknown
1798
- """
1799
- Every block of the draft (trigger first) as this reactor resolves it:
1800
- which piece version runs, from where, and how it matches the pin.
1801
- """
1802
- blockResolutions(workflowId: String!): [BlockResolutionRecord!]!
1803
- """
1804
- Every powerhouse/connection document, for connection pickers.
1805
- """
1806
- connections: [ConnectionRecord!]!
1807
- """
1808
- The webhook endpoint for a workflow: the URL to hand the provider. Minted
1809
- on first ask, whether or not the workflow is armed — an author needs the
1810
- URL before enabling, and the armed field carries that difference. Null
1811
- only when the host has no webhook service. With driveId, a workflow not
1812
- synced here yet is waited for briefly, then fails as WORKFLOW_SYNCING.
1813
- """
1814
- webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord
1815
- """
1816
- Secret metadata (label, version, status). Never the value.
1817
- """
1818
- secret(ref: String!): SecretRecord
1819
- secrets: [SecretRecord!]!
1820
- """
1821
- The URL an OAuth2 app must register as its redirect. A bare path when
1822
- this host does not know its public origin; resolve it against the URL
1823
- this API is reached at. Null when the host serves no HTTP routes.
1824
- """
1825
- oauthRedirectUri: String
1826
- """
1827
- How an OAuth2 sign-in opened by startOAuth stands; null when unknown.
1828
- """
1829
- oauthAttempt(state: String!): OAuthAttempt
1830
- }
1831
-
1832
- type OAuthAttempt {
1833
- connectionId: String!
1834
- "PENDING | EXCHANGING | OK | ERROR"
1835
- status: String!
1836
- error: String
1837
- }
1838
-
1839
- type OAuthStart {
1840
- state: String!
1841
- "Where to send the user to sign in."
1842
- authorizationUrl: String!
1843
- redirectUri: String!
1844
- expiresAt: String!
1845
- }
1846
-
1847
- """
1848
- One action or trigger of a piece, as a workflow pins it. The engine's own
1849
- blocks are the piece @powerhousedao/piece-core.
1850
- """
1851
- input BlockInput {
1852
- pieceName: String!
1853
- "Exact semver."
1854
- pieceVersion: String!
1855
- "The action or trigger name."
1856
- name: String!
1857
- "action | trigger"
1858
- kind: String!
1859
- }
1860
-
1861
- type BlockSearchHit {
1862
- pieceName: String!
1863
- "The version the hit is listed at; pin to it when picking the block."
1864
- pieceVersion: String!
1865
- "The action or trigger name."
1866
- name: String!
1867
- pieceDisplayName: String!
1868
- logoUrl: String!
1869
- displayName: String!
1870
- description: String!
1871
- "action | trigger"
1872
- kind: String!
1873
- "Triggers only: POLLING | WEBHOOK | APP_WEBHOOK | MANUAL"
1874
- strategy: String
1875
- "Why this block cannot run on this reactor; null when it can."
1876
- unsupported: String
1877
- }
1878
-
1879
- type BlockResolutionRecord {
1880
- "The trigger's or step's id."
1881
- stepId: String!
1882
- pieceName: String!
1883
- "The version the block pins."
1884
- pieceVersion: String!
1885
- "The action or trigger name."
1886
- name: String!
1887
- "action | trigger"
1888
- kind: String!
1889
- "The version that runs; null when nothing resolves."
1890
- resolvedVersion: String
1891
- "local | registry | activepieces | npm; null when nothing resolves."
1892
- source: String
1893
- "exact | compatible | fallback | installed | missing"
1894
- match: String!
1895
- "Why the version that runs differs from the pin, or why nothing resolves."
1896
- note: String
1897
- "The newest version any source offers."
1898
- latestVersion: String
1899
- }
1900
-
1901
- type PieceSearchMatch {
1902
- pieceName: String!
1903
- pieceVersion: String!
1904
- displayName: String!
1905
- description: String!
1906
- logoUrl: String!
1907
- categories: [String!]!
1908
- "local | registry | activepieces"
1909
- source: String!
1910
- deprecated: Boolean
1911
- "Why no block of the piece can run on this reactor."
1912
- unsupported: String
1913
- "Every query token matched the piece's own name."
1914
- namedPiece: Boolean!
1915
- "Matching blocks of the kind asked for, best first."
1916
- blocks: [BlockSearchHit!]!
1917
- }
1918
-
1919
- type PieceSearchResult {
1920
- "ready | indexing | error"
1921
- status: String!
1922
- pieces: [PieceSearchMatch!]!
1923
- indexedPieces: Int!
1924
- error: String
1925
- }
1926
-
1927
- type SecretRecord {
1928
- ref: String!
1929
- label: String
1930
- version: Int!
1931
- status: String!
1932
- createdAt: String!
1933
- updatedAt: String!
1934
- }
1935
-
1936
- type ConnectionRecord {
1937
- id: String!
1938
- name: String!
1939
- connectorId: String!
1940
- authType: String!
1941
- status: String!
1942
- accountLabel: String
1943
- }
1944
-
1945
- type ReactorIdentity {
1946
- "The address the host signs as; null without a signed-in identity."
1947
- address: String
1948
- "The did:key that signs the host's operations."
1949
- key: String!
1950
- }
1951
-
1952
- type ConnectionCheckResult {
1953
- ok: Boolean!
1954
- detail: String
1955
- """
1956
- From auth.getConnectionIdentifier when the check passes; otherwise the
1957
- label the connection already holds.
1958
- """
1959
- accountLabel: String
1960
- }
1961
-
1962
- type WebhookEndpointRecord {
1963
- workflowId: String!
1964
- url: String!
1965
- """
1966
- False when the host gave the webhook service no public origin, so the url
1967
- above is a bare path. Switchboard always gives one, falling back to
1968
- http://localhost:<port> when PUBLIC_URL is unset.
1969
- """
1970
- absoluteUrl: Boolean!
1971
- "True while the workflow is ENABLED with a valid webhook trigger"
1972
- armed: Boolean!
1973
- createdAt: String!
1974
- }
1975
-
1976
- type TriggerStateRecord {
1977
- workflowId: String!
1978
- pieceName: String!
1979
- triggerName: String!
1980
- status: String!
1981
- intervalMs: Int!
1982
- nextPollAt: String
1983
- lastPollAt: String
1984
- lastError: String
1985
- consecutiveFailures: Int!
1986
- "When a webhook trigger next renews its subscription; null if it never does."
1987
- nextRenewAt: String
1988
- "The last failed renewal, kept apart from lastError, the poll's."
1989
- renewError: String
1990
- renewFailures: Int!
1991
- "The piece version the trigger armed with; null for a host-fed trigger."
1992
- pieceVersion: String
1993
- pieceSource: String
1994
- versionMatch: String
1995
- versionNote: String
1996
- }
1997
-
1998
- type Query {
1999
- workflowRuntime: WorkflowRuntimeQueries!
2000
- }
2001
-
2002
- type WorkflowStepRunRecord {
2003
- stepId: String!
2004
- stepKey: String!
2005
- pieceName: String!
2006
- "The action the step ran, or the trigger a trigger test sampled."
2007
- blockName: String!
2008
- status: String!
2009
- input: Unknown
2010
- output: Unknown
2011
- port: String
2012
- error: String
2013
- "The thrown error's name, e.g. ReactorAccessDeniedError."
2014
- errorName: String
2015
- startedAt: String
2016
- endedAt: String
2017
- "The piece version that ran; null for an unresolved block."
2018
- pieceVersion: String
2019
- "local | registry | activepieces | npm"
2020
- pieceSource: String
2021
- "exact | compatible | fallback | installed | missing"
2022
- versionMatch: String
2023
- "Why the version that ran differs from the pin."
2024
- versionNote: String
2025
- }
2026
-
2027
- type WorkflowRunRecord {
2028
- id: String!
2029
- workflowId: String!
2030
- workflowName: String!
2031
- workflowVersion: Int!
2032
- triggerKind: String!
2033
- triggerPayload: Unknown
2034
- status: String!
2035
- error: String
2036
- errorName: String
2037
- "When the run began executing; a PENDING run's is when it was journaled."
2038
- startedAt: String!
2039
- endedAt: String
2040
- rerunOf: String
2041
- "How many warningNotes the run has; a run with any is not a plain success."
2042
- warnings: Int!
2043
- "Steps that ran a fallback piece version, edges on ports nothing emits."
2044
- warningNotes: [String!]!
2045
- steps: [WorkflowStepRunRecord!]!
2046
- }
2047
-
2048
- input WorkflowRunsPagingInput {
2049
- "Page size; default 25, at most 100."
2050
- limit: Int
2051
- "The cursor of the previous page."
2052
- cursor: String
2053
- }
2054
-
2055
- type WorkflowRunResultPage {
2056
- items: [WorkflowRunRecord!]!
2057
- hasNextPage: Boolean!
2058
- "True when the page was read after a cursor."
2059
- hasPreviousPage: Boolean!
2060
- "Resumes after this page's last run; null for an empty page."
2061
- cursor: String
2062
- }
2063
-
2064
- type WorkflowStepRun {
2065
- stepId: String!
2066
- key: String!
2067
- pieceName: String!
2068
- blockName: String!
2069
- status: String!
2070
- input: Unknown
2071
- output: Unknown
2072
- port: String
2073
- error: String
2074
- errorName: String
2075
- }
2076
-
2077
- type WorkflowRunPayload {
2078
- runId: String
2079
- status: String!
2080
- error: String
2081
- errorName: String
2082
- steps: [WorkflowStepRun!]!
2083
- }
2084
-
2085
- type WorkflowStepTestResult {
2086
- "Null when the test never started, e.g. an upstream block is untested."
2087
- runId: String
2088
- """
2089
- SUCCEEDED | FAILED | INDETERMINATE. INDETERMINATE is neither: a host call
2090
- the block made timed out, so a write it asked for may well have landed.
2091
- Show it distinctly - it is not a confirmed pass.
2092
- """
2093
- status: String!
2094
- output: Unknown
2095
- error: String
2096
- errorName: String
2097
- durationMs: Int!
2098
- }
2099
-
2100
- """
2101
- WorkflowRuntime Mutations
2102
- """
2103
- type WorkflowRuntimeMutations {
2104
- """
2105
- Fires a workflow's manual trigger (the core piece's) and runs it to completion.
2106
- """
2107
- fire(workflowId: String!, payload: Unknown): WorkflowRunPayload!
2108
- """
2109
- Samples the draft trigger and saves it as the trigger's last test. A piece
2110
- trigger runs its test hook (no cursor changes). Of the core piece's
2111
- triggers, manual takes payload, schedule samples a fire now, and webhook
2112
- waits for the next delivery to the workflow's endpoint, up to
2113
- timeoutSeconds (default and cap 300), and that delivery runs nothing.
2114
- """
2115
- testTrigger(
2116
- workflowId: String!
2117
- payload: Unknown
2118
- timeoutSeconds: Int
2119
- driveId: String
2120
- ): Unknown
2121
- """
2122
- Stops a webhook trigger test that is waiting; false when none was.
2123
- """
2124
- cancelTriggerTest(workflowId: String!): Boolean!
2125
- """
2126
- Runs one draft step against the latest test outputs of the blocks it
2127
- reads, journaled as a "test" run and noted as the step's lastTest.
2128
- driveId waits for an unsynced workflow, as for webhookEndpoint.
2129
- """
2130
- testStep(
2131
- workflowId: String!
2132
- stepId: String!
2133
- driveId: String
2134
- ): WorkflowStepTestResult!
2135
- """
2136
- Resumes a FAILED run: succeeded steps replay from the journal,
2137
- execution restarts at the failure. Produces a new run.
2138
- """
2139
- rerun(runId: String!): WorkflowRunPayload!
2140
- """
2141
- Mints a managed secret and returns its ref; the value is stored
2142
- encrypted and is never readable back over any API.
2143
- """
2144
- createSecret(value: String!, label: String): SecretRecord!
2145
- """
2146
- Replaces the value behind an existing ref; documents stay untouched.
2147
- """
2148
- rotateSecret(ref: String!, value: String!): SecretRecord!
2149
- """
2150
- Tombstones a secret; its value becomes unrecoverable.
2151
- """
2152
- deleteSecret(ref: String!): Boolean!
2153
- """
2154
- Runs the piece's auth.validate against the connection's credentials,
2155
- then auth.getConnectionIdentifier for the account label, and records the
2156
- outcome on the connection document.
2157
- """
2158
- checkConnection(connectionId: String!): ConnectionCheckResult!
2159
- """
2160
- Opens an OAuth2 sign-in with the connection's own app (client_id in its
2161
- config, client_secret in its secretRefs). redirectUri is needed only when
2162
- oauthRedirectUri is a bare path. With returnUrl, which must be on the
2163
- caller's origin, the callback sends the browser back there with
2164
- ?ph_oauth=<state> instead of closing the window.
2165
- """
2166
- startOAuth(
2167
- connectionId: String!
2168
- redirectUri: String
2169
- returnUrl: String
2170
- ): OAuthStart!
2171
- }
2172
-
2173
- type Mutation {
2174
- workflowRuntime: WorkflowRuntimeMutations!
2175
- }
2176
- `;
2177
- //#endregion
2178
- //#region src/workflow/subgraph.ts
2179
- /** The runtime's read/write surface. The runtime itself is composed by the
2180
- * host, so the subgraph only serves what it is handed. */
2181
- function createWorkflowRuntimeSubgraph(runtime, oauth, access) {
2182
- return class WorkflowRuntimeSubgraph extends BaseSubgraph {
2183
- name = "workflow-runtime";
2184
- typeDefs = schema;
2185
- resolvers = getResolvers(runtime, this.authorizationService, oauth, access, (documentId, ctx) => this.assertCanRead(documentId, ctx));
2186
- additionalContextFields = {};
2187
- };
2188
- }
2189
- //#endregion
2190
- //#region src/workflow-runtime.mts
2191
- /** The npm name the workflow package owns: its HTTP namespace and its models. */
2192
- const WORKFLOW_PACKAGE_NAME = "@powerhousedao/workflow";
2193
- const WORKFLOW_TELEMETRY_SCOPE = "@powerhousedao/reactor-workflow";
2194
- /** The env var and OpenFeature flag key that turns workflows on. */
2195
- const PH_WORKFLOWS_ENABLED = "PH_WORKFLOWS_ENABLED";
2196
- const SINGLETON_LOST = {
2197
- status: "unavailable",
2198
- reason: "workflow-singleton-lost"
2199
- };
2200
- /** Precedence, unchanged from the reactor-api resolver this replaces: the
2201
- * host's option, then PH_WORKFLOWS_ENABLED, then the config file, then off. */
2202
- async function resolveWorkflowsEnabled({ featureFlags, override, configEnabled = false, env = process.env }) {
2203
- if (override !== void 0) return override;
2204
- const raw = env[PH_WORKFLOWS_ENABLED]?.trim();
2205
- if (raw === "1") return true;
2206
- if (raw === "0") return false;
2207
- return featureFlags.getBooleanValue(PH_WORKFLOWS_ENABLED, configEnabled);
2208
- }
2209
- async function assertWorkflowPackageLoadable(load = () => import("@powerhousedao/workflow/document-models")) {
2210
- try {
2211
- await load();
2212
- } catch (error) {
2213
- throw new Error(`Workflows are enabled but ${WORKFLOW_PACKAGE_NAME} could not be loaded`, { cause: error });
2214
- }
2215
- }
2216
- /**
2217
- * Whether a composition failure was the workflow singleton refusing this
2218
- * process, rather than something that should take the boot down.
2219
- *
2220
- * Matched by NAME: the engine loads lazily, and importing it here for the
2221
- * constructor would defeat that. The fields the engine's error carries are
2222
- * typed optional for the same reason.
2223
- */
2224
- function isWorkflowSingletonConflict(error) {
2225
- return error instanceof Error && error.name === "WorkflowSingletonConflictError";
2226
- }
2227
- /**
2228
- * Retries the singleton claim for a host that booted without it, and hands
2229
- * the runtime over once a claim succeeds.
2230
- *
2231
- * Without it a rolling deploy whose slots have different owner names ends
2232
- * with nobody running workflows: the new pod is refused while the old one
2233
- * still holds the lease, and nothing retries once the old pod releases it.
2234
- * Only for a host that never composed; one that lost the lease after
2235
- * composing stays without workflows until it restarts.
2236
- */
2237
- function retryWorkflowSingleton(options) {
2238
- const intervalMs = options.intervalMs ?? 2e4;
2239
- let stopped = false;
2240
- let timer;
2241
- let attempt;
2242
- const run = async () => {
2243
- let workflows;
2244
- try {
2245
- workflows = await options.compose();
2246
- } catch (error) {
2247
- if (!isWorkflowSingletonConflict(error)) options.logger.error("Composing the workflow runtime after the singleton came free failed: @error", error);
2248
- schedule();
2249
- return;
2250
- }
2251
- if (stopped) {
2252
- await workflows.stop();
2253
- return;
2254
- }
2255
- options.logger.info("Claimed the workflow singleton after boot; starting the workflow runtime");
2256
- try {
2257
- await options.onComposed(workflows);
2258
- } catch (error) {
2259
- options.logger.error("Starting the workflow runtime after the singleton came free failed: @error", error);
2260
- schedule();
2261
- }
2262
- };
2263
- const schedule = () => {
2264
- if (stopped) return;
2265
- timer = setTimeout(() => {
2266
- timer = void 0;
2267
- attempt = run().finally(() => {
2268
- attempt = void 0;
2269
- });
2270
- }, intervalMs);
2271
- timer.unref();
2272
- };
2273
- schedule();
2274
- return { async stop() {
2275
- stopped = true;
2276
- if (timer) clearTimeout(timer);
2277
- timer = void 0;
2278
- await attempt?.catch(() => void 0);
2279
- } };
2280
- }
2281
- /**
2282
- * What a host does once its composed runtime has shut down for losing the
2283
- * workflow singleton.
2284
- *
2285
- * Taken over by another claim: that process runs workflows now, so this one
2286
- * stays without them until it restarts. Unrenewable with no takeover seen (a
2287
- * database blip): nothing else runs them, so the process goes down through
2288
- * the fatal shutdown and its supervisor restarts it, which re-claims at boot.
2289
- * A host with no fatal shutdown installed (embedded) stays without workflows
2290
- * and says a restart is needed.
2291
- */
2292
- function workflowSingletonLossHandler(logger, fatal = triggerFatalShutdown) {
2293
- return (loss) => {
2294
- if (loss.reason === "taken") {
2295
- logger.error(`Another process ("${loss.heldBy ?? "unknown"}") took the workflow singleton. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted; everything else serves normally.`);
2296
- return;
2297
- }
2298
- const error = /* @__PURE__ */ new Error(`The workflow singleton lease could not be renewed for ${Math.round(loss.silentMs)}ms; no other process was seen taking it over`);
2299
- if (fatal("Workflow singleton lease unrenewable", error)) return;
2300
- logger.error(`${error.message}. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted.`);
2301
- };
2302
- }
2303
- function modelManifestSource(builder) {
2304
- return {
2305
- modelManifest: () => builder.getResolvedModelManifest() ?? [],
2306
- modelEntries: (documentType) => builder.getImportableEntries(documentType)
2307
- };
2308
- }
2309
- function readAssertion(authorizationService, reactorClient) {
2310
- const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
2311
- const hostCanRead = async (identifier, ctx) => {
2312
- if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
2313
- if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
2314
- let documentId;
2315
- try {
2316
- documentId = await resolveCanonical(identifier);
2317
- } catch {
2318
- throw new ForbiddenError();
2319
- }
2320
- if (!await authorizationService.canRead(documentId, ctx.user?.address)) throw new ForbiddenError("to read this document");
2321
- };
2322
- return async (identifier, caller) => {
2323
- const ctx = caller;
2324
- await hostCanRead(identifier, ctx);
2325
- let served;
2326
- try {
2327
- served = await reactorClient.isServed(identifier, { subject: callerSubject(ctx.user) });
2328
- } catch {
2329
- throw new ForbiddenError();
2330
- }
2331
- if (!served) throw new ForbiddenError("to read this document");
2332
- };
2333
- }
2334
- /** The same, for a design-time call that writes what it names. */
2335
- function writeAssertion(authorizationService, reactorClient) {
2336
- const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
2337
- return async (identifier, caller) => {
2338
- const ctx = caller;
2339
- if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
2340
- if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
2341
- let documentId;
2342
- try {
2343
- documentId = await resolveCanonical(identifier);
2344
- } catch {
2345
- throw new ForbiddenError();
2346
- }
2347
- if (!await authorizationService.canWrite(documentId, ctx.user?.address)) throw new ForbiddenError("to write this document");
2348
- };
2349
- }
2350
- /** What the reactor enforces and who it signs as; unknown counts as enforced. */
2351
- function reactorAccessOf(clientModule) {
2352
- const flags = clientModule?.reactorModule?.featureFlags;
2353
- const signer = clientModule?.signer;
2354
- const key = signer?.app?.key;
2355
- const identity = key ? {
2356
- address: signer.user?.address ?? null,
2357
- key
2358
- } : null;
2359
- return {
2360
- authEnforcement: flags ? flags.authEnforcement : true,
2361
- authConditions: flags?.authConditions === true,
2362
- identity
2363
- };
2364
- }
2365
- /** Whom a run's created documents also grant: the host, as §8 grants it. */
2366
- function hostPrincipalOf(access) {
2367
- const identity = access.identity;
2368
- if (!identity) return void 0;
2369
- if (access.authConditions) return { match: { eq: [{ attr: "subject.key" }, { lit: identity.key }] } };
2370
- return identity.address ? { address: identity.address } : void 0;
2371
- }
2372
- /** Who the host signs as, so a publish it signs makes no run user. */
2373
- function hostIdentityOf(access) {
2374
- const identity = access.identity;
2375
- if (!identity) return void 0;
2376
- return identity.address ? {
2377
- address: identity.address,
2378
- key: identity.key
2379
- } : { key: identity.key };
2380
- }
2381
- const REFERENCE_INDEX_RETRIES = 8;
2382
- const REFERENCE_INDEX_RETRY_MS = 250;
2383
- /** A step reads an attachment the way the download route serves one: when the
2384
- * run's user may read a document that references it. The candidates are the
2385
- * documents the run was handed; the reference index can trail the operation
2386
- * that fired the trigger, so a denial is retried briefly. */
2387
- function attachmentReadPolicy(access, retryMs = REFERENCE_INDEX_RETRY_MS) {
2388
- return async (request) => {
2389
- try {
2390
- if (parseRef(request.ref).version !== 1) return false;
2391
- } catch {
2392
- return false;
2393
- }
2394
- if (!access || request.documentIds.length === 0) return false;
2395
- const subject = request.runUser?.subject;
2396
- const caller = {
2397
- ...subject?.address ? { userAddress: subject.address } : {},
2398
- ...subject?.key ? { appKey: subject.key } : {}
2399
- };
2400
- for (let attempt = 0; attempt <= REFERENCE_INDEX_RETRIES; attempt++) {
2401
- for (const documentId of request.documentIds) if ((await access.canReadAttachment({
2402
- documentId,
2403
- attachmentRef: request.ref,
2404
- ...caller
2405
- })).kind === "allowed") return true;
2406
- if (attempt < REFERENCE_INDEX_RETRIES) await new Promise((resolve) => setTimeout(resolve, retryMs));
2407
- }
2408
- return false;
2409
- };
2410
- }
2411
- async function registerWorkflowTriggersReadModel(engine, runtime, clientModule, registration) {
2412
- const reactorModule = clientModule?.reactorModule;
2413
- if (!reactorModule) return {
2414
- status: "unavailable",
2415
- reason: "in-process-reactor-module-unavailable"
2416
- };
2417
- const coordinator = reactorModule.readModelCoordinator;
2418
- if (!supportsLiveReadModelRegistration(coordinator)) return {
2419
- status: "unavailable",
2420
- reason: "live-read-model-registration-unsupported"
2421
- };
2422
- const readModel = new engine.WorkflowTriggersReadModel(reactorModule.database.withSchema(REACTOR_SCHEMA), reactorModule.operationIndex, reactorModule.writeCache, reactorModule.processorManagerConsistencyTracker, runtime);
2423
- await readModel.init();
2424
- if (registration.tornDown) return SINGLETON_LOST;
2425
- coordinator.addReadModel(readModel, engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE);
2426
- registration.detach = () => coordinator.removeReadModel(readModel);
2427
- return { status: "available" };
2428
- }
2429
- function bindPackagePieces(registry, source) {
2430
- const apply = (byPackage) => {
2431
- registry.setPieces([...byPackage.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).flatMap(([, pieces]) => pieces));
2432
- };
2433
- apply(source.getPieces());
2434
- source.onPiecesChange(apply);
2435
- }
2436
- async function composeWorkflowRuntime(deps) {
2437
- const load = deps.load ?? (() => import("@powerhousedao/reactor-workflow"));
2438
- let engine;
2439
- try {
2440
- engine = await load();
2441
- } catch (error) {
2442
- throw new Error("Workflows are enabled but @powerhousedao/reactor-workflow could not be loaded", { cause: error });
2443
- }
2444
- const loss = { lost: false };
2445
- const lease = deps.singletonLease === false ? void 0 : await engine.acquireWorkflowSingletonLease({
2446
- relationalDb: deps.relationalDb,
2447
- logger: deps.logger,
2448
- ...deps.storageId ? { storageId: deps.storageId } : {},
2449
- selfFence: deps.exclusiveJournal !== true,
2450
- onLost: (lost) => {
2451
- loss.lost = true;
2452
- if (lost.reason === "taken") loss.heldBy = lost.heldBy;
2453
- loss.tearDown?.();
2454
- if (loss.composed) deps.onSingletonLost?.(lost);
2455
- }
2456
- });
2457
- try {
2458
- const composed = await composeClaimed(engine, deps, lease, loss);
2459
- if (loss.lost) throw singletonLostError(engine, loss, lease);
2460
- loss.composed = true;
2461
- return composed;
2462
- } catch (error) {
2463
- loss.tearDown?.();
2464
- await lease?.release();
2465
- throw error;
2466
- }
2467
- }
2468
- function singletonLostError(engine, loss, lease) {
2469
- return new engine.WorkflowSingletonConflictError(loss.heldBy ?? "unknown", "unknown", lease?.owner ?? "unknown");
2470
- }
2471
- async function composeClaimed(engine, deps, lease, loss) {
2472
- engine.setPieceRegistryUrl(deps.pieceRegistryUrl);
2473
- if (deps.pieces) bindPackagePieces(engine.packagePieces, deps.pieces);
2474
- if (loss.lost) throw singletonLostError(engine, loss, lease);
2475
- const access = reactorAccessOf(deps.clientModule);
2476
- const models = deps.models;
2477
- const runtime = engine.createWorkflowRuntime({
2478
- relationalDb: deps.relationalDb,
2479
- secretsKeyFile: deps.secretsKeyFile,
2480
- reactorClient: deps.reactorClient,
2481
- assertCanRead: readAssertion(deps.authorizationService, deps.reactorClient),
2482
- subjectOf: (caller) => callerSubject(caller.user),
2483
- assertCanWrite: writeAssertion(deps.authorizationService, deps.reactorClient),
2484
- ...deps.clientModule?.reactorModule ? { authEnforcement: access.authEnforcement } : {},
2485
- hostPrincipal: hostPrincipalOf(access),
2486
- hostIdentity: hostIdentityOf(access),
2487
- ...models ? {
2488
- modelManifest: () => models.modelManifest(),
2489
- modelEntries: (documentType) => models.modelEntries(documentType)
2490
- } : {},
2491
- webhooks: deps.webhooks,
2492
- attachments: deps.attachments,
2493
- canReadAttachmentRef: attachmentReadPolicy(deps.attachmentAccess),
2494
- logger: deps.logger,
2495
- ...deps.reactorThreads ? { reactorThreads: deps.reactorThreads } : {},
2496
- ...deps.telemetry ? { telemetry: deps.telemetry } : {}
2497
- });
2498
- const routes = {};
2499
- const registration = { tornDown: false };
2500
- const tearDown = () => {
2501
- if (registration.tornDown) return;
2502
- registration.tornDown = true;
2503
- routes.oauthCallback?.dispose();
2504
- runtime.shutdown();
2505
- registration.detach?.();
2506
- };
2507
- loss.tearDown = tearDown;
2508
- const triggers = await registerWorkflowTriggersReadModel(engine, runtime, deps.clientModule, registration);
2509
- if (registration.tornDown) throw singletonLostError(engine, loss, lease);
2510
- if (triggers.status === "available") deps.logger.info(`Workflow trigger read model registered (${engine.WORKFLOW_TRIGGERS_READ_MODEL}, ${engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE})`);
2511
- else deps.logger.error("Workflow document triggers are NOT armed (@reason): this reactor's read-model coordinator takes no live registration, so no document operation reaches the runtime. Webhook and schedule triggers are unaffected.", triggers.reason);
2512
- let stopped = false;
2513
- if (deps.http) routes.oauthCallback = registerOAuthCallback(deps.http, runtime);
2514
- return {
2515
- subgraph: createWorkflowRuntimeSubgraph(runtime, deps.http ? { callbackUrl: callbackUrlOf(deps.http) } : void 0, access),
2516
- get triggers() {
2517
- return loss.lost ? SINGLETON_LOST : triggers;
2518
- },
2519
- ...lease ? { singletonOwner: lease.owner } : {},
2520
- async start() {
2521
- if (registration.tornDown) return;
2522
- await runtime.registerWebhookEndpoint();
2523
- if (loss.lost || stopped) return;
2524
- runtime.startTriggerSupervisor();
2525
- runtime.warmPieceSearch();
2526
- },
2527
- async stop() {
2528
- if (stopped) return;
2529
- stopped = true;
2530
- tearDown();
2531
- await lease?.release();
2532
- }
2533
- };
2534
- }
2535
- //#endregion
2536
1315
  //#region src/pglite-dialect.ts
2537
1316
  /** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */
2538
1317
  function reactorPgliteDialectOptions(logger, proc) {
@@ -3033,6 +1812,16 @@ function deriveAttachmentServiceConfig(options, serverPort, renown) {
3033
1812
  }
3034
1813
  async function initServer(serverPort, options, renown, renownConfig) {
3035
1814
  const { dev, packages = [], remoteDrives = [], logger = defaultLogger } = options;
1815
+ const pluginHost = isPluginHostEnabled() ? createSwitchboardPluginHost({
1816
+ logger,
1817
+ options,
1818
+ renown
1819
+ }, options.pluginComposition) : null;
1820
+ if (pluginHost) {
1821
+ options = await pluginHost.transformOptions(options);
1822
+ options.mcp ??= false;
1823
+ options.workflows = { enabled: options.workflows?.enabled === true };
1824
+ }
3036
1825
  logger.level = LogLevel;
3037
1826
  const dbPath = options.dbPath ?? process.env.DATABASE_URL ?? process.env.PH_SWITCHBOARD_DATABASE_URL;
3038
1827
  const readModelPath = dbPath || ".ph/read-storage";
@@ -3110,7 +1899,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
3110
1899
  process.kill(process.pid, "SIGTERM");
3111
1900
  };
3112
1901
  const workflowsEnabled = options.workflows?.enabled === true;
3113
- const privacyConfig = resolvePrivacy(options.privacy, process.env);
1902
+ const privacyConfig = pluginHost ? { enabled: false } : resolvePrivacy(options.privacy, process.env);
3114
1903
  if (workflowsEnabled) {
3115
1904
  await assertWorkflowPackageLoadable();
3116
1905
  if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
@@ -3332,11 +2121,26 @@ async function initServer(serverPort, options, renown, renownConfig) {
3332
2121
  localCredentialCheck = createLocalCredentialVerifier(localRenownRequest, { onError: (error) => logger.error("Renown read model query failed: @error", error) });
3333
2122
  logger.info("Renown credentials will be verified against this switchboard's own renown read model");
3334
2123
  }
3335
- registerAttachmentRoutes(api);
3336
- const attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
2124
+ let attachmentService;
2125
+ if (pluginHost) {
2126
+ pluginHost.ctx.api = api;
2127
+ pluginHost.ctx.serverPort = serverPort;
2128
+ await pluginHost.observe("onHttpMounting");
2129
+ attachmentService = pluginHost.ctx.attachmentService;
2130
+ } else {
2131
+ registerAttachmentRoutes(api);
2132
+ attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
2133
+ }
3337
2134
  if (process.env.SENTRY_DSN) api.httpAdapter.setupSentryErrorHandler(Sentry);
3338
2135
  const { client, graphqlManager, documentModelRegistry } = api;
3339
2136
  const lateSubgraphs = [];
2137
+ if (pluginHost) {
2138
+ pluginHost.ctx.client = client;
2139
+ pluginHost.ctx.graphqlManager = graphqlManager;
2140
+ pluginHost.ctx.lateSubgraphs = lateSubgraphs;
2141
+ pluginHost.ctx.reactorClientModule = options.reactor ?? ownedReactorModule;
2142
+ await pluginHost.observe("onReactorReady");
2143
+ }
3340
2144
  let workflows;
3341
2145
  let workflowsRetry;
3342
2146
  const composeWorkflows = () => composeWorkflowRuntime({
@@ -3379,7 +2183,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
3379
2183
  reportFailure(reporting, error, "Failed to register workflow-runtime subgraph: @error");
3380
2184
  });
3381
2185
  };
3382
- if (workflowsEnabled) try {
2186
+ if (!pluginHost && workflowsEnabled) try {
3383
2187
  workflows = await composeWorkflows();
3384
2188
  } catch (error) {
3385
2189
  if (!isWorkflowSingletonConflict(error)) throw error;
@@ -3415,8 +2219,26 @@ async function initServer(serverPort, options, renown, renownConfig) {
3415
2219
  logger.info("Workflow runtime started");
3416
2220
  api.inspection?.facts.setWorkflows(true);
3417
2221
  }
2222
+ if (pluginHost) {
2223
+ pluginHost.ctx.workflowsOrchestration = {
2224
+ enabled: options.workflows?.enabled === true,
2225
+ composeWorkflows,
2226
+ registerWorkflowSubgraph,
2227
+ updateRouter: () => graphqlManager.updateRouter(true),
2228
+ reportMountFailure: (error) => reportFailure(reporting, error, "Mounting the late workflow-runtime subgraph failed: @error"),
2229
+ setWorkflowsFact: () => api.inspection?.facts.setWorkflows(true)
2230
+ };
2231
+ try {
2232
+ await pluginHost.observe("onSubgraphsRegistering");
2233
+ } catch (error) {
2234
+ await pluginHost.ctx.workflowsRetry?.stop();
2235
+ await pluginHost.ctx.workflows?.stop();
2236
+ await abortBoot(api);
2237
+ throw error;
2238
+ }
2239
+ }
3418
2240
  let privacy;
3419
- if (privacyConfig.enabled) {
2241
+ if (!pluginHost && privacyConfig.enabled) {
3420
2242
  const signer = options.reactor ? options.privacy?.signer : options.privacy?.signer ?? renown?.signer;
3421
2243
  try {
3422
2244
  privacy = await startPrivacy({
@@ -3437,6 +2259,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
3437
2259
  }
3438
2260
  }
3439
2261
  const shutdown = async () => {
2262
+ if (pluginHost) await pluginHost.observe("onShutdown");
3440
2263
  await privacy?.stop();
3441
2264
  await workflowsRetry?.stop();
3442
2265
  await workflows?.stop();
@@ -3526,6 +2349,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
3526
2349
  if (!defaultDriveUrl && driveId) defaultDriveUrl = `${options.https ? "https" : "http"}://localhost:${serverPort}/d/${driveId}`;
3527
2350
  }
3528
2351
  }
2352
+ if (pluginHost) await pluginHost.observe("onDrivesReady");
3529
2353
  return {
3530
2354
  defaultDriveUrl,
3531
2355
  api,
@@ -3533,11 +2357,14 @@ async function initServer(serverPort, options, renown, renownConfig) {
3533
2357
  attachmentService,
3534
2358
  attachmentReferenceProjection: api.attachmentReferenceProjection,
3535
2359
  get workflowTriggers() {
3536
- return workflows?.triggers;
2360
+ return (workflows ?? pluginHost?.ctx.workflows)?.triggers;
3537
2361
  },
3538
2362
  workflowsEnabled,
3539
2363
  modelManifest: () => workerModels?.modelManifest() ?? [],
3540
- privacy: privacy ? { erasure: privacy.erasure } : void 0,
2364
+ privacy: (() => {
2365
+ const running = privacy ?? pluginHost?.ctx.privacy;
2366
+ return running ? { erasure: running.erasure } : void 0;
2367
+ })(),
3541
2368
  mcpEnabled: options.mcp !== false,
3542
2369
  inspectionEnabled: options.inspection !== false,
3543
2370
  renown,
@@ -3570,21 +2397,22 @@ const startSwitchboard = async (options = {}) => {
3570
2397
  const featureFlags = await initFeatureFlags();
3571
2398
  const enableDocumentModelSubgraphs = await featureFlags.getBooleanValue(DOCUMENT_MODEL_SUBGRAPHS_ENABLED, options.enableDocumentModelSubgraphs ?? DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT);
3572
2399
  options.enableDocumentModelSubgraphs = enableDocumentModelSubgraphs;
3573
- options.mcp = await resolveMcpEnabled({
3574
- featureFlags,
3575
- option: options.mcp
3576
- });
2400
+ if (!isPluginHostEnabled()) {
2401
+ options.mcp = await resolveMcpEnabled({
2402
+ featureFlags,
2403
+ option: options.mcp
2404
+ });
2405
+ const configPathForFlags = resolveConfigPath(options.configFile);
2406
+ options.workflows = { enabled: await resolveWorkflowsEnabled({
2407
+ featureFlags,
2408
+ override: options.workflows?.enabled,
2409
+ configEnabled: readConfigWorkflowsEnabled(configPathForFlags)
2410
+ }) };
2411
+ }
3577
2412
  options.inspection = await resolveInspectionEnabled({
3578
2413
  featureFlags,
3579
2414
  option: options.inspection
3580
2415
  });
3581
- const configPathForFlags = resolveConfigPath(options.configFile);
3582
- const workflowsEnabled = await resolveWorkflowsEnabled({
3583
- featureFlags,
3584
- override: options.workflows?.enabled,
3585
- configEnabled: readConfigWorkflowsEnabled(configPathForFlags)
3586
- });
3587
- options.workflows = { enabled: workflowsEnabled };
3588
2416
  const renownConfig = resolveRenownConfig(getConfig(resolveConfigPath(options.configFile)).auth?.renown, process.env, logger);
3589
2417
  options.identity = {
3590
2418
  ...options.identity,
@@ -3594,7 +2422,7 @@ const startSwitchboard = async (options = {}) => {
3594
2422
  DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,
3595
2423
  MCP_ENABLED: options.mcp,
3596
2424
  INSPECTION_ENABLED: options.inspection,
3597
- PH_WORKFLOWS_ENABLED: workflowsEnabled
2425
+ PH_WORKFLOWS_ENABLED: options.workflows?.enabled
3598
2426
  }, null, 2));
3599
2427
  let renown = null;
3600
2428
  try {
@@ -3614,7 +2442,7 @@ const startSwitchboard = async (options = {}) => {
3614
2442
  };
3615
2443
  if (import.meta.main) await startSwitchboard({ fatalErrorShutdown: true });
3616
2444
  //#endregion
3617
- export { StoredDocumentsRefusedError as a, initProfilerFromEnv as c, startSwitchboard as i, parseForcePgVersion as l, deriveAttachmentServiceConfig as n, resolveUnsupportedStoredDocuments as o, isPortAvailable as r, applySwitchboardReactorDefaults as s, createReactorKysely as t };
2445
+ export { StoredDocumentsRefusedError as a, applySwitchboardReactorDefaults as c, startSwitchboard as i, initProfilerFromEnv as l, deriveAttachmentServiceConfig as n, resolveUnsupportedStoredDocuments as o, isPortAvailable as r, attachmentsPlugin as s, createReactorKysely as t, parseForcePgVersion as u };
3618
2446
 
3619
- //# sourceMappingURL=server-Cw2WnaCA.mjs.map
3620
- //# debugId=99cead54-dc11-5711-a454-9efc98498890
2447
+ //# sourceMappingURL=server-Ncv91CrC.mjs.map
2448
+ //# debugId=686b0a5d-6f56-5f96-8277-8dcb19167510