@powerhousedao/switchboard 6.2.3-dev.84 → 6.2.3-dev.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.tsbuild/test/ai-gateway.test.d.ts +2 -0
  2. package/.tsbuild/test/ai-gateway.test.d.ts.map +1 -0
  3. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
  4. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
  5. package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
  6. package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
  7. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts +2 -0
  8. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts.map +1 -0
  9. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts +2 -0
  10. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts.map +1 -0
  11. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  12. package/CHANGELOG.md +33 -0
  13. package/README.md +33 -0
  14. package/dist/boot.d.mts +1 -1
  15. package/dist/boot.mjs +1 -1
  16. package/dist/config/from-env.d.mts +1 -1
  17. package/dist/config/from-env.d.mts.map +1 -1
  18. package/dist/config/from-env.mjs +3 -3
  19. package/dist/config/schema.d.mts +1 -1
  20. package/dist/config/schema.mjs +3 -3
  21. package/dist/{from-env-BO0n9R02.mjs → from-env-BgyZQAxw.mjs} +79 -7
  22. package/dist/from-env-BgyZQAxw.mjs.map +1 -0
  23. package/dist/index.mjs +13 -10
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/{plugin-host-C1sYEm8g.d.mts → plugin-host-C0bSz1Oe.d.mts} +2 -2
  26. package/dist/{plugin-host-C1sYEm8g.d.mts.map → plugin-host-C0bSz1Oe.d.mts.map} +1 -1
  27. package/dist/plugins/ai.d.mts +37 -0
  28. package/dist/plugins/ai.d.mts.map +1 -0
  29. package/dist/plugins/ai.mjs +352 -0
  30. package/dist/plugins/ai.mjs.map +1 -0
  31. package/dist/plugins/attachments.d.mts +1 -1
  32. package/dist/plugins/attachments.mjs +3 -3
  33. package/dist/plugins/mcp.d.mts +1 -1
  34. package/dist/plugins/privacy.d.mts +1 -1
  35. package/dist/plugins/workflows.d.mts +2 -2
  36. package/dist/plugins/workflows.mjs +3 -3
  37. package/dist/{schema-ivUWPQOn.d.mts → schema-DhempFjb.d.mts} +41 -1
  38. package/dist/schema-DhempFjb.d.mts.map +1 -0
  39. package/dist/{schema-0g_QdOWn.mjs → schema-XEZrdmag.mjs} +55 -6
  40. package/dist/schema-XEZrdmag.mjs.map +1 -0
  41. package/dist/{server-B3qhPKNn.mjs → server-BRVMofWD.mjs} +102 -14
  42. package/dist/server-BRVMofWD.mjs.map +1 -0
  43. package/dist/server.d.mts +7 -3
  44. package/dist/server.d.mts.map +1 -1
  45. package/dist/server.mjs +5 -5
  46. package/dist/{workflow-runtime-7GaJ13c9.d.mts → workflow-runtime-CF5pc8mt.d.mts} +5 -2
  47. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
  48. package/dist/{workflows-B1VsL5Lo.mjs → workflows-C_pWcP2u.mjs} +446 -9
  49. package/dist/workflows-C_pWcP2u.mjs.map +1 -0
  50. package/package.json +22 -16
  51. package/test/ai-gateway.test.ts +555 -0
  52. package/test/config-from-env.test.ts +184 -0
  53. package/test/config-schema.test.ts +28 -0
  54. package/test/goldens/packages.graphql +1 -1
  55. package/test/goldens/privacy.graphql +1 -1
  56. package/test/goldens/reactor-drive-nodes.graphql +1 -1
  57. package/test/goldens/resolvers.json +4 -0
  58. package/test/goldens/supergraph.graphql +217 -1
  59. package/test/goldens/workflow-runtime.graphql +95 -1
  60. package/test/keyframe-reclaim-store.test.ts +156 -0
  61. package/test/processor-timing-log.test.ts +109 -0
  62. package/test/redact-webhook-path.test.ts +9 -0
  63. package/test/workflow/resolvers.test.ts +106 -0
  64. package/test/workflow/waitpoint-routes.test.ts +284 -0
  65. package/test/workflow/waitpoint-runtime.test.ts +204 -0
  66. package/tsdown.config.ts +1 -0
  67. package/dist/from-env-BO0n9R02.mjs.map +0 -1
  68. package/dist/schema-0g_QdOWn.mjs.map +0 -1
  69. package/dist/schema-ivUWPQOn.d.mts.map +0 -1
  70. package/dist/server-B3qhPKNn.mjs.map +0 -1
  71. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +0 -1
  72. package/dist/workflows-B1VsL5Lo.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflows-C_pWcP2u.mjs","sources":["../src/fatal-shutdown.mts","../src/workflow/oauth-callback.ts","../src/workflow/waitpoint-routes.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 \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\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","// A WEBHOOK waitpoint's resume URL: POST resumes, GET on it or `/confirm` serves\n// a confirm page. A GET never resumes, so link scanners cannot consume one.\nimport type {\n WaitpointDescription,\n WaitpointResumePayload,\n} from \"@powerhousedao/reactor-workflow\";\nimport type {\n IHttpScope,\n RouteMethod,\n ScopedRouteHandle,\n WebhookReply,\n} from \"@powerhousedao/shared/processors\";\n\nexport const WAITPOINT_PATH = \"waitpoints\";\nexport const MAX_REASON_LENGTH = 2000;\nconst MAX_BODY_BYTES = 1_048_576;\n\nexport interface WaitpointRouteRuntime {\n describeWaitpointByToken(\n token: string,\n ): Promise<WaitpointDescription | undefined>;\n resumeWaitpointByToken(\n token: string,\n payload: WaitpointResumePayload,\n ): Promise<{ status: \"resumed\" | \"already\" | \"gone\" }>;\n // Held until the resumed leg responds, waits again or ends.\n resumeWaitpointByTokenSync(\n token: string,\n payload: WaitpointResumePayload,\n ): Promise<{ status: \"resumed\" | \"already\" | \"gone\"; reply?: WebhookReply }>;\n}\n\ntype SubPath = \"\" | \"confirm\" | \"sync\";\ntype Action = \"approve\" | \"disapprove\";\n\nconst PAGE_HEADERS: Record<string, string> = {\n \"content-security-policy\":\n \"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'\",\n \"x-content-type-options\": \"nosniff\",\n \"cache-control\": \"no-store\",\n // The token is in the URL.\n \"referrer-policy\": \"no-referrer\",\n};\n\n// Credentials a caller may send that must not be journaled with the payload.\nconst DROPPED_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"proxy-authorization\",\n]);\n\n// Absent when the host knows no public origin: a bare path is no resume URL.\nexport function waitpointBaseUrlOf(http: IHttpScope): string | undefined {\n const url = `${http.baseUrl.replace(/\\/+$/, \"\")}/${WAITPOINT_PATH}`;\n return URL.canParse(url) ? url : undefined;\n}\n\n// Public: the unguessable token in the path is the whole credential.\nexport function registerWaitpointRoutes(\n http: IHttpScope,\n runtime: WaitpointRouteRuntime,\n): ScopedRouteHandle[] {\n const route = (method: RouteMethod[], subPath: SubPath): ScopedRouteHandle =>\n http.route({\n method,\n path: [WAITPOINT_PATH, \":token\", subPath].filter(Boolean).join(\"/\"),\n auth: \"public\",\n maxBodyBytes: MAX_BODY_BYTES,\n handler: (request, ctx) =>\n handleWaitpointRequest(runtime, request, ctx.params.token, subPath),\n });\n return [\n route([\"GET\", \"HEAD\", \"POST\"], \"\"),\n route([\"GET\", \"HEAD\", \"POST\"], \"sync\"),\n route([\"GET\", \"HEAD\", \"POST\"], \"confirm\"),\n ];\n}\n\nexport async function handleWaitpointRequest(\n runtime: WaitpointRouteRuntime,\n request: Request,\n token: string,\n subPath: SubPath,\n): Promise<Response> {\n const method = request.method.toUpperCase();\n const url = new URL(request.url);\n const queryParams = Object.fromEntries(url.searchParams);\n\n if (method === \"GET\" || method === \"HEAD\") {\n if (subPath === \"confirm\") {\n return confirmPage(runtime, token, queryParams, \"\");\n }\n if (subPath === \"\") {\n // Relative, so the form posts to `/confirm` behind any proxy prefix.\n const target = url.pathname.endsWith(\"/\")\n ? \"confirm\"\n : `${encodeURIComponent(token)}/confirm`;\n return confirmPage(runtime, token, queryParams, target);\n }\n return json(405, \"Use POST to resume, or open the /confirm page\", {\n allow: \"POST\",\n });\n }\n\n const headers = headerRecord(request);\n const body = await readBody(request, headers[\"content-type\"]);\n const html = subPath === \"confirm\" && fromBrowser(headers);\n let payloadBody = body;\n if (subPath === \"confirm\") {\n const action = queryParams.action;\n if (action !== \"approve\" && action !== \"disapprove\") {\n return refuse(\n html,\n 400,\n \"Nothing was recorded\",\n \"This link needs to say whether you approve or disapprove. Open it in a browser and use one of the buttons.\",\n );\n }\n const reason = readReason(body) || queryParams.reason || undefined;\n if (reason !== undefined && reason.length > MAX_REASON_LENGTH) {\n return refuse(\n html,\n 400,\n \"Your reason is too long\",\n `Keep it under ${MAX_REASON_LENGTH} characters and submit again. Nothing was recorded.`,\n );\n }\n // The reason reads the same from the query string and the body.\n if (reason !== undefined) {\n queryParams.reason = reason;\n payloadBody = {\n ...(body && typeof body === \"object\" ? (body as object) : {}),\n reason,\n };\n }\n }\n\n const payload = { body: payloadBody, headers, queryParams };\n if (subPath === \"sync\") {\n const { status, reply } = await runtime.resumeWaitpointByTokenSync(\n token,\n payload,\n );\n if (status === \"resumed\" && reply) return replyResponse(reply);\n return status === \"resumed\"\n ? json(200, recordedMessage(queryParams.action), undefined, status)\n : json(\n status === \"already\" ? 200 : 410,\n status === \"already\"\n ? \"This request was already responded to.\"\n : \"This request is no longer waiting.\",\n undefined,\n status,\n );\n }\n const { status } = await runtime.resumeWaitpointByToken(token, payload);\n\n if (status === \"resumed\") {\n const message = recordedMessage(queryParams.action);\n return html\n ? page(200, { title: \"Response recorded\", message, tone: \"done\" })\n : json(200, message, undefined, status);\n }\n if (status === \"already\") {\n return html\n ? page(200, ALREADY)\n : json(200, \"This request was already responded to.\", undefined, status);\n }\n return html\n ? page(410, EXPIRED)\n : json(410, \"This request is no longer waiting.\", undefined, status);\n}\n\nasync function confirmPage(\n runtime: WaitpointRouteRuntime,\n token: string,\n queryParams: Record<string, string>,\n target: string,\n): Promise<Response> {\n const described = await runtime.describeWaitpointByToken(token);\n if (!described) {\n return page(404, {\n title: \"Link not found\",\n message: \"This link is not valid, or it has been removed.\",\n tone: \"closed\",\n });\n }\n if (described.status === \"COMPLETED\" || described.status === \"CONSUMED\") {\n return page(200, { ...ALREADY, context: described });\n }\n if (described.status === \"CANCELLED\") {\n return page(200, {\n title: \"Run cancelled\",\n message: \"This run was cancelled. There is nothing left to do here.\",\n tone: \"closed\",\n context: described,\n });\n }\n if (described.status === \"EXPIRED\") {\n return page(200, { ...EXPIRED, context: described });\n }\n return page(200, {\n title: \"Confirm your response\",\n message: \"This workflow is paused and waiting for your response.\",\n tone: \"open\",\n context: described,\n form: {\n approveUrl: actionUrl(target, queryParams, \"approve\"),\n disapproveUrl: actionUrl(target, queryParams, \"disapprove\"),\n },\n });\n}\n\n// Relative to the page; an empty target is the confirm page itself.\nfunction actionUrl(\n target: string,\n queryParams: Record<string, string>,\n action: Action,\n) {\n const params = new URLSearchParams(queryParams);\n params.set(\"action\", action);\n return `${target}?${params.toString()}`;\n}\n\nfunction headerRecord(request: Request): Record<string, string> {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n if (!DROPPED_HEADERS.has(name)) headers[name] = value;\n });\n return headers;\n}\n\n// JSON and form bodies decoded; anything else as text, an empty one as undefined.\nasync function readBody(request: Request, contentType = \"\"): Promise<unknown> {\n const text = await request.text();\n if (text === \"\") return undefined;\n if (contentType.startsWith(\"application/x-www-form-urlencoded\")) {\n return Object.fromEntries(new URLSearchParams(text));\n }\n if (contentType.includes(\"json\")) {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction fromBrowser(headers: Record<string, string>): boolean {\n return (\n (headers[\"content-type\"] ?? \"\").startsWith(\n \"application/x-www-form-urlencoded\",\n ) || (headers.accept ?? \"\").includes(\"text/html\")\n );\n}\n\nfunction readReason(body: unknown): string | undefined {\n if (!body || typeof body !== \"object\") return undefined;\n const reason = (body as Record<string, unknown>).reason;\n return typeof reason === \"string\" ? reason : undefined;\n}\n\nfunction recordedMessage(action: string | undefined): string {\n if (action === \"approve\") return \"You approved this request.\";\n if (action === \"disapprove\") return \"You disapproved this request.\";\n return \"Your response has been recorded.\";\n}\n\nfunction refuse(\n html: boolean,\n status: number,\n title: string,\n message: string,\n): Response {\n return html\n ? page(status, { title, message, tone: \"closed\" })\n : json(status, message);\n}\n\n// The resumed run's own answer: what a step responded, or how the leg ended.\nfunction replyResponse(reply: WebhookReply): Response {\n // A null-body status cannot carry one.\n const body = [204, 205, 304].includes(reply.status) ? undefined : reply.body;\n return new Response(body ?? null, {\n status: reply.status,\n headers: {\n \"cache-control\": \"no-store\",\n ...reply.headers,\n ...(body !== undefined\n ? { \"content-type\": reply.contentType ?? \"text/plain\" }\n : {}),\n },\n });\n}\n\nfunction json(\n status: number,\n message: string,\n headers?: Record<string, string>,\n outcome?: string,\n): Response {\n return new Response(\n JSON.stringify(outcome ? { status: outcome, message } : { message }),\n {\n status,\n headers: {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n ...headers,\n },\n },\n );\n}\n\ninterface PageContent {\n title: string;\n message: string;\n tone: \"open\" | \"done\" | \"closed\";\n context?: Omit<WaitpointDescription, \"status\">;\n form?: { approveUrl: string; disapproveUrl: string };\n}\n\nconst ALREADY: PageContent = {\n title: \"Already responded\",\n message:\n \"This request was already responded to. There is nothing left to do here.\",\n tone: \"closed\",\n};\n\nconst EXPIRED: PageContent = {\n title: \"Request expired\",\n message: \"This request is no longer waiting for a response.\",\n tone: \"closed\",\n};\n\nfunction page(status: number, content: PageContent): Response {\n return new Response(renderPage(content), {\n status,\n headers: { \"content-type\": \"text/html; charset=utf-8\", ...PAGE_HEADERS },\n });\n}\n\nexport function escapeHtml(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n\nconst STYLE = `\n:root { color-scheme: light dark; --bg: #fafafa; --card: #fff; --fg: #0a0a0a; --muted: #6b7280; --line: #e5e7eb; --ok: #059669; --no: #dc2626; }\n@media (prefers-color-scheme: dark) { :root { --bg: #0a0a0a; --card: #171717; --fg: #fafafa; --muted: #a3a3a3; --line: #262626; } }\n* { box-sizing: border-box; }\nbody { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 16px; background: var(--bg); color: var(--fg); font: 14px/1.5 system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif; }\nmain { width: 440px; max-width: 100%; background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 24px; }\nh1 { font-size: 20px; margin: 0 0 8px; }\np { margin: 0 0 16px; color: var(--muted); }\ndl { margin: 0 0 16px; padding: 12px; border: 1px solid var(--line); border-radius: 8px; display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; }\ndt { color: var(--muted); } dd { margin: 0; overflow-wrap: anywhere; }\n.description { color: var(--fg); white-space: pre-line; }\nlabel { display: block; font-weight: 500; margin-bottom: 4px; }\ntextarea { width: 100%; min-height: 72px; resize: vertical; padding: 8px; border: 1px solid var(--line); border-radius: 8px; background: transparent; color: inherit; font: inherit; }\n.actions { display: flex; gap: 8px; margin-top: 16px; }\nbutton { flex: 1; height: 36px; border: 0; border-radius: 8px; color: #fff; font: inherit; font-weight: 500; cursor: pointer; }\n.approve { background: var(--ok); } .disapprove { background: var(--no); }\n.done h1 { color: var(--ok); }\n`;\n\n// No script runs on the page, so times are shown in UTC.\nfunction formatTime(iso: string | undefined): string | undefined {\n if (!iso) return undefined;\n const time = new Date(iso);\n if (Number.isNaN(time.getTime())) return undefined;\n return `${time.toLocaleString(\"en-GB\", {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n timeZone: \"UTC\",\n })} UTC`;\n}\n\nfunction contextRows(context: Omit<WaitpointDescription, \"status\">) {\n const started = formatTime(context.startedAt);\n const rows: [string, string | undefined][] = [\n [\"Workflow\", context.workflowName || undefined],\n [\n \"Step\",\n context.actionName &&\n context.actionName.toLowerCase() !== context.stepName.toLowerCase()\n ? `${context.stepName} · ${context.actionName}`\n : context.stepName,\n ],\n [\n \"Started\",\n started && context.triggerName\n ? `${started}, by ${context.triggerName}`\n : started,\n ],\n [\"Waiting since\", formatTime(context.waitingSince)],\n [\"Expires\", formatTime(context.expiresAt)],\n ];\n return rows\n .filter((row): row is [string, string] => row[1] !== undefined)\n .map(([term, value]) => `<dt>${term}</dt><dd>${escapeHtml(value)}</dd>`)\n .join(\"\");\n}\n\nfunction renderPage({ title, message, tone, context, form }: PageContent) {\n const description = context?.workflowDescription\n ? `<p class=\"description\">${escapeHtml(context.workflowDescription)}</p>`\n : \"\";\n const details = context\n ? `${description}<dl>${contextRows(context)}</dl>`\n : \"\";\n const actions = form\n ? `<form method=\"post\">\n<label for=\"reason\">Reason (optional)</label>\n<textarea id=\"reason\" name=\"reason\" maxlength=\"${MAX_REASON_LENGTH}\"></textarea>\n<div class=\"actions\">\n<button type=\"submit\" class=\"disapprove\" formaction=\"${escapeHtml(form.disapproveUrl)}\">Disapprove</button>\n<button type=\"submit\" class=\"approve\" formaction=\"${escapeHtml(form.approveUrl)}\">Approve</button>\n</div>\n</form>`\n : \"\";\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<meta name=\"robots\" content=\"noindex\">\n<title>${escapeHtml(title)}</title>\n<style>${STYLE}</style>\n</head>\n<body>\n<main class=\"${tone}\">\n<h1>${escapeHtml(title)}</h1>\n<p>${escapeHtml(message)}</p>\n${details}\n${actions}\n</main>\n</body>\n</html>`;\n}\n","import { hostname } from \"node:os\";\nimport type { Context } from \"@powerhousedao/reactor-api\";\nimport {\n waitpointRecord,\n type RunRow,\n type StepExecutionRow,\n type WaitpointRecord,\n type WaitpointRow,\n type 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 SecretStat = Parameters<WorkflowRuntimeService[\"canManageSecret\"]>[0];\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// 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(\n row: RunRow,\n steps: StepExecutionRow[],\n waitpoints?: WaitpointRecord[],\n) {\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 // Absent: the waitpoints field resolver reads them for this run.\n waitpoints,\n };\n}\n\ntype RunRecordShape = ReturnType<typeof toRunRecord>;\n\ntype WaitpointLoader = (runId: string) => Promise<WaitpointRecord[]>;\n\n// One store read per request for every run whose waitpoints it selects.\n// The parent resolver already served the run to this caller.\nfunction waitpointLoader(runtime: WorkflowRuntimeService): WaitpointLoader {\n const cache = new Map<string, Promise<WaitpointRecord[]>>();\n let batch: {\n ids: string[];\n rows: Promise<Map<string, WaitpointRow[]>>;\n } | null = null;\n return (runId) => {\n const cached = cache.get(runId);\n if (cached) return cached;\n if (!batch) {\n const ids: string[] = [];\n // Dispatches after the current promise jobs, as DataLoader does.\n const rows = new Promise<void>((tick) => {\n void Promise.resolve().then(() => process.nextTick(tick));\n }).then(async () => {\n batch = null;\n const store = await runtime.store();\n return store\n ? store.listWaitpointsForRuns(ids)\n : new Map<string, WaitpointRow[]>();\n });\n batch = { ids, rows };\n }\n batch.ids.push(runId);\n const loaded = batch.rows;\n const promise = loaded.then((rows) =>\n (rows.get(runId) ?? []).map(waitpointRecord),\n );\n cache.set(runId, promise);\n return promise;\n };\n}\n\n// cancelRun answers as fire and rerun do.\nfunction toRunPayload(row: RunRow, steps: StepExecutionRow[]) {\n return {\n runId: row.id,\n status: row.status,\n error: row.error,\n errorName: row.error_name,\n steps: steps.map((step) => ({\n stepId: step.step_id,\n key: step.step_key,\n pieceName: step.piece_name,\n blockName: step.block_name,\n status: step.status,\n input: parseJson(step.input),\n output: parseJson(step.output),\n port: step.port,\n error: step.error,\n errorName: step.error_name,\n })),\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 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 const loaders = new WeakMap<Context, WaitpointLoader>();\n const loadWaitpoints = (runId: string, ctx: Context) => {\n let load = loaders.get(ctx);\n if (!load) {\n load = waitpointLoader(runtime);\n loaders.set(ctx, load);\n }\n return load(runId);\n };\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 // Only secrets whose owning document the caller can read.\n secret: (_parent: unknown, args: { ref: string }, ctx: Context) =>\n runtime.secretStat(args.ref, ctx),\n secrets: (_parent: unknown, _args: unknown, ctx: Context) =>\n runtime.listSecrets(ctx),\n oauthRedirectUri: () => oauth?.callbackUrl ?? null,\n // The decision startOAuth makes, for the redirect it would use; a host\n // that cannot name that redirect signs in with no app.\n oauthSignIn: async (\n _parent: unknown,\n args: { appId: string; redirectUri?: string | null },\n ) => {\n let redirectUri: string;\n try {\n redirectUri = redirectUriFor(oauth, args.redirectUri);\n } catch {\n return \"NONE\";\n }\n return (\n await runtime.oauthSignInMode(args.appId, redirectUri)\n ).toUpperCase();\n },\n // The runner id apps record (folder-sync and integrations): the\n // machine, which processors can name too; they see no signing key.\n host: () => ({ id: `switchboard@${hostname()}`, label: hostname() }),\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 waitingRuns: async (\n _parent: unknown,\n args: {\n driveId?: string | null;\n workflowId?: string | null;\n first?: number | null;\n },\n ctx: Context,\n ) =>\n (\n await runtime.waitingRuns(\n {\n driveId: args.driveId ?? undefined,\n workflowId: args.workflowId ?? undefined,\n first: args.first ?? undefined,\n },\n ctx,\n )\n ).map(({ run, waitpoints }) =>\n toRunRecord(run.row, run.steps, waitpoints),\n ),\n },\n WorkflowRunRecord: {\n waitpoints: (parent: RunRecordShape, _args: unknown, ctx: Context) =>\n parent.waitpoints ?? loadWaitpoints(parent.id, ctx),\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 pollNow: (_parent: unknown, args: { workflowId: string }, ctx: Context) =>\n runtime.pollNow(args.workflowId, 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 resolveWaitpoint: (\n _parent: unknown,\n args: {\n waitpointId: string;\n approved: boolean;\n reason?: string | null;\n },\n ctx: Context,\n ) =>\n // The runtime checks write access and the approver list against ctx.\n runtime.resolveWaitpoint(\n args.waitpointId,\n {\n approved: args.approved,\n ...(args.reason ? { reason: args.reason } : {}),\n },\n ctx,\n ),\n cancelRun: async (\n _parent: unknown,\n args: { runId: string },\n ctx: Context,\n ) => {\n const record = await runtime.cancelRun(args.runId, ctx);\n return toRunPayload(record.row, record.steps);\n },\n // The runtime requires write access to the owner, and to change a\n // secret, being its creator; admins get nothing more.\n createSecret: (\n _parent: unknown,\n args: { value: string; label?: string | null; documentId: string },\n ctx: Context,\n ) =>\n syncAware(() =>\n runtime.createSecret(\n {\n value: args.value,\n label: args.label ?? undefined,\n ownerId: args.documentId,\n },\n ctx,\n ),\n ),\n rotateSecret: (\n _parent: unknown,\n args: { ref: string; value: string },\n ctx: Context,\n ) => runtime.rotateSecret(args.ref, args.value, ctx),\n deleteSecret: async (\n _parent: unknown,\n args: { ref: string },\n ctx: Context,\n ) => {\n await runtime.deleteSecret(args.ref, ctx);\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: the runtime requires write access.\n startOAuth: (\n _parent: unknown,\n args: {\n connectionId: string;\n redirectUri?: string | null;\n returnUrl?: string | null;\n },\n ctx: Context,\n ) => {\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 SecretRecord: {\n manageable: (parent: SecretStat, _args: unknown, ctx: Context) =>\n runtime.canManageSecret(parent, ctx),\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 WAITING runs, each with its waitpoints. Scope them to one\n workflow, or to every workflow a drive holds; workflowId wins.\n \"\"\"\n waitingRuns(\n driveId: String\n workflowId: String\n first: Int\n ): [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. Only secrets\n whose owning document the caller can read.\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 startOAuth would sign in with the publisher's OAuth2 app appId (a\n connection's oauth_app) on this host, so an editor can tell before it\n opens one. redirectUri as for startOAuth. NONE for an app this host does\n not know, or when it cannot name its callback.\n \"\"\"\n oauthSignIn(appId: String!, redirectUri: String): OAuthSignInMode!\n \"\"\"\n The switchboard this runtime lives in: what an app records as the runner\n of the workflows and connections it sets up here.\n \"\"\"\n host: RuntimeHost!\n \"\"\"\n How an OAuth2 sign-in opened by startOAuth stands; null when unknown.\n \"\"\"\n oauthAttempt(state: String!): OAuthAttempt\n }\n\n type RuntimeHost {\n \"switchboard@<machine>: what apps record as the runner\"\n id: String!\n \"The machine's name, for people: where a sign-in has to happen\"\n label: String!\n }\n\n type OAuthAttempt {\n connectionId: String!\n \"PENDING | EXCHANGING | OK | ERROR\"\n status: String!\n error: String\n }\n\n \"\"\"\n How a host signs in with a publisher's OAuth2 app: DESKTOP, the app's\n desktop client for a callback to this machine; WEB, its web client, whose\n file this host has; RELAY, through the app's relay, which forwards the\n provider's answer here and exchanges codes without this host holding the\n secret; NONE, not at all.\n \"\"\"\n enum OAuthSignInMode {\n DESKTOP\n WEB\n RELAY\n NONE\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 \"The document the secret resolves for; null for a host secret (an OAuth app's).\"\n ownerId: String\n \"Whether the caller may rotate or delete it: its creator, able to write its owner.\"\n manageable: Boolean!\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 \"\"\"\n PENDING | RUNNING | WAITING | SUCCEEDED | FAILED | CANCELLED. WAITING: paused\n at a waitpoint (approval, webhook or delay); the run holds no worker.\n \"\"\"\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 \"Where the run paused, resolved ones included.\"\n waitpoints: [WaitpointRecord!]!\n }\n\n \"Who may decide an approval, and how the editor renders it.\"\n type ApprovalRequest {\n title: String!\n \"Markdown.\"\n body: String\n approveLabel: String!\n rejectLabel: String!\n \"none | reject | both\"\n reasonRequiredOn: String!\n \"DIDs allowed to decide; empty means anyone with write access.\"\n approvers: [String!]!\n }\n\n \"A point where a run paused, and how it resumes.\"\n type WaitpointRecord {\n id: String!\n runId: String!\n workflowId: String!\n stepId: String!\n stepKey: String!\n stepPath: String!\n pieceName: String!\n blockName: String!\n \"DELAY | WEBHOOK\"\n type: String!\n \"approval | webhook | delay\"\n kind: String!\n \"PENDING | COMPLETED | CONSUMED | EXPIRED | CANCELLED\"\n status: String!\n createdAt: String!\n \"DELAY only: when the run resumes.\"\n resumeAt: String\n expiresAt: String\n resolvedAt: String\n \"The DID that resolved it from the editor.\"\n decidedBy: String\n \"Set by the Request approval block; null otherwise.\"\n approval: ApprovalRequest\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 Runs the workflow's trigger now, as its schedule or poll would: a\n schedule fires the workflow, a polling trigger polls its source (\"sync\n now\"). False when it has no armed trigger (disabled, parked, erroring).\n \"\"\"\n pollNow(workflowId: String!): Boolean!\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 Approves or rejects a PENDING WEBHOOK waitpoint, resuming its run. Needs\n write access to the workflow; with approvers listed, the caller's DID must\n be one. reason may be required, per approval.reasonRequiredOn.\n \"\"\"\n resolveWaitpoint(\n waitpointId: String!\n approved: Boolean!\n reason: String\n ): WaitpointRecord!\n \"\"\"\n Cancels a WAITING or PENDING run and its open waitpoints. A RUNNING run\n cannot be cancelled yet.\n \"\"\"\n cancelRun(runId: String!): WorkflowRunPayload\n \"\"\"\n Mints a managed secret for a connection or workflow document and returns\n its ref; only that document resolves it. The value is stored encrypted\n and is never readable back over any API.\n \"\"\"\n createSecret(\n value: String!\n label: String\n documentId: String!\n ): SecretRecord!\n \"\"\"\n Replaces the value behind an existing ref; documents stay untouched.\n Only its creator, while able to write its owning document.\n \"\"\"\n rotateSecret(ref: String!, value: String!): SecretRecord!\n \"\"\"\n Tombstones a secret; its value becomes unrecoverable. Only its creator,\n while able to write its owning document.\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 override name = \"workflow-runtime\";\n override typeDefs: DocumentNode = schema;\n override resolvers = getResolvers(\n runtime,\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 GraphQLManager,\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 {\n Principal,\n UserActionSigner,\n} 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 {\n registerWaitpointRoutes,\n waitpointBaseUrlOf,\n} from \"./workflow/waitpoint-routes.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/** 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 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 /** The publisher's OAuth2 apps, by id: client file paths per kind, and\n * the relay a web sign-in goes through without a web client file. */\n oauthApps?: {\n id: string;\n clients: { desktop?: string; web?: string };\n relay?: { clientId: string; redirectUri: string; tokenUrl: string };\n }[];\n authorizationService: IAuthorizationService;\n /** Answers a piece's read of a read-model index (`ctx.reactor.query`) in\n * process, as the run's user: the GraphQL manager that serves the same\n * subgraphs over HTTP. Absent, pieces get the method refused by name. */\n indexQueries?: Pick<GraphQLManager, \"executeSubgraph\">;\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\ntype WorkflowRuntimeSecrets = WorkflowEngine.WorkflowRuntimeService[\"secrets\"];\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 /** The runtime's secret store, for host secrets its own surface never lists. */\n secrets: WorkflowRuntimeSecrets;\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/**\n * A piece's read of a read-model index, run in process as the run's user\n * through the same GraphQL manager that serves the index over HTTP. The\n * request's caller is the run user's address on the host's own network and\n * chain, what a Renown bearer for that address would carry; the index's\n * access declarations decide from the address.\n *\n * A run with no user (its publish was unsigned or host-signed) is refused\n * before this under enforcement. With enforcement off the host acts for such\n * a run already, signing its writes with its own key, so its index reads are\n * the host's too: the request's caller is the host's signed-in address. A\n * host with no signed-in identity reads anonymously, which the\n * authenticated-caller floor refuses as it would an anonymous HTTP request.\n */\nexport function indexQueryFor(\n manager: Pick<GraphQLManager, \"executeSubgraph\">,\n clientModule: InProcessReactorClientModule | undefined,\n): NonNullable<WorkflowEngine.WorkflowRuntimeHostDeps[\"queryIndex\"]> {\n const signer = clientModule?.signer;\n const host = signer?.user as Partial<UserActionSigner> | undefined;\n const hostKey = signer?.app?.key ?? \"\";\n const chainId = host?.chainId ?? 1;\n const networkId = host?.networkId ?? \"eip155\";\n return async (request, runUser) => {\n const user = runUser\n ? {\n address: runUser.address,\n chainId,\n networkId,\n appKey: runUser.subject.key ?? hostKey,\n }\n : host?.address\n ? { address: host.address, chainId, networkId, appKey: hostKey }\n : undefined;\n const result = await manager.executeSubgraph(request.subgraph, {\n query: request.query,\n variables: request.variables,\n user,\n });\n return {\n data: (result.data as Record<string, unknown> | null | undefined) ?? null,\n ...(result.errors\n ? { errors: result.errors.map((e) => ({ message: e.message })) }\n : {}),\n };\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 ...(deps.oauthApps?.length ? { oauthApps: deps.oauthApps } : {}),\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 ...(deps.indexQueries\n ? { queryIndex: indexQueryFor(deps.indexQueries, deps.clientModule) }\n : {}),\n ...(models\n ? {\n modelManifest: () => models.modelManifest(),\n modelEntries: (documentType: string) =>\n models.modelEntries(documentType),\n }\n : {}),\n webhooks: deps.webhooks,\n waitpointBaseUrl: deps.http ? waitpointBaseUrlOf(deps.http) : undefined,\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: {\n oauthCallback?: ScopedRouteHandle;\n waitpoints?: ScopedRouteHandle[];\n } = {};\n const registration: TriggersRegistration = { tornDown: false };\n const tearDown = () => {\n if (registration.tornDown) return;\n registration.tornDown = true;\n routes.oauthCallback?.dispose();\n for (const handle of routes.waitpoints ?? []) handle.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 routes.waitpoints = registerWaitpointRoutes(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 secrets: () => runtime.secrets(),\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":["escapeHtml"],"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;EACp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EACF;CACF;AACF;;AAGA,MAAa,kBAAmC,sBAAsB,CAAC,CAAC","debug_id":"6b9e5899-0452-5e20-bb38-75fb66d37239"}
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.84",
4
+ "version": "6.2.3-dev.86",
5
5
  "main": "dist/index.mjs",
