@powerhousedao/switchboard 6.2.3-dev.70 → 6.2.3-dev.72
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/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
- package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
- package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
- package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
- package/.tsbuild/test/port-probe.test.d.ts +2 -0
- package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
- package/.tsbuild/test/shutdown.test.d.ts +2 -0
- package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
- package/.tsbuild/test/store-lock.test.d.ts +2 -0
- package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
- package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
- package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
- package/.tsbuild/tsconfig.tsbuildinfo +1 -1
- package/CHANGELOG.md +44 -0
- package/dist/index.mjs +1 -1
- package/dist/{mcp-cNWW82NH.mjs → mcp-SsBK14Jm.mjs} +10 -5
- package/dist/mcp-SsBK14Jm.mjs.map +1 -0
- package/dist/plugins/attachments.d.mts +10 -0
- package/dist/plugins/attachments.d.mts.map +1 -1
- package/dist/plugins/attachments.mjs +4 -4
- package/dist/plugins/mcp.d.mts +10 -0
- package/dist/plugins/mcp.d.mts.map +1 -1
- package/dist/plugins/mcp.mjs +4 -4
- package/dist/plugins/privacy.d.mts +10 -0
- package/dist/plugins/privacy.d.mts.map +1 -1
- package/dist/plugins/privacy.mjs +4 -4
- package/dist/plugins/workflows.d.mts +46 -3
- package/dist/plugins/workflows.d.mts.map +1 -1
- package/dist/plugins/workflows.mjs +4 -4
- package/dist/{privacy-C8KVimKF.mjs → privacy-BsFl7GzK.mjs} +9 -4
- package/dist/{privacy-C8KVimKF.mjs.map → privacy-BsFl7GzK.mjs.map} +1 -1
- package/dist/{server-CF_mjyJi.mjs → server-CrWPtMG6.mjs} +114 -29
- package/dist/server-CrWPtMG6.mjs.map +1 -0
- package/dist/server.d.mts +18 -15
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +3 -3
- package/dist/{utils-uaBlzyjS.mjs → utils-Dh845exv.mjs} +42 -9
- package/dist/utils-Dh845exv.mjs.map +1 -0
- package/dist/utils.d.mts +8 -2
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +3 -3
- package/dist/{workflows-qKtqZhn3.mjs → workflows-fsBcElEi.mjs} +111 -67
- package/dist/{workflows-qKtqZhn3.mjs.map → workflows-fsBcElEi.mjs.map} +1 -1
- package/package.json +18 -17
- package/test/attachments/routes.test.ts +26 -11
- package/test/default-drive-slug.test.ts +97 -0
- package/test/plugin-config-schemas.test.ts +83 -0
- package/test/port-probe.test.ts +45 -0
- package/test/shutdown.test.ts +278 -0
- package/test/store-lock.test.ts +65 -0
- package/test/workflows-plugin-config.test.ts +77 -0
- package/dist/mcp-cNWW82NH.mjs.map +0 -1
- package/dist/server-CF_mjyJi.mjs.map +0 -1
- package/dist/utils-uaBlzyjS.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflows-qKtqZhn3.mjs","sources":["../src/fatal-shutdown.mts","../src/workflow/oauth-callback.ts","../src/workflow/resolvers.ts","../src/workflow/schema.ts","../src/workflow/subgraph.ts","../src/workflow-runtime.mts","../src/plugins/workflows.mts"],"sourcesContent":["import type { ILogger } from \"document-model\";\n\nconst FORCED_EXIT_MS = 15_000;\n\ntype FatalProcess = Pick<\n NodeJS.Process,\n \"on\" | \"kill\" | \"exit\" | \"pid\" | \"listenerCount\"\n> & {\n exitCode?: NodeJS.Process[\"exitCode\"];\n};\n\nconst fatalHandlers = new WeakMap<\n FatalProcess,\n (kind: string, err: unknown) => void\n>();\n\n/**\n * Sends an uncaught exception or unhandled rejection through the SIGTERM\n * shutdown that `withSignalHandlers()` installs, so the reactor and read-model\n * PGlite stores close with a shutdown checkpoint before the process exits\n * with code 1. Node's default is to exit at once, which leaves both stores\n * to WAL recovery on the next open. A store whose wasm runtime aborted\n * (ENOSPC) rejects its close; the builder logs that and still exits. A\n * shutdown that hangs is cut off after FORCED_EXIT_MS.\n *\n * A rejection is fatal only when this is its sole listener: Node exits on an\n * unhandled rejection only when nothing listens for it, and Sentry's\n * listener deliberately keeps the process running.\n */\nexport function installFatalErrorShutdown(\n logger: ILogger,\n proc: FatalProcess = process,\n): void {\n if (fatalHandlers.has(proc)) return;\n\n // Captured before shutdown starts: the builder replaces process.exit with a\n // recording shim while it drains.\n const realExit = proc.exit.bind(proc);\n let shuttingDown = false;\n\n /**\n * Logs without ever throwing. onFatal runs inside the uncaughtException\n * handler, so a logger whose transport is gone (EPIPE on a closed stdout)\n * would otherwise throw from the handler that reports throws, killing the\n * process before the shutdown it is supposed to run. A logging failure is\n * swallowed: there is nowhere left to report it.\n */\n const logFatal = (message: string, err?: unknown): void => {\n try {\n if (err === undefined) {\n logger.error(message);\n } else {\n logger.error(message, err);\n }\n } catch {\n // The log transport itself failed; shutdown must keep moving.\n }\n };\n\n const onFatal = (kind: string, err: unknown): void => {\n logFatal(`${kind}: @error`, err);\n if (shuttingDown) return;\n shuttingDown = true;\n proc.exitCode = 1;\n setTimeout(() => {\n logFatal(\"Shutdown after fatal error timed out; exiting\");\n realExit(1);\n }, FORCED_EXIT_MS).unref();\n proc.kill(proc.pid, \"SIGTERM\");\n };\n fatalHandlers.set(proc, onFatal);\n\n proc.on(\"uncaughtException\", (err) => onFatal(\"Uncaught exception\", err));\n proc.on(\"unhandledRejection\", (reason) => {\n if (proc.listenerCount(\"unhandledRejection\") > 1) return;\n onFatal(\"Unhandled rejection\", reason);\n });\n}\n\n/**\n * Routes a fatal condition the caller detected through the same shutdown as an\n * uncaught error. Returns false, and does nothing, when\n * `installFatalErrorShutdown` has not run for `proc`.\n */\nexport function triggerFatalShutdown(\n kind: string,\n err: unknown,\n proc: FatalProcess = process,\n): boolean {\n const onFatal = fatalHandlers.get(proc);\n if (!onFatal) return false;\n onFatal(kind, err);\n return true;\n}\n","import type { WorkflowRuntimeService } from \"@powerhousedao/reactor-workflow\";\nimport type {\n IHttpScope,\n ScopedRouteHandle,\n} from \"@powerhousedao/shared/processors\";\n\nexport const OAUTH_CALLBACK_PATH = \"oauth/callback\";\n\nfunction escapeHtml(text: string): string {\n return text.replace(\n /[&<>\"']/g,\n (char) =>\n ({\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n })[char]!,\n );\n}\n\n// The popup's last page. The editor that opened it polls the attempt, so this\n// only has to say how it went; closing itself is a courtesy.\nfunction resultPage(ok: boolean, detail: string | null): string {\n const title = ok ? \"Connected\" : \"Sign-in failed\";\n const message = ok\n ? \"You can close this window.\"\n : escapeHtml(detail ?? \"The sign-in did not finish.\");\n return `<!doctype html>\n<html><head><meta charset=\"utf-8\"><title>${title}</title>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<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>\n</head><body><main><h1>${title}</h1><p>${message}</p></main>\n${ok ? \"<script>setTimeout(function(){window.close()},600)</script>\" : \"\"}\n</body></html>`;\n}\n\n// The provider's redirect lands here. Public: the provider sends no bearer,\n// and the one-time state is what the runtime checks instead.\nexport function registerOAuthCallback(\n http: IHttpScope,\n runtime: Pick<WorkflowRuntimeService, \"completeOAuth\">,\n): ScopedRouteHandle {\n return http.get(OAUTH_CALLBACK_PATH, { auth: \"public\" }, async (request) => {\n const params = new URL(request.url).searchParams;\n const state = params.get(\"state\");\n const result = state\n ? await runtime.completeOAuth({\n state,\n code: params.get(\"code\") ?? undefined,\n error: params.get(\"error\") ?? undefined,\n errorDescription: params.get(\"error_description\") ?? undefined,\n })\n : { ok: false, detail: \"The provider sent no state\", returnUrl: null };\n if (result.returnUrl && state) {\n const back = new URL(result.returnUrl);\n back.searchParams.set(\"ph_oauth\", state);\n return new Response(null, {\n status: 303,\n headers: { location: back.href, \"cache-control\": \"no-store\" },\n });\n }\n return new Response(resultPage(result.ok, result.detail), {\n status: result.ok ? 200 : 400,\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"referrer-policy\": \"no-referrer\",\n },\n });\n });\n}\n\nexport function callbackUrlOf(http: IHttpScope): string {\n return `${http.baseUrl.replace(/\\/+$/, \"\")}/${OAUTH_CALLBACK_PATH}`;\n}\n","import type {\n Context,\n IAuthorizationService,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n RunRow,\n StepExecutionRow,\n WorkflowRuntimeService,\n} from \"@powerhousedao/reactor-workflow\";\nimport {\n GraphQLError,\n Kind,\n type GraphQLResolveInfo,\n type SelectionSetNode,\n} from \"graphql\";\n\ninterface FireArgs {\n workflowId: string;\n payload?: unknown;\n}\n\ninterface PieceArgs {\n packageName: string;\n version?: string | null;\n}\n\ntype BlockRef = Parameters<WorkflowRuntimeService[\"blockDescriptor\"]>[0];\n\ntype PieceSource = NonNullable<\n Parameters<WorkflowRuntimeService[\"searchPieces\"]>[1][\"sources\"]\n>[number];\n\nconst PIECE_SOURCES: readonly string[] = [\n \"local\",\n \"registry\",\n \"activepieces\",\n] satisfies PieceSource[];\n\nfunction isPieceSource(value: string): value is PieceSource {\n return PIECE_SOURCES.includes(value);\n}\n\ninterface BlockInput {\n pieceName: string;\n pieceVersion: string;\n name: string;\n kind: string;\n}\n\nfunction blockRef(input: BlockInput): BlockRef {\n if (input.kind !== \"action\" && input.kind !== \"trigger\") {\n throw new GraphQLError(\n `A block's kind is \"action\" or \"trigger\", got \"${input.kind}\"`,\n );\n }\n return {\n pieceName: input.pieceName,\n pieceVersion: input.pieceVersion,\n name: input.name,\n kind: input.kind,\n };\n}\n\ninterface RunsArgs {\n workflowId?: string;\n driveId?: string;\n limit?: number;\n excludeTriggerKinds?: string[];\n}\n\ninterface RunsPageArgs {\n workflowId?: string;\n driveId?: string;\n excludeTriggerKinds?: string[];\n paging?: { limit?: number | null; cursor?: string | null } | null;\n}\n\n// A cursor the runtime did not issue is the caller's error, not ours.\nasync function cursorAware<T>(call: () => Promise<T>): Promise<T> {\n try {\n return await call();\n } catch (error) {\n if (error instanceof Error && error.name === \"InvalidRunCursorError\") {\n throw new GraphQLError(error.message, {\n extensions: { code: \"BAD_USER_INPUT\" },\n });\n }\n throw error;\n }\n}\n\n// Whether a runs query reads any step's input or output, so a listing that\n// doesn't can skip those blobs. Fragments count as asking for them.\nfunction selectsStepData(\n selections: readonly SelectionSetNode[],\n path: string[],\n): boolean {\n let level = selections;\n for (const name of [...path, \"steps\"]) {\n const next: SelectionSetNode[] = [];\n for (const set of level) {\n for (const selection of set.selections) {\n if (selection.kind !== Kind.FIELD) return true;\n if (selection.name.value === name && selection.selectionSet) {\n next.push(selection.selectionSet);\n }\n }\n }\n if (next.length === 0) return false;\n level = next;\n }\n return level.some((set) =>\n set.selections.some(\n (selection) =>\n selection.kind !== Kind.FIELD ||\n selection.name.value === \"input\" ||\n selection.name.value === \"output\",\n ),\n );\n}\n\n// With no resolve info (a direct call) the full shape is served.\nfunction readsStepData(\n info: GraphQLResolveInfo | undefined,\n path: string[],\n): boolean {\n if (!info) return true;\n const selections = info.fieldNodes.flatMap((node) =>\n node.selectionSet ? [node.selectionSet] : [],\n );\n return selectsStepData(selections, path);\n}\n\n// A secret belongs to the reactor, not to any one document, so writing one is\n// an administrator's call — the gate the package mutations already use.\nfunction requireAdmin(\n authorizationService: IAuthorizationService,\n ctx: Context,\n): void {\n if (!authorizationService.isSupremeAdmin(ctx.user?.address)) {\n throw new GraphQLError(\"Admin access required\");\n }\n}\n\n// The runtime's retryable \"not synced here yet\", tagged for clients.\nasync function syncAware<T>(call: () => Promise<T>): Promise<T> {\n try {\n return await call();\n } catch (error) {\n if (error instanceof Error && error.name === \"WorkflowSyncingError\") {\n throw new GraphQLError(error.message, {\n extensions: { code: \"WORKFLOW_SYNCING\", retryable: true },\n });\n }\n throw error;\n }\n}\n\nfunction parseJson(value: string | null): unknown {\n if (value === null) return null;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n}\n\nfunction toStepRecord(row: StepExecutionRow) {\n return {\n stepId: row.step_id,\n stepKey: row.step_key,\n pieceName: row.piece_name,\n blockName: row.block_name,\n status: row.status,\n input: parseJson(row.input),\n output: parseJson(row.output),\n port: row.port,\n error: row.error,\n errorName: row.error_name,\n startedAt: row.started_at,\n endedAt: row.ended_at,\n pieceVersion: row.piece_version,\n pieceSource: row.piece_source,\n versionMatch: row.version_match,\n versionNote: row.version_note,\n };\n}\n\nfunction toRunRecord(row: RunRow, steps: StepExecutionRow[]) {\n return {\n id: row.id,\n workflowId: row.workflow_id,\n workflowName: row.workflow_name,\n workflowVersion: row.workflow_version,\n triggerKind: row.trigger_kind,\n triggerPayload: parseJson(row.trigger_payload),\n status: row.status,\n error: row.error,\n errorName: row.error_name,\n startedAt: row.started_at,\n endedAt: row.ended_at,\n rerunOf: row.rerun_of,\n warnings: row.warnings,\n warningNotes: parseJson(row.warning_notes) ?? [],\n steps: steps.map(toStepRecord),\n };\n}\n\nexport type ReadAssertion = (\n documentId: string,\n ctx: Context,\n) => Promise<unknown>;\n\n/** Who the host signs as: the principal a target document must grant. */\nexport interface ReactorIdentity {\n address: string | null;\n key: string;\n}\n\n/** What the editor needs to decide on sign-in and grants (ADR 0005 §8). */\nexport interface ReactorAccessInfo {\n authEnforcement: boolean;\n authConditions: boolean;\n identity: ReactorIdentity | null;\n}\n\n// Strict when the host does not say.\nconst UNKNOWN_ACCESS: ReactorAccessInfo = {\n authEnforcement: true,\n authConditions: false,\n identity: null,\n};\n\nfunction signedIn(ctx: Context): boolean {\n return Boolean(ctx.user?.address);\n}\n\nexport interface OAuthRouting {\n // Absolute, or a bare path when the host's public origin is unknown.\n callbackUrl: string;\n}\n\nfunction isAbsolute(url: string): boolean {\n return /^https?:\\/\\//i.test(url);\n}\n\n// The redirect a sign-in uses: the host's own when it knows its origin,\n// otherwise the caller's, provided it names this host's callback path.\nfunction redirectUriFor(\n routing: OAuthRouting | undefined,\n requested: string | null | undefined,\n): string {\n if (!routing) throw new GraphQLError(\"This host serves no OAuth2 callback\");\n if (isAbsolute(routing.callbackUrl)) return routing.callbackUrl;\n if (!requested) {\n throw new GraphQLError(\n \"This host does not know its public URL; pass redirectUri\",\n );\n }\n let url: URL;\n try {\n url = new URL(requested);\n } catch {\n throw new GraphQLError(`\"${requested}\" is not a URL`);\n }\n if (\n (url.protocol !== \"https:\" && url.protocol !== \"http:\") ||\n url.pathname !== routing.callbackUrl ||\n url.search !== \"\" ||\n url.hash !== \"\"\n ) {\n throw new GraphQLError(\n `redirectUri must be this host's ${routing.callbackUrl}`,\n );\n }\n return url.href;\n}\n\n// Only back to the page that asked: its Origin header is the browser's.\nfunction returnUrlFor(\n requested: string | null | undefined,\n ctx: Context,\n): string | undefined {\n if (!requested) return undefined;\n const origin = ctx.headers.origin;\n let url: URL | undefined;\n try {\n url = new URL(requested);\n } catch {\n url = undefined;\n }\n if (!url || !origin || url.origin !== origin) {\n throw new GraphQLError(\"returnUrl must be on the requesting page's origin\");\n }\n return url.href;\n}\n\nexport const getResolvers = (\n runtime: WorkflowRuntimeService,\n authorizationService: IAuthorizationService,\n oauth?: OAuthRouting,\n access: ReactorAccessInfo = UNKNOWN_ACCESS,\n // The subgraph's own read gate; fields that need it refuse without one.\n assertCanRead?: ReadAssertion,\n): Record<string, unknown> => {\n return {\n Query: {\n workflowRuntime: () => ({}),\n },\n WorkflowRuntimeQueries: {\n health: () => \"ok\",\n authEnforcement: () => access.authEnforcement,\n reactorIdentity: (_parent: unknown, _args: unknown, ctx: Context) =>\n signedIn(ctx) ? access.identity : null,\n authConditions: (_parent: unknown, _args: unknown, ctx: Context) =>\n signedIn(ctx) ? access.authConditions : null,\n reactorAccessDenial: async (\n _parent: unknown,\n args: { workflowId: string },\n ctx: Context,\n ) => {\n if (!assertCanRead) throw new GraphQLError(\"No read check configured\");\n await assertCanRead(args.workflowId, ctx);\n return runtime.reactorAccessDenial(args.workflowId) ?? null;\n },\n blockDescriptor: (_parent: unknown, args: { block: BlockInput }) =>\n runtime.blockDescriptor(blockRef(args.block)),\n blockOptions: (\n _parent: unknown,\n args: {\n block: BlockInput;\n propName: string;\n input?: unknown;\n connectionId?: string | null;\n searchValue?: string | null;\n reactorConnectionId?: string | null;\n },\n ctx: Context,\n ) =>\n runtime.blockOptions(\n blockRef(args.block),\n args.propName,\n args.input,\n args.connectionId ?? undefined,\n ctx,\n args.searchValue ?? undefined,\n args.reactorConnectionId ?? undefined,\n ),\n pieceCatalog: () => runtime.pieceCatalog(),\n pieceActions: (_parent: unknown, args: PieceArgs) =>\n runtime.pieceActions(args.packageName, args.version ?? undefined),\n pieceTriggers: (_parent: unknown, args: PieceArgs) =>\n runtime.pieceTriggers(args.packageName, args.version ?? undefined),\n blockOutputTree: (\n _parent: unknown,\n args: { block: BlockInput; config?: unknown },\n ) => runtime.blockOutputTree(blockRef(args.block), args.config),\n stepOutputTree: (\n _parent: unknown,\n args: { workflowId: string; stepId: string },\n ctx: Context,\n ) => runtime.stepOutputTree(args.workflowId, args.stepId, ctx),\n blockResolutions: (\n _parent: unknown,\n args: { workflowId: string },\n ctx: Context,\n ) => runtime.blockResolutions(args.workflowId, ctx),\n pieceDetail: (_parent: unknown, args: PieceArgs) =>\n runtime.pieceDetail(args.packageName, args.version ?? undefined),\n searchPieces: (\n _parent: unknown,\n args: {\n query: string;\n kind: string;\n sources?: string[] | null;\n categories?: string[] | null;\n limit?: number | null;\n },\n ) => {\n // A misspelt value would otherwise widen the search without a word.\n if (args.kind !== \"action\" && args.kind !== \"trigger\") {\n throw new GraphQLError(\n `A search's kind is \"action\" or \"trigger\", got \"${args.kind}\"`,\n );\n }\n const unknown = (args.sources ?? []).filter(\n (source) => !isPieceSource(source),\n );\n if (unknown.length > 0) {\n throw new GraphQLError(\n `A search's sources are ${PIECE_SOURCES.join(\", \")}, got ${unknown.join(\", \")}`,\n );\n }\n return runtime.searchPieces(args.query, {\n kind: args.kind,\n sources: (args.sources ?? []).filter(isPieceSource),\n categories: args.categories ?? undefined,\n limit: args.limit ?? undefined,\n });\n },\n connections: (_parent: unknown, _args: unknown, ctx: Context) =>\n runtime.connections(ctx),\n webhookEndpoint: (\n _parent: unknown,\n args: { workflowId: string; driveId?: string | null },\n ctx: Context,\n ) =>\n syncAware(() =>\n runtime.webhookEndpoint(args.workflowId, ctx, {\n driveId: args.driveId ?? undefined,\n }),\n ),\n secret: async (_parent: unknown, args: { ref: string }) => {\n try {\n return await (await runtime.secrets()).stat(args.ref);\n } catch {\n // Unknown or malformed ref reads as \"no such secret\".\n return null;\n }\n },\n secrets: async () => (await runtime.secrets()).list(),\n oauthRedirectUri: () => oauth?.callbackUrl ?? null,\n oauthAttempt: (_parent: unknown, args: { state: string }, ctx: Context) =>\n runtime.oauthAttempt(args.state, ctx),\n triggerStates: async (_parent: unknown, _args: unknown, ctx: Context) =>\n (await runtime.triggerStates(ctx)).map((row) => ({\n workflowId: row.workflow_id,\n pieceName: row.piece_name,\n triggerName: row.trigger_name,\n status: row.status,\n intervalMs: row.interval_ms,\n nextPollAt: row.next_poll_at,\n lastPollAt: row.last_poll_at,\n lastError: row.last_error,\n consecutiveFailures: row.consecutive_failures,\n nextRenewAt: row.next_renew_at,\n renewError: row.renew_error,\n renewFailures: row.renew_failures,\n pieceVersion: row.piece_version,\n pieceSource: row.piece_source,\n versionMatch: row.version_match,\n versionNote: row.version_note,\n })),\n runs: async (\n _parent: unknown,\n args: RunsArgs,\n ctx: Context,\n info?: GraphQLResolveInfo,\n ) =>\n (\n await runtime.runs(\n { ...args, withStepData: readsStepData(info, []) },\n ctx,\n )\n ).map((record) => toRunRecord(record.row, record.steps)),\n runsPage: async (\n _parent: unknown,\n args: RunsPageArgs,\n ctx: Context,\n info?: GraphQLResolveInfo,\n ) => {\n const { paging, ...scope } = args;\n const page = await cursorAware(() =>\n runtime.runsPage(\n {\n ...scope,\n limit: paging?.limit ?? undefined,\n cursor: paging?.cursor ?? null,\n withStepData: readsStepData(info, [\"items\"]),\n },\n ctx,\n ),\n );\n return {\n items: page.records.map((record) =>\n toRunRecord(record.row, record.steps),\n ),\n hasNextPage: page.hasNextPage,\n hasPreviousPage: Boolean(paging?.cursor),\n cursor: page.cursor,\n };\n },\n run: async (_parent: unknown, args: { id: string }, ctx: Context) => {\n const record = await runtime.run(args.id, ctx);\n return record ? toRunRecord(record.row, record.steps) : null;\n },\n },\n Mutation: {\n workflowRuntime: () => ({}),\n },\n WorkflowRuntimeMutations: {\n fire: (_parent: unknown, args: FireArgs, ctx: Context) =>\n runtime.fire(args.workflowId, args.payload, \"manual\", undefined, ctx),\n testTrigger: (\n _parent: unknown,\n args: {\n workflowId: string;\n payload?: unknown;\n timeoutSeconds?: number | null;\n driveId?: string | null;\n },\n ctx: Context,\n ) =>\n syncAware(() =>\n runtime.testTrigger(args.workflowId, ctx, {\n ...(args.payload !== undefined ? { payload: args.payload } : {}),\n ...(typeof args.timeoutSeconds === \"number\"\n ? { timeoutMs: args.timeoutSeconds * 1000 }\n : {}),\n driveId: args.driveId ?? undefined,\n }),\n ),\n cancelTriggerTest: (\n _parent: unknown,\n args: { workflowId: string },\n ctx: Context,\n ) => runtime.cancelTriggerTestFor(args.workflowId, ctx),\n testStep: (\n _parent: unknown,\n args: { workflowId: string; stepId: string; driveId?: string | null },\n ctx: Context,\n ) =>\n syncAware(() =>\n runtime.testStep(args.workflowId, args.stepId, ctx, {\n driveId: args.driveId ?? undefined,\n }),\n ),\n rerun: (_parent: unknown, args: { runId: string }, ctx: Context) =>\n runtime.rerun(args.runId, ctx),\n createSecret: async (\n _parent: unknown,\n args: { value: string; label?: string | null },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n return (await runtime.secrets()).create({\n value: args.value,\n label: args.label ?? undefined,\n });\n },\n rotateSecret: async (\n _parent: unknown,\n args: { ref: string; value: string },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n return (await runtime.secrets()).rotate(args.ref, args.value);\n },\n deleteSecret: async (\n _parent: unknown,\n args: { ref: string },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n await (await runtime.secrets()).delete(args.ref);\n return true;\n },\n checkConnection: (\n _parent: unknown,\n args: { connectionId: string },\n ctx: Context,\n ) => runtime.checkConnection(args.connectionId, ctx),\n // Signing in mints a secret, so it takes what createSecret takes.\n startOAuth: (\n _parent: unknown,\n args: {\n connectionId: string;\n redirectUri?: string | null;\n returnUrl?: string | null;\n },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n const returnUrl = returnUrlFor(args.returnUrl, ctx);\n return runtime.startOAuth(args.connectionId, ctx, {\n redirectUri: redirectUriFor(oauth, args.redirectUri),\n ...(returnUrl ? { returnUrl } : {}),\n });\n },\n },\n };\n};\n","import type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nexport const schema: DocumentNode = gql`\n \"\"\"\n WorkflowRuntime Queries\n \"\"\"\n type WorkflowRuntimeQueries {\n health: String!\n \"\"\"\n Whether this reactor enforces document auth (REACTOR_AUTH_ENFORCEMENT).\n On, a workflow needs a signed publish, and the host grants, to reach\n documents. Answered to any caller.\n \"\"\"\n authEnforcement: Boolean!\n \"\"\"\n Who this host signs as: grant it on each document a step writes. Null for\n a caller who is not signed in, or a host with no signer.\n \"\"\"\n reactorIdentity: ReactorIdentity\n \"\"\"\n REACTOR_AUTH_CONDITIONS. True: grant the host by key, with\n { match: subject.key == key }; false: by address. Null for a caller who\n is not signed in.\n \"\"\"\n authConditions: Boolean\n \"\"\"\n Why the workflow's last publish or enable got no reactor access, naming\n the publisher and the connection; null when the check passed.\n \"\"\"\n reactorAccessDenial(workflowId: String!): String\n \"\"\"\n Persisted runs, newest first. Scope them to one workflow, or to every\n workflow a drive holds; workflowId wins when both are given.\n \"\"\"\n runs(\n workflowId: String\n driveId: String\n limit: Int\n \"Trigger kinds to leave out, e.g. test.\"\n excludeTriggerKinds: [String!]\n ): [WorkflowRunRecord!]!\n \"\"\"\n The same listing a page at a time, newest journaled first. Pass a page's\n cursor back in paging to read the next; a page is short only when\n hasNextPage is false, or when the caller could read none of a long\n stretch of runs. A run that starts between pages keeps its place.\n \"\"\"\n runsPage(\n workflowId: String\n driveId: String\n excludeTriggerKinds: [String!]\n paging: WorkflowRunsPagingInput\n ): WorkflowRunResultPage!\n run(id: String!): WorkflowRunRecord\n \"\"\"\n The descriptor (props, auth, ports) of one action or trigger, as the\n version that runs it describes it; triggers come back under \"trigger\".\n \"\"\"\n blockDescriptor(block: BlockInput!): Unknown\n \"\"\"\n Resolves a dynamic prop against the current config values: a DROPDOWN\n yields { options, placeholder, disabled }, a DYNAMIC prop yields the\n resolved sub-property descriptor list.\n \"\"\"\n blockOptions(\n block: BlockInput!\n propName: String!\n input: Unknown\n connectionId: String\n \"What the author typed, for a DROPDOWN declared with refreshOnSearch.\"\n searchValue: String\n \"The step's reactor connection; its filter narrows what the resolver reads.\"\n reactorConnectionId: String\n ): Unknown\n \"\"\"\n Every piece this reactor offers: the core piece, its package pieces, and\n the pieces the registry and Activepieces publish.\n \"\"\"\n pieceCatalog: Unknown\n \"\"\"\n A piece's actions at one version; pin a step to that version.\n \"\"\"\n pieceActions(\n packageName: String!\n \"That version; the installed or latest one when omitted.\"\n version: String\n ): Unknown\n \"\"\"\n A piece's triggers at one version; pin a trigger to that version.\n \"\"\"\n pieceTriggers(\n packageName: String!\n \"That version; the installed or latest one when omitted.\"\n version: String\n ): Unknown\n \"\"\"\n Full piece detail (PieceMetadataModel-shaped), verbatim from the cloud API.\n \"\"\"\n pieceDetail(\n packageName: String!\n \"That version; the installed or latest one when omitted.\"\n version: String\n ): Unknown\n \"\"\"\n Piece and block search across the catalog, grouped by piece. The index\n builds lazily on first use; poll while status is \"indexing\".\n \"\"\"\n searchPieces(\n query: String!\n \"action | trigger\"\n kind: String!\n \"local | registry | activepieces; all when omitted.\"\n sources: [String!]\n \"Category ids, any of; all when omitted.\"\n categories: [String!]\n \"Pieces returned.\"\n limit: Int\n ): PieceSearchResult!\n \"\"\"\n Health of every registered piece trigger (poll schedule, errors).\n \"\"\"\n triggerStates: [TriggerStateRecord!]!\n \"\"\"\n Authored output shape of a block (SDL / outputSchema / sampleData).\n \"\"\"\n blockOutputTree(block: BlockInput!, config: Unknown): Unknown\n \"\"\"\n Output shape of a draft step or trigger: its latest test output\n (source \"test\", with sample and testedAt) when tested, else as blockOutputTree.\n \"\"\"\n stepOutputTree(workflowId: String!, stepId: String!): Unknown\n \"\"\"\n Every block of the draft (trigger first) as this reactor resolves it:\n which piece version runs, from where, and how it matches the pin.\n \"\"\"\n blockResolutions(workflowId: String!): [BlockResolutionRecord!]!\n \"\"\"\n Every powerhouse/connection document, for connection pickers.\n \"\"\"\n connections: [ConnectionRecord!]!\n \"\"\"\n The webhook endpoint for a workflow: the URL to hand the provider. Minted\n on first ask, whether or not the workflow is armed — an author needs the\n URL before enabling, and the armed field carries that difference. Null\n only when the host has no webhook service. With driveId, a workflow not\n synced here yet is waited for briefly, then fails as WORKFLOW_SYNCING.\n \"\"\"\n webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord\n \"\"\"\n Secret metadata (label, version, status). Never the value.\n \"\"\"\n secret(ref: String!): SecretRecord\n secrets: [SecretRecord!]!\n \"\"\"\n The URL an OAuth2 app must register as its redirect. A bare path when\n this host does not know its public origin; resolve it against the URL\n this API is reached at. Null when the host serves no HTTP routes.\n \"\"\"\n oauthRedirectUri: String\n \"\"\"\n How an OAuth2 sign-in opened by startOAuth stands; null when unknown.\n \"\"\"\n oauthAttempt(state: String!): OAuthAttempt\n }\n\n type OAuthAttempt {\n connectionId: String!\n \"PENDING | EXCHANGING | OK | ERROR\"\n status: String!\n error: String\n }\n\n type OAuthStart {\n state: String!\n \"Where to send the user to sign in.\"\n authorizationUrl: String!\n redirectUri: String!\n expiresAt: String!\n }\n\n \"\"\"\n One action or trigger of a piece, as a workflow pins it. The engine's own\n blocks are the piece @powerhousedao/piece-core.\n \"\"\"\n input BlockInput {\n pieceName: String!\n \"Exact semver.\"\n pieceVersion: String!\n \"The action or trigger name.\"\n name: String!\n \"action | trigger\"\n kind: String!\n }\n\n type BlockSearchHit {\n pieceName: String!\n \"The version the hit is listed at; pin to it when picking the block.\"\n pieceVersion: String!\n \"The action or trigger name.\"\n name: String!\n pieceDisplayName: String!\n logoUrl: String!\n displayName: String!\n description: String!\n \"action | trigger\"\n kind: String!\n \"Triggers only: POLLING | WEBHOOK | APP_WEBHOOK | MANUAL\"\n strategy: String\n \"Why this block cannot run on this reactor; null when it can.\"\n unsupported: String\n }\n\n type BlockResolutionRecord {\n \"The trigger's or step's id.\"\n stepId: String!\n pieceName: String!\n \"The version the block pins.\"\n pieceVersion: String!\n \"The action or trigger name.\"\n name: String!\n \"action | trigger\"\n kind: String!\n \"The version that runs; null when nothing resolves.\"\n resolvedVersion: String\n \"local | registry | activepieces | npm; null when nothing resolves.\"\n source: String\n \"exact | compatible | fallback | installed | missing\"\n match: String!\n \"Why the version that runs differs from the pin, or why nothing resolves.\"\n note: String\n \"The newest version any source offers.\"\n latestVersion: String\n }\n\n type PieceSearchMatch {\n pieceName: String!\n pieceVersion: String!\n displayName: String!\n description: String!\n logoUrl: String!\n categories: [String!]!\n \"local | registry | activepieces\"\n source: String!\n deprecated: Boolean\n \"Why no block of the piece can run on this reactor.\"\n unsupported: String\n \"Every query token matched the piece's own name.\"\n namedPiece: Boolean!\n \"Matching blocks of the kind asked for, best first.\"\n blocks: [BlockSearchHit!]!\n }\n\n type PieceSearchResult {\n \"ready | indexing | error\"\n status: String!\n pieces: [PieceSearchMatch!]!\n indexedPieces: Int!\n error: String\n }\n\n type SecretRecord {\n ref: String!\n label: String\n version: Int!\n status: String!\n createdAt: String!\n updatedAt: String!\n }\n\n type ConnectionRecord {\n id: String!\n name: String!\n connectorId: String!\n authType: String!\n status: String!\n accountLabel: String\n }\n\n type ReactorIdentity {\n \"The address the host signs as; null without a signed-in identity.\"\n address: String\n \"The did:key that signs the host's operations.\"\n key: String!\n }\n\n type ConnectionCheckResult {\n ok: Boolean!\n detail: String\n \"\"\"\n From auth.getConnectionIdentifier when the check passes; otherwise the\n label the connection already holds.\n \"\"\"\n accountLabel: String\n }\n\n type WebhookEndpointRecord {\n workflowId: String!\n url: String!\n \"\"\"\n False when the host gave the webhook service no public origin, so the url\n above is a bare path. Switchboard always gives one, falling back to\n http://localhost:<port> when PUBLIC_URL is unset.\n \"\"\"\n absoluteUrl: Boolean!\n \"True while the workflow is ENABLED with a valid webhook trigger\"\n armed: Boolean!\n createdAt: String!\n }\n\n type TriggerStateRecord {\n workflowId: String!\n pieceName: String!\n triggerName: String!\n status: String!\n intervalMs: Int!\n nextPollAt: String\n lastPollAt: String\n lastError: String\n consecutiveFailures: Int!\n \"When a webhook trigger next renews its subscription; null if it never does.\"\n nextRenewAt: String\n \"The last failed renewal, kept apart from lastError, the poll's.\"\n renewError: String\n renewFailures: Int!\n \"The piece version the trigger armed with; null for a host-fed trigger.\"\n pieceVersion: String\n pieceSource: String\n versionMatch: String\n versionNote: String\n }\n\n type Query {\n workflowRuntime: WorkflowRuntimeQueries!\n }\n\n type WorkflowStepRunRecord {\n stepId: String!\n stepKey: String!\n pieceName: String!\n \"The action the step ran, or the trigger a trigger test sampled.\"\n blockName: String!\n status: String!\n input: Unknown\n output: Unknown\n port: String\n error: String\n \"The thrown error's name, e.g. ReactorAccessDeniedError.\"\n errorName: String\n startedAt: String\n endedAt: String\n \"The piece version that ran; null for an unresolved block.\"\n pieceVersion: String\n \"local | registry | activepieces | npm\"\n pieceSource: String\n \"exact | compatible | fallback | installed | missing\"\n versionMatch: String\n \"Why the version that ran differs from the pin.\"\n versionNote: String\n }\n\n type WorkflowRunRecord {\n id: String!\n workflowId: String!\n workflowName: String!\n workflowVersion: Int!\n triggerKind: String!\n triggerPayload: Unknown\n status: String!\n error: String\n errorName: String\n \"When the run began executing; a PENDING run's is when it was journaled.\"\n startedAt: String!\n endedAt: String\n rerunOf: String\n \"How many warningNotes the run has; a run with any is not a plain success.\"\n warnings: Int!\n \"Steps that ran a fallback piece version, edges on ports nothing emits.\"\n warningNotes: [String!]!\n steps: [WorkflowStepRunRecord!]!\n }\n\n input WorkflowRunsPagingInput {\n \"Page size; default 25, at most 100.\"\n limit: Int\n \"The cursor of the previous page.\"\n cursor: String\n }\n\n type WorkflowRunResultPage {\n items: [WorkflowRunRecord!]!\n hasNextPage: Boolean!\n \"True when the page was read after a cursor.\"\n hasPreviousPage: Boolean!\n \"Resumes after this page's last run; null for an empty page.\"\n cursor: String\n }\n\n type WorkflowStepRun {\n stepId: String!\n key: String!\n pieceName: String!\n blockName: String!\n status: String!\n input: Unknown\n output: Unknown\n port: String\n error: String\n errorName: String\n }\n\n type WorkflowRunPayload {\n runId: String\n status: String!\n error: String\n errorName: String\n steps: [WorkflowStepRun!]!\n }\n\n type WorkflowStepTestResult {\n \"Null when the test never started, e.g. an upstream block is untested.\"\n runId: String\n \"\"\"\n SUCCEEDED | FAILED | INDETERMINATE. INDETERMINATE is neither: a host call\n the block made timed out, so a write it asked for may well have landed.\n Show it distinctly - it is not a confirmed pass.\n \"\"\"\n status: String!\n output: Unknown\n error: String\n errorName: String\n durationMs: Int!\n }\n\n \"\"\"\n WorkflowRuntime Mutations\n \"\"\"\n type WorkflowRuntimeMutations {\n \"\"\"\n Fires a workflow's manual trigger (the core piece's) and runs it to completion.\n \"\"\"\n fire(workflowId: String!, payload: Unknown): WorkflowRunPayload!\n \"\"\"\n Samples the draft trigger and saves it as the trigger's last test. A piece\n trigger runs its test hook (no cursor changes). Of the core piece's\n triggers, manual takes payload, schedule samples a fire now, and webhook\n waits for the next delivery to the workflow's endpoint, up to\n timeoutSeconds (default and cap 300), and that delivery runs nothing.\n \"\"\"\n testTrigger(\n workflowId: String!\n payload: Unknown\n timeoutSeconds: Int\n driveId: String\n ): Unknown\n \"\"\"\n Stops a webhook trigger test that is waiting; false when none was.\n \"\"\"\n cancelTriggerTest(workflowId: String!): Boolean!\n \"\"\"\n Runs one draft step against the latest test outputs of the blocks it\n reads, journaled as a \"test\" run and noted as the step's lastTest.\n driveId waits for an unsynced workflow, as for webhookEndpoint.\n \"\"\"\n testStep(\n workflowId: String!\n stepId: String!\n driveId: String\n ): WorkflowStepTestResult!\n \"\"\"\n Resumes a FAILED run: succeeded steps replay from the journal,\n execution restarts at the failure. Produces a new run.\n \"\"\"\n rerun(runId: String!): WorkflowRunPayload!\n \"\"\"\n Mints a managed secret and returns its ref; the value is stored\n encrypted and is never readable back over any API.\n \"\"\"\n createSecret(value: String!, label: String): SecretRecord!\n \"\"\"\n Replaces the value behind an existing ref; documents stay untouched.\n \"\"\"\n rotateSecret(ref: String!, value: String!): SecretRecord!\n \"\"\"\n Tombstones a secret; its value becomes unrecoverable.\n \"\"\"\n deleteSecret(ref: String!): Boolean!\n \"\"\"\n Runs the piece's auth.validate against the connection's credentials,\n then auth.getConnectionIdentifier for the account label, and records the\n outcome on the connection document.\n \"\"\"\n checkConnection(connectionId: String!): ConnectionCheckResult!\n \"\"\"\n Opens an OAuth2 sign-in with the connection's own app (client_id in its\n config, client_secret in its secretRefs). redirectUri is needed only when\n oauthRedirectUri is a bare path. With returnUrl, which must be on the\n caller's origin, the callback sends the browser back there with\n ?ph_oauth=<state> instead of closing the window.\n \"\"\"\n startOAuth(\n connectionId: String!\n redirectUri: String\n returnUrl: String\n ): OAuthStart!\n }\n\n type Mutation {\n workflowRuntime: WorkflowRuntimeMutations!\n }\n`;\n","import { BaseSubgraph, type SubgraphClass } from \"@powerhousedao/reactor-api\";\nimport type { WorkflowRuntimeService } from \"@powerhousedao/reactor-workflow\";\nimport type { DocumentNode } from \"graphql\";\nimport {\n getResolvers,\n type OAuthRouting,\n type ReactorAccessInfo,\n} from \"./resolvers.js\";\nimport { schema } from \"./schema.js\";\n\n/** The runtime's read/write surface. The runtime itself is composed by the\n * host, so the subgraph only serves what it is handed. */\nexport function createWorkflowRuntimeSubgraph(\n runtime: WorkflowRuntimeService,\n oauth?: OAuthRouting,\n access?: ReactorAccessInfo,\n): SubgraphClass {\n return class WorkflowRuntimeSubgraph extends BaseSubgraph {\n name = \"workflow-runtime\";\n typeDefs: DocumentNode = schema;\n // A field initializer runs after super(), so the authorization service\n // the secret mutations gate on is already in place.\n resolvers = getResolvers(\n runtime,\n this.authorizationService,\n oauth,\n access,\n (documentId, ctx) => this.assertCanRead(documentId, ctx),\n );\n additionalContextFields = {};\n };\n}\n","// Switchboard composes the workflow runtime from what it holds (the reactor\n// module) and what startAPI hands back. The intake is a read model.\nimport {\n REACTOR_SCHEMA,\n supportsLiveReadModelRegistration,\n type AttachmentRef,\n type DocumentViewDatabase,\n type InProcessReactorClientModule,\n type IReactorClient,\n type IRelationalDb,\n type ModelManifestEntry,\n type ReactorBuilder,\n} from \"@powerhousedao/reactor\";\nimport {\n AuthorizationPolicy,\n ForbiddenError,\n callerSubject,\n createCanonicalDocumentIdResolver,\n type CanonicalDocumentId,\n type Context,\n type IAttachmentAccessService,\n type IAuthorizationService,\n type IPackagePieceSource,\n type PackagePieceEntry,\n type SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport { parseRef } from \"@powerhousedao/reactor-attachments\";\nimport type * as WorkflowEngine from \"@powerhousedao/reactor-workflow\";\nimport type {\n AttachmentClientLike,\n AttachmentReadRequest,\n HostIdentity,\n WorkflowCaller,\n WorkflowRuntimeHostDeps,\n} from \"@powerhousedao/reactor-workflow\";\nimport type {\n IHttpScope,\n IWebhookScope,\n ScopedRouteHandle,\n} from \"@powerhousedao/shared/processors\";\nimport type { Principal } from \"@powerhousedao/shared/document-model\";\nimport type { ILogger } from \"document-model\";\nimport type { Kysely } from \"kysely\";\nimport {\n callbackUrlOf,\n registerOAuthCallback,\n} from \"./workflow/oauth-callback.js\";\nimport type {\n ReactorAccessInfo,\n ReactorIdentity,\n} from \"./workflow/resolvers.js\";\nimport { triggerFatalShutdown } from \"./fatal-shutdown.mjs\";\nimport { createWorkflowRuntimeSubgraph } from \"./workflow/subgraph.js\";\n\ntype WorkflowEngineModule = typeof WorkflowEngine;\n\n/** The npm name the workflow package owns: its HTTP namespace and its models. */\nexport const WORKFLOW_PACKAGE_NAME = \"@powerhousedao/workflow\";\nexport const WORKFLOW_TELEMETRY_SCOPE = \"@powerhousedao/reactor-workflow\";\n\n/** The env var and OpenFeature flag key that turns workflows on. */\nexport const PH_WORKFLOWS_ENABLED = \"PH_WORKFLOWS_ENABLED\";\n\n/** Whether the operation intake is indexing. Same shape as the attachment\n * reference projection, because it is the same limitation. */\nexport type WorkflowTriggersCapability =\n | { status: \"available\" }\n | {\n status: \"unavailable\";\n reason:\n | \"in-process-reactor-module-unavailable\"\n | \"live-read-model-registration-unsupported\"\n | \"workflow-singleton-lost\";\n };\n\nconst SINGLETON_LOST: WorkflowTriggersCapability = {\n status: \"unavailable\",\n reason: \"workflow-singleton-lost\",\n};\n\n/** The slice of switchboard's OpenFeature client this needs. */\nexport interface BooleanFlagSource {\n getBooleanValue(flagKey: string, defaultValue: boolean): Promise<boolean>;\n}\n\nexport interface WorkflowsFlagInput {\n featureFlags: BooleanFlagSource;\n /** The host's own answer; wins over everything. */\n override?: boolean;\n /** `workflows.enabled` from the powerhouse config file. */\n configEnabled?: boolean;\n /** Defaults to process.env; the tests pass their own. */\n env?: Record<string, string | undefined>;\n}\n\n/** Precedence, unchanged from the reactor-api resolver this replaces: the\n * host's option, then PH_WORKFLOWS_ENABLED, then the config file, then off. */\nexport async function resolveWorkflowsEnabled({\n featureFlags,\n override,\n configEnabled = false,\n env = process.env,\n}: WorkflowsFlagInput): Promise<boolean> {\n if (override !== undefined) return override;\n\n // The env layer is switchboard's OpenFeature client, which casts only\n // \"true\"/\"false\": the numeric forms reactor-api took are answered here.\n const raw = env[PH_WORKFLOWS_ENABLED]?.trim();\n if (raw === \"1\") return true;\n if (raw === \"0\") return false;\n\n return featureFlags.getBooleanValue(PH_WORKFLOWS_ENABLED, configEnabled);\n}\n\n// The package manager reports an unresolvable package and continues; for one\n// the host added itself that is a misconfigured switchboard, not a degraded\n// one. The manager imports this subpath moments later, so the cache absorbs it.\nexport async function assertWorkflowPackageLoadable(\n load: () => Promise<unknown> = () =>\n import(\"@powerhousedao/workflow/document-models\"),\n): Promise<void> {\n try {\n await load();\n } catch (error) {\n throw new Error(\n `Workflows are enabled but ${WORKFLOW_PACKAGE_NAME} could not be loaded`,\n { cause: error },\n );\n }\n}\n\n/**\n * Whether a composition failure was the workflow singleton refusing this\n * process, rather than something that should take the boot down.\n *\n * Matched by NAME: the engine loads lazily, and importing it here for the\n * constructor would defeat that. The fields the engine's error carries are\n * typed optional for the same reason.\n */\nexport function isWorkflowSingletonConflict(\n error: unknown,\n): error is Error & { owner?: string; expiresAt?: string; wouldBe?: string } {\n return (\n error instanceof Error && error.name === \"WorkflowSingletonConflictError\"\n );\n}\n\n/** How often a host refused the singleton at boot tries the claim again: the\n * engine's renewal period. */\nexport const WORKFLOW_SINGLETON_RETRY_MS = 20_000;\n\nexport interface WorkflowSingletonRetry {\n /** Stops retrying; waits for an attempt in flight, and stops what it\n * composed if the host is going away. */\n stop(): Promise<void>;\n}\n\n/**\n * Retries the singleton claim for a host that booted without it, and hands\n * the runtime over once a claim succeeds.\n *\n * Without it a rolling deploy whose slots have different owner names ends\n * with nobody running workflows: the new pod is refused while the old one\n * still holds the lease, and nothing retries once the old pod releases it.\n * Only for a host that never composed; one that lost the lease after\n * composing stays without workflows until it restarts.\n */\nexport function retryWorkflowSingleton(options: {\n compose: () => Promise<ComposedWorkflowRuntime>;\n onComposed: (workflows: ComposedWorkflowRuntime) => Promise<void>;\n logger: ILogger;\n intervalMs?: number;\n}): WorkflowSingletonRetry {\n const intervalMs = options.intervalMs ?? WORKFLOW_SINGLETON_RETRY_MS;\n let stopped = false;\n let timer: NodeJS.Timeout | undefined;\n let attempt: Promise<void> | undefined;\n\n const run = async () => {\n let workflows: ComposedWorkflowRuntime;\n try {\n workflows = await options.compose();\n } catch (error) {\n if (!isWorkflowSingletonConflict(error)) {\n options.logger.error(\n \"Composing the workflow runtime after the singleton came free failed: @error\",\n error,\n );\n }\n schedule();\n return;\n }\n if (stopped) {\n await workflows.stop();\n return;\n }\n options.logger.info(\n \"Claimed the workflow singleton after boot; starting the workflow runtime\",\n );\n try {\n await options.onComposed(workflows);\n } catch (error) {\n options.logger.error(\n \"Starting the workflow runtime after the singleton came free failed: @error\",\n error,\n );\n schedule();\n }\n };\n\n const schedule = () => {\n if (stopped) return;\n timer = setTimeout(() => {\n timer = undefined;\n attempt = run().finally(() => {\n attempt = undefined;\n });\n }, intervalMs);\n timer.unref();\n };\n\n schedule();\n return {\n async stop() {\n stopped = true;\n if (timer) clearTimeout(timer);\n timer = undefined;\n await attempt?.catch(() => undefined);\n },\n };\n}\n\n/**\n * What a host does once its composed runtime has shut down for losing the\n * workflow singleton.\n *\n * Taken over by another claim: that process runs workflows now, so this one\n * stays without them until it restarts. Unrenewable with no takeover seen (a\n * database blip): nothing else runs them, so the process goes down through\n * the fatal shutdown and its supervisor restarts it, which re-claims at boot.\n * A host with no fatal shutdown installed (embedded) stays without workflows\n * and says a restart is needed.\n */\nexport function workflowSingletonLossHandler(\n logger: ILogger,\n fatal: (kind: string, error: unknown) => boolean = triggerFatalShutdown,\n): (loss: WorkflowEngine.WorkflowSingletonLoss) => void {\n return (loss) => {\n if (loss.reason === \"taken\") {\n logger.error(\n `Another process (\"${loss.heldBy ?? \"unknown\"}\") took the workflow ` +\n \"singleton. This Switchboard has stopped its workflow runtime \" +\n \"and runs no workflows until it is restarted; everything else \" +\n \"serves normally.\",\n );\n return;\n }\n const error = new Error(\n \"The workflow singleton lease could not be renewed for \" +\n `${Math.round(loss.silentMs)}ms; no other process was seen taking it ` +\n \"over\",\n );\n if (fatal(\"Workflow singleton lease unrenewable\", error)) return;\n logger.error(\n `${error.message}. This Switchboard has stopped its workflow runtime ` +\n \"and runs no workflows until it is restarted.\",\n );\n };\n}\n\n/** The importable models piece workers load: the boot list, and a type's entries. */\nexport interface ModelManifestSource {\n modelManifest(): ModelManifestEntry[];\n modelEntries(documentType: string): ModelManifestEntry[];\n}\n\nexport function modelManifestSource(\n builder: Pick<\n ReactorBuilder,\n \"getResolvedModelManifest\" | \"getImportableEntries\"\n >,\n): ModelManifestSource {\n return {\n modelManifest: () => builder.getResolvedModelManifest() ?? [],\n modelEntries: (documentType) => builder.getImportableEntries(documentType),\n };\n}\n\nexport interface ComposeWorkflowRuntimeDeps {\n reactorClient: IReactorClient;\n /** The registry this host installs packages from; pieces come from it too.\n * Absent on a host that installs from none, and only the cloud is read. */\n pieceRegistryUrl?: string;\n /** Where the trigger read model registers; absent leaves the intake\n * unavailable rather than quietly dropping every document trigger. */\n clientModule?: InProcessReactorClientModule;\n relationalDb: IRelationalDb;\n /** False when relationalDb outlives the working directory, so the secret\n * store needs PH_WORKFLOWS_SECRETS_MASTER_KEY rather than a generated key. */\n secretsKeyFile?: false;\n attachments: AttachmentClientLike;\n /** Decides a step's attachment reads like the attachment routes do;\n * absent, a step reads none but the files its own run wrote. */\n attachmentAccess?: IAttachmentAccessService;\n webhooks?: IWebhookScope;\n /** The workflow package's HTTP namespace; the OAuth2 callback lives on it.\n * Absent leaves OAuth2 connections unable to sign in. */\n http?: IHttpScope;\n authorizationService: IAuthorizationService;\n /** Where the pieces installed packages ship come from; absent leaves the\n * runtime with none and only published bundles resolvable. */\n pieces?: IPackagePieceSource;\n logger: ILogger;\n /** Absent leaves pieces with no document models in their worker. */\n models?: ModelManifestSource;\n /** The reactor's executor and projection threads, for sizing the piece pool. */\n reactorThreads?: number;\n /** Where run, step, worker and reactor-call spans and metrics go. */\n telemetry?: WorkflowEngine.WorkflowRuntimeHostDeps[\"telemetry\"];\n /** Overridden by the tests; production always loads the real engine. */\n load?: () => Promise<WorkflowEngineModule>;\n /**\n * Whether to claim the workflow singleton before composing (plan agreed\n * decision 3). On by default, and the only honest setting for a real host:\n * two replicas over one run journal fail each other's live runs. A suite\n * that composes several runtimes over separate databases turns it off.\n */\n singletonLease?: boolean;\n /**\n * Where this host's read-model database lives — the Postgres URL, or the\n * absolute PGlite directory. It is the stable half of the default singleton\n * owner name, so a restart of THIS slot re-claims its own lease at once\n * instead of waiting out the 60s TTL for a killed process's claim. Hashed\n * before it is used, so a connection string's credentials go no further.\n */\n storageId?: string;\n /**\n * True when the journal's database is an embedded one no other process can\n * open (PGlite). Nothing can then take the lease, so a renewal that stalls\n * (a busy queue, a blocked event loop) is logged rather than turning\n * workflows off.\n */\n exclusiveJournal?: boolean;\n /** Called once when the composed runtime has shut down for losing the\n * singleton; see {@link workflowSingletonLossHandler}. */\n onSingletonLost?: (loss: WorkflowEngine.WorkflowSingletonLoss) => void;\n}\n\nexport interface ComposedWorkflowRuntime {\n subgraph: SubgraphClass;\n /** Whether document operations reach the runtime at all; unavailable once\n * the singleton is lost. */\n readonly triggers: WorkflowTriggersCapability;\n /** The owner name this host holds the workflow singleton under; undefined\n * when the lease was not taken (a suite that opted out). */\n singletonOwner?: string;\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\n// The engine's own access check, answered as BaseSubgraph answers it: the\n// host ACL (an admin passes, another policy fails closed, an unresolvable\n// identifier is a denial), then the reactor's read gate as the caller.\nfunction readAssertion(\n authorizationService: IAuthorizationService,\n reactorClient: IReactorClient,\n): WorkflowRuntimeHostDeps[\"assertCanRead\"] {\n const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);\n const hostCanRead = async (identifier: string, ctx: Context) => {\n if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;\n if (\n authorizationService.config.policy !==\n AuthorizationPolicy.DOCUMENT_PERMISSIONS\n ) {\n throw new ForbiddenError();\n }\n let documentId: CanonicalDocumentId;\n try {\n documentId = await resolveCanonical(identifier);\n } catch {\n throw new ForbiddenError();\n }\n const canRead = await authorizationService.canRead(\n documentId,\n ctx.user?.address,\n );\n if (!canRead) throw new ForbiddenError(\"to read this document\");\n };\n return async (identifier: string, caller: WorkflowCaller) => {\n const ctx = caller as Context;\n await hostCanRead(identifier, ctx);\n let served: boolean;\n try {\n served = await reactorClient.isServed(identifier, {\n subject: callerSubject(ctx.user),\n });\n } catch {\n throw new ForbiddenError();\n }\n if (!served) throw new ForbiddenError(\"to read this document\");\n };\n}\n\n/** The same, for a design-time call that writes what it names. */\nfunction writeAssertion(\n authorizationService: IAuthorizationService,\n reactorClient: IReactorClient,\n): WorkflowRuntimeHostDeps[\"assertCanWrite\"] {\n const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);\n return async (identifier: string, caller: WorkflowCaller) => {\n const ctx = caller as Context;\n if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;\n if (\n authorizationService.config.policy !==\n AuthorizationPolicy.DOCUMENT_PERMISSIONS\n ) {\n throw new ForbiddenError();\n }\n let documentId: CanonicalDocumentId;\n try {\n documentId = await resolveCanonical(identifier);\n } catch {\n throw new ForbiddenError();\n }\n const canWrite = await authorizationService.canWrite(\n documentId,\n ctx.user?.address,\n );\n if (!canWrite) throw new ForbiddenError(\"to write this document\");\n };\n}\n\n/** What the reactor enforces and who it signs as; unknown counts as enforced. */\nexport function reactorAccessOf(\n clientModule: InProcessReactorClientModule | undefined,\n): ReactorAccessInfo {\n const flags = clientModule?.reactorModule?.featureFlags;\n const signer = clientModule?.signer;\n const key = signer?.app?.key;\n const identity: ReactorIdentity | null = key\n ? { address: signer.user?.address ?? null, key }\n : null;\n return {\n authEnforcement: flags ? flags.authEnforcement : true,\n authConditions: flags?.authConditions === true,\n identity,\n };\n}\n\n/** Whom a run's created documents also grant: the host, as §8 grants it. */\nexport function hostPrincipalOf(\n access: ReactorAccessInfo,\n): Principal | undefined {\n const identity = access.identity;\n if (!identity) return undefined;\n if (access.authConditions) {\n return { match: { eq: [{ attr: \"subject.key\" }, { lit: identity.key }] } };\n }\n return identity.address ? { address: identity.address } : undefined;\n}\n\n/** Who the host signs as, so a publish it signs makes no run user. */\nexport function hostIdentityOf(\n access: ReactorAccessInfo,\n): HostIdentity | undefined {\n const identity = access.identity;\n if (!identity) return undefined;\n return identity.address\n ? { address: identity.address, key: identity.key }\n : { key: identity.key };\n}\n\nconst REFERENCE_INDEX_RETRIES = 8;\nconst REFERENCE_INDEX_RETRY_MS = 250;\n\n/** A step reads an attachment the way the download route serves one: when the\n * run's user may read a document that references it. The candidates are the\n * documents the run was handed; the reference index can trail the operation\n * that fired the trigger, so a denial is retried briefly. */\nexport function attachmentReadPolicy(\n access: IAttachmentAccessService | undefined,\n retryMs = REFERENCE_INDEX_RETRY_MS,\n): (request: AttachmentReadRequest) => Promise<boolean> {\n return async (request) => {\n try {\n if (parseRef(request.ref as AttachmentRef).version !== 1) return false;\n } catch {\n return false;\n }\n if (!access || request.documentIds.length === 0) return false;\n const subject = request.runUser?.subject;\n const caller = {\n ...(subject?.address ? { userAddress: subject.address } : {}),\n ...(subject?.key ? { appKey: subject.key } : {}),\n };\n for (let attempt = 0; attempt <= REFERENCE_INDEX_RETRIES; attempt++) {\n for (const documentId of request.documentIds) {\n const result = await access.canReadAttachment({\n documentId,\n attachmentRef: request.ref,\n ...caller,\n });\n if (result.kind === \"allowed\") return true;\n }\n if (attempt < REFERENCE_INDEX_RETRIES) {\n await new Promise((resolve) => setTimeout(resolve, retryMs));\n }\n }\n return false;\n };\n}\n\n// The trigger read model lives exactly as long as its runtime: tearDown takes\n// it off the coordinator, so a later compose in this process can register.\ninterface TriggersRegistration {\n tornDown: boolean;\n detach?: () => void;\n}\n\n// Live registration is the capability the attachment reference index needs\n// too, so a coordinator without it reads unavailable for the same reason.\nasync function registerWorkflowTriggersReadModel(\n engine: WorkflowEngineModule,\n runtime: WorkflowEngine.WorkflowRuntimeService,\n clientModule: InProcessReactorClientModule | undefined,\n registration: TriggersRegistration,\n): Promise<WorkflowTriggersCapability> {\n const reactorModule = clientModule?.reactorModule;\n if (!reactorModule) {\n return {\n status: \"unavailable\",\n reason: \"in-process-reactor-module-unavailable\",\n };\n }\n\n const coordinator = reactorModule.readModelCoordinator;\n if (!supportsLiveReadModelRegistration(coordinator)) {\n return {\n status: \"unavailable\",\n reason: \"live-read-model-registration-unsupported\",\n };\n }\n\n // Schema-qualified: the cursor row lives in the reactor's own ViewState.\n const readModel = new engine.WorkflowTriggersReadModel(\n (reactorModule.database as unknown as Kysely<unknown>).withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<DocumentViewDatabase>,\n reactorModule.operationIndex,\n reactorModule.writeCache,\n reactorModule.processorManagerConsistencyTracker,\n runtime,\n );\n await readModel.init();\n // Torn down while it replayed: registered now, it would outlive the runtime.\n if (registration.tornDown) return SINGLETON_LOST;\n coordinator.addReadModel(\n readModel,\n engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE,\n );\n registration.detach = () => coordinator.removeReadModel(readModel);\n\n return { status: \"available\" };\n}\n\n// The runtime holds pieces; reactor-api is what resolves them. Rebound on\n// every change, so a package rebuilt while this runs needs no restart.\nexport function bindPackagePieces(\n registry: { setPieces(pieces: readonly PackagePieceEntry[]): void },\n source: IPackagePieceSource,\n): void {\n // Sorted by package name, so which package keeps a contested piece is stable.\n const apply = (byPackage: Map<string, PackagePieceEntry[]>) => {\n registry.setPieces(\n [...byPackage.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .flatMap(([, pieces]) => pieces),\n );\n };\n // The initial load already happened inside startAPI, so what it reported is\n // read here rather than waited for.\n apply(source.getPieces());\n source.onPiecesChange(apply);\n}\n\n// Builds the runtime, registers its intake, and returns its GraphQL face plus\n// the lifecycle the host drives. The engine loads lazily: off means unloaded.\nexport async function composeWorkflowRuntime(\n deps: ComposeWorkflowRuntimeDeps,\n): Promise<ComposedWorkflowRuntime> {\n const load = deps.load ?? (() => import(\"@powerhousedao/reactor-workflow\"));\n\n let engine: WorkflowEngineModule;\n try {\n engine = await load();\n } catch (error) {\n throw new Error(\n \"Workflows are enabled but @powerhousedao/reactor-workflow could not be loaded\",\n { cause: error },\n );\n }\n\n // BEFORE anything else touches the run journal. Opening the journal runs\n // its orphan/abandoned sweeps, which close out every RUNNING and PENDING\n // run that is not this process's — i.e. a second replica booting fails the\n // first replica's live runs. The claim is what makes the plan's singleton\n // decision structural instead of documented; it refuses by name.\n const loss: SingletonLoss = { lost: false };\n const lease =\n deps.singletonLease === false\n ? undefined\n : await engine.acquireWorkflowSingletonLease({\n relationalDb: deps.relationalDb,\n logger: deps.logger,\n ...(deps.storageId ? { storageId: deps.storageId } : {}),\n selfFence: deps.exclusiveJournal !== true,\n onLost: (lost) => {\n loss.lost = true;\n if (lost.reason === \"taken\") loss.heldBy = lost.heldBy;\n loss.tearDown?.();\n // While composing, the compose itself fails with a conflict and\n // the host retries the claim.\n if (loss.composed) deps.onSingletonLost?.(lost);\n },\n });\n\n try {\n const composed = await composeClaimed(engine, deps, lease, loss);\n if (loss.lost) throw singletonLostError(engine, loss, lease);\n loss.composed = true;\n return composed;\n } catch (error) {\n // Renewing since the claim, so a compose that fails hands it back, after\n // stopping whatever runtime it had already built.\n loss.tearDown?.();\n await lease?.release();\n throw error;\n }\n}\n\ntype SingletonLease = Awaited<\n ReturnType<WorkflowEngineModule[\"acquireWorkflowSingletonLease\"]>\n>;\n\n// Losing the lease shuts the runtime down; tearDown is set once it exists.\ninterface SingletonLoss {\n lost: boolean;\n composed?: boolean;\n heldBy?: string;\n tearDown?: () => void;\n}\n\nfunction singletonLostError(\n engine: WorkflowEngineModule,\n loss: SingletonLoss,\n lease: SingletonLease | undefined,\n): Error {\n return new engine.WorkflowSingletonConflictError(\n loss.heldBy ?? \"unknown\",\n \"unknown\",\n lease?.owner ?? \"unknown\",\n );\n}\n\nasync function composeClaimed(\n engine: WorkflowEngineModule,\n deps: ComposeWorkflowRuntimeDeps,\n lease: SingletonLease | undefined,\n loss: SingletonLoss,\n): Promise<ComposedWorkflowRuntime> {\n // The same registry the host installs packages from, so a piece it indexes\n // is reachable without a second setting to keep in step.\n engine.setPieceRegistryUrl(deps.pieceRegistryUrl);\n\n // Before the runtime exists: a restored trigger asks for a piece as soon as\n // the supervisor starts, and the catalog is served from the same holder.\n if (deps.pieces) bindPackagePieces(engine.packagePieces, deps.pieces);\n\n // Creating the runtime opens the journal, whose sweeps fail every run not\n // in this process: never after the lease has gone.\n if (loss.lost) throw singletonLostError(engine, loss, lease);\n const access = reactorAccessOf(deps.clientModule);\n const models = deps.models;\n const runtime = engine.createWorkflowRuntime({\n relationalDb: deps.relationalDb,\n secretsKeyFile: deps.secretsKeyFile,\n reactorClient: deps.reactorClient,\n assertCanRead: readAssertion(deps.authorizationService, deps.reactorClient),\n subjectOf: (caller) => callerSubject((caller as Context).user),\n assertCanWrite: writeAssertion(\n deps.authorizationService,\n deps.reactorClient,\n ),\n // Unknown flags leave it absent, which the engine takes as on.\n ...(deps.clientModule?.reactorModule\n ? { authEnforcement: access.authEnforcement }\n : {}),\n hostPrincipal: hostPrincipalOf(access),\n hostIdentity: hostIdentityOf(access),\n ...(models\n ? {\n modelManifest: () => models.modelManifest(),\n modelEntries: (documentType: string) =>\n models.modelEntries(documentType),\n }\n : {}),\n webhooks: deps.webhooks,\n attachments: deps.attachments,\n canReadAttachmentRef: attachmentReadPolicy(deps.attachmentAccess),\n logger: deps.logger,\n ...(deps.reactorThreads ? { reactorThreads: deps.reactorThreads } : {}),\n ...(deps.telemetry ? { telemetry: deps.telemetry } : {}),\n });\n\n // Set before anything below can throw, so a failed compose stops it.\n const routes: { oauthCallback?: ScopedRouteHandle } = {};\n const registration: TriggersRegistration = { tornDown: false };\n const tearDown = () => {\n if (registration.tornDown) return;\n registration.tornDown = true;\n routes.oauthCallback?.dispose();\n runtime.shutdown();\n // After the shutdown, so a batch already queued for it is refused and\n // replays on the next owner instead of being acknowledged here.\n registration.detach?.();\n };\n loss.tearDown = tearDown;\n\n const triggers = await registerWorkflowTriggersReadModel(\n engine,\n runtime,\n deps.clientModule,\n registration,\n );\n // Lost while registering: mount nothing a torn-down runtime would leave.\n if (registration.tornDown) throw singletonLostError(engine, loss, lease);\n if (triggers.status === \"available\") {\n deps.logger.info(\n `Workflow trigger read model registered (${engine.WORKFLOW_TRIGGERS_READ_MODEL}, ${engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE})`,\n );\n } else {\n // Loudly: the runtime still serves GraphQL and still runs webhook and\n // schedule triggers, so nothing else says the document ones are dead.\n deps.logger.error(\n \"Workflow document triggers are NOT armed (@reason): this reactor's \" +\n \"read-model coordinator takes no live registration, so no document \" +\n \"operation reaches the runtime. Webhook and schedule triggers are \" +\n \"unaffected.\",\n triggers.reason,\n );\n }\n\n let stopped = false;\n if (deps.http) {\n routes.oauthCallback = registerOAuthCallback(deps.http, runtime);\n }\n\n return {\n subgraph: createWorkflowRuntimeSubgraph(\n runtime,\n deps.http ? { callbackUrl: callbackUrlOf(deps.http) } : undefined,\n access,\n ),\n get triggers() {\n return loss.lost ? SINGLETON_LOST : triggers;\n },\n ...(lease ? { singletonOwner: lease.owner } : {}),\n\n async start() {\n if (registration.tornDown) return;\n // The endpoint family first: a restored webhook trigger asks for its URL\n // as soon as the supervisor starts.\n await runtime.registerWebhookEndpoint();\n // Lost or stopped while registering.\n if (loss.lost || stopped) return;\n runtime.startTriggerSupervisor();\n // So the first search in the editor finds the catalog indexed.\n runtime.warmPieceSearch();\n },\n\n async stop() {\n if (stopped) return;\n stopped = true;\n tearDown();\n // Released, so the next boot owns workflows immediately instead of\n // waiting out the lease TTL.\n await lease?.release();\n },\n };\n}\n","import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport type { ILogger } from \"document-model\";\nimport {\n isWorkflowSingletonConflict,\n retryWorkflowSingleton,\n type ComposedWorkflowRuntime,\n type WorkflowSingletonRetry,\n} from \"../workflow-runtime.mjs\";\nimport type { SwitchboardHostContext } from \"../plugin-host.mjs\";\n\n/**\n * R2.5 — the workflows subsystem as a built-in plugin. Presence is activation\n * (an explicit options.workflows.enabled === false still wins, mirroring the\n * mcp carve); the PH_WORKFLOWS_ENABLED env/config resolution governs the\n * classic path only.\n *\n * The orchestration (compose, singleton-conflict retry, subgraph\n * registration, start, inspection fact) moves here VERBATIM from the inline\n * block; the dependency-heavy wiring closures (composeWorkflows,\n * registerWorkflowSubgraph) stay in server.mts and travel via ctx — same\n * realm, code moved not redesigned. Carve-map constraints preserved: the\n * retry path's onComposed registers + updates the router ITSELF (it may fire\n * after the readiness drain); teardown stops retry then runtime, and runs\n * AFTER privacy's (sequential onShutdown, registration order).\n */\n\nexport interface WorkflowsOrchestration {\n enabled: boolean;\n composeWorkflows: () => Promise<ComposedWorkflowRuntime>;\n registerWorkflowSubgraph: (\n composed: ComposedWorkflowRuntime,\n ) => Promise<void>;\n updateRouter: () => Promise<void>;\n reportMountFailure: (error: unknown) => void;\n setWorkflowsFact: () => void;\n}\n\ntype WorkflowsOptions = Record<string, unknown> & {\n workflows?: { enabled?: boolean };\n};\n\nexport const workflowsPlugin: HostPlugin<{\n transformServerOptions: (\n options: Record<string, unknown>,\n ctx: SwitchboardHostContext,\n ) => Record<string, unknown>;\n onSubgraphsRegistering: (ctx: SwitchboardHostContext) => Promise<void>;\n onShutdown: (ctx: SwitchboardHostContext) => Promise<void>;\n}> = {\n name: \"switchboard-workflows\",\n appliesTo: \"switchboard\",\n hooks: {\n transformServerOptions: (options) => {\n const current = (options as WorkflowsOptions).workflows;\n if (current?.enabled === false) return options;\n return { ...options, workflows: { ...current, enabled: true } };\n },\n onSubgraphsRegistering: async (ctx) => {\n const orchestration = ctx.workflowsOrchestration as\n | WorkflowsOrchestration\n | undefined;\n if (!orchestration?.enabled) return;\n const logger = ctx.logger as ILogger;\n const lateSubgraphs = ctx.lateSubgraphs!;\n\n let workflows: ComposedWorkflowRuntime | undefined;\n let workflowsRetry: WorkflowSingletonRetry | undefined;\n try {\n workflows = await orchestration.composeWorkflows();\n } catch (error) {\n // Without the claim this host must not run workflows, but everything\n // else it serves still works, so it boots without the runtime.\n if (!isWorkflowSingletonConflict(error)) throw error;\n logger.warn(\n `Workflows are enabled but another live process (\"${error.owner ?? \"unknown\"}\") ` +\n `holds the workflow singleton until ${error.expiresAt ?? \"unknown\"}. ` +\n \"This Switchboard has booted WITHOUT the workflow runtime: no \" +\n \"trigger of any kind fires here, and the workflow GraphQL face is \" +\n \"absent. Everything else serves normally. Stop the other owner, or \" +\n \"set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the \" +\n \"slot that owns workflows. This Switchboard retries the claim and \" +\n \"starts workflows once the lease comes free.\",\n );\n workflowsRetry = retryWorkflowSingleton({\n compose: orchestration.composeWorkflows,\n onComposed: async (composed) => {\n try {\n await composed.start();\n } catch (error) {\n // Hands the lease back so a retry or another replica can claim it.\n try {\n await composed.stop();\n } catch (stopError) {\n logger.error(\n \"Stopping the late workflow runtime failed: @error\",\n stopError,\n );\n }\n throw error;\n }\n logger.info(\"Workflow runtime started\");\n ctx.workflows = composed;\n await orchestration.registerWorkflowSubgraph(composed);\n // Past boot nothing else rebuilds the router, so a subgraph\n // registered now is not served until this runs.\n try {\n await orchestration.updateRouter();\n } catch (error) {\n orchestration.reportMountFailure(error);\n }\n },\n logger,\n });\n }\n ctx.workflowsRetry = workflowsRetry;\n if (workflows) {\n ctx.workflows = workflows;\n lateSubgraphs.push(orchestration.registerWorkflowSubgraph(workflows));\n await workflows.start();\n logger.info(\"Workflow runtime started\");\n orchestration.setWorkflowsFact();\n }\n },\n onShutdown: async (ctx) => {\n await (ctx.workflowsRetry as WorkflowSingletonRetry | undefined)?.stop();\n await (ctx.workflows as ComposedWorkflowRuntime | undefined)?.stop();\n },\n },\n};\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default workflowsPlugin;\n"],"names":[],"mappings":";;;;;;;;AAEA,MAAM,iBAAiB;AASvB,MAAM,gCAAgB,IAAI,QAGxB;;;;;;;;;;;;;;AAeF,SAAgB,0BACd,QACA,OAAqB,SACf;CACN,IAAI,cAAc,IAAI,IAAI,GAAG;CAI7B,MAAM,WAA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AM;IAC/C,OAAO,KACL,oDAAoD,MAAM,SAAS,UAAU,wCACrC,MAAM,aAAa,UAAU,+WAOvE;IACA,iBAAiB,uBAAuB;KACtC,SAAS,cAAc;KACvB,YAAY,OAAO,aAAa;MAC9B,IAAI;OACF,MAAM,SAAS,MAAM;MACvB,SAAS,OAAO;OAEd,IAAI;QACF,MAAM,SAAS,KAAK;OACtB,SAAS,WAAW;QAClB,OAAO,MACL,qDACA,SACF;OACF;OACA,MAAM;MACR;MACA,OAAO,KAAK,0BAA0B;MACtC,IAAI,YAAY;MAChB,MAAM,cAAc,yBAAyB,QAAQ;MAGrD,IAAI;OACF,MAAM,cAAc,aAAa;MACnC,SAAS,OAAO;OACd,cAAc,mBAAmB,KAAK;MACxC;KACF;KACA;IACF,CAAC;GACH;GACA,IAAI,iBAAiB;GACrB,IAAI,WAAW;IACb,IAAI,YAAY;IAChB,cAAc,KAAK,cAAc,yBAAyB,SAAS,CAAC;IACpE,MAAM,UAAU,MAAM;IACtB,OAAO,KAAK,0BAA0B;IACtC,cAAc,iBAAiB;GACjC;EACF;EACA,YAAY,OAAO,QAAQ;GACzB,MAAO,IAAI,gBAAuD,KAAK;GACvE,MAAO,IAAI,WAAmD,KAAK;EACrE;CACF;AACF","debug_id":"3ac978b6-5ddf-546e-848d-1557f6ab7aeb"}
|
|
1
|
+
{"version":3,"file":"workflows-fsBcElEi.mjs","sources":["../src/fatal-shutdown.mts","../src/workflow/oauth-callback.ts","../src/workflow/resolvers.ts","../src/workflow/schema.ts","../src/workflow/subgraph.ts","../src/workflow-runtime.mts","../src/plugins/workflows.mts"],"sourcesContent":["import type { ILogger } from \"document-model\";\n\nconst FORCED_EXIT_MS = 15_000;\n\ntype FatalProcess = Pick<\n NodeJS.Process,\n \"on\" | \"kill\" | \"exit\" | \"pid\" | \"listenerCount\"\n> & {\n exitCode?: NodeJS.Process[\"exitCode\"];\n};\n\nconst fatalHandlers = new WeakMap<\n FatalProcess,\n (kind: string, err: unknown) => void\n>();\n\n/**\n * Sends an uncaught exception or unhandled rejection through the SIGTERM\n * shutdown that `withSignalHandlers()` installs, so the reactor and read-model\n * PGlite stores close with a shutdown checkpoint before the process exits\n * with code 1. Node's default is to exit at once, which leaves both stores\n * to WAL recovery on the next open. A store whose wasm runtime aborted\n * (ENOSPC) rejects its close; the builder logs that and still exits. A\n * shutdown that hangs is cut off after FORCED_EXIT_MS.\n *\n * A rejection is fatal only when this is its sole listener: Node exits on an\n * unhandled rejection only when nothing listens for it, and Sentry's\n * listener deliberately keeps the process running.\n */\nexport function installFatalErrorShutdown(\n logger: ILogger,\n proc: FatalProcess = process,\n): void {\n if (fatalHandlers.has(proc)) return;\n\n // Captured before shutdown starts: the builder replaces process.exit with a\n // recording shim while it drains.\n const realExit = proc.exit.bind(proc);\n let shuttingDown = false;\n\n /**\n * Logs without ever throwing. onFatal runs inside the uncaughtException\n * handler, so a logger whose transport is gone (EPIPE on a closed stdout)\n * would otherwise throw from the handler that reports throws, killing the\n * process before the shutdown it is supposed to run. A logging failure is\n * swallowed: there is nowhere left to report it.\n */\n const logFatal = (message: string, err?: unknown): void => {\n try {\n if (err === undefined) {\n logger.error(message);\n } else {\n logger.error(message, err);\n }\n } catch {\n // The log transport itself failed; shutdown must keep moving.\n }\n };\n\n const onFatal = (kind: string, err: unknown): void => {\n logFatal(`${kind}: @error`, err);\n if (shuttingDown) return;\n shuttingDown = true;\n proc.exitCode = 1;\n setTimeout(() => {\n logFatal(\"Shutdown after fatal error timed out; exiting\");\n realExit(1);\n }, FORCED_EXIT_MS).unref();\n proc.kill(proc.pid, \"SIGTERM\");\n };\n fatalHandlers.set(proc, onFatal);\n\n proc.on(\"uncaughtException\", (err) => onFatal(\"Uncaught exception\", err));\n proc.on(\"unhandledRejection\", (reason) => {\n if (proc.listenerCount(\"unhandledRejection\") > 1) return;\n onFatal(\"Unhandled rejection\", reason);\n });\n}\n\n/**\n * Routes a fatal condition the caller detected through the same shutdown as an\n * uncaught error. Returns false, and does nothing, when\n * `installFatalErrorShutdown` has not run for `proc`.\n */\nexport function triggerFatalShutdown(\n kind: string,\n err: unknown,\n proc: FatalProcess = process,\n): boolean {\n const onFatal = fatalHandlers.get(proc);\n if (!onFatal) return false;\n onFatal(kind, err);\n return true;\n}\n","import type { WorkflowRuntimeService } from \"@powerhousedao/reactor-workflow\";\nimport type {\n IHttpScope,\n ScopedRouteHandle,\n} from \"@powerhousedao/shared/processors\";\n\nexport const OAUTH_CALLBACK_PATH = \"oauth/callback\";\n\nfunction escapeHtml(text: string): string {\n return text.replace(\n /[&<>\"']/g,\n (char) =>\n ({\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n })[char]!,\n );\n}\n\n// The popup's last page. The editor that opened it polls the attempt, so this\n// only has to say how it went; closing itself is a courtesy.\nfunction resultPage(ok: boolean, detail: string | null): string {\n const title = ok ? \"Connected\" : \"Sign-in failed\";\n const message = ok\n ? \"You can close this window.\"\n : escapeHtml(detail ?? \"The sign-in did not finish.\");\n return `<!doctype html>\n<html><head><meta charset=\"utf-8\"><title>${title}</title>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<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>\n</head><body><main><h1>${title}</h1><p>${message}</p></main>\n${ok ? \"<script>setTimeout(function(){window.close()},600)</script>\" : \"\"}\n</body></html>`;\n}\n\n// The provider's redirect lands here. Public: the provider sends no bearer,\n// and the one-time state is what the runtime checks instead.\nexport function registerOAuthCallback(\n http: IHttpScope,\n runtime: Pick<WorkflowRuntimeService, \"completeOAuth\">,\n): ScopedRouteHandle {\n return http.get(OAUTH_CALLBACK_PATH, { auth: \"public\" }, async (request) => {\n const params = new URL(request.url).searchParams;\n const state = params.get(\"state\");\n const result = state\n ? await runtime.completeOAuth({\n state,\n code: params.get(\"code\") ?? undefined,\n error: params.get(\"error\") ?? undefined,\n errorDescription: params.get(\"error_description\") ?? undefined,\n })\n : { ok: false, detail: \"The provider sent no state\", returnUrl: null };\n if (result.returnUrl && state) {\n const back = new URL(result.returnUrl);\n back.searchParams.set(\"ph_oauth\", state);\n return new Response(null, {\n status: 303,\n headers: { location: back.href, \"cache-control\": \"no-store\" },\n });\n }\n return new Response(resultPage(result.ok, result.detail), {\n status: result.ok ? 200 : 400,\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"referrer-policy\": \"no-referrer\",\n },\n });\n });\n}\n\nexport function callbackUrlOf(http: IHttpScope): string {\n return `${http.baseUrl.replace(/\\/+$/, \"\")}/${OAUTH_CALLBACK_PATH}`;\n}\n","import type {\n Context,\n IAuthorizationService,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n RunRow,\n StepExecutionRow,\n WorkflowRuntimeService,\n} from \"@powerhousedao/reactor-workflow\";\nimport {\n GraphQLError,\n Kind,\n type GraphQLResolveInfo,\n type SelectionSetNode,\n} from \"graphql\";\n\ninterface FireArgs {\n workflowId: string;\n payload?: unknown;\n}\n\ninterface PieceArgs {\n packageName: string;\n version?: string | null;\n}\n\ntype BlockRef = Parameters<WorkflowRuntimeService[\"blockDescriptor\"]>[0];\n\ntype PieceSource = NonNullable<\n Parameters<WorkflowRuntimeService[\"searchPieces\"]>[1][\"sources\"]\n>[number];\n\nconst PIECE_SOURCES: readonly string[] = [\n \"local\",\n \"registry\",\n \"activepieces\",\n] satisfies PieceSource[];\n\nfunction isPieceSource(value: string): value is PieceSource {\n return PIECE_SOURCES.includes(value);\n}\n\ninterface BlockInput {\n pieceName: string;\n pieceVersion: string;\n name: string;\n kind: string;\n}\n\nfunction blockRef(input: BlockInput): BlockRef {\n if (input.kind !== \"action\" && input.kind !== \"trigger\") {\n throw new GraphQLError(\n `A block's kind is \"action\" or \"trigger\", got \"${input.kind}\"`,\n );\n }\n return {\n pieceName: input.pieceName,\n pieceVersion: input.pieceVersion,\n name: input.name,\n kind: input.kind,\n };\n}\n\ninterface RunsArgs {\n workflowId?: string;\n driveId?: string;\n limit?: number;\n excludeTriggerKinds?: string[];\n}\n\ninterface RunsPageArgs {\n workflowId?: string;\n driveId?: string;\n excludeTriggerKinds?: string[];\n paging?: { limit?: number | null; cursor?: string | null } | null;\n}\n\n// A cursor the runtime did not issue is the caller's error, not ours.\nasync function cursorAware<T>(call: () => Promise<T>): Promise<T> {\n try {\n return await call();\n } catch (error) {\n if (error instanceof Error && error.name === \"InvalidRunCursorError\") {\n throw new GraphQLError(error.message, {\n extensions: { code: \"BAD_USER_INPUT\" },\n });\n }\n throw error;\n }\n}\n\n// Whether a runs query reads any step's input or output, so a listing that\n// doesn't can skip those blobs. Fragments count as asking for them.\nfunction selectsStepData(\n selections: readonly SelectionSetNode[],\n path: string[],\n): boolean {\n let level = selections;\n for (const name of [...path, \"steps\"]) {\n const next: SelectionSetNode[] = [];\n for (const set of level) {\n for (const selection of set.selections) {\n if (selection.kind !== Kind.FIELD) return true;\n if (selection.name.value === name && selection.selectionSet) {\n next.push(selection.selectionSet);\n }\n }\n }\n if (next.length === 0) return false;\n level = next;\n }\n return level.some((set) =>\n set.selections.some(\n (selection) =>\n selection.kind !== Kind.FIELD ||\n selection.name.value === \"input\" ||\n selection.name.value === \"output\",\n ),\n );\n}\n\n// With no resolve info (a direct call) the full shape is served.\nfunction readsStepData(\n info: GraphQLResolveInfo | undefined,\n path: string[],\n): boolean {\n if (!info) return true;\n const selections = info.fieldNodes.flatMap((node) =>\n node.selectionSet ? [node.selectionSet] : [],\n );\n return selectsStepData(selections, path);\n}\n\n// A secret belongs to the reactor, not to any one document, so writing one is\n// an administrator's call — the gate the package mutations already use.\nfunction requireAdmin(\n authorizationService: IAuthorizationService,\n ctx: Context,\n): void {\n if (!authorizationService.isSupremeAdmin(ctx.user?.address)) {\n throw new GraphQLError(\"Admin access required\");\n }\n}\n\n// The runtime's retryable \"not synced here yet\", tagged for clients.\nasync function syncAware<T>(call: () => Promise<T>): Promise<T> {\n try {\n return await call();\n } catch (error) {\n if (error instanceof Error && error.name === \"WorkflowSyncingError\") {\n throw new GraphQLError(error.message, {\n extensions: { code: \"WORKFLOW_SYNCING\", retryable: true },\n });\n }\n throw error;\n }\n}\n\nfunction parseJson(value: string | null): unknown {\n if (value === null) return null;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n}\n\nfunction toStepRecord(row: StepExecutionRow) {\n return {\n stepId: row.step_id,\n stepKey: row.step_key,\n pieceName: row.piece_name,\n blockName: row.block_name,\n status: row.status,\n input: parseJson(row.input),\n output: parseJson(row.output),\n port: row.port,\n error: row.error,\n errorName: row.error_name,\n startedAt: row.started_at,\n endedAt: row.ended_at,\n pieceVersion: row.piece_version,\n pieceSource: row.piece_source,\n versionMatch: row.version_match,\n versionNote: row.version_note,\n };\n}\n\nfunction toRunRecord(row: RunRow, steps: StepExecutionRow[]) {\n return {\n id: row.id,\n workflowId: row.workflow_id,\n workflowName: row.workflow_name,\n workflowVersion: row.workflow_version,\n triggerKind: row.trigger_kind,\n triggerPayload: parseJson(row.trigger_payload),\n status: row.status,\n error: row.error,\n errorName: row.error_name,\n startedAt: row.started_at,\n endedAt: row.ended_at,\n rerunOf: row.rerun_of,\n warnings: row.warnings,\n warningNotes: parseJson(row.warning_notes) ?? [],\n steps: steps.map(toStepRecord),\n };\n}\n\nexport type ReadAssertion = (\n documentId: string,\n ctx: Context,\n) => Promise<unknown>;\n\n/** Who the host signs as: the principal a target document must grant. */\nexport interface ReactorIdentity {\n address: string | null;\n key: string;\n}\n\n/** What the editor needs to decide on sign-in and grants (ADR 0005 §8). */\nexport interface ReactorAccessInfo {\n authEnforcement: boolean;\n authConditions: boolean;\n identity: ReactorIdentity | null;\n}\n\n// Strict when the host does not say.\nconst UNKNOWN_ACCESS: ReactorAccessInfo = {\n authEnforcement: true,\n authConditions: false,\n identity: null,\n};\n\nfunction signedIn(ctx: Context): boolean {\n return Boolean(ctx.user?.address);\n}\n\nexport interface OAuthRouting {\n // Absolute, or a bare path when the host's public origin is unknown.\n callbackUrl: string;\n}\n\nfunction isAbsolute(url: string): boolean {\n return /^https?:\\/\\//i.test(url);\n}\n\n// The redirect a sign-in uses: the host's own when it knows its origin,\n// otherwise the caller's, provided it names this host's callback path.\nfunction redirectUriFor(\n routing: OAuthRouting | undefined,\n requested: string | null | undefined,\n): string {\n if (!routing) throw new GraphQLError(\"This host serves no OAuth2 callback\");\n if (isAbsolute(routing.callbackUrl)) return routing.callbackUrl;\n if (!requested) {\n throw new GraphQLError(\n \"This host does not know its public URL; pass redirectUri\",\n );\n }\n let url: URL;\n try {\n url = new URL(requested);\n } catch {\n throw new GraphQLError(`\"${requested}\" is not a URL`);\n }\n if (\n (url.protocol !== \"https:\" && url.protocol !== \"http:\") ||\n url.pathname !== routing.callbackUrl ||\n url.search !== \"\" ||\n url.hash !== \"\"\n ) {\n throw new GraphQLError(\n `redirectUri must be this host's ${routing.callbackUrl}`,\n );\n }\n return url.href;\n}\n\n// Only back to the page that asked: its Origin header is the browser's.\nfunction returnUrlFor(\n requested: string | null | undefined,\n ctx: Context,\n): string | undefined {\n if (!requested) return undefined;\n const origin = ctx.headers.origin;\n let url: URL | undefined;\n try {\n url = new URL(requested);\n } catch {\n url = undefined;\n }\n if (!url || !origin || url.origin !== origin) {\n throw new GraphQLError(\"returnUrl must be on the requesting page's origin\");\n }\n return url.href;\n}\n\nexport const getResolvers = (\n runtime: WorkflowRuntimeService,\n authorizationService: IAuthorizationService,\n oauth?: OAuthRouting,\n access: ReactorAccessInfo = UNKNOWN_ACCESS,\n // The subgraph's own read gate; fields that need it refuse without one.\n assertCanRead?: ReadAssertion,\n): Record<string, unknown> => {\n return {\n Query: {\n workflowRuntime: () => ({}),\n },\n WorkflowRuntimeQueries: {\n health: () => \"ok\",\n authEnforcement: () => access.authEnforcement,\n reactorIdentity: (_parent: unknown, _args: unknown, ctx: Context) =>\n signedIn(ctx) ? access.identity : null,\n authConditions: (_parent: unknown, _args: unknown, ctx: Context) =>\n signedIn(ctx) ? access.authConditions : null,\n reactorAccessDenial: async (\n _parent: unknown,\n args: { workflowId: string },\n ctx: Context,\n ) => {\n if (!assertCanRead) throw new GraphQLError(\"No read check configured\");\n await assertCanRead(args.workflowId, ctx);\n return runtime.reactorAccessDenial(args.workflowId) ?? null;\n },\n blockDescriptor: (_parent: unknown, args: { block: BlockInput }) =>\n runtime.blockDescriptor(blockRef(args.block)),\n blockOptions: (\n _parent: unknown,\n args: {\n block: BlockInput;\n propName: string;\n input?: unknown;\n connectionId?: string | null;\n searchValue?: string | null;\n reactorConnectionId?: string | null;\n },\n ctx: Context,\n ) =>\n runtime.blockOptions(\n blockRef(args.block),\n args.propName,\n args.input,\n args.connectionId ?? undefined,\n ctx,\n args.searchValue ?? undefined,\n args.reactorConnectionId ?? undefined,\n ),\n pieceCatalog: () => runtime.pieceCatalog(),\n pieceActions: (_parent: unknown, args: PieceArgs) =>\n runtime.pieceActions(args.packageName, args.version ?? undefined),\n pieceTriggers: (_parent: unknown, args: PieceArgs) =>\n runtime.pieceTriggers(args.packageName, args.version ?? undefined),\n blockOutputTree: (\n _parent: unknown,\n args: { block: BlockInput; config?: unknown },\n ) => runtime.blockOutputTree(blockRef(args.block), args.config),\n stepOutputTree: (\n _parent: unknown,\n args: { workflowId: string; stepId: string },\n ctx: Context,\n ) => runtime.stepOutputTree(args.workflowId, args.stepId, ctx),\n blockResolutions: (\n _parent: unknown,\n args: { workflowId: string },\n ctx: Context,\n ) => runtime.blockResolutions(args.workflowId, ctx),\n pieceDetail: (_parent: unknown, args: PieceArgs) =>\n runtime.pieceDetail(args.packageName, args.version ?? undefined),\n searchPieces: (\n _parent: unknown,\n args: {\n query: string;\n kind: string;\n sources?: string[] | null;\n categories?: string[] | null;\n limit?: number | null;\n },\n ) => {\n // A misspelt value would otherwise widen the search without a word.\n if (args.kind !== \"action\" && args.kind !== \"trigger\") {\n throw new GraphQLError(\n `A search's kind is \"action\" or \"trigger\", got \"${args.kind}\"`,\n );\n }\n const unknown = (args.sources ?? []).filter(\n (source) => !isPieceSource(source),\n );\n if (unknown.length > 0) {\n throw new GraphQLError(\n `A search's sources are ${PIECE_SOURCES.join(\", \")}, got ${unknown.join(\", \")}`,\n );\n }\n return runtime.searchPieces(args.query, {\n kind: args.kind,\n sources: (args.sources ?? []).filter(isPieceSource),\n categories: args.categories ?? undefined,\n limit: args.limit ?? undefined,\n });\n },\n connections: (_parent: unknown, _args: unknown, ctx: Context) =>\n runtime.connections(ctx),\n webhookEndpoint: (\n _parent: unknown,\n args: { workflowId: string; driveId?: string | null },\n ctx: Context,\n ) =>\n syncAware(() =>\n runtime.webhookEndpoint(args.workflowId, ctx, {\n driveId: args.driveId ?? undefined,\n }),\n ),\n secret: async (_parent: unknown, args: { ref: string }) => {\n try {\n return await (await runtime.secrets()).stat(args.ref);\n } catch {\n // Unknown or malformed ref reads as \"no such secret\".\n return null;\n }\n },\n secrets: async () => (await runtime.secrets()).list(),\n oauthRedirectUri: () => oauth?.callbackUrl ?? null,\n oauthAttempt: (_parent: unknown, args: { state: string }, ctx: Context) =>\n runtime.oauthAttempt(args.state, ctx),\n triggerStates: async (_parent: unknown, _args: unknown, ctx: Context) =>\n (await runtime.triggerStates(ctx)).map((row) => ({\n workflowId: row.workflow_id,\n pieceName: row.piece_name,\n triggerName: row.trigger_name,\n status: row.status,\n intervalMs: row.interval_ms,\n nextPollAt: row.next_poll_at,\n lastPollAt: row.last_poll_at,\n lastError: row.last_error,\n consecutiveFailures: row.consecutive_failures,\n nextRenewAt: row.next_renew_at,\n renewError: row.renew_error,\n renewFailures: row.renew_failures,\n pieceVersion: row.piece_version,\n pieceSource: row.piece_source,\n versionMatch: row.version_match,\n versionNote: row.version_note,\n })),\n runs: async (\n _parent: unknown,\n args: RunsArgs,\n ctx: Context,\n info?: GraphQLResolveInfo,\n ) =>\n (\n await runtime.runs(\n { ...args, withStepData: readsStepData(info, []) },\n ctx,\n )\n ).map((record) => toRunRecord(record.row, record.steps)),\n runsPage: async (\n _parent: unknown,\n args: RunsPageArgs,\n ctx: Context,\n info?: GraphQLResolveInfo,\n ) => {\n const { paging, ...scope } = args;\n const page = await cursorAware(() =>\n runtime.runsPage(\n {\n ...scope,\n limit: paging?.limit ?? undefined,\n cursor: paging?.cursor ?? null,\n withStepData: readsStepData(info, [\"items\"]),\n },\n ctx,\n ),\n );\n return {\n items: page.records.map((record) =>\n toRunRecord(record.row, record.steps),\n ),\n hasNextPage: page.hasNextPage,\n hasPreviousPage: Boolean(paging?.cursor),\n cursor: page.cursor,\n };\n },\n run: async (_parent: unknown, args: { id: string }, ctx: Context) => {\n const record = await runtime.run(args.id, ctx);\n return record ? toRunRecord(record.row, record.steps) : null;\n },\n },\n Mutation: {\n workflowRuntime: () => ({}),\n },\n WorkflowRuntimeMutations: {\n fire: (_parent: unknown, args: FireArgs, ctx: Context) =>\n runtime.fire(args.workflowId, args.payload, \"manual\", undefined, ctx),\n testTrigger: (\n _parent: unknown,\n args: {\n workflowId: string;\n payload?: unknown;\n timeoutSeconds?: number | null;\n driveId?: string | null;\n },\n ctx: Context,\n ) =>\n syncAware(() =>\n runtime.testTrigger(args.workflowId, ctx, {\n ...(args.payload !== undefined ? { payload: args.payload } : {}),\n ...(typeof args.timeoutSeconds === \"number\"\n ? { timeoutMs: args.timeoutSeconds * 1000 }\n : {}),\n driveId: args.driveId ?? undefined,\n }),\n ),\n cancelTriggerTest: (\n _parent: unknown,\n args: { workflowId: string },\n ctx: Context,\n ) => runtime.cancelTriggerTestFor(args.workflowId, ctx),\n testStep: (\n _parent: unknown,\n args: { workflowId: string; stepId: string; driveId?: string | null },\n ctx: Context,\n ) =>\n syncAware(() =>\n runtime.testStep(args.workflowId, args.stepId, ctx, {\n driveId: args.driveId ?? undefined,\n }),\n ),\n rerun: (_parent: unknown, args: { runId: string }, ctx: Context) =>\n runtime.rerun(args.runId, ctx),\n createSecret: async (\n _parent: unknown,\n args: { value: string; label?: string | null },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n return (await runtime.secrets()).create({\n value: args.value,\n label: args.label ?? undefined,\n });\n },\n rotateSecret: async (\n _parent: unknown,\n args: { ref: string; value: string },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n return (await runtime.secrets()).rotate(args.ref, args.value);\n },\n deleteSecret: async (\n _parent: unknown,\n args: { ref: string },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n await (await runtime.secrets()).delete(args.ref);\n return true;\n },\n checkConnection: (\n _parent: unknown,\n args: { connectionId: string },\n ctx: Context,\n ) => runtime.checkConnection(args.connectionId, ctx),\n // Signing in mints a secret, so it takes what createSecret takes.\n startOAuth: (\n _parent: unknown,\n args: {\n connectionId: string;\n redirectUri?: string | null;\n returnUrl?: string | null;\n },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n const returnUrl = returnUrlFor(args.returnUrl, ctx);\n return runtime.startOAuth(args.connectionId, ctx, {\n redirectUri: redirectUriFor(oauth, args.redirectUri),\n ...(returnUrl ? { returnUrl } : {}),\n });\n },\n },\n };\n};\n","import type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nexport const schema: DocumentNode = gql`\n \"\"\"\n WorkflowRuntime Queries\n \"\"\"\n type WorkflowRuntimeQueries {\n health: String!\n \"\"\"\n Whether this reactor enforces document auth (REACTOR_AUTH_ENFORCEMENT).\n On, a workflow needs a signed publish, and the host grants, to reach\n documents. Answered to any caller.\n \"\"\"\n authEnforcement: Boolean!\n \"\"\"\n Who this host signs as: grant it on each document a step writes. Null for\n a caller who is not signed in, or a host with no signer.\n \"\"\"\n reactorIdentity: ReactorIdentity\n \"\"\"\n REACTOR_AUTH_CONDITIONS. True: grant the host by key, with\n { match: subject.key == key }; false: by address. Null for a caller who\n is not signed in.\n \"\"\"\n authConditions: Boolean\n \"\"\"\n Why the workflow's last publish or enable got no reactor access, naming\n the publisher and the connection; null when the check passed.\n \"\"\"\n reactorAccessDenial(workflowId: String!): String\n \"\"\"\n Persisted runs, newest first. Scope them to one workflow, or to every\n workflow a drive holds; workflowId wins when both are given.\n \"\"\"\n runs(\n workflowId: String\n driveId: String\n limit: Int\n \"Trigger kinds to leave out, e.g. test.\"\n excludeTriggerKinds: [String!]\n ): [WorkflowRunRecord!]!\n \"\"\"\n The same listing a page at a time, newest journaled first. Pass a page's\n cursor back in paging to read the next; a page is short only when\n hasNextPage is false, or when the caller could read none of a long\n stretch of runs. A run that starts between pages keeps its place.\n \"\"\"\n runsPage(\n workflowId: String\n driveId: String\n excludeTriggerKinds: [String!]\n paging: WorkflowRunsPagingInput\n ): WorkflowRunResultPage!\n run(id: String!): WorkflowRunRecord\n \"\"\"\n The descriptor (props, auth, ports) of one action or trigger, as the\n version that runs it describes it; triggers come back under \"trigger\".\n \"\"\"\n blockDescriptor(block: BlockInput!): Unknown\n \"\"\"\n Resolves a dynamic prop against the current config values: a DROPDOWN\n yields { options, placeholder, disabled }, a DYNAMIC prop yields the\n resolved sub-property descriptor list.\n \"\"\"\n blockOptions(\n block: BlockInput!\n propName: String!\n input: Unknown\n connectionId: String\n \"What the author typed, for a DROPDOWN declared with refreshOnSearch.\"\n searchValue: String\n \"The step's reactor connection; its filter narrows what the resolver reads.\"\n reactorConnectionId: String\n ): Unknown\n \"\"\"\n Every piece this reactor offers: the core piece, its package pieces, and\n the pieces the registry and Activepieces publish.\n \"\"\"\n pieceCatalog: Unknown\n \"\"\"\n A piece's actions at one version; pin a step to that version.\n \"\"\"\n pieceActions(\n packageName: String!\n \"That version; the installed or latest one when omitted.\"\n version: String\n ): Unknown\n \"\"\"\n A piece's triggers at one version; pin a trigger to that version.\n \"\"\"\n pieceTriggers(\n packageName: String!\n \"That version; the installed or latest one when omitted.\"\n version: String\n ): Unknown\n \"\"\"\n Full piece detail (PieceMetadataModel-shaped), verbatim from the cloud API.\n \"\"\"\n pieceDetail(\n packageName: String!\n \"That version; the installed or latest one when omitted.\"\n version: String\n ): Unknown\n \"\"\"\n Piece and block search across the catalog, grouped by piece. The index\n builds lazily on first use; poll while status is \"indexing\".\n \"\"\"\n searchPieces(\n query: String!\n \"action | trigger\"\n kind: String!\n \"local | registry | activepieces; all when omitted.\"\n sources: [String!]\n \"Category ids, any of; all when omitted.\"\n categories: [String!]\n \"Pieces returned.\"\n limit: Int\n ): PieceSearchResult!\n \"\"\"\n Health of every registered piece trigger (poll schedule, errors).\n \"\"\"\n triggerStates: [TriggerStateRecord!]!\n \"\"\"\n Authored output shape of a block (SDL / outputSchema / sampleData).\n \"\"\"\n blockOutputTree(block: BlockInput!, config: Unknown): Unknown\n \"\"\"\n Output shape of a draft step or trigger: its latest test output\n (source \"test\", with sample and testedAt) when tested, else as blockOutputTree.\n \"\"\"\n stepOutputTree(workflowId: String!, stepId: String!): Unknown\n \"\"\"\n Every block of the draft (trigger first) as this reactor resolves it:\n which piece version runs, from where, and how it matches the pin.\n \"\"\"\n blockResolutions(workflowId: String!): [BlockResolutionRecord!]!\n \"\"\"\n Every powerhouse/connection document, for connection pickers.\n \"\"\"\n connections: [ConnectionRecord!]!\n \"\"\"\n The webhook endpoint for a workflow: the URL to hand the provider. Minted\n on first ask, whether or not the workflow is armed — an author needs the\n URL before enabling, and the armed field carries that difference. Null\n only when the host has no webhook service. With driveId, a workflow not\n synced here yet is waited for briefly, then fails as WORKFLOW_SYNCING.\n \"\"\"\n webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord\n \"\"\"\n Secret metadata (label, version, status). Never the value.\n \"\"\"\n secret(ref: String!): SecretRecord\n secrets: [SecretRecord!]!\n \"\"\"\n The URL an OAuth2 app must register as its redirect. A bare path when\n this host does not know its public origin; resolve it against the URL\n this API is reached at. Null when the host serves no HTTP routes.\n \"\"\"\n oauthRedirectUri: String\n \"\"\"\n How an OAuth2 sign-in opened by startOAuth stands; null when unknown.\n \"\"\"\n oauthAttempt(state: String!): OAuthAttempt\n }\n\n type OAuthAttempt {\n connectionId: String!\n \"PENDING | EXCHANGING | OK | ERROR\"\n status: String!\n error: String\n }\n\n type OAuthStart {\n state: String!\n \"Where to send the user to sign in.\"\n authorizationUrl: String!\n redirectUri: String!\n expiresAt: String!\n }\n\n \"\"\"\n One action or trigger of a piece, as a workflow pins it. The engine's own\n blocks are the piece @powerhousedao/piece-core.\n \"\"\"\n input BlockInput {\n pieceName: String!\n \"Exact semver.\"\n pieceVersion: String!\n \"The action or trigger name.\"\n name: String!\n \"action | trigger\"\n kind: String!\n }\n\n type BlockSearchHit {\n pieceName: String!\n \"The version the hit is listed at; pin to it when picking the block.\"\n pieceVersion: String!\n \"The action or trigger name.\"\n name: String!\n pieceDisplayName: String!\n logoUrl: String!\n displayName: String!\n description: String!\n \"action | trigger\"\n kind: String!\n \"Triggers only: POLLING | WEBHOOK | APP_WEBHOOK | MANUAL\"\n strategy: String\n \"Why this block cannot run on this reactor; null when it can.\"\n unsupported: String\n }\n\n type BlockResolutionRecord {\n \"The trigger's or step's id.\"\n stepId: String!\n pieceName: String!\n \"The version the block pins.\"\n pieceVersion: String!\n \"The action or trigger name.\"\n name: String!\n \"action | trigger\"\n kind: String!\n \"The version that runs; null when nothing resolves.\"\n resolvedVersion: String\n \"local | registry | activepieces | npm; null when nothing resolves.\"\n source: String\n \"exact | compatible | fallback | installed | missing\"\n match: String!\n \"Why the version that runs differs from the pin, or why nothing resolves.\"\n note: String\n \"The newest version any source offers.\"\n latestVersion: String\n }\n\n type PieceSearchMatch {\n pieceName: String!\n pieceVersion: String!\n displayName: String!\n description: String!\n logoUrl: String!\n categories: [String!]!\n \"local | registry | activepieces\"\n source: String!\n deprecated: Boolean\n \"Why no block of the piece can run on this reactor.\"\n unsupported: String\n \"Every query token matched the piece's own name.\"\n namedPiece: Boolean!\n \"Matching blocks of the kind asked for, best first.\"\n blocks: [BlockSearchHit!]!\n }\n\n type PieceSearchResult {\n \"ready | indexing | error\"\n status: String!\n pieces: [PieceSearchMatch!]!\n indexedPieces: Int!\n error: String\n }\n\n type SecretRecord {\n ref: String!\n label: String\n version: Int!\n status: String!\n createdAt: String!\n updatedAt: String!\n }\n\n type ConnectionRecord {\n id: String!\n name: String!\n connectorId: String!\n authType: String!\n status: String!\n accountLabel: String\n }\n\n type ReactorIdentity {\n \"The address the host signs as; null without a signed-in identity.\"\n address: String\n \"The did:key that signs the host's operations.\"\n key: String!\n }\n\n type ConnectionCheckResult {\n ok: Boolean!\n detail: String\n \"\"\"\n From auth.getConnectionIdentifier when the check passes; otherwise the\n label the connection already holds.\n \"\"\"\n accountLabel: String\n }\n\n type WebhookEndpointRecord {\n workflowId: String!\n url: String!\n \"\"\"\n False when the host gave the webhook service no public origin, so the url\n above is a bare path. Switchboard always gives one, falling back to\n http://localhost:<port> when PUBLIC_URL is unset.\n \"\"\"\n absoluteUrl: Boolean!\n \"True while the workflow is ENABLED with a valid webhook trigger\"\n armed: Boolean!\n createdAt: String!\n }\n\n type TriggerStateRecord {\n workflowId: String!\n pieceName: String!\n triggerName: String!\n status: String!\n intervalMs: Int!\n nextPollAt: String\n lastPollAt: String\n lastError: String\n consecutiveFailures: Int!\n \"When a webhook trigger next renews its subscription; null if it never does.\"\n nextRenewAt: String\n \"The last failed renewal, kept apart from lastError, the poll's.\"\n renewError: String\n renewFailures: Int!\n \"The piece version the trigger armed with; null for a host-fed trigger.\"\n pieceVersion: String\n pieceSource: String\n versionMatch: String\n versionNote: String\n }\n\n type Query {\n workflowRuntime: WorkflowRuntimeQueries!\n }\n\n type WorkflowStepRunRecord {\n stepId: String!\n stepKey: String!\n pieceName: String!\n \"The action the step ran, or the trigger a trigger test sampled.\"\n blockName: String!\n status: String!\n input: Unknown\n output: Unknown\n port: String\n error: String\n \"The thrown error's name, e.g. ReactorAccessDeniedError.\"\n errorName: String\n startedAt: String\n endedAt: String\n \"The piece version that ran; null for an unresolved block.\"\n pieceVersion: String\n \"local | registry | activepieces | npm\"\n pieceSource: String\n \"exact | compatible | fallback | installed | missing\"\n versionMatch: String\n \"Why the version that ran differs from the pin.\"\n versionNote: String\n }\n\n type WorkflowRunRecord {\n id: String!\n workflowId: String!\n workflowName: String!\n workflowVersion: Int!\n triggerKind: String!\n triggerPayload: Unknown\n status: String!\n error: String\n errorName: String\n \"When the run began executing; a PENDING run's is when it was journaled.\"\n startedAt: String!\n endedAt: String\n rerunOf: String\n \"How many warningNotes the run has; a run with any is not a plain success.\"\n warnings: Int!\n \"Steps that ran a fallback piece version, edges on ports nothing emits.\"\n warningNotes: [String!]!\n steps: [WorkflowStepRunRecord!]!\n }\n\n input WorkflowRunsPagingInput {\n \"Page size; default 25, at most 100.\"\n limit: Int\n \"The cursor of the previous page.\"\n cursor: String\n }\n\n type WorkflowRunResultPage {\n items: [WorkflowRunRecord!]!\n hasNextPage: Boolean!\n \"True when the page was read after a cursor.\"\n hasPreviousPage: Boolean!\n \"Resumes after this page's last run; null for an empty page.\"\n cursor: String\n }\n\n type WorkflowStepRun {\n stepId: String!\n key: String!\n pieceName: String!\n blockName: String!\n status: String!\n input: Unknown\n output: Unknown\n port: String\n error: String\n errorName: String\n }\n\n type WorkflowRunPayload {\n runId: String\n status: String!\n error: String\n errorName: String\n steps: [WorkflowStepRun!]!\n }\n\n type WorkflowStepTestResult {\n \"Null when the test never started, e.g. an upstream block is untested.\"\n runId: String\n \"\"\"\n SUCCEEDED | FAILED | INDETERMINATE. INDETERMINATE is neither: a host call\n the block made timed out, so a write it asked for may well have landed.\n Show it distinctly - it is not a confirmed pass.\n \"\"\"\n status: String!\n output: Unknown\n error: String\n errorName: String\n durationMs: Int!\n }\n\n \"\"\"\n WorkflowRuntime Mutations\n \"\"\"\n type WorkflowRuntimeMutations {\n \"\"\"\n Fires a workflow's manual trigger (the core piece's) and runs it to completion.\n \"\"\"\n fire(workflowId: String!, payload: Unknown): WorkflowRunPayload!\n \"\"\"\n Samples the draft trigger and saves it as the trigger's last test. A piece\n trigger runs its test hook (no cursor changes). Of the core piece's\n triggers, manual takes payload, schedule samples a fire now, and webhook\n waits for the next delivery to the workflow's endpoint, up to\n timeoutSeconds (default and cap 300), and that delivery runs nothing.\n \"\"\"\n testTrigger(\n workflowId: String!\n payload: Unknown\n timeoutSeconds: Int\n driveId: String\n ): Unknown\n \"\"\"\n Stops a webhook trigger test that is waiting; false when none was.\n \"\"\"\n cancelTriggerTest(workflowId: String!): Boolean!\n \"\"\"\n Runs one draft step against the latest test outputs of the blocks it\n reads, journaled as a \"test\" run and noted as the step's lastTest.\n driveId waits for an unsynced workflow, as for webhookEndpoint.\n \"\"\"\n testStep(\n workflowId: String!\n stepId: String!\n driveId: String\n ): WorkflowStepTestResult!\n \"\"\"\n Resumes a FAILED run: succeeded steps replay from the journal,\n execution restarts at the failure. Produces a new run.\n \"\"\"\n rerun(runId: String!): WorkflowRunPayload!\n \"\"\"\n Mints a managed secret and returns its ref; the value is stored\n encrypted and is never readable back over any API.\n \"\"\"\n createSecret(value: String!, label: String): SecretRecord!\n \"\"\"\n Replaces the value behind an existing ref; documents stay untouched.\n \"\"\"\n rotateSecret(ref: String!, value: String!): SecretRecord!\n \"\"\"\n Tombstones a secret; its value becomes unrecoverable.\n \"\"\"\n deleteSecret(ref: String!): Boolean!\n \"\"\"\n Runs the piece's auth.validate against the connection's credentials,\n then auth.getConnectionIdentifier for the account label, and records the\n outcome on the connection document.\n \"\"\"\n checkConnection(connectionId: String!): ConnectionCheckResult!\n \"\"\"\n Opens an OAuth2 sign-in with the connection's own app (client_id in its\n config, client_secret in its secretRefs). redirectUri is needed only when\n oauthRedirectUri is a bare path. With returnUrl, which must be on the\n caller's origin, the callback sends the browser back there with\n ?ph_oauth=<state> instead of closing the window.\n \"\"\"\n startOAuth(\n connectionId: String!\n redirectUri: String\n returnUrl: String\n ): OAuthStart!\n }\n\n type Mutation {\n workflowRuntime: WorkflowRuntimeMutations!\n }\n`;\n","import { BaseSubgraph, type SubgraphClass } from \"@powerhousedao/reactor-api\";\nimport type { WorkflowRuntimeService } from \"@powerhousedao/reactor-workflow\";\nimport type { DocumentNode } from \"graphql\";\nimport {\n getResolvers,\n type OAuthRouting,\n type ReactorAccessInfo,\n} from \"./resolvers.js\";\nimport { schema } from \"./schema.js\";\n\n/** The runtime's read/write surface. The runtime itself is composed by the\n * host, so the subgraph only serves what it is handed. */\nexport function createWorkflowRuntimeSubgraph(\n runtime: WorkflowRuntimeService,\n oauth?: OAuthRouting,\n access?: ReactorAccessInfo,\n): SubgraphClass {\n return class WorkflowRuntimeSubgraph extends BaseSubgraph {\n name = \"workflow-runtime\";\n typeDefs: DocumentNode = schema;\n // A field initializer runs after super(), so the authorization service\n // the secret mutations gate on is already in place.\n resolvers = getResolvers(\n runtime,\n this.authorizationService,\n oauth,\n access,\n (documentId, ctx) => this.assertCanRead(documentId, ctx),\n );\n additionalContextFields = {};\n };\n}\n","// Switchboard composes the workflow runtime from what it holds (the reactor\n// module) and what startAPI hands back. The intake is a read model.\nimport {\n REACTOR_SCHEMA,\n supportsLiveReadModelRegistration,\n type AttachmentRef,\n type DocumentViewDatabase,\n type InProcessReactorClientModule,\n type IReactorClient,\n type IRelationalDb,\n type ModelManifestEntry,\n type ReactorBuilder,\n} from \"@powerhousedao/reactor\";\nimport {\n AuthorizationPolicy,\n ForbiddenError,\n callerSubject,\n createCanonicalDocumentIdResolver,\n type CanonicalDocumentId,\n type Context,\n type IAttachmentAccessService,\n type IAuthorizationService,\n type IPackagePieceSource,\n type PackagePieceEntry,\n type SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport { parseRef } from \"@powerhousedao/reactor-attachments\";\nimport type * as WorkflowEngine from \"@powerhousedao/reactor-workflow\";\nimport type {\n AttachmentClientLike,\n AttachmentReadRequest,\n HostIdentity,\n WorkflowCaller,\n WorkflowRuntimeHostDeps,\n} from \"@powerhousedao/reactor-workflow\";\nimport type {\n IHttpScope,\n IWebhookScope,\n ScopedRouteHandle,\n} from \"@powerhousedao/shared/processors\";\nimport type { Principal } from \"@powerhousedao/shared/document-model\";\nimport type { ILogger } from \"document-model\";\nimport type { Kysely } from \"kysely\";\nimport {\n callbackUrlOf,\n registerOAuthCallback,\n} from \"./workflow/oauth-callback.js\";\nimport type {\n ReactorAccessInfo,\n ReactorIdentity,\n} from \"./workflow/resolvers.js\";\nimport { triggerFatalShutdown } from \"./fatal-shutdown.mjs\";\nimport { createWorkflowRuntimeSubgraph } from \"./workflow/subgraph.js\";\n\ntype WorkflowEngineModule = typeof WorkflowEngine;\n\n/** The npm name the workflow package owns: its HTTP namespace and its models. */\nexport const WORKFLOW_PACKAGE_NAME = \"@powerhousedao/workflow\";\nexport const WORKFLOW_TELEMETRY_SCOPE = \"@powerhousedao/reactor-workflow\";\n\n/** The env var and OpenFeature flag key that turns workflows on. */\nexport const PH_WORKFLOWS_ENABLED = \"PH_WORKFLOWS_ENABLED\";\n\n/** Whether the operation intake is indexing. Same shape as the attachment\n * reference projection, because it is the same limitation. */\nexport type WorkflowTriggersCapability =\n | { status: \"available\" }\n | {\n status: \"unavailable\";\n reason:\n | \"in-process-reactor-module-unavailable\"\n | \"live-read-model-registration-unsupported\"\n | \"workflow-singleton-lost\";\n };\n\nconst SINGLETON_LOST: WorkflowTriggersCapability = {\n status: \"unavailable\",\n reason: \"workflow-singleton-lost\",\n};\n\n/** The slice of switchboard's OpenFeature client this needs. */\nexport interface BooleanFlagSource {\n getBooleanValue(flagKey: string, defaultValue: boolean): Promise<boolean>;\n}\n\nexport interface WorkflowsFlagInput {\n featureFlags: BooleanFlagSource;\n /** The host's own answer; wins over everything. */\n override?: boolean;\n /** `workflows.enabled` from the powerhouse config file. */\n configEnabled?: boolean;\n /** Defaults to process.env; the tests pass their own. */\n env?: Record<string, string | undefined>;\n}\n\n/** Precedence, unchanged from the reactor-api resolver this replaces: the\n * host's option, then PH_WORKFLOWS_ENABLED, then the config file, then off. */\nexport async function resolveWorkflowsEnabled({\n featureFlags,\n override,\n configEnabled = false,\n env = process.env,\n}: WorkflowsFlagInput): Promise<boolean> {\n if (override !== undefined) return override;\n\n // The env layer is switchboard's OpenFeature client, which casts only\n // \"true\"/\"false\": the numeric forms reactor-api took are answered here.\n const raw = env[PH_WORKFLOWS_ENABLED]?.trim();\n if (raw === \"1\") return true;\n if (raw === \"0\") return false;\n\n return featureFlags.getBooleanValue(PH_WORKFLOWS_ENABLED, configEnabled);\n}\n\n// The package manager reports an unresolvable package and continues; for one\n// the host added itself that is a misconfigured switchboard, not a degraded\n// one. The manager imports this subpath moments later, so the cache absorbs it.\nexport async function assertWorkflowPackageLoadable(\n load: () => Promise<unknown> = () =>\n import(\"@powerhousedao/workflow/document-models\"),\n): Promise<void> {\n try {\n await load();\n } catch (error) {\n throw new Error(\n `Workflows are enabled but ${WORKFLOW_PACKAGE_NAME} could not be loaded`,\n { cause: error },\n );\n }\n}\n\n/**\n * Whether a composition failure was the workflow singleton refusing this\n * process, rather than something that should take the boot down.\n *\n * Matched by NAME: the engine loads lazily, and importing it here for the\n * constructor would defeat that. The fields the engine's error carries are\n * typed optional for the same reason.\n */\nexport function isWorkflowSingletonConflict(\n error: unknown,\n): error is Error & { owner?: string; expiresAt?: string; wouldBe?: string } {\n return (\n error instanceof Error && error.name === \"WorkflowSingletonConflictError\"\n );\n}\n\n/** How often a host refused the singleton at boot tries the claim again: the\n * engine's renewal period. */\nexport const WORKFLOW_SINGLETON_RETRY_MS = 20_000;\n\nexport interface WorkflowSingletonRetry {\n /** Stops retrying; waits for an attempt in flight, and stops what it\n * composed if the host is going away. */\n stop(): Promise<void>;\n}\n\n/**\n * Retries the singleton claim for a host that booted without it, and hands\n * the runtime over once a claim succeeds.\n *\n * Without it a rolling deploy whose slots have different owner names ends\n * with nobody running workflows: the new pod is refused while the old one\n * still holds the lease, and nothing retries once the old pod releases it.\n * Only for a host that never composed; one that lost the lease after\n * composing stays without workflows until it restarts.\n */\nexport function retryWorkflowSingleton(options: {\n compose: () => Promise<ComposedWorkflowRuntime>;\n onComposed: (workflows: ComposedWorkflowRuntime) => Promise<void>;\n logger: ILogger;\n intervalMs?: number;\n}): WorkflowSingletonRetry {\n const intervalMs = options.intervalMs ?? WORKFLOW_SINGLETON_RETRY_MS;\n let stopped = false;\n let timer: NodeJS.Timeout | undefined;\n let attempt: Promise<void> | undefined;\n\n const run = async () => {\n let workflows: ComposedWorkflowRuntime;\n try {\n workflows = await options.compose();\n } catch (error) {\n if (!isWorkflowSingletonConflict(error)) {\n options.logger.error(\n \"Composing the workflow runtime after the singleton came free failed: @error\",\n error,\n );\n }\n schedule();\n return;\n }\n if (stopped) {\n await workflows.stop();\n return;\n }\n options.logger.info(\n \"Claimed the workflow singleton after boot; starting the workflow runtime\",\n );\n try {\n await options.onComposed(workflows);\n } catch (error) {\n options.logger.error(\n \"Starting the workflow runtime after the singleton came free failed: @error\",\n error,\n );\n schedule();\n }\n };\n\n const schedule = () => {\n if (stopped) return;\n timer = setTimeout(() => {\n timer = undefined;\n attempt = run().finally(() => {\n attempt = undefined;\n });\n }, intervalMs);\n timer.unref();\n };\n\n schedule();\n return {\n async stop() {\n stopped = true;\n if (timer) clearTimeout(timer);\n timer = undefined;\n await attempt?.catch(() => undefined);\n },\n };\n}\n\n/**\n * What a host does once its composed runtime has shut down for losing the\n * workflow singleton.\n *\n * Taken over by another claim: that process runs workflows now, so this one\n * stays without them until it restarts. Unrenewable with no takeover seen (a\n * database blip): nothing else runs them, so the process goes down through\n * the fatal shutdown and its supervisor restarts it, which re-claims at boot.\n * A host with no fatal shutdown installed (embedded) stays without workflows\n * and says a restart is needed.\n */\nexport function workflowSingletonLossHandler(\n logger: ILogger,\n fatal: (kind: string, error: unknown) => boolean = triggerFatalShutdown,\n): (loss: WorkflowEngine.WorkflowSingletonLoss) => void {\n return (loss) => {\n if (loss.reason === \"taken\") {\n logger.error(\n `Another process (\"${loss.heldBy ?? \"unknown\"}\") took the workflow ` +\n \"singleton. This Switchboard has stopped its workflow runtime \" +\n \"and runs no workflows until it is restarted; everything else \" +\n \"serves normally.\",\n );\n return;\n }\n const error = new Error(\n \"The workflow singleton lease could not be renewed for \" +\n `${Math.round(loss.silentMs)}ms; no other process was seen taking it ` +\n \"over\",\n );\n if (fatal(\"Workflow singleton lease unrenewable\", error)) return;\n logger.error(\n `${error.message}. This Switchboard has stopped its workflow runtime ` +\n \"and runs no workflows until it is restarted.\",\n );\n };\n}\n\n/** The importable models piece workers load: the boot list, and a type's entries. */\nexport interface ModelManifestSource {\n modelManifest(): ModelManifestEntry[];\n modelEntries(documentType: string): ModelManifestEntry[];\n}\n\nexport function modelManifestSource(\n builder: Pick<\n ReactorBuilder,\n \"getResolvedModelManifest\" | \"getImportableEntries\"\n >,\n): ModelManifestSource {\n return {\n modelManifest: () => builder.getResolvedModelManifest() ?? [],\n modelEntries: (documentType) => builder.getImportableEntries(documentType),\n };\n}\n\nexport interface ComposeWorkflowRuntimeDeps {\n reactorClient: IReactorClient;\n /** The registry this host installs packages from; pieces come from it too.\n * Absent on a host that installs from none, and only the cloud is read. */\n pieceRegistryUrl?: string;\n /** Where the trigger read model registers; absent leaves the intake\n * unavailable rather than quietly dropping every document trigger. */\n clientModule?: InProcessReactorClientModule;\n relationalDb: IRelationalDb;\n /** False when relationalDb outlives the working directory, so the secret\n * store needs PH_WORKFLOWS_SECRETS_MASTER_KEY rather than a generated key. */\n secretsKeyFile?: false;\n attachments: AttachmentClientLike;\n /** Decides a step's attachment reads like the attachment routes do;\n * absent, a step reads none but the files its own run wrote. */\n attachmentAccess?: IAttachmentAccessService;\n webhooks?: IWebhookScope;\n /** The workflow package's HTTP namespace; the OAuth2 callback lives on it.\n * Absent leaves OAuth2 connections unable to sign in. */\n http?: IHttpScope;\n authorizationService: IAuthorizationService;\n /** Where the pieces installed packages ship come from; absent leaves the\n * runtime with none and only published bundles resolvable. */\n pieces?: IPackagePieceSource;\n logger: ILogger;\n /** Absent leaves pieces with no document models in their worker. */\n models?: ModelManifestSource;\n /** The reactor's executor and projection threads, for sizing the piece pool. */\n reactorThreads?: number;\n /** Where run, step, worker and reactor-call spans and metrics go. */\n telemetry?: WorkflowEngine.WorkflowRuntimeHostDeps[\"telemetry\"];\n /** Overridden by the tests; production always loads the real engine. */\n load?: () => Promise<WorkflowEngineModule>;\n /**\n * Whether to claim the workflow singleton before composing (plan agreed\n * decision 3). On by default, and the only honest setting for a real host:\n * two replicas over one run journal fail each other's live runs. A suite\n * that composes several runtimes over separate databases turns it off.\n */\n singletonLease?: boolean;\n /**\n * Where this host's read-model database lives — the Postgres URL, or the\n * absolute PGlite directory. It is the stable half of the default singleton\n * owner name, so a restart of THIS slot re-claims its own lease at once\n * instead of waiting out the 60s TTL for a killed process's claim. Hashed\n * before it is used, so a connection string's credentials go no further.\n */\n storageId?: string;\n /**\n * True when the journal's database is an embedded one no other process can\n * open (PGlite). Nothing can then take the lease, so a renewal that stalls\n * (a busy queue, a blocked event loop) is logged rather than turning\n * workflows off.\n */\n exclusiveJournal?: boolean;\n /** Called once when the composed runtime has shut down for losing the\n * singleton; see {@link workflowSingletonLossHandler}. */\n onSingletonLost?: (loss: WorkflowEngine.WorkflowSingletonLoss) => void;\n}\n\nexport interface ComposedWorkflowRuntime {\n subgraph: SubgraphClass;\n /** Whether document operations reach the runtime at all; unavailable once\n * the singleton is lost. */\n readonly triggers: WorkflowTriggersCapability;\n /** The owner name this host holds the workflow singleton under; undefined\n * when the lease was not taken (a suite that opted out). */\n singletonOwner?: string;\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\n// The engine's own access check, answered as BaseSubgraph answers it: the\n// host ACL (an admin passes, another policy fails closed, an unresolvable\n// identifier is a denial), then the reactor's read gate as the caller.\nfunction readAssertion(\n authorizationService: IAuthorizationService,\n reactorClient: IReactorClient,\n): WorkflowRuntimeHostDeps[\"assertCanRead\"] {\n const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);\n const hostCanRead = async (identifier: string, ctx: Context) => {\n if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;\n if (\n authorizationService.config.policy !==\n AuthorizationPolicy.DOCUMENT_PERMISSIONS\n ) {\n throw new ForbiddenError();\n }\n let documentId: CanonicalDocumentId;\n try {\n documentId = await resolveCanonical(identifier);\n } catch {\n throw new ForbiddenError();\n }\n const canRead = await authorizationService.canRead(\n documentId,\n ctx.user?.address,\n );\n if (!canRead) throw new ForbiddenError(\"to read this document\");\n };\n return async (identifier: string, caller: WorkflowCaller) => {\n const ctx = caller as Context;\n await hostCanRead(identifier, ctx);\n let served: boolean;\n try {\n served = await reactorClient.isServed(identifier, {\n subject: callerSubject(ctx.user),\n });\n } catch {\n throw new ForbiddenError();\n }\n if (!served) throw new ForbiddenError(\"to read this document\");\n };\n}\n\n/** The same, for a design-time call that writes what it names. */\nfunction writeAssertion(\n authorizationService: IAuthorizationService,\n reactorClient: IReactorClient,\n): WorkflowRuntimeHostDeps[\"assertCanWrite\"] {\n const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);\n return async (identifier: string, caller: WorkflowCaller) => {\n const ctx = caller as Context;\n if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;\n if (\n authorizationService.config.policy !==\n AuthorizationPolicy.DOCUMENT_PERMISSIONS\n ) {\n throw new ForbiddenError();\n }\n let documentId: CanonicalDocumentId;\n try {\n documentId = await resolveCanonical(identifier);\n } catch {\n throw new ForbiddenError();\n }\n const canWrite = await authorizationService.canWrite(\n documentId,\n ctx.user?.address,\n );\n if (!canWrite) throw new ForbiddenError(\"to write this document\");\n };\n}\n\n/** What the reactor enforces and who it signs as; unknown counts as enforced. */\nexport function reactorAccessOf(\n clientModule: InProcessReactorClientModule | undefined,\n): ReactorAccessInfo {\n const flags = clientModule?.reactorModule?.featureFlags;\n const signer = clientModule?.signer;\n const key = signer?.app?.key;\n const identity: ReactorIdentity | null = key\n ? { address: signer.user?.address ?? null, key }\n : null;\n return {\n authEnforcement: flags ? flags.authEnforcement : true,\n authConditions: flags?.authConditions === true,\n identity,\n };\n}\n\n/** Whom a run's created documents also grant: the host, as §8 grants it. */\nexport function hostPrincipalOf(\n access: ReactorAccessInfo,\n): Principal | undefined {\n const identity = access.identity;\n if (!identity) return undefined;\n if (access.authConditions) {\n return { match: { eq: [{ attr: \"subject.key\" }, { lit: identity.key }] } };\n }\n return identity.address ? { address: identity.address } : undefined;\n}\n\n/** Who the host signs as, so a publish it signs makes no run user. */\nexport function hostIdentityOf(\n access: ReactorAccessInfo,\n): HostIdentity | undefined {\n const identity = access.identity;\n if (!identity) return undefined;\n return identity.address\n ? { address: identity.address, key: identity.key }\n : { key: identity.key };\n}\n\nconst REFERENCE_INDEX_RETRIES = 8;\nconst REFERENCE_INDEX_RETRY_MS = 250;\n\n/** A step reads an attachment the way the download route serves one: when the\n * run's user may read a document that references it. The candidates are the\n * documents the run was handed; the reference index can trail the operation\n * that fired the trigger, so a denial is retried briefly. */\nexport function attachmentReadPolicy(\n access: IAttachmentAccessService | undefined,\n retryMs = REFERENCE_INDEX_RETRY_MS,\n): (request: AttachmentReadRequest) => Promise<boolean> {\n return async (request) => {\n try {\n if (parseRef(request.ref as AttachmentRef).version !== 1) return false;\n } catch {\n return false;\n }\n if (!access || request.documentIds.length === 0) return false;\n const subject = request.runUser?.subject;\n const caller = {\n ...(subject?.address ? { userAddress: subject.address } : {}),\n ...(subject?.key ? { appKey: subject.key } : {}),\n };\n for (let attempt = 0; attempt <= REFERENCE_INDEX_RETRIES; attempt++) {\n for (const documentId of request.documentIds) {\n const result = await access.canReadAttachment({\n documentId,\n attachmentRef: request.ref,\n ...caller,\n });\n if (result.kind === \"allowed\") return true;\n }\n if (attempt < REFERENCE_INDEX_RETRIES) {\n await new Promise((resolve) => setTimeout(resolve, retryMs));\n }\n }\n return false;\n };\n}\n\n// The trigger read model lives exactly as long as its runtime: tearDown takes\n// it off the coordinator, so a later compose in this process can register.\ninterface TriggersRegistration {\n tornDown: boolean;\n detach?: () => void;\n}\n\n// Live registration is the capability the attachment reference index needs\n// too, so a coordinator without it reads unavailable for the same reason.\nasync function registerWorkflowTriggersReadModel(\n engine: WorkflowEngineModule,\n runtime: WorkflowEngine.WorkflowRuntimeService,\n clientModule: InProcessReactorClientModule | undefined,\n registration: TriggersRegistration,\n): Promise<WorkflowTriggersCapability> {\n const reactorModule = clientModule?.reactorModule;\n if (!reactorModule) {\n return {\n status: \"unavailable\",\n reason: \"in-process-reactor-module-unavailable\",\n };\n }\n\n const coordinator = reactorModule.readModelCoordinator;\n if (!supportsLiveReadModelRegistration(coordinator)) {\n return {\n status: \"unavailable\",\n reason: \"live-read-model-registration-unsupported\",\n };\n }\n\n // Schema-qualified: the cursor row lives in the reactor's own ViewState.\n const readModel = new engine.WorkflowTriggersReadModel(\n (reactorModule.database as unknown as Kysely<unknown>).withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<DocumentViewDatabase>,\n reactorModule.operationIndex,\n reactorModule.writeCache,\n reactorModule.processorManagerConsistencyTracker,\n runtime,\n );\n await readModel.init();\n // Torn down while it replayed: registered now, it would outlive the runtime.\n if (registration.tornDown) return SINGLETON_LOST;\n coordinator.addReadModel(\n readModel,\n engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE,\n );\n registration.detach = () => coordinator.removeReadModel(readModel);\n\n return { status: \"available\" };\n}\n\n// The runtime holds pieces; reactor-api is what resolves them. Rebound on\n// every change, so a package rebuilt while this runs needs no restart.\nexport function bindPackagePieces(\n registry: { setPieces(pieces: readonly PackagePieceEntry[]): void },\n source: IPackagePieceSource,\n): void {\n // Sorted by package name, so which package keeps a contested piece is stable.\n const apply = (byPackage: Map<string, PackagePieceEntry[]>) => {\n registry.setPieces(\n [...byPackage.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .flatMap(([, pieces]) => pieces),\n );\n };\n // The initial load already happened inside startAPI, so what it reported is\n // read here rather than waited for.\n apply(source.getPieces());\n source.onPiecesChange(apply);\n}\n\n// Builds the runtime, registers its intake, and returns its GraphQL face plus\n// the lifecycle the host drives. The engine loads lazily: off means unloaded.\nexport async function composeWorkflowRuntime(\n deps: ComposeWorkflowRuntimeDeps,\n): Promise<ComposedWorkflowRuntime> {\n const load = deps.load ?? (() => import(\"@powerhousedao/reactor-workflow\"));\n\n let engine: WorkflowEngineModule;\n try {\n engine = await load();\n } catch (error) {\n throw new Error(\n \"Workflows are enabled but @powerhousedao/reactor-workflow could not be loaded\",\n { cause: error },\n );\n }\n\n // BEFORE anything else touches the run journal. Opening the journal runs\n // its orphan/abandoned sweeps, which close out every RUNNING and PENDING\n // run that is not this process's — i.e. a second replica booting fails the\n // first replica's live runs. The claim is what makes the plan's singleton\n // decision structural instead of documented; it refuses by name.\n const loss: SingletonLoss = { lost: false };\n const lease =\n deps.singletonLease === false\n ? undefined\n : await engine.acquireWorkflowSingletonLease({\n relationalDb: deps.relationalDb,\n logger: deps.logger,\n ...(deps.storageId ? { storageId: deps.storageId } : {}),\n selfFence: deps.exclusiveJournal !== true,\n onLost: (lost) => {\n loss.lost = true;\n if (lost.reason === \"taken\") loss.heldBy = lost.heldBy;\n loss.tearDown?.();\n // While composing, the compose itself fails with a conflict and\n // the host retries the claim.\n if (loss.composed) deps.onSingletonLost?.(lost);\n },\n });\n\n try {\n const composed = await composeClaimed(engine, deps, lease, loss);\n if (loss.lost) throw singletonLostError(engine, loss, lease);\n loss.composed = true;\n return composed;\n } catch (error) {\n // Renewing since the claim, so a compose that fails hands it back, after\n // stopping whatever runtime it had already built.\n loss.tearDown?.();\n await lease?.release();\n throw error;\n }\n}\n\ntype SingletonLease = Awaited<\n ReturnType<WorkflowEngineModule[\"acquireWorkflowSingletonLease\"]>\n>;\n\n// Losing the lease shuts the runtime down; tearDown is set once it exists.\ninterface SingletonLoss {\n lost: boolean;\n composed?: boolean;\n heldBy?: string;\n tearDown?: () => void;\n}\n\nfunction singletonLostError(\n engine: WorkflowEngineModule,\n loss: SingletonLoss,\n lease: SingletonLease | undefined,\n): Error {\n return new engine.WorkflowSingletonConflictError(\n loss.heldBy ?? \"unknown\",\n \"unknown\",\n lease?.owner ?? \"unknown\",\n );\n}\n\nasync function composeClaimed(\n engine: WorkflowEngineModule,\n deps: ComposeWorkflowRuntimeDeps,\n lease: SingletonLease | undefined,\n loss: SingletonLoss,\n): Promise<ComposedWorkflowRuntime> {\n // The same registry the host installs packages from, so a piece it indexes\n // is reachable without a second setting to keep in step.\n engine.setPieceRegistryUrl(deps.pieceRegistryUrl);\n\n // Before the runtime exists: a restored trigger asks for a piece as soon as\n // the supervisor starts, and the catalog is served from the same holder.\n if (deps.pieces) bindPackagePieces(engine.packagePieces, deps.pieces);\n\n // Creating the runtime opens the journal, whose sweeps fail every run not\n // in this process: never after the lease has gone.\n if (loss.lost) throw singletonLostError(engine, loss, lease);\n const access = reactorAccessOf(deps.clientModule);\n const models = deps.models;\n const runtime = engine.createWorkflowRuntime({\n relationalDb: deps.relationalDb,\n secretsKeyFile: deps.secretsKeyFile,\n reactorClient: deps.reactorClient,\n assertCanRead: readAssertion(deps.authorizationService, deps.reactorClient),\n subjectOf: (caller) => callerSubject((caller as Context).user),\n assertCanWrite: writeAssertion(\n deps.authorizationService,\n deps.reactorClient,\n ),\n // Unknown flags leave it absent, which the engine takes as on.\n ...(deps.clientModule?.reactorModule\n ? { authEnforcement: access.authEnforcement }\n : {}),\n hostPrincipal: hostPrincipalOf(access),\n hostIdentity: hostIdentityOf(access),\n ...(models\n ? {\n modelManifest: () => models.modelManifest(),\n modelEntries: (documentType: string) =>\n models.modelEntries(documentType),\n }\n : {}),\n webhooks: deps.webhooks,\n attachments: deps.attachments,\n canReadAttachmentRef: attachmentReadPolicy(deps.attachmentAccess),\n logger: deps.logger,\n ...(deps.reactorThreads ? { reactorThreads: deps.reactorThreads } : {}),\n ...(deps.telemetry ? { telemetry: deps.telemetry } : {}),\n });\n\n // Set before anything below can throw, so a failed compose stops it.\n const routes: { oauthCallback?: ScopedRouteHandle } = {};\n const registration: TriggersRegistration = { tornDown: false };\n const tearDown = () => {\n if (registration.tornDown) return;\n registration.tornDown = true;\n routes.oauthCallback?.dispose();\n runtime.shutdown();\n // After the shutdown, so a batch already queued for it is refused and\n // replays on the next owner instead of being acknowledged here.\n registration.detach?.();\n };\n loss.tearDown = tearDown;\n\n const triggers = await registerWorkflowTriggersReadModel(\n engine,\n runtime,\n deps.clientModule,\n registration,\n );\n // Lost while registering: mount nothing a torn-down runtime would leave.\n if (registration.tornDown) throw singletonLostError(engine, loss, lease);\n if (triggers.status === \"available\") {\n deps.logger.info(\n `Workflow trigger read model registered (${engine.WORKFLOW_TRIGGERS_READ_MODEL}, ${engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE})`,\n );\n } else {\n // Loudly: the runtime still serves GraphQL and still runs webhook and\n // schedule triggers, so nothing else says the document ones are dead.\n deps.logger.error(\n \"Workflow document triggers are NOT armed (@reason): this reactor's \" +\n \"read-model coordinator takes no live registration, so no document \" +\n \"operation reaches the runtime. Webhook and schedule triggers are \" +\n \"unaffected.\",\n triggers.reason,\n );\n }\n\n let stopped = false;\n if (deps.http) {\n routes.oauthCallback = registerOAuthCallback(deps.http, runtime);\n }\n\n return {\n subgraph: createWorkflowRuntimeSubgraph(\n runtime,\n deps.http ? { callbackUrl: callbackUrlOf(deps.http) } : undefined,\n access,\n ),\n get triggers() {\n return loss.lost ? SINGLETON_LOST : triggers;\n },\n ...(lease ? { singletonOwner: lease.owner } : {}),\n\n async start() {\n if (registration.tornDown) return;\n // The endpoint family first: a restored webhook trigger asks for its URL\n // as soon as the supervisor starts.\n await runtime.registerWebhookEndpoint();\n // Lost or stopped while registering.\n if (loss.lost || stopped) return;\n runtime.startTriggerSupervisor();\n // So the first search in the editor finds the catalog indexed.\n runtime.warmPieceSearch();\n },\n\n async stop() {\n if (stopped) return;\n stopped = true;\n tearDown();\n // Released, so the next boot owns workflows immediately instead of\n // waiting out the lease TTL.\n await lease?.release();\n },\n };\n}\n","import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport type { ILogger } from \"document-model\";\nimport { z } from \"zod\";\nimport {\n isWorkflowSingletonConflict,\n retryWorkflowSingleton,\n type ComposedWorkflowRuntime,\n type WorkflowSingletonRetry,\n} from \"../workflow-runtime.mjs\";\nimport type { SwitchboardHostContext } from \"../plugin-host.mjs\";\n\n/**\n * R2.5 — the workflows subsystem as a built-in plugin. Presence is activation\n * (an explicit options.workflows.enabled === false still wins, mirroring the\n * mcp carve); the PH_WORKFLOWS_ENABLED env/config resolution governs the\n * classic path only.\n *\n * The plugin also DECLARES the drive the runtime serves — the Workflows drive\n * that opens in Workflow Studio — as a drive contribution (workflow-plugins\n * plan). The switchboard runner merges it into the host's drive plan (a host\n * declaration with the same slug wins), seeds it, reports it on the handle so\n * a compound can hand it to its connect member, and `--explain drives` lists\n * it with this plugin as provenance. Before, the runner seeded that drive as\n * an implicit side effect of the workflows flag; now the entry's `config.drive`\n * names it (`drive: false` serves the runtime without seeding a drive).\n *\n * The orchestration (compose, singleton-conflict retry, subgraph\n * registration, start, inspection fact) moves here VERBATIM from the inline\n * block; the dependency-heavy wiring closures (composeWorkflows,\n * registerWorkflowSubgraph) stay in server.mts and travel via ctx — same\n * realm, code moved not redesigned. Carve-map constraints preserved: the\n * retry path's onComposed registers + updates the router ITSELF (it may fire\n * after the readiness drain); teardown stops retry then runtime, and runs\n * AFTER privacy's (sequential onShutdown, registration order).\n */\n\nexport interface WorkflowsOrchestration {\n enabled: boolean;\n composeWorkflows: () => Promise<ComposedWorkflowRuntime>;\n registerWorkflowSubgraph: (\n composed: ComposedWorkflowRuntime,\n ) => Promise<void>;\n updateRouter: () => Promise<void>;\n reportMountFailure: (error: unknown) => void;\n setWorkflowsFact: () => void;\n}\n\ntype WorkflowsOptions = Record<string, unknown> & {\n workflows?: { enabled?: boolean };\n};\n\n/** The drive app Workflow Studio registers under (packages/workflow). */\nexport const WORKFLOW_STUDIO_EDITOR_ID = \"workflow-studio\";\n\n/** The drive the plugin seeds unless the entry says otherwise. */\nexport const DEFAULT_WORKFLOWS_DRIVE = {\n slug: \"workflows\",\n name: \"Workflows\",\n} as const;\n\nconst workflowsDriveSchema = z.strictObject({\n /** The seeding key and the served `/d/<slug>` path (default \"workflows\"). */\n slug: z.string().min(1).optional(),\n /** Display name (default \"Workflows\"). */\n name: z.string().min(1).optional(),\n /** Fixed id; without one the id is project-hashed like classic `ph vetra`\n * (`workflows-<sha256(projectPath)[0:8]>`, slug unchanged), so existing\n * stores keep theirs. `projectHash: true` hashes the served slug as well. */\n id: z.string().min(1).optional(),\n projectHash: z.union([z.boolean(), z.literal(\"id\")]).optional(),\n icon: z.string().optional(),\n});\n\nexport const workflowsPluginConfigSchema = z.strictObject({\n /** The Workflows drive to seed; `false` runs the runtime without one. */\n drive: z.union([workflowsDriveSchema, z.literal(false)]).optional(),\n});\n\nexport type WorkflowsPluginConfig = z.infer<typeof workflowsPluginConfigSchema>;\n\n/** What a host.js entry writes (typed-host-configs 1.4). Kept a type alias,\n * not an interface, so it stays assignable to the runtime `PluginEntryData`\n * config record. */\nexport type WorkflowsPluginConfigInput = z.input<\n typeof workflowsPluginConfigSchema\n>;\n\ndeclare global {\n interface PHPluginConfigs {\n \"@powerhousedao/switchboard/plugins/workflows\": WorkflowsPluginConfigInput;\n }\n}\n\nexport type WorkflowsPlugin = HostPlugin<\n {\n transformServerOptions: (\n options: Record<string, unknown>,\n ctx: SwitchboardHostContext,\n ) => Record<string, unknown>;\n onSubgraphsRegistering: (ctx: SwitchboardHostContext) => Promise<void>;\n onShutdown: (ctx: SwitchboardHostContext) => Promise<void>;\n },\n WorkflowsPluginConfig\n>;\n\n/** The drive declaration the entry config amounts to (host-core's\n * DriveDeclaration shape; kept structural here to avoid the import cycle the\n * Contributions type documents). `undefined` when `drive: false`. */\nexport function workflowsDriveDeclaration(\n config: WorkflowsPluginConfig,\n): Record<string, unknown> | undefined {\n if (config.drive === false) return undefined;\n const drive = config.drive ?? {};\n return {\n slug: drive.slug ?? DEFAULT_WORKFLOWS_DRIVE.slug,\n name: drive.name ?? DEFAULT_WORKFLOWS_DRIVE.name,\n preferredEditor: WORKFLOW_STUDIO_EDITOR_ID,\n ...(drive.id !== undefined\n ? { id: drive.id }\n : { projectHash: drive.projectHash ?? \"id\" }),\n ...(drive.icon !== undefined ? { icon: drive.icon } : {}),\n };\n}\n\nexport function createWorkflowsPlugin(\n rawConfig: unknown = {},\n): WorkflowsPlugin {\n const config = workflowsPluginConfigSchema.parse(rawConfig ?? {});\n const drive = workflowsDriveDeclaration(config);\n return {\n name: \"switchboard-workflows\",\n appliesTo: \"switchboard\",\n configSchema: workflowsPluginConfigSchema,\n contributions: { drives: drive ? [drive] : [] },\n hooks: {\n transformServerOptions: (options) => {\n const current = (options as WorkflowsOptions).workflows;\n if (current?.enabled === false) return options;\n return { ...options, workflows: { ...current, enabled: true } };\n },\n onSubgraphsRegistering: async (ctx) => {\n const orchestration = ctx.workflowsOrchestration as\n | WorkflowsOrchestration\n | undefined;\n if (!orchestration?.enabled) return;\n const logger = ctx.logger as ILogger;\n const lateSubgraphs = ctx.lateSubgraphs!;\n\n let workflows: ComposedWorkflowRuntime | undefined;\n let workflowsRetry: WorkflowSingletonRetry | undefined;\n try {\n workflows = await orchestration.composeWorkflows();\n } catch (error) {\n // Without the claim this host must not run workflows, but everything\n // else it serves still works, so it boots without the runtime.\n if (!isWorkflowSingletonConflict(error)) throw error;\n logger.warn(\n `Workflows are enabled but another live process (\"${error.owner ?? \"unknown\"}\") ` +\n `holds the workflow singleton until ${error.expiresAt ?? \"unknown\"}. ` +\n \"This Switchboard has booted WITHOUT the workflow runtime: no \" +\n \"trigger of any kind fires here, and the workflow GraphQL face is \" +\n \"absent. Everything else serves normally. Stop the other owner, or \" +\n \"set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the \" +\n \"slot that owns workflows. This Switchboard retries the claim and \" +\n \"starts workflows once the lease comes free.\",\n );\n workflowsRetry = retryWorkflowSingleton({\n compose: orchestration.composeWorkflows,\n onComposed: async (composed) => {\n try {\n await composed.start();\n } catch (error) {\n // Hands the lease back so a retry or another replica can claim it.\n try {\n await composed.stop();\n } catch (stopError) {\n logger.error(\n \"Stopping the late workflow runtime failed: @error\",\n stopError,\n );\n }\n throw error;\n }\n logger.info(\"Workflow runtime started\");\n ctx.workflows = composed;\n await orchestration.registerWorkflowSubgraph(composed);\n // Past boot nothing else rebuilds the router, so a subgraph\n // registered now is not served until this runs.\n try {\n await orchestration.updateRouter();\n } catch (error) {\n orchestration.reportMountFailure(error);\n }\n },\n logger,\n });\n }\n ctx.workflowsRetry = workflowsRetry;\n if (workflows) {\n ctx.workflows = workflows;\n lateSubgraphs.push(orchestration.registerWorkflowSubgraph(workflows));\n await workflows.start();\n logger.info(\"Workflow runtime started\");\n orchestration.setWorkflowsFact();\n }\n },\n onShutdown: async (ctx) => {\n await (\n ctx.workflowsRetry as WorkflowSingletonRetry | undefined\n )?.stop();\n await (ctx.workflows as ComposedWorkflowRuntime | undefined)?.stop();\n },\n },\n };\n}\n\n/** The default-config instance: the built-in composition's entry. */\nexport const workflowsPlugin: WorkflowsPlugin = createWorkflowsPlugin({});\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory);\n// a factory lets the entry carry `config: { drive }`.\nexport default createWorkflowsPlugin;\n"],"names":[],"mappings":";;;;;;;;;AAEA,MAAM,iBAAiB;AASvB,MAAM,gCAAgB,IAAI,QAGxB;;;;;;;;;;;;;;AAeF,SAAgB,0BACd,QACA,OAAqB,SACf;CACN,IAAI,cAAc,IAAI,IAAI,GAAG;CAI7B,MAAM,WAAW,KAAK,KAAK,KAAK,IAAI;CACpC,IAAI,eAAe;;;;;;;;CASnB,MAAM,YAAY,SAAiB,QAAwB;EACzD,IAAI;GACF,IAAI,QAAQ,KAAA,GACV,OAAO,MAAM,OAAO;QAEpB,OAAO,MAAM,SAAS,GAAG;EAE7B,QAAQ,CAER;CACF;CAEA,MAAM,WAAW,MAAc,QAAuB;EACpD,SAAS,GAAG,KAAK,WAAW,GAAG;EAC/B,IAAI,cAAc;EAClB,eAAe;EACf,KAAK,WAAW;EAChB,iBAAiB;GACf,SAAS,+CAA+C;GACxD,SAAS,CAAC;EACZ,GAAG,cAAc,CAAC,CAAC,MAAM;EACzB,KAAK,KAAK,KAAK,KAAK,SAAS;CAC/B;CACA,cA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,IAAI,YAAY;KAChB,cAAc,KAAK,cAAc,yBAAyB,SAAS,CAAC;KACpE,MAAM,UAAU,MAAM;KACtB,OAAO,KAAK,0BAA0B;KACtC,cAAc,iBAAiB;IACjC;GACF;GACA,YAAY,OAAO,QAAQ;IACzB,MACE,IAAI,gBACH,KAAK;IACR,MAAO,IAAI,WAAmD,KAAK;GACrE;EACF;CACF;AACF;;AAGA,MAAa,kBAAmC,sBAAsB,CAAC,CAAC","debug_id":"643936e6-57f0-5d17-b85e-b80a8d07783c"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/switchboard",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "6.2.3-dev.
|
|
4
|
+
"version": "6.2.3-dev.72",
|
|
5
5
|
"main": "dist/index.mjs",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": {
|
|
@@ -76,24 +76,24 @@
|
|
|
76
76
|
"@opentelemetry/sdk-node": "^0.218.0",
|
|
77
77
|
"@opentelemetry/sdk-trace-base": "^2.7.1",
|
|
78
78
|
"@opentelemetry/semantic-conventions": "^1.41.1",
|
|
79
|
-
"@powerhousedao/config": "6.2.3-dev.
|
|
80
|
-
"@powerhousedao/host-core": "6.2.3-dev.
|
|
81
|
-
"@powerhousedao/opentelemetry-instrumentation-reactor": "6.2.3-dev.
|
|
82
|
-
"@powerhousedao/reactor": "6.2.3-dev.
|
|
83
|
-
"@powerhousedao/reactor-api": "6.2.3-dev.
|
|
84
|
-
"@powerhousedao/reactor-attachments": "6.2.3-dev.
|
|
85
|
-
"@powerhousedao/reactor-drive": "6.2.3-dev.
|
|
86
|
-
"@powerhousedao/reactor-group": "6.2.3-dev.
|
|
87
|
-
"@powerhousedao/reactor-privacy": "6.2.3-dev.
|
|
88
|
-
"@powerhousedao/reactor-workflow": "6.2.3-dev.
|
|
89
|
-
"@powerhousedao/shared": "6.2.3-dev.
|
|
90
|
-
"@powerhousedao/vetra": "6.2.3-dev.
|
|
91
|
-
"@powerhousedao/workflow": "6.2.3-dev.
|
|
79
|
+
"@powerhousedao/config": "6.2.3-dev.72",
|
|
80
|
+
"@powerhousedao/host-core": "6.2.3-dev.72",
|
|
81
|
+
"@powerhousedao/opentelemetry-instrumentation-reactor": "6.2.3-dev.72",
|
|
82
|
+
"@powerhousedao/reactor": "6.2.3-dev.72",
|
|
83
|
+
"@powerhousedao/reactor-api": "6.2.3-dev.72",
|
|
84
|
+
"@powerhousedao/reactor-attachments": "6.2.3-dev.72",
|
|
85
|
+
"@powerhousedao/reactor-drive": "6.2.3-dev.72",
|
|
86
|
+
"@powerhousedao/reactor-group": "6.2.3-dev.72",
|
|
87
|
+
"@powerhousedao/reactor-privacy": "6.2.3-dev.72",
|
|
88
|
+
"@powerhousedao/reactor-workflow": "6.2.3-dev.72",
|
|
89
|
+
"@powerhousedao/shared": "6.2.3-dev.72",
|
|
90
|
+
"@powerhousedao/vetra": "6.2.3-dev.72",
|
|
91
|
+
"@powerhousedao/workflow": "6.2.3-dev.72",
|
|
92
92
|
"@pyroscope/nodejs": "^0.4.5",
|
|
93
|
-
"@renown/sdk": "6.2.3-dev.
|
|
93
|
+
"@renown/sdk": "6.2.3-dev.72",
|
|
94
94
|
"@sentry/node": "^10.53.1",
|
|
95
95
|
"@sentry/opentelemetry": "^10.53.1",
|
|
96
|
-
"document-model": "6.2.3-dev.
|
|
96
|
+
"document-model": "6.2.3-dev.72",
|
|
97
97
|
"dotenv": "^16.4.7",
|
|
98
98
|
"express": "^4.22.1",
|
|
99
99
|
"graphql": "^16",
|
|
@@ -103,7 +103,8 @@
|
|
|
103
103
|
"pg": "8.18.0",
|
|
104
104
|
"pglite-legacy-02": "npm:@electric-sql/pglite@0.2.17",
|
|
105
105
|
"pglite-tools-legacy-02": "npm:@electric-sql/pglite-tools@0.2.4",
|
|
106
|
-
"vite": "8.3.4"
|
|
106
|
+
"vite": "8.3.4",
|
|
107
|
+
"zod": "^4.5.4"
|
|
107
108
|
},
|
|
108
109
|
"devDependencies": {
|
|
109
110
|
"@types/express": "^4.17.25",
|
|
@@ -1203,6 +1203,32 @@ describe("attachment routes", () => {
|
|
|
1203
1203
|
).toBeNull();
|
|
1204
1204
|
});
|
|
1205
1205
|
|
|
1206
|
+
it("parseReserveOptions accepts an empty file in hash-first mode", () => {
|
|
1207
|
+
const emptyHash =
|
|
1208
|
+
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
|
|
1209
|
+
const opts = parseReserveOptions({
|
|
1210
|
+
mimeType: "application/octet-stream",
|
|
1211
|
+
fileName: "empty",
|
|
1212
|
+
clientHash: emptyHash,
|
|
1213
|
+
sizeBytes: 0,
|
|
1214
|
+
});
|
|
1215
|
+
expect(opts).not.toBeNull();
|
|
1216
|
+
expect(opts!.sizeBytes).toBe(0);
|
|
1217
|
+
});
|
|
1218
|
+
|
|
1219
|
+
it("parseReserveOptions rejects a negative or fractional sizeBytes", () => {
|
|
1220
|
+
for (const sizeBytes of [-1, 1.5]) {
|
|
1221
|
+
expect(
|
|
1222
|
+
parseReserveOptions({
|
|
1223
|
+
mimeType: "text/plain",
|
|
1224
|
+
fileName: "file.txt",
|
|
1225
|
+
clientHash: "a".repeat(64),
|
|
1226
|
+
sizeBytes,
|
|
1227
|
+
}),
|
|
1228
|
+
).toBeNull();
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
|
|
1206
1232
|
it("parseReserveOptions rejects when clientHash is present but sizeBytes is absent", () => {
|
|
1207
1233
|
expect(
|
|
1208
1234
|
parseReserveOptions({
|
|
@@ -1227,17 +1253,6 @@ describe("attachment routes", () => {
|
|
|
1227
1253
|
});
|
|
1228
1254
|
});
|
|
1229
1255
|
|
|
1230
|
-
it("parseReserveOptions rejects sizeBytes of zero", () => {
|
|
1231
|
-
expect(
|
|
1232
|
-
parseReserveOptions({
|
|
1233
|
-
mimeType: "text/plain",
|
|
1234
|
-
fileName: "file.txt",
|
|
1235
|
-
clientHash: "a".repeat(64),
|
|
1236
|
-
sizeBytes: 0,
|
|
1237
|
-
}),
|
|
1238
|
-
).toBeNull();
|
|
1239
|
-
});
|
|
1240
|
-
|
|
1241
1256
|
it("parseReserveOptions rejects negative sizeBytes", () => {
|
|
1242
1257
|
expect(
|
|
1243
1258
|
parseReserveOptions({
|