6
6
  "exports": {
7
7
  ".": {
@@ -57,6 +57,12 @@
57
57
  "types": "./dist/plugins/workflows.d.mts",
58
58
  "import": "./dist/plugins/workflows.mjs",
59
59
  "default": "./dist/plugins/workflows.mjs"
60
+ },
61
+ "./plugins/ai": {
62
+ "source": "./src/plugins/ai.mts",
63
+ "types": "./dist/plugins/ai.d.mts",
64
+ "import": "./dist/plugins/ai.mjs",
65
+ "default": "./dist/plugins/ai.mjs"
60
66
  }
61
67
  },
62
68
  "engines": {
@@ -88,24 +94,24 @@
88
94
  "@opentelemetry/sdk-node": "^0.218.0",
89
95
  "@opentelemetry/sdk-trace-base": "^2.7.1",
90
96
  "@opentelemetry/semantic-conventions": "^1.41.1",
91
- "@powerhousedao/config": "6.2.3-dev.84",
92
- "@powerhousedao/host-core": "6.2.3-dev.84",
93
- "@powerhousedao/opentelemetry-instrumentation-reactor": "6.2.3-dev.84",
94
- "@powerhousedao/reactor": "6.2.3-dev.84",
95
- "@powerhousedao/reactor-api": "6.2.3-dev.84",
96
- "@powerhousedao/reactor-attachments": "6.2.3-dev.84",
97
- "@powerhousedao/reactor-drive": "6.2.3-dev.84",
98
- "@powerhousedao/reactor-group": "6.2.3-dev.84",
99
- "@powerhousedao/reactor-privacy": "6.2.3-dev.84",
100
- "@powerhousedao/reactor-workflow": "6.2.3-dev.84",
101
- "@powerhousedao/shared": "6.2.3-dev.84",
102
- "@powerhousedao/vetra": "6.2.3-dev.84",
103
- "@powerhousedao/workflow": "6.2.3-dev.84",
97
+ "@powerhousedao/config": "6.2.3-dev.86",
98
+ "@powerhousedao/host-core": "6.2.3-dev.86",
99
+ "@powerhousedao/opentelemetry-instrumentation-reactor": "6.2.3-dev.86",
100
+ "@powerhousedao/reactor": "6.2.3-dev.86",
101
+ "@powerhousedao/reactor-api": "6.2.3-dev.86",
102
+ "@powerhousedao/reactor-attachments": "6.2.3-dev.86",
103
+ "@powerhousedao/reactor-drive": "6.2.3-dev.86",
104
+ "@powerhousedao/reactor-group": "6.2.3-dev.86",
105
+ "@powerhousedao/reactor-privacy": "6.2.3-dev.86",
106
+ "@powerhousedao/reactor-workflow": "6.2.3-dev.86",
107
+ "@powerhousedao/shared": "6.2.3-dev.86",
108
+ "@powerhousedao/vetra": "6.2.3-dev.86",
109
+ "@powerhousedao/workflow": "6.2.3-dev.86",
104
110
  "@pyroscope/nodejs": "^0.4.5",
105
- "@renown/sdk": "6.2.3-dev.84",
111
+ "@renown/sdk": "6.2.3-dev.86",
106
112
  "@sentry/node": "^10.53.1",
107
113
  "@sentry/opentelemetry": "^10.53.1",
108
- "document-model": "6.2.3-dev.84",
114
+ "document-model": "6.2.3-dev.86",
109
115
  "dotenv": "^16.4.7",
110
116
  "express": "^4.22.1",
111
117
  "graphql": "^16",