@powerhousedao/switchboard 6.2.3 → 6.3.0-dev.1

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 (271) 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/attachments/reserve-metadata-parity.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  5. package/.tsbuild/test/boot-auth-config.test.d.ts +2 -0
  6. package/.tsbuild/test/boot-auth-config.test.d.ts.map +1 -0
  7. package/.tsbuild/test/boot-desktop-auth.test.d.ts +2 -0
  8. package/.tsbuild/test/boot-desktop-auth.test.d.ts.map +1 -0
  9. package/.tsbuild/test/boot-env-isolation.test.d.ts +2 -0
  10. package/.tsbuild/test/boot-env-isolation.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-helpers.d.ts +5 -0
  12. package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-mcp-auth.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-mcp-auth.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-port-zero.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-port-zero.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-preconditions.test.d.ts +2 -0
  20. package/.tsbuild/test/boot-preconditions.test.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-ready-drives.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-ready-drives.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-undo-v3-flag.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-undo-v3-flag.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  29. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  30. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  31. package/.tsbuild/test/config-from-env.test.d.ts +2 -0
  32. package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
  33. package/.tsbuild/test/config-merge.test.d.ts +2 -0
  34. package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
  35. package/.tsbuild/test/config-schema.test.d.ts +2 -0
  36. package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
  37. package/.tsbuild/test/default-composition.test.d.ts +2 -0
  38. package/.tsbuild/test/default-composition.test.d.ts.map +1 -0
  39. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts +2 -0
  40. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts.map +1 -0
  41. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  42. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  43. package/.tsbuild/test/delegated-publish.test.d.ts +2 -0
  44. package/.tsbuild/test/delegated-publish.test.d.ts.map +1 -0
  45. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  46. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  47. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/greetings/index.d.ts +13 -0
  48. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/greetings/index.d.ts.map +1 -0
  49. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/index.d.ts +3 -0
  50. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/index.d.ts.map +1 -0
  51. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/tally/index.d.ts +7 -0
  52. package/.tsbuild/test/fixtures/mixed-subgraphs/subgraphs/tally/index.d.ts.map +1 -0
  53. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  54. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  55. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
  56. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
  57. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  58. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  59. package/.tsbuild/test/permissions-backfill.test.d.ts +2 -0
  60. package/.tsbuild/test/permissions-backfill.test.d.ts.map +1 -0
  61. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  62. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  63. package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
  64. package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
  65. package/.tsbuild/test/pglite-store.test.d.ts +2 -0
  66. package/.tsbuild/test/pglite-store.test.d.ts.map +1 -0
  67. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  68. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  69. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  70. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  71. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  72. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  73. package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
  74. package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
  75. package/.tsbuild/test/renown-storage-path.test.d.ts +2 -0
  76. package/.tsbuild/test/renown-storage-path.test.d.ts.map +1 -0
  77. package/.tsbuild/test/served-schemas-mixed-package.test.d.ts +2 -0
  78. package/.tsbuild/test/served-schemas-mixed-package.test.d.ts.map +1 -0
  79. package/.tsbuild/test/served-schemas.test.d.ts +2 -0
  80. package/.tsbuild/test/served-schemas.test.d.ts.map +1 -0
  81. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  82. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  83. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  84. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  85. package/.tsbuild/test/store-lock.test.d.ts +2 -0
  86. package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
  87. package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
  88. package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
  89. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts +2 -0
  90. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts.map +1 -0
  91. package/.tsbuild/test/workflow/runtime-host.test.d.ts +2 -0
  92. package/.tsbuild/test/workflow/runtime-host.test.d.ts.map +1 -0
  93. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts +2 -0
  94. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts.map +1 -0
  95. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts +2 -0
  96. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts.map +1 -0
  97. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  98. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  99. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  100. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  101. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  102. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  103. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  104. package/Auth.md +108 -2
  105. package/CHANGELOG.md +1062 -2
  106. package/README.md +69 -24
  107. package/dist/boot.d.mts +46 -0
  108. package/dist/boot.d.mts.map +1 -0
  109. package/dist/boot.mjs +67 -0
  110. package/dist/boot.mjs.map +1 -0
  111. package/dist/config/from-env.d.mts +15 -0
  112. package/dist/config/from-env.d.mts.map +1 -0
  113. package/dist/config/from-env.mjs +4 -0
  114. package/dist/config/schema.d.mts +3 -0
  115. package/dist/config/schema.mjs +4 -0
  116. package/dist/from-env-DKK_wPrO.mjs +497 -0
  117. package/dist/from-env-DKK_wPrO.mjs.map +1 -0
  118. package/dist/index.d.mts +1 -2
  119. package/dist/index.mjs +40 -219
  120. package/dist/index.mjs.map +1 -1
  121. package/dist/mcp-VW52B8KD.mjs +32 -0
  122. package/dist/mcp-VW52B8KD.mjs.map +1 -0
  123. package/dist/migrate.mjs +5 -4
  124. package/dist/migrate.mjs.map +1 -1
  125. package/dist/observability-CldagyT_.mjs +224 -0
  126. package/dist/observability-CldagyT_.mjs.map +1 -0
  127. package/dist/observability.d.mts +30 -0
  128. package/dist/observability.d.mts.map +1 -0
  129. package/dist/observability.mjs +4 -0
  130. package/dist/plugin-host-tTjDTNz0.d.mts +46 -0
  131. package/dist/plugin-host-tTjDTNz0.d.mts.map +1 -0
  132. package/dist/plugins/ai.d.mts +37 -0
  133. package/dist/plugins/ai.d.mts.map +1 -0
  134. package/dist/plugins/ai.mjs +400 -0
  135. package/dist/plugins/ai.mjs.map +1 -0
  136. package/dist/plugins/attachments.d.mts +33 -0
  137. package/dist/plugins/attachments.d.mts.map +1 -0
  138. package/dist/plugins/attachments.mjs +4 -0
  139. package/dist/plugins/mcp.d.mts +31 -0
  140. package/dist/plugins/mcp.d.mts.map +1 -0
  141. package/dist/plugins/mcp.mjs +4 -0
  142. package/dist/plugins/privacy.d.mts +22 -0
  143. package/dist/plugins/privacy.d.mts.map +1 -0
  144. package/dist/plugins/privacy.mjs +4 -0
  145. package/dist/plugins/workflows.d.mts +80 -0
  146. package/dist/plugins/workflows.d.mts.map +1 -0
  147. package/dist/plugins/workflows.mjs +4 -0
  148. package/dist/postgres-url-DTDhBjXX.mjs +11 -0
  149. package/dist/postgres-url-DTDhBjXX.mjs.map +1 -0
  150. package/dist/privacy-HQnhqf2H.mjs +91 -0
  151. package/dist/privacy-HQnhqf2H.mjs.map +1 -0
  152. package/dist/privacy-UodgY0i_.mjs +44 -0
  153. package/dist/privacy-UodgY0i_.mjs.map +1 -0
  154. package/dist/renown-layers-DmbWLt46.mjs +42 -0
  155. package/dist/renown-layers-DmbWLt46.mjs.map +1 -0
  156. package/dist/schema-BJ-OFAox.mjs +359 -0
  157. package/dist/schema-BJ-OFAox.mjs.map +1 -0
  158. package/dist/schema-w1lShimw.d.mts +258 -0
  159. package/dist/schema-w1lShimw.d.mts.map +1 -0
  160. package/dist/server-BS-PFzoK.mjs +2752 -0
  161. package/dist/server-BS-PFzoK.mjs.map +1 -0
  162. package/dist/server.d.mts +94 -228
  163. package/dist/server.d.mts.map +1 -1
  164. package/dist/server.mjs +5 -4
  165. package/dist/types-Bk4T4D9F.d.mts +318 -0
  166. package/dist/types-Bk4T4D9F.d.mts.map +1 -0
  167. package/dist/utils-Cm0TE6dP.mjs +148 -0
  168. package/dist/utils-Cm0TE6dP.mjs.map +1 -0
  169. package/dist/utils.d.mts +29 -3
  170. package/dist/utils.d.mts.map +1 -1
  171. package/dist/utils.mjs +5 -4
  172. package/dist/worker-pool-gyxJnCxA.mjs +304 -0
  173. package/dist/worker-pool-gyxJnCxA.mjs.map +1 -0
  174. package/dist/workflow-runtime-CF5pc8mt.d.mts +33 -0
  175. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
  176. package/dist/workflows-mdYUh3Us.mjs +1947 -0
  177. package/dist/workflows-mdYUh3Us.mjs.map +1 -0
  178. package/package.json +86 -24
  179. package/scripts/install-packages.sh +0 -0
  180. package/test/ai-gateway.test.ts +612 -0
  181. package/test/attachment-reference-read-model.test.ts +28 -20
  182. package/test/attachments/byte-grants.test.ts +4 -1
  183. package/test/attachments/download-target.test.ts +36 -20
  184. package/test/attachments/index.test.ts +13 -1
  185. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  186. package/test/attachments/routes-integration.test.ts +1 -0
  187. package/test/attachments/routes.test.ts +132 -12
  188. package/test/attachments/service-config.test.ts +28 -16
  189. package/test/boot-auth-config.test.ts +146 -0
  190. package/test/boot-create-signature-policy.test.ts +15 -13
  191. package/test/boot-desktop-auth.test.ts +278 -0
  192. package/test/boot-env-isolation.test.ts +26 -0
  193. package/test/boot-helpers.ts +19 -0
  194. package/test/boot-inspection-enabled.test.ts +140 -0
  195. package/test/boot-mcp-auth.test.ts +449 -0
  196. package/test/boot-mcp-enabled.test.ts +27 -27
  197. package/test/boot-port-zero.test.ts +101 -0
  198. package/test/boot-preconditions.test.ts +213 -0
  199. package/test/boot-privacy.test.ts +232 -0
  200. package/test/boot-ready-drives.test.ts +141 -0
  201. package/test/boot-undo-v3-flag.test.ts +120 -0
  202. package/test/boot-unsupported-stored-documents.test.ts +23 -19
  203. package/test/boot-without-renown.test.ts +11 -9
  204. package/test/boot-without-require-signatures.test.ts +12 -10
  205. package/test/boot-worker-trust-policy.test.ts +11 -10
  206. package/test/boot-workflow-singleton-conflict.test.ts +109 -0
  207. package/test/boot-workflow-singleton-retry.test.ts +122 -0
  208. package/test/config-from-env.test.ts +968 -0
  209. package/test/config-merge.test.ts +351 -0
  210. package/test/config-schema.test.ts +183 -0
  211. package/test/default-composition.test.ts +290 -0
  212. package/test/default-drive-protocol-versions.test.ts +79 -0
  213. package/test/default-drive-slug.test.ts +265 -0
  214. package/test/delegated-publish.test.ts +435 -0
  215. package/test/durable-node-fs-pg16.test.ts +80 -0
  216. package/test/fatal-shutdown.test.ts +104 -1
  217. package/test/fixtures/mixed-subgraphs/subgraphs/greetings/index.ts +16 -0
  218. package/test/fixtures/mixed-subgraphs/subgraphs/index.ts +3 -0
  219. package/test/fixtures/mixed-subgraphs/subgraphs/tally/index.ts +73 -0
  220. package/test/goldens/packages.graphql +797 -0
  221. package/test/goldens/privacy.graphql +853 -0
  222. package/test/goldens/reactor-drive-nodes.graphql +827 -0
  223. package/test/goldens/resolvers.json +327 -0
  224. package/test/goldens/supergraph.graphql +5918 -0
  225. package/test/goldens/workflow-runtime.graphql +1548 -0
  226. package/test/inspection-throttle.test.ts +23 -0
  227. package/test/keyframe-reclaim-store.test.ts +156 -0
  228. package/test/observability-signals.test.ts +131 -0
  229. package/test/permissions-backfill.test.ts +486 -0
  230. package/test/pglite-dialect.test.ts +237 -2
  231. package/test/pglite-preflight.test.ts +313 -0
  232. package/test/pglite-storage-dirs.test.ts +113 -0
  233. package/test/pglite-store.test.ts +441 -0
  234. package/test/pglite-version.test.ts +9 -1
  235. package/test/plugin-config-schemas.test.ts +83 -0
  236. package/test/plugin-presence.test.ts +262 -0
  237. package/test/port-probe.test.ts +45 -0
  238. package/test/processor-timing-log.test.ts +109 -0
  239. package/test/reactor-feature-flags.test.ts +20 -0
  240. package/test/redact-webhook-path.test.ts +9 -0
  241. package/test/renown-storage-path.test.ts +40 -0
  242. package/test/renown-trust-policy.test.ts +7 -9
  243. package/test/served-schemas-mixed-package.test.ts +251 -0
  244. package/test/served-schemas.test.ts +134 -0
  245. package/test/shutdown.test.ts +278 -0
  246. package/test/snapshot-writer.ts +94 -0
  247. package/test/store-lock.test.ts +65 -0
  248. package/test/two-switchboards.test.ts +146 -0
  249. package/test/worker-pool.test.ts +27 -1
  250. package/test/workflow/oauth-apps-config.test.ts +66 -0
  251. package/test/workflow/oauth.test.ts +82 -10
  252. package/test/workflow/resolvers.test.ts +230 -38
  253. package/test/workflow/runtime-host.test.ts +19 -0
  254. package/test/workflow/waitpoint-routes.test.ts +306 -0
  255. package/test/workflow/waitpoint-runtime.test.ts +204 -0
  256. package/test/workflow/webhook-trigger-test.test.ts +8 -0
  257. package/test/workflow-reactor-access.test.ts +384 -0
  258. package/test/workflow-reactor-enforcement.test.ts +808 -0
  259. package/test/workflow-read-gate.test.ts +128 -60
  260. package/test/workflow-runtime.test.ts +1005 -237
  261. package/test/workflows-plugin-config.test.ts +77 -0
  262. package/tsconfig.json +5 -2
  263. package/tsdown.config.ts +12 -0
  264. package/vitest.config.ts +66 -1
  265. package/.tsbuild/test/mcp-flag.test.d.ts +0 -2
  266. package/.tsbuild/test/mcp-flag.test.d.ts.map +0 -1
  267. package/dist/server-sQoWp21G.mjs +0 -2939
  268. package/dist/server-sQoWp21G.mjs.map +0 -1
  269. package/dist/utils-uaBlzyjS.mjs +0 -86
  270. package/dist/utils-uaBlzyjS.mjs.map +0 -1
  271. package/test/mcp-flag.test.ts +0 -56
@@ -0,0 +1,1947 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c9a4d238-312b-50e4-86c0-d888f00a2e3d")}catch(e){}}();
3
+ import { REACTOR_SCHEMA, supportsLiveReadModelRegistration, withProgressHeartbeat } from "@powerhousedao/reactor";
4
+ import { AuthorizationPolicy, BaseSubgraph, ForbiddenError, callerSubject, createCanonicalDocumentIdResolver } from "@powerhousedao/reactor-api";
5
+ import { hostname } from "node:os";
6
+ import { z } from "zod";
7
+ import { parseRef } from "@powerhousedao/reactor-attachments";
8
+ import { waitpointRecord } from "@powerhousedao/reactor-workflow";
9
+ import { GraphQLError, Kind } from "graphql";
10
+ import { gql } from "graphql-tag";
11
+ //#region src/fatal-shutdown.mts
12
+ const FORCED_EXIT_MS = 15e3;
13
+ /**
14
+ * Starts the shutdown that SIGTERM's listeners run. Windows has no signals:
15
+ * `kill` there ends the process at once, stores open, so the listeners are
16
+ * called directly. False when nothing is listening.
17
+ */
18
+ function raiseSigterm(proc = process) {
19
+ if (proc.platform === "win32") return proc.emit("SIGTERM", "SIGTERM");
20
+ return proc.kill(proc.pid, "SIGTERM");
21
+ }
22
+ /** A write to a stdout or stderr that nobody reads any more. */
23
+ function isClosedPipe(err) {
24
+ return err?.code === "EPIPE";
25
+ }
26
+ const fatalHandlers = /* @__PURE__ */ new WeakMap();
27
+ /**
28
+ * Sends an uncaught exception or unhandled rejection through the SIGTERM
29
+ * shutdown that `withSignalHandlers()` installs, so the reactor and read-model
30
+ * PGlite stores close with a shutdown checkpoint before the process exits
31
+ * with code 1. Node's default is to exit at once, which leaves both stores
32
+ * to WAL recovery on the next open. A store whose wasm runtime aborted
33
+ * (ENOSPC) rejects its close; the builder logs that and still exits. A
34
+ * shutdown that hangs is cut off after FORCED_EXIT_MS.
35
+ *
36
+ * A rejection is fatal only when this is its sole listener: Node exits on an
37
+ * unhandled rejection only when nothing listens for it, and Sentry's
38
+ * listener deliberately keeps the process running.
39
+ */
40
+ function installFatalErrorShutdown(logger, proc = process) {
41
+ if (fatalHandlers.has(proc)) return;
42
+ const realExit = proc.exit.bind(proc);
43
+ let shuttingDown = false;
44
+ /**
45
+ * Logs without ever throwing. onFatal runs inside the uncaughtException
46
+ * handler, so a logger whose transport is gone (EPIPE on a closed stdout)
47
+ * would otherwise throw from the handler that reports throws, killing the
48
+ * process before the shutdown it is supposed to run. A logging failure is
49
+ * swallowed: there is nowhere left to report it.
50
+ */
51
+ const logFatal = (message, err) => {
52
+ try {
53
+ if (err === void 0) logger.error(message);
54
+ else logger.error(message, err);
55
+ } catch {}
56
+ };
57
+ const onFatal = (kind, err) => {
58
+ if (shuttingDown && isClosedPipe(err)) return;
59
+ logFatal(`${kind}: @error`, err);
60
+ if (shuttingDown) return;
61
+ shuttingDown = true;
62
+ proc.exitCode = 1;
63
+ setTimeout(() => {
64
+ logFatal("Shutdown after fatal error timed out; exiting");
65
+ realExit(1);
66
+ }, FORCED_EXIT_MS).unref();
67
+ if (!raiseSigterm(proc)) realExit(1);
68
+ };
69
+ fatalHandlers.set(proc, onFatal);
70
+ proc.on("uncaughtException", (err) => onFatal("Uncaught exception", err));
71
+ proc.on("unhandledRejection", (reason) => {
72
+ if (proc.listenerCount("unhandledRejection") > 1) return;
73
+ onFatal("Unhandled rejection", reason);
74
+ });
75
+ }
76
+ /**
77
+ * Routes a fatal condition the caller detected through the same shutdown as an
78
+ * uncaught error. Returns false, and does nothing, when
79
+ * `installFatalErrorShutdown` has not run for `proc`.
80
+ */
81
+ function triggerFatalShutdown(kind, err, proc = process) {
82
+ const onFatal = fatalHandlers.get(proc);
83
+ if (!onFatal) return false;
84
+ onFatal(kind, err);
85
+ return true;
86
+ }
87
+ //#endregion
88
+ //#region src/workflow/oauth-callback.ts
89
+ const OAUTH_CALLBACK_PATH = "oauth/callback";
90
+ function escapeHtml$1(text) {
91
+ return text.replace(/[&<>"']/g, (char) => ({
92
+ "&": "&amp;",
93
+ "<": "&lt;",
94
+ ">": "&gt;",
95
+ "\"": "&quot;",
96
+ "'": "&#39;"
97
+ })[char]);
98
+ }
99
+ function resultPage(ok, detail) {
100
+ const title = ok ? "Connected" : "Sign-in failed";
101
+ return `<!doctype html>
102
+ <html><head><meta charset="utf-8"><title>${title}</title>
103
+ <meta name="viewport" content="width=device-width, initial-scale=1">
104
+ <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>
105
+ </head><body><main><h1>${title}</h1><p>${ok ? "You can close this window." : escapeHtml$1(detail ?? "The sign-in did not finish.")}</p></main>
106
+ ${ok ? "<script>setTimeout(function(){window.close()},600)<\/script>" : ""}
107
+ </body></html>`;
108
+ }
109
+ function registerOAuthCallback(http, runtime) {
110
+ return http.get(OAUTH_CALLBACK_PATH, { auth: "public" }, async (request) => {
111
+ const params = new URL(request.url).searchParams;
112
+ const state = params.get("state");
113
+ const result = state ? await runtime.completeOAuth({
114
+ state,
115
+ code: params.get("code") ?? void 0,
116
+ error: params.get("error") ?? void 0,
117
+ errorDescription: params.get("error_description") ?? void 0
118
+ }) : {
119
+ ok: false,
120
+ detail: "The provider sent no state",
121
+ returnUrl: null
122
+ };
123
+ if (result.returnUrl && state) {
124
+ const back = new URL(result.returnUrl);
125
+ back.searchParams.set("ph_oauth", state);
126
+ return new Response(null, {
127
+ status: 303,
128
+ headers: {
129
+ location: back.href,
130
+ "cache-control": "no-store"
131
+ }
132
+ });
133
+ }
134
+ return new Response(resultPage(result.ok, result.detail), {
135
+ status: result.ok ? 200 : 400,
136
+ headers: {
137
+ "content-type": "text/html; charset=utf-8",
138
+ "cache-control": "no-store",
139
+ "referrer-policy": "no-referrer"
140
+ }
141
+ });
142
+ });
143
+ }
144
+ function callbackUrlOf(http) {
145
+ return `${http.baseUrl.replace(/\/+$/, "")}/${OAUTH_CALLBACK_PATH}`;
146
+ }
147
+ //#endregion
148
+ //#region src/workflow/waitpoint-routes.ts
149
+ const WAITPOINT_PATH = "waitpoints";
150
+ const MAX_REASON_LENGTH = 2e3;
151
+ const MAX_BODY_BYTES = 1048576;
152
+ const PAGE_HEADERS = {
153
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
154
+ "x-content-type-options": "nosniff",
155
+ "cache-control": "no-store",
156
+ "referrer-policy": "no-referrer"
157
+ };
158
+ const DROPPED_HEADERS = /* @__PURE__ */ new Set([
159
+ "authorization",
160
+ "cookie",
161
+ "proxy-authorization"
162
+ ]);
163
+ function waitpointBaseUrlOf(http) {
164
+ const url = `${http.baseUrl.replace(/\/+$/, "")}/${WAITPOINT_PATH}`;
165
+ return URL.canParse(url) ? url : void 0;
166
+ }
167
+ function registerWaitpointRoutes(http, runtime) {
168
+ const route = (method, subPath) => http.route({
169
+ method,
170
+ path: [
171
+ WAITPOINT_PATH,
172
+ ":token",
173
+ subPath
174
+ ].filter(Boolean).join("/"),
175
+ auth: "public",
176
+ maxBodyBytes: MAX_BODY_BYTES,
177
+ handler: (request, ctx) => handleWaitpointRequest(runtime, request, ctx.params.token, subPath)
178
+ });
179
+ return [
180
+ route([
181
+ "GET",
182
+ "HEAD",
183
+ "POST"
184
+ ], ""),
185
+ route([
186
+ "GET",
187
+ "HEAD",
188
+ "POST"
189
+ ], "sync"),
190
+ route([
191
+ "GET",
192
+ "HEAD",
193
+ "POST"
194
+ ], "confirm")
195
+ ];
196
+ }
197
+ async function handleWaitpointRequest(runtime, request, token, subPath) {
198
+ const method = request.method.toUpperCase();
199
+ const url = new URL(request.url);
200
+ const queryParams = Object.fromEntries(url.searchParams);
201
+ if (method === "GET" || method === "HEAD") {
202
+ if (subPath === "confirm") return confirmPage(runtime, token, queryParams, "");
203
+ if (subPath === "") return confirmPage(runtime, token, queryParams, url.pathname.endsWith("/") ? "confirm" : `${encodeURIComponent(token)}/confirm`);
204
+ return json(405, "Use POST to resume, or open the /confirm page", { allow: "POST" });
205
+ }
206
+ const headers = headerRecord(request);
207
+ const body = await readBody(request, headers["content-type"]);
208
+ const html = subPath === "confirm" && fromBrowser(headers);
209
+ let payloadBody = body;
210
+ if (subPath === "confirm") {
211
+ const action = queryParams.action;
212
+ if (action !== "approve" && action !== "disapprove") return refuse(html, 400, "Nothing was recorded", "This link needs to say whether you approve or disapprove. Open it in a browser and use one of the buttons.");
213
+ const reason = readReason(body) || queryParams.reason || void 0;
214
+ if (reason !== void 0 && reason.length > 2e3) return refuse(html, 400, "Your reason is too long", `Keep it under ${MAX_REASON_LENGTH} characters and submit again. Nothing was recorded.`);
215
+ if (reason !== void 0) {
216
+ queryParams.reason = reason;
217
+ payloadBody = {
218
+ ...body && typeof body === "object" ? body : {},
219
+ reason
220
+ };
221
+ }
222
+ }
223
+ const payload = {
224
+ body: payloadBody,
225
+ headers,
226
+ queryParams
227
+ };
228
+ if (subPath === "sync") {
229
+ const { status, reply } = await runtime.resumeWaitpointByTokenSync(token, payload);
230
+ if (status === "resumed" && reply) return replyResponse(reply);
231
+ return status === "resumed" ? json(200, recordedMessage(queryParams.action), void 0, status) : json(status === "already" ? 200 : 410, status === "already" ? "This request was already responded to." : "This request is no longer waiting.", void 0, status);
232
+ }
233
+ const { status } = await runtime.resumeWaitpointByToken(token, payload);
234
+ if (status === "resumed") {
235
+ const message = recordedMessage(queryParams.action);
236
+ return html ? page(200, {
237
+ title: "Response recorded",
238
+ message,
239
+ tone: "done"
240
+ }) : json(200, message, void 0, status);
241
+ }
242
+ if (status === "already") return html ? page(200, ALREADY) : json(200, "This request was already responded to.", void 0, status);
243
+ return html ? page(410, EXPIRED) : json(410, "This request is no longer waiting.", void 0, status);
244
+ }
245
+ async function confirmPage(runtime, token, queryParams, target) {
246
+ const described = await runtime.describeWaitpointByToken(token);
247
+ if (!described) return page(404, {
248
+ title: "Link not found",
249
+ message: "This link is not valid, or it has been removed.",
250
+ tone: "closed"
251
+ });
252
+ if (described.status === "COMPLETED" || described.status === "CONSUMED") return page(200, {
253
+ ...ALREADY,
254
+ context: described
255
+ });
256
+ if (described.status === "CANCELLED") return page(200, {
257
+ title: "Run cancelled",
258
+ message: "This run was cancelled. There is nothing left to do here.",
259
+ tone: "closed",
260
+ context: described
261
+ });
262
+ if (described.status === "EXPIRED") return page(200, {
263
+ ...EXPIRED,
264
+ context: described
265
+ });
266
+ return page(200, {
267
+ title: "Confirm your response",
268
+ message: "This workflow is paused and waiting for your response.",
269
+ tone: "open",
270
+ context: described,
271
+ form: {
272
+ approveUrl: actionUrl(target, queryParams, "approve"),
273
+ disapproveUrl: actionUrl(target, queryParams, "disapprove")
274
+ }
275
+ });
276
+ }
277
+ function actionUrl(target, queryParams, action) {
278
+ const params = new URLSearchParams(queryParams);
279
+ params.set("action", action);
280
+ return `${target}?${params.toString()}`;
281
+ }
282
+ function headerRecord(request) {
283
+ const headers = {};
284
+ request.headers.forEach((value, name) => {
285
+ if (!DROPPED_HEADERS.has(name)) headers[name] = value;
286
+ });
287
+ return headers;
288
+ }
289
+ async function readBody(request, contentType = "") {
290
+ const text = await request.text();
291
+ if (text === "") return void 0;
292
+ if (contentType.startsWith("application/x-www-form-urlencoded")) return Object.fromEntries(new URLSearchParams(text));
293
+ if (contentType.includes("json")) try {
294
+ return JSON.parse(text);
295
+ } catch {
296
+ return text;
297
+ }
298
+ return text;
299
+ }
300
+ function fromBrowser(headers) {
301
+ return (headers["content-type"] ?? "").startsWith("application/x-www-form-urlencoded") || (headers.accept ?? "").includes("text/html");
302
+ }
303
+ function readReason(body) {
304
+ if (!body || typeof body !== "object") return void 0;
305
+ const reason = body.reason;
306
+ return typeof reason === "string" ? reason : void 0;
307
+ }
308
+ function recordedMessage(action) {
309
+ if (action === "approve") return "You approved this request.";
310
+ if (action === "disapprove") return "You disapproved this request.";
311
+ return "Your response has been recorded.";
312
+ }
313
+ function refuse(html, status, title, message) {
314
+ return html ? page(status, {
315
+ title,
316
+ message,
317
+ tone: "closed"
318
+ }) : json(status, message);
319
+ }
320
+ function replyResponse(reply) {
321
+ const body = [
322
+ 204,
323
+ 205,
324
+ 304
325
+ ].includes(reply.status) ? void 0 : reply.body;
326
+ return new Response(body ?? null, {
327
+ status: reply.status,
328
+ headers: {
329
+ "cache-control": "no-store",
330
+ ...reply.headers,
331
+ ...body !== void 0 ? { "content-type": reply.contentType ?? "text/plain" } : {}
332
+ }
333
+ });
334
+ }
335
+ function json(status, message, headers, outcome) {
336
+ return new Response(JSON.stringify(outcome ? {
337
+ status: outcome,
338
+ message,
339
+ discarded: outcome === "gone"
340
+ } : { message }), {
341
+ status,
342
+ headers: {
343
+ "content-type": "application/json",
344
+ "cache-control": "no-store",
345
+ ...headers
346
+ }
347
+ });
348
+ }
349
+ const ALREADY = {
350
+ title: "Already responded",
351
+ message: "This request was already responded to. There is nothing left to do here.",
352
+ tone: "closed"
353
+ };
354
+ const EXPIRED = {
355
+ title: "Request expired",
356
+ message: "This request is no longer waiting for a response.",
357
+ tone: "closed"
358
+ };
359
+ function page(status, content) {
360
+ return new Response(renderPage(content), {
361
+ status,
362
+ headers: {
363
+ "content-type": "text/html; charset=utf-8",
364
+ ...PAGE_HEADERS
365
+ }
366
+ });
367
+ }
368
+ function escapeHtml(value) {
369
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
370
+ }
371
+ const STYLE = `
372
+ :root { color-scheme: light dark; --bg: #fafafa; --card: #fff; --fg: #0a0a0a; --muted: #6b7280; --line: #e5e7eb; --ok: #059669; --no: #dc2626; }
373
+ @media (prefers-color-scheme: dark) { :root { --bg: #0a0a0a; --card: #171717; --fg: #fafafa; --muted: #a3a3a3; --line: #262626; } }
374
+ * { box-sizing: border-box; }
375
+ body { 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; }
376
+ main { width: 440px; max-width: 100%; background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 24px; }
377
+ h1 { font-size: 20px; margin: 0 0 8px; }
378
+ p { margin: 0 0 16px; color: var(--muted); }
379
+ dl { margin: 0 0 16px; padding: 12px; border: 1px solid var(--line); border-radius: 8px; display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; }
380
+ dt { color: var(--muted); } dd { margin: 0; overflow-wrap: anywhere; }
381
+ .description { color: var(--fg); white-space: pre-line; }
382
+ label { display: block; font-weight: 500; margin-bottom: 4px; }
383
+ textarea { width: 100%; min-height: 72px; resize: vertical; padding: 8px; border: 1px solid var(--line); border-radius: 8px; background: transparent; color: inherit; font: inherit; }
384
+ .actions { display: flex; gap: 8px; margin-top: 16px; }
385
+ button { flex: 1; height: 36px; border: 0; border-radius: 8px; color: #fff; font: inherit; font-weight: 500; cursor: pointer; }
386
+ .approve { background: var(--ok); } .disapprove { background: var(--no); }
387
+ .done h1 { color: var(--ok); }
388
+ `;
389
+ function formatTime(iso) {
390
+ if (!iso) return void 0;
391
+ const time = new Date(iso);
392
+ if (Number.isNaN(time.getTime())) return void 0;
393
+ return `${time.toLocaleString("en-GB", {
394
+ dateStyle: "medium",
395
+ timeStyle: "short",
396
+ timeZone: "UTC"
397
+ })} UTC`;
398
+ }
399
+ function contextRows(context) {
400
+ const started = formatTime(context.startedAt);
401
+ return [
402
+ ["Workflow", context.workflowName || void 0],
403
+ ["Step", context.actionName && context.actionName.toLowerCase() !== context.stepName.toLowerCase() ? `${context.stepName} · ${context.actionName}` : context.stepName],
404
+ ["Started", started && context.triggerName ? `${started}, by ${context.triggerName}` : started],
405
+ ["Waiting since", formatTime(context.waitingSince)],
406
+ ["Expires", formatTime(context.expiresAt)]
407
+ ].filter((row) => row[1] !== void 0).map(([term, value]) => `<dt>${term}</dt><dd>${escapeHtml(value)}</dd>`).join("");
408
+ }
409
+ function renderPage({ title, message, tone, context, form }) {
410
+ const description = context?.workflowDescription ? `<p class="description">${escapeHtml(context.workflowDescription)}</p>` : "";
411
+ const details = context ? `${description}<dl>${contextRows(context)}</dl>` : "";
412
+ const actions = form ? `<form method="post">
413
+ <label for="reason">Reason (optional)</label>
414
+ <textarea id="reason" name="reason" maxlength="${MAX_REASON_LENGTH}"></textarea>
415
+ <div class="actions">
416
+ <button type="submit" class="disapprove" formaction="${escapeHtml(form.disapproveUrl)}">Disapprove</button>
417
+ <button type="submit" class="approve" formaction="${escapeHtml(form.approveUrl)}">Approve</button>
418
+ </div>
419
+ </form>` : "";
420
+ return `<!doctype html>
421
+ <html lang="en">
422
+ <head>
423
+ <meta charset="utf-8">
424
+ <meta name="viewport" content="width=device-width, initial-scale=1">
425
+ <meta name="robots" content="noindex">
426
+ <title>${escapeHtml(title)}</title>
427
+ <style>${STYLE}</style>
428
+ </head>
429
+ <body>
430
+ <main class="${tone}">
431
+ <h1>${escapeHtml(title)}</h1>
432
+ <p>${escapeHtml(message)}</p>
433
+ ${details}
434
+ ${actions}
435
+ </main>
436
+ </body>
437
+ </html>`;
438
+ }
439
+ //#endregion
440
+ //#region src/workflow/resolvers.ts
441
+ const PIECE_SOURCES = [
442
+ "local",
443
+ "registry",
444
+ "activepieces"
445
+ ];
446
+ function isPieceSource(value) {
447
+ return PIECE_SOURCES.includes(value);
448
+ }
449
+ function blockRef(input) {
450
+ if (input.kind !== "action" && input.kind !== "trigger") throw new GraphQLError(`A block's kind is "action" or "trigger", got "${input.kind}"`);
451
+ return {
452
+ pieceName: input.pieceName,
453
+ pieceVersion: input.pieceVersion,
454
+ name: input.name,
455
+ kind: input.kind
456
+ };
457
+ }
458
+ async function cursorAware(call) {
459
+ try {
460
+ return await call();
461
+ } catch (error) {
462
+ if (error instanceof Error && error.name === "InvalidRunCursorError") throw new GraphQLError(error.message, { extensions: { code: "BAD_USER_INPUT" } });
463
+ throw error;
464
+ }
465
+ }
466
+ function selectsStepData(selections, path) {
467
+ let level = selections;
468
+ for (const name of [...path, "steps"]) {
469
+ const next = [];
470
+ for (const set of level) for (const selection of set.selections) {
471
+ if (selection.kind !== Kind.FIELD) return true;
472
+ if (selection.name.value === name && selection.selectionSet) next.push(selection.selectionSet);
473
+ }
474
+ if (next.length === 0) return false;
475
+ level = next;
476
+ }
477
+ return level.some((set) => set.selections.some((selection) => selection.kind !== Kind.FIELD || selection.name.value === "input" || selection.name.value === "output"));
478
+ }
479
+ function readsStepData(info, path) {
480
+ if (!info) return true;
481
+ return selectsStepData(info.fieldNodes.flatMap((node) => node.selectionSet ? [node.selectionSet] : []), path);
482
+ }
483
+ async function syncAware(call) {
484
+ try {
485
+ return await call();
486
+ } catch (error) {
487
+ if (error instanceof Error && error.name === "WorkflowSyncingError") throw new GraphQLError(error.message, { extensions: {
488
+ code: "WORKFLOW_SYNCING",
489
+ retryable: true
490
+ } });
491
+ throw error;
492
+ }
493
+ }
494
+ function parseJson(value) {
495
+ if (value === null) return null;
496
+ try {
497
+ return JSON.parse(value);
498
+ } catch {
499
+ return value;
500
+ }
501
+ }
502
+ function toStepRecord(row) {
503
+ return {
504
+ stepId: row.step_id,
505
+ stepKey: row.step_key,
506
+ path: row.step_path === row.step_id ? null : row.step_path,
507
+ pieceName: row.piece_name,
508
+ blockName: row.block_name,
509
+ status: row.status,
510
+ input: parseJson(row.input),
511
+ output: parseJson(row.output),
512
+ port: row.port,
513
+ error: row.error,
514
+ errorName: row.error_name,
515
+ startedAt: row.started_at,
516
+ endedAt: row.ended_at,
517
+ pieceVersion: row.piece_version,
518
+ pieceSource: row.piece_source,
519
+ versionMatch: row.version_match,
520
+ versionNote: row.version_note
521
+ };
522
+ }
523
+ function toRunRecord(row, steps, waitpoints, iterationsTotal) {
524
+ return {
525
+ id: row.id,
526
+ workflowId: row.workflow_id,
527
+ workflowName: row.workflow_name,
528
+ workflowVersion: row.workflow_version,
529
+ triggerKind: row.trigger_kind,
530
+ triggerPayload: parseJson(row.trigger_payload),
531
+ status: row.status,
532
+ error: row.error,
533
+ errorName: row.error_name,
534
+ startedAt: row.started_at,
535
+ endedAt: row.ended_at,
536
+ rerunOf: row.rerun_of,
537
+ warnings: row.warnings,
538
+ warningNotes: parseJson(row.warning_notes) ?? [],
539
+ steps: steps.map(toStepRecord),
540
+ iterationsTotal: iterationsTotal ?? null,
541
+ waitpoints
542
+ };
543
+ }
544
+ function waitpointLoader(runtime) {
545
+ const cache = /* @__PURE__ */ new Map();
546
+ let batch = null;
547
+ return (runId) => {
548
+ const cached = cache.get(runId);
549
+ if (cached) return cached;
550
+ if (!batch) {
551
+ const ids = [];
552
+ batch = {
553
+ ids,
554
+ rows: new Promise((tick) => {
555
+ Promise.resolve().then(() => process.nextTick(tick));
556
+ }).then(async () => {
557
+ batch = null;
558
+ const store = await runtime.store();
559
+ return store ? store.listWaitpointsForRuns(ids) : /* @__PURE__ */ new Map();
560
+ })
561
+ };
562
+ }
563
+ batch.ids.push(runId);
564
+ const promise = batch.rows.then((rows) => (rows.get(runId) ?? []).map(waitpointRecord));
565
+ cache.set(runId, promise);
566
+ return promise;
567
+ };
568
+ }
569
+ function toRunPayload(row, steps) {
570
+ return {
571
+ runId: row.id,
572
+ status: row.status,
573
+ error: row.error,
574
+ errorName: row.error_name,
575
+ steps: steps.map((step) => ({
576
+ stepId: step.step_id,
577
+ key: step.step_key,
578
+ pieceName: step.piece_name,
579
+ blockName: step.block_name,
580
+ status: step.status,
581
+ input: parseJson(step.input),
582
+ output: parseJson(step.output),
583
+ port: step.port,
584
+ error: step.error,
585
+ errorName: step.error_name
586
+ }))
587
+ };
588
+ }
589
+ const UNKNOWN_ACCESS = {
590
+ authEnforcement: true,
591
+ authConditions: false,
592
+ identity: null
593
+ };
594
+ function signedIn(ctx) {
595
+ return Boolean(ctx.user?.address);
596
+ }
597
+ function isAbsolute(url) {
598
+ return /^https?:\/\//i.test(url);
599
+ }
600
+ function redirectUriFor(routing, requested) {
601
+ if (!routing) throw new GraphQLError("This host serves no OAuth2 callback");
602
+ if (isAbsolute(routing.callbackUrl)) return routing.callbackUrl;
603
+ if (!requested) throw new GraphQLError("This host does not know its public URL; pass redirectUri");
604
+ let url;
605
+ try {
606
+ url = new URL(requested);
607
+ } catch {
608
+ throw new GraphQLError(`"${requested}" is not a URL`);
609
+ }
610
+ if (url.protocol !== "https:" && url.protocol !== "http:" || url.pathname !== routing.callbackUrl || url.search !== "" || url.hash !== "") throw new GraphQLError(`redirectUri must be this host's ${routing.callbackUrl}`);
611
+ return url.href;
612
+ }
613
+ function returnUrlFor(requested, ctx) {
614
+ if (!requested) return void 0;
615
+ const origin = ctx.headers.origin;
616
+ let url;
617
+ try {
618
+ url = new URL(requested);
619
+ } catch {
620
+ url = void 0;
621
+ }
622
+ if (!url || !origin || url.origin !== origin) throw new GraphQLError("returnUrl must be on the requesting page's origin");
623
+ return url.href;
624
+ }
625
+ const getResolvers = (runtime, oauth, access = UNKNOWN_ACCESS, assertCanRead) => {
626
+ const loaders = /* @__PURE__ */ new WeakMap();
627
+ const loadWaitpoints = (runId, ctx) => {
628
+ let load = loaders.get(ctx);
629
+ if (!load) {
630
+ load = waitpointLoader(runtime);
631
+ loaders.set(ctx, load);
632
+ }
633
+ return load(runId);
634
+ };
635
+ return {
636
+ Query: { workflowRuntime: () => ({}) },
637
+ WorkflowRuntimeQueries: {
638
+ health: () => "ok",
639
+ authEnforcement: () => access.authEnforcement,
640
+ reactorIdentity: (_parent, _args, ctx) => signedIn(ctx) ? access.identity : null,
641
+ authConditions: (_parent, _args, ctx) => signedIn(ctx) ? access.authConditions : null,
642
+ reactorAccessDenial: async (_parent, args, ctx) => {
643
+ if (!assertCanRead) throw new GraphQLError("No read check configured");
644
+ await assertCanRead(args.workflowId, ctx);
645
+ return runtime.reactorAccessDenial(args.workflowId) ?? null;
646
+ },
647
+ blockDescriptor: (_parent, args) => runtime.blockDescriptor(blockRef(args.block)),
648
+ blockOptions: (_parent, args, ctx) => runtime.blockOptions(blockRef(args.block), args.propName, args.input, args.connectionId ?? void 0, ctx, args.searchValue ?? void 0, args.reactorConnectionId ?? void 0, args.workflowId ?? void 0),
649
+ pieceCatalog: () => runtime.pieceCatalog(),
650
+ pieceActions: (_parent, args) => runtime.pieceActions(args.packageName, args.version ?? void 0),
651
+ pieceTriggers: (_parent, args) => runtime.pieceTriggers(args.packageName, args.version ?? void 0),
652
+ blockOutputTree: (_parent, args) => runtime.blockOutputTree(blockRef(args.block), args.config),
653
+ stepOutputTree: (_parent, args, ctx) => runtime.stepOutputTree(args.workflowId, args.stepId, ctx),
654
+ blockResolutions: (_parent, args, ctx) => runtime.blockResolutions(args.workflowId, ctx),
655
+ pieceDetail: (_parent, args) => runtime.pieceDetail(args.packageName, args.version ?? void 0),
656
+ searchPieces: (_parent, args) => {
657
+ if (args.kind !== "action" && args.kind !== "trigger") throw new GraphQLError(`A search's kind is "action" or "trigger", got "${args.kind}"`);
658
+ const unknown = (args.sources ?? []).filter((source) => !isPieceSource(source));
659
+ if (unknown.length > 0) throw new GraphQLError(`A search's sources are ${PIECE_SOURCES.join(", ")}, got ${unknown.join(", ")}`);
660
+ return runtime.searchPieces(args.query, {
661
+ kind: args.kind,
662
+ sources: (args.sources ?? []).filter(isPieceSource),
663
+ categories: args.categories ?? void 0,
664
+ limit: args.limit ?? void 0
665
+ });
666
+ },
667
+ connections: (_parent, _args, ctx) => runtime.connections(ctx),
668
+ webhookEndpoint: (_parent, args, ctx) => syncAware(() => runtime.webhookEndpoint(args.workflowId, ctx, { driveId: args.driveId ?? void 0 })),
669
+ secret: (_parent, args, ctx) => runtime.secretStat(args.ref, ctx),
670
+ secrets: (_parent, _args, ctx) => runtime.listSecrets(ctx),
671
+ oauthRedirectUri: () => oauth?.callbackUrl ?? null,
672
+ oauthSignIn: async (_parent, args) => {
673
+ let redirectUri;
674
+ try {
675
+ redirectUri = redirectUriFor(oauth, args.redirectUri);
676
+ } catch {
677
+ return "NONE";
678
+ }
679
+ return (await runtime.oauthSignInMode(args.appId, redirectUri)).toUpperCase();
680
+ },
681
+ host: () => ({
682
+ id: `switchboard@${hostname()}`,
683
+ label: hostname()
684
+ }),
685
+ oauthAttempt: (_parent, args, ctx) => runtime.oauthAttempt(args.state, ctx),
686
+ triggerStates: async (_parent, _args, ctx) => (await runtime.triggerStates(ctx)).map((row) => ({
687
+ workflowId: row.workflow_id,
688
+ pieceName: row.piece_name,
689
+ triggerName: row.trigger_name,
690
+ status: row.status,
691
+ intervalMs: row.interval_ms,
692
+ nextPollAt: row.next_poll_at,
693
+ lastPollAt: row.last_poll_at,
694
+ lastError: row.last_error,
695
+ consecutiveFailures: row.consecutive_failures,
696
+ nextRenewAt: row.next_renew_at,
697
+ renewError: row.renew_error,
698
+ renewFailures: row.renew_failures,
699
+ pieceVersion: row.piece_version,
700
+ pieceSource: row.piece_source,
701
+ versionMatch: row.version_match,
702
+ versionNote: row.version_note
703
+ })),
704
+ runs: async (_parent, args, ctx, info) => (await runtime.runs({
705
+ ...args,
706
+ withStepData: readsStepData(info, [])
707
+ }, ctx)).map((record) => toRunRecord(record.row, record.steps)),
708
+ runsPage: async (_parent, args, ctx, info) => {
709
+ const { paging, ...scope } = args;
710
+ const page = await cursorAware(() => runtime.runsPage({
711
+ ...scope,
712
+ limit: paging?.limit ?? void 0,
713
+ cursor: paging?.cursor ?? null,
714
+ withStepData: readsStepData(info, ["items"])
715
+ }, ctx));
716
+ return {
717
+ items: page.records.map((record) => toRunRecord(record.row, record.steps)),
718
+ hasNextPage: page.hasNextPage,
719
+ hasPreviousPage: Boolean(paging?.cursor),
720
+ cursor: page.cursor
721
+ };
722
+ },
723
+ run: async (_parent, args, ctx) => {
724
+ const record = await runtime.run(args.id, ctx);
725
+ return record ? toRunRecord(record.row, record.steps, void 0, record.iterationsTotal) : null;
726
+ },
727
+ waitingRuns: async (_parent, args, ctx) => (await runtime.waitingRuns({
728
+ driveId: args.driveId ?? void 0,
729
+ workflowId: args.workflowId ?? void 0,
730
+ first: args.first ?? void 0
731
+ }, ctx)).map(({ run, waitpoints }) => toRunRecord(run.row, run.steps, waitpoints))
732
+ },
733
+ WorkflowRunRecord: { waitpoints: (parent, _args, ctx) => parent.waitpoints ?? loadWaitpoints(parent.id, ctx) },
734
+ Mutation: { workflowRuntime: () => ({}) },
735
+ WorkflowRuntimeMutations: {
736
+ fire: (_parent, args, ctx) => runtime.fire(args.workflowId, args.payload, "manual", void 0, ctx),
737
+ pollNow: (_parent, args, ctx) => runtime.pollNow(args.workflowId, ctx),
738
+ testTrigger: (_parent, args, ctx) => syncAware(() => runtime.testTrigger(args.workflowId, ctx, {
739
+ ...args.payload !== void 0 ? { payload: args.payload } : {},
740
+ ...typeof args.timeoutSeconds === "number" ? { timeoutMs: args.timeoutSeconds * 1e3 } : {},
741
+ driveId: args.driveId ?? void 0
742
+ })),
743
+ cancelTriggerTest: (_parent, args, ctx) => runtime.cancelTriggerTestFor(args.workflowId, ctx),
744
+ testStep: (_parent, args, ctx) => syncAware(() => runtime.testStep(args.workflowId, args.stepId, ctx, { driveId: args.driveId ?? void 0 })),
745
+ rerun: (_parent, args, ctx) => runtime.rerun(args.runId, ctx),
746
+ resolveWaitpoint: (_parent, args, ctx) => runtime.resolveWaitpoint(args.waitpointId, {
747
+ approved: args.approved,
748
+ ...args.reason ? { reason: args.reason } : {}
749
+ }, ctx),
750
+ cancelRun: async (_parent, args, ctx) => {
751
+ const record = await runtime.cancelRun(args.runId, ctx);
752
+ return toRunPayload(record.row, record.steps);
753
+ },
754
+ createSecret: (_parent, args, ctx) => syncAware(() => runtime.createSecret({
755
+ value: args.value,
756
+ label: args.label ?? void 0,
757
+ ownerId: args.documentId
758
+ }, ctx)),
759
+ rotateSecret: (_parent, args, ctx) => runtime.rotateSecret(args.ref, args.value, ctx),
760
+ deleteSecret: async (_parent, args, ctx) => {
761
+ await runtime.deleteSecret(args.ref, ctx);
762
+ return true;
763
+ },
764
+ checkConnection: (_parent, args, ctx) => runtime.checkConnection(args.connectionId, ctx),
765
+ startOAuth: (_parent, args, ctx) => {
766
+ const returnUrl = returnUrlFor(args.returnUrl, ctx);
767
+ return runtime.startOAuth(args.connectionId, ctx, {
768
+ redirectUri: redirectUriFor(oauth, args.redirectUri),
769
+ ...returnUrl ? { returnUrl } : {}
770
+ });
771
+ }
772
+ },
773
+ SecretRecord: { manageable: (parent, _args, ctx) => runtime.canManageSecret(parent, ctx) }
774
+ };
775
+ };
776
+ //#endregion
777
+ //#region src/workflow/schema.ts
778
+ const schema = gql`
779
+ """
780
+ WorkflowRuntime Queries
781
+ """
782
+ type WorkflowRuntimeQueries {
783
+ health: String!
784
+ """
785
+ Whether this reactor enforces document auth (REACTOR_AUTH_ENFORCEMENT).
786
+ On, a workflow needs a signed publish, and the host grants, to reach
787
+ documents. Answered to any caller.
788
+ """
789
+ authEnforcement: Boolean!
790
+ """
791
+ Who this host signs as: grant it on each document a step writes. Null for
792
+ a caller who is not signed in, or a host with no signer.
793
+ """
794
+ reactorIdentity: ReactorIdentity
795
+ """
796
+ REACTOR_AUTH_CONDITIONS. True: grant the host by key, with
797
+ { match: subject.key == key }; false: by address. Null for a caller who
798
+ is not signed in.
799
+ """
800
+ authConditions: Boolean
801
+ """
802
+ Why the workflow's last publish or enable got no reactor access, naming
803
+ the publisher and the connection; null when the check passed.
804
+ """
805
+ reactorAccessDenial(workflowId: String!): String
806
+ """
807
+ Persisted runs, newest first. Scope them to one workflow, or to every
808
+ workflow a drive holds; workflowId wins when both are given.
809
+ """
810
+ runs(
811
+ workflowId: String
812
+ driveId: String
813
+ limit: Int
814
+ "Trigger kinds to leave out, e.g. test."
815
+ excludeTriggerKinds: [String!]
816
+ ): [WorkflowRunRecord!]!
817
+ """
818
+ The same listing a page at a time, newest journaled first. Pass a page's
819
+ cursor back in paging to read the next; a page is short only when
820
+ hasNextPage is false, or when the caller could read none of a long
821
+ stretch of runs. A run that starts between pages keeps its place.
822
+ """
823
+ runsPage(
824
+ workflowId: String
825
+ driveId: String
826
+ excludeTriggerKinds: [String!]
827
+ paging: WorkflowRunsPagingInput
828
+ ): WorkflowRunResultPage!
829
+ run(id: String!): WorkflowRunRecord
830
+ """
831
+ WAITING runs, each with its waitpoints. Scope them to one
832
+ workflow, or to every workflow a drive holds; workflowId wins.
833
+ """
834
+ waitingRuns(
835
+ driveId: String
836
+ workflowId: String
837
+ first: Int
838
+ ): [WorkflowRunRecord!]!
839
+ """
840
+ The descriptor (props, auth, ports) of one action or trigger, as the
841
+ version that runs it describes it; triggers come back under "trigger".
842
+ """
843
+ blockDescriptor(block: BlockInput!): Unknown
844
+ """
845
+ Resolves a dynamic prop against the current config values: a DROPDOWN
846
+ yields { options, placeholder, disabled }, a DYNAMIC prop yields the
847
+ resolved sub-property descriptor list.
848
+ """
849
+ blockOptions(
850
+ block: BlockInput!
851
+ propName: String!
852
+ input: Unknown
853
+ connectionId: String
854
+ "What the author typed, for a DROPDOWN declared with refreshOnSearch."
855
+ searchValue: String
856
+ "The step's reactor connection; its filter narrows what the resolver reads."
857
+ reactorConnectionId: String
858
+ "The workflow being edited; a sub-flow dropdown lists what it may call."
859
+ workflowId: String
860
+ ): Unknown
861
+ """
862
+ Every piece this reactor offers: the core piece, its package pieces, and
863
+ the pieces the registry and Activepieces publish.
864
+ """
865
+ pieceCatalog: Unknown
866
+ """
867
+ A piece's actions at one version; pin a step to that version.
868
+ """
869
+ pieceActions(
870
+ packageName: String!
871
+ "That version; the installed or latest one when omitted."
872
+ version: String
873
+ ): Unknown
874
+ """
875
+ A piece's triggers at one version; pin a trigger to that version.
876
+ """
877
+ pieceTriggers(
878
+ packageName: String!
879
+ "That version; the installed or latest one when omitted."
880
+ version: String
881
+ ): Unknown
882
+ """
883
+ Full piece detail (PieceMetadataModel-shaped), verbatim from the cloud API.
884
+ """
885
+ pieceDetail(
886
+ packageName: String!
887
+ "That version; the installed or latest one when omitted."
888
+ version: String
889
+ ): Unknown
890
+ """
891
+ Piece and block search across the catalog, grouped by piece. The index
892
+ builds lazily on first use; poll while status is "indexing".
893
+ """
894
+ searchPieces(
895
+ query: String!
896
+ "action | trigger"
897
+ kind: String!
898
+ "local | registry | activepieces; all when omitted."
899
+ sources: [String!]
900
+ "Category ids, any of; all when omitted."
901
+ categories: [String!]
902
+ "Pieces returned."
903
+ limit: Int
904
+ ): PieceSearchResult!
905
+ """
906
+ Health of every registered piece trigger (poll schedule, errors).
907
+ """
908
+ triggerStates: [TriggerStateRecord!]!
909
+ """
910
+ Authored output shape of a block (SDL / outputSchema / sampleData).
911
+ """
912
+ blockOutputTree(block: BlockInput!, config: Unknown): Unknown
913
+ """
914
+ Output shape of a draft step or trigger: its latest test output
915
+ (source "test", with sample and testedAt) when tested, else as blockOutputTree.
916
+ """
917
+ stepOutputTree(workflowId: String!, stepId: String!): Unknown
918
+ """
919
+ Every block of the draft (trigger first) as this reactor resolves it:
920
+ which piece version runs, from where, and how it matches the pin.
921
+ """
922
+ blockResolutions(workflowId: String!): [BlockResolutionRecord!]!
923
+ """
924
+ Every powerhouse/connection document, for connection pickers.
925
+ """
926
+ connections: [ConnectionRecord!]!
927
+ """
928
+ The webhook endpoint for a workflow: the URL to hand the provider. Minted
929
+ on first ask, whether or not the workflow is armed — an author needs the
930
+ URL before enabling, and the armed field carries that difference. Null
931
+ only when the host has no webhook service. With driveId, a workflow not
932
+ synced here yet is waited for briefly, then fails as WORKFLOW_SYNCING.
933
+ """
934
+ webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord
935
+ """
936
+ Secret metadata (label, version, status). Never the value. Only secrets
937
+ whose owning document the caller can read.
938
+ """
939
+ secret(ref: String!): SecretRecord
940
+ secrets: [SecretRecord!]!
941
+ """
942
+ The URL an OAuth2 app must register as its redirect. A bare path when
943
+ this host does not know its public origin; resolve it against the URL
944
+ this API is reached at. Null when the host serves no HTTP routes.
945
+ """
946
+ oauthRedirectUri: String
947
+ """
948
+ How startOAuth would sign in with the publisher's OAuth2 app appId (a
949
+ connection's oauth_app) on this host, so an editor can tell before it
950
+ opens one. redirectUri as for startOAuth. NONE for an app this host does
951
+ not know, or when it cannot name its callback.
952
+ """
953
+ oauthSignIn(appId: String!, redirectUri: String): OAuthSignInMode!
954
+ """
955
+ The switchboard this runtime lives in: what an app records as the runner
956
+ of the workflows and connections it sets up here.
957
+ """
958
+ host: RuntimeHost!
959
+ """
960
+ How an OAuth2 sign-in opened by startOAuth stands; null when unknown.
961
+ """
962
+ oauthAttempt(state: String!): OAuthAttempt
963
+ }
964
+
965
+ type RuntimeHost {
966
+ "switchboard@<machine>: what apps record as the runner"
967
+ id: String!
968
+ "The machine's name, for people: where a sign-in has to happen"
969
+ label: String!
970
+ }
971
+
972
+ type OAuthAttempt {
973
+ connectionId: String!
974
+ "PENDING | EXCHANGING | OK | ERROR"
975
+ status: String!
976
+ error: String
977
+ }
978
+
979
+ """
980
+ How a host signs in with a publisher's OAuth2 app: DESKTOP, the app's
981
+ desktop client for a callback to this machine; WEB, its web client, whose
982
+ file this host has; RELAY, through the app's relay, which forwards the
983
+ provider's answer here and exchanges codes without this host holding the
984
+ secret; NONE, not at all.
985
+ """
986
+ enum OAuthSignInMode {
987
+ DESKTOP
988
+ WEB
989
+ RELAY
990
+ NONE
991
+ }
992
+
993
+ type OAuthStart {
994
+ state: String!
995
+ "Where to send the user to sign in."
996
+ authorizationUrl: String!
997
+ redirectUri: String!
998
+ expiresAt: String!
999
+ }
1000
+
1001
+ """
1002
+ One action or trigger of a piece, as a workflow pins it. The engine's own
1003
+ blocks are the piece @powerhousedao/piece-core.
1004
+ """
1005
+ input BlockInput {
1006
+ pieceName: String!
1007
+ "Exact semver."
1008
+ pieceVersion: String!
1009
+ "The action or trigger name."
1010
+ name: String!
1011
+ "action | trigger"
1012
+ kind: String!
1013
+ }
1014
+
1015
+ type BlockSearchHit {
1016
+ pieceName: String!
1017
+ "The version the hit is listed at; pin to it when picking the block."
1018
+ pieceVersion: String!
1019
+ "The action or trigger name."
1020
+ name: String!
1021
+ pieceDisplayName: String!
1022
+ logoUrl: String!
1023
+ displayName: String!
1024
+ description: String!
1025
+ "action | trigger"
1026
+ kind: String!
1027
+ "Triggers only: POLLING | WEBHOOK | APP_WEBHOOK | MANUAL"
1028
+ strategy: String
1029
+ "Why this block cannot run on this reactor; null when it can."
1030
+ unsupported: String
1031
+ }
1032
+
1033
+ type BlockResolutionRecord {
1034
+ "The trigger's or step's id."
1035
+ stepId: String!
1036
+ pieceName: String!
1037
+ "The version the block pins."
1038
+ pieceVersion: String!
1039
+ "The action or trigger name."
1040
+ name: String!
1041
+ "action | trigger"
1042
+ kind: String!
1043
+ "The version that runs; null when nothing resolves."
1044
+ resolvedVersion: String
1045
+ "local | registry | activepieces | npm; null when nothing resolves."
1046
+ source: String
1047
+ "exact | compatible | fallback | installed | missing"
1048
+ match: String!
1049
+ "Why the version that runs differs from the pin, or why nothing resolves."
1050
+ note: String
1051
+ "The newest version any source offers."
1052
+ latestVersion: String
1053
+ }
1054
+
1055
+ type PieceSearchMatch {
1056
+ pieceName: String!
1057
+ pieceVersion: String!
1058
+ displayName: String!
1059
+ description: String!
1060
+ logoUrl: String!
1061
+ categories: [String!]!
1062
+ "local | registry | activepieces"
1063
+ source: String!
1064
+ deprecated: Boolean
1065
+ "Why no block of the piece can run on this reactor."
1066
+ unsupported: String
1067
+ "Every query token matched the piece's own name."
1068
+ namedPiece: Boolean!
1069
+ "Matching blocks of the kind asked for, best first."
1070
+ blocks: [BlockSearchHit!]!
1071
+ }
1072
+
1073
+ type PieceSearchResult {
1074
+ "ready | indexing | error"
1075
+ status: String!
1076
+ pieces: [PieceSearchMatch!]!
1077
+ indexedPieces: Int!
1078
+ error: String
1079
+ }
1080
+
1081
+ type SecretRecord {
1082
+ ref: String!
1083
+ label: String
1084
+ "The document the secret resolves for; null for a host secret (an OAuth app's)."
1085
+ ownerId: String
1086
+ "Whether the caller may rotate or delete it: its creator, able to write its owner."
1087
+ manageable: Boolean!
1088
+ version: Int!
1089
+ status: String!
1090
+ createdAt: String!
1091
+ updatedAt: String!
1092
+ }
1093
+
1094
+ type ConnectionRecord {
1095
+ id: String!
1096
+ name: String!
1097
+ connectorId: String!
1098
+ authType: String!
1099
+ status: String!
1100
+ accountLabel: String
1101
+ }
1102
+
1103
+ type ReactorIdentity {
1104
+ "The address the host signs as; null without a signed-in identity."
1105
+ address: String
1106
+ "The did:key that signs the host's operations."
1107
+ key: String!
1108
+ }
1109
+
1110
+ type ConnectionCheckResult {
1111
+ ok: Boolean!
1112
+ detail: String
1113
+ """
1114
+ From auth.getConnectionIdentifier when the check passes; otherwise the
1115
+ label the connection already holds.
1116
+ """
1117
+ accountLabel: String
1118
+ }
1119
+
1120
+ type WebhookEndpointRecord {
1121
+ workflowId: String!
1122
+ url: String!
1123
+ """
1124
+ False when the host gave the webhook service no public origin, so the url
1125
+ above is a bare path. Switchboard always gives one, falling back to
1126
+ http://localhost:<port> when PUBLIC_URL is unset.
1127
+ """
1128
+ absoluteUrl: Boolean!
1129
+ "True while the workflow is ENABLED with a valid webhook trigger"
1130
+ armed: Boolean!
1131
+ createdAt: String!
1132
+ }
1133
+
1134
+ type TriggerStateRecord {
1135
+ workflowId: String!
1136
+ pieceName: String!
1137
+ triggerName: String!
1138
+ status: String!
1139
+ intervalMs: Int!
1140
+ nextPollAt: String
1141
+ lastPollAt: String
1142
+ lastError: String
1143
+ consecutiveFailures: Int!
1144
+ "When a webhook trigger next renews its subscription; null if it never does."
1145
+ nextRenewAt: String
1146
+ "The last failed renewal, kept apart from lastError, the poll's."
1147
+ renewError: String
1148
+ renewFailures: Int!
1149
+ "The piece version the trigger armed with; null for a host-fed trigger."
1150
+ pieceVersion: String
1151
+ pieceSource: String
1152
+ versionMatch: String
1153
+ versionNote: String
1154
+ }
1155
+
1156
+ type Query {
1157
+ workflowRuntime: WorkflowRuntimeQueries!
1158
+ }
1159
+
1160
+ type WorkflowStepRunRecord {
1161
+ stepId: String!
1162
+ stepKey: String!
1163
+ """
1164
+ One iteration of a loop body: "<loop>[<i>]/<step>", nested loops
1165
+ concatenated, i from 1. Null for the step's own row.
1166
+ """
1167
+ path: String
1168
+ pieceName: String!
1169
+ "The action the step ran, or the trigger a trigger test sampled."
1170
+ blockName: String!
1171
+ status: String!
1172
+ input: Unknown
1173
+ output: Unknown
1174
+ port: String
1175
+ error: String
1176
+ "The thrown error's name, e.g. ReactorAccessDeniedError."
1177
+ errorName: String
1178
+ startedAt: String
1179
+ endedAt: String
1180
+ "The piece version that ran; null for an unresolved block."
1181
+ pieceVersion: String
1182
+ "local | registry | activepieces | npm"
1183
+ pieceSource: String
1184
+ "exact | compatible | fallback | installed | missing"
1185
+ versionMatch: String
1186
+ "Why the version that ran differs from the pin."
1187
+ versionNote: String
1188
+ }
1189
+
1190
+ type WorkflowRunRecord {
1191
+ id: String!
1192
+ workflowId: String!
1193
+ workflowName: String!
1194
+ workflowVersion: Int!
1195
+ triggerKind: String!
1196
+ triggerPayload: Unknown
1197
+ """
1198
+ PENDING | RUNNING | WAITING | SUCCEEDED | FAILED | CANCELLED. WAITING: paused
1199
+ at a waitpoint (approval, webhook or delay); the run holds no worker.
1200
+ """
1201
+ status: String!
1202
+ error: String
1203
+ errorName: String
1204
+ "When the run began executing; a PENDING run's is when it was journaled."
1205
+ startedAt: String!
1206
+ endedAt: String
1207
+ rerunOf: String
1208
+ "How many warningNotes the run has; a run with any is not a plain success."
1209
+ warnings: Int!
1210
+ "Steps that ran a fallback piece version, edges on ports nothing emits."
1211
+ warningNotes: [String!]!
1212
+ steps: [WorkflowStepRunRecord!]!
1213
+ """
1214
+ Loop iteration rows the run journaled, when steps holds only the first of
1215
+ them; null when it holds every one. Listings hold none.
1216
+ """
1217
+ iterationsTotal: Int
1218
+ "Where the run paused, resolved ones included."
1219
+ waitpoints: [WaitpointRecord!]!
1220
+ }
1221
+
1222
+ "Who may decide an approval, and how the editor renders it."
1223
+ type ApprovalRequest {
1224
+ title: String!
1225
+ "Markdown."
1226
+ body: String
1227
+ approveLabel: String!
1228
+ rejectLabel: String!
1229
+ "none | reject | both"
1230
+ reasonRequiredOn: String!
1231
+ "DIDs allowed to decide; empty means anyone with write access."
1232
+ approvers: [String!]!
1233
+ }
1234
+
1235
+ "A point where a run paused, and how it resumes."
1236
+ type WaitpointRecord {
1237
+ id: String!
1238
+ runId: String!
1239
+ workflowId: String!
1240
+ stepId: String!
1241
+ stepKey: String!
1242
+ stepPath: String!
1243
+ pieceName: String!
1244
+ blockName: String!
1245
+ "DELAY | WEBHOOK"
1246
+ type: String!
1247
+ "approval | webhook | delay"
1248
+ kind: String!
1249
+ "PENDING | COMPLETED | CONSUMED | EXPIRED | CANCELLED"
1250
+ status: String!
1251
+ createdAt: String!
1252
+ "DELAY only: when the run resumes."
1253
+ resumeAt: String
1254
+ expiresAt: String
1255
+ resolvedAt: String
1256
+ "The DID that resolved it from the editor."
1257
+ decidedBy: String
1258
+ "Set by the Request approval block; null otherwise."
1259
+ approval: ApprovalRequest
1260
+ }
1261
+
1262
+ input WorkflowRunsPagingInput {
1263
+ "Page size; default 25, at most 100."
1264
+ limit: Int
1265
+ "The cursor of the previous page."
1266
+ cursor: String
1267
+ }
1268
+
1269
+ type WorkflowRunResultPage {
1270
+ items: [WorkflowRunRecord!]!
1271
+ hasNextPage: Boolean!
1272
+ "True when the page was read after a cursor."
1273
+ hasPreviousPage: Boolean!
1274
+ "Resumes after this page's last run; null for an empty page."
1275
+ cursor: String
1276
+ }
1277
+
1278
+ type WorkflowStepRun {
1279
+ stepId: String!
1280
+ key: String!
1281
+ pieceName: String!
1282
+ blockName: String!
1283
+ status: String!
1284
+ input: Unknown
1285
+ output: Unknown
1286
+ port: String
1287
+ error: String
1288
+ errorName: String
1289
+ }
1290
+
1291
+ type WorkflowRunPayload {
1292
+ runId: String
1293
+ status: String!
1294
+ error: String
1295
+ errorName: String
1296
+ steps: [WorkflowStepRun!]!
1297
+ }
1298
+
1299
+ type WorkflowStepTestResult {
1300
+ "Null when the test never started, e.g. an upstream block is untested."
1301
+ runId: String
1302
+ """
1303
+ SUCCEEDED | FAILED | INDETERMINATE. INDETERMINATE is neither: a host call
1304
+ the block made timed out, so a write it asked for may well have landed.
1305
+ Show it distinctly - it is not a confirmed pass.
1306
+ """
1307
+ status: String!
1308
+ output: Unknown
1309
+ error: String
1310
+ errorName: String
1311
+ durationMs: Int!
1312
+ }
1313
+
1314
+ """
1315
+ WorkflowRuntime Mutations
1316
+ """
1317
+ type WorkflowRuntimeMutations {
1318
+ """
1319
+ Fires a workflow's manual trigger (the core piece's) and runs it to completion.
1320
+ """
1321
+ fire(workflowId: String!, payload: Unknown): WorkflowRunPayload!
1322
+ """
1323
+ Runs the workflow's trigger now, as its schedule or poll would: a
1324
+ schedule fires the workflow, a polling trigger polls its source ("sync
1325
+ now"). False when it has no armed trigger (disabled, parked, erroring).
1326
+ """
1327
+ pollNow(workflowId: String!): Boolean!
1328
+ """
1329
+ Samples the draft trigger and saves it as the trigger's last test. A piece
1330
+ trigger runs its test hook (no cursor changes). Of the core piece's
1331
+ triggers, manual takes payload, schedule samples a fire now, and webhook
1332
+ waits for the next delivery to the workflow's endpoint, up to
1333
+ timeoutSeconds (default and cap 300), and that delivery runs nothing.
1334
+ """
1335
+ testTrigger(
1336
+ workflowId: String!
1337
+ payload: Unknown
1338
+ timeoutSeconds: Int
1339
+ driveId: String
1340
+ ): Unknown
1341
+ """
1342
+ Stops a webhook trigger test that is waiting; false when none was.
1343
+ """
1344
+ cancelTriggerTest(workflowId: String!): Boolean!
1345
+ """
1346
+ Runs one draft step against the latest test outputs of the blocks it
1347
+ reads, journaled as a "test" run and noted as the step's lastTest.
1348
+ driveId waits for an unsynced workflow, as for webhookEndpoint.
1349
+ """
1350
+ testStep(
1351
+ workflowId: String!
1352
+ stepId: String!
1353
+ driveId: String
1354
+ ): WorkflowStepTestResult!
1355
+ """
1356
+ Resumes a FAILED run: succeeded steps replay from the journal,
1357
+ execution restarts at the failure. Produces a new run.
1358
+ """
1359
+ rerun(runId: String!): WorkflowRunPayload!
1360
+ """
1361
+ Approves or rejects a PENDING WEBHOOK waitpoint, resuming its run. Needs
1362
+ write access to the workflow; with approvers listed, the caller's DID must
1363
+ be one. reason may be required, per approval.reasonRequiredOn.
1364
+ """
1365
+ resolveWaitpoint(
1366
+ waitpointId: String!
1367
+ approved: Boolean!
1368
+ reason: String
1369
+ ): WaitpointRecord!
1370
+ """
1371
+ Cancels a WAITING or PENDING run and its open waitpoints. A RUNNING run
1372
+ cannot be cancelled yet.
1373
+ """
1374
+ cancelRun(runId: String!): WorkflowRunPayload
1375
+ """
1376
+ Mints a managed secret for a connection or workflow document and returns
1377
+ its ref; only that document resolves it. The value is stored encrypted
1378
+ and is never readable back over any API.
1379
+ """
1380
+ createSecret(
1381
+ value: String!
1382
+ label: String
1383
+ documentId: String!
1384
+ ): SecretRecord!
1385
+ """
1386
+ Replaces the value behind an existing ref; documents stay untouched.
1387
+ Only its creator, while able to write its owning document.
1388
+ """
1389
+ rotateSecret(ref: String!, value: String!): SecretRecord!
1390
+ """
1391
+ Tombstones a secret; its value becomes unrecoverable. Only its creator,
1392
+ while able to write its owning document.
1393
+ """
1394
+ deleteSecret(ref: String!): Boolean!
1395
+ """
1396
+ Runs the piece's auth.validate against the connection's credentials,
1397
+ then auth.getConnectionIdentifier for the account label, and records the
1398
+ outcome on the connection document.
1399
+ """
1400
+ checkConnection(connectionId: String!): ConnectionCheckResult!
1401
+ """
1402
+ Opens an OAuth2 sign-in with the connection's own app (client_id in its
1403
+ config, client_secret in its secretRefs). redirectUri is needed only when
1404
+ oauthRedirectUri is a bare path. With returnUrl, which must be on the
1405
+ caller's origin, the callback sends the browser back there with
1406
+ ?ph_oauth=<state> instead of closing the window.
1407
+ """
1408
+ startOAuth(
1409
+ connectionId: String!
1410
+ redirectUri: String
1411
+ returnUrl: String
1412
+ ): OAuthStart!
1413
+ }
1414
+
1415
+ type Mutation {
1416
+ workflowRuntime: WorkflowRuntimeMutations!
1417
+ }
1418
+ `;
1419
+ //#endregion
1420
+ //#region src/workflow/subgraph.ts
1421
+ /** The runtime's read/write surface. The runtime itself is composed by the
1422
+ * host, so the subgraph only serves what it is handed. */
1423
+ function createWorkflowRuntimeSubgraph(runtime, oauth, access) {
1424
+ return class WorkflowRuntimeSubgraph extends BaseSubgraph {
1425
+ name = "workflow-runtime";
1426
+ typeDefs = schema;
1427
+ resolvers = getResolvers(runtime, oauth, access, (documentId, ctx) => this.assertCanRead(documentId, ctx));
1428
+ additionalContextFields = {};
1429
+ };
1430
+ }
1431
+ //#endregion
1432
+ //#region src/workflow-runtime.mts
1433
+ /** The npm name the workflow package owns: its HTTP namespace and its models. */
1434
+ const WORKFLOW_PACKAGE_NAME = "@powerhousedao/workflow";
1435
+ const WORKFLOW_TELEMETRY_SCOPE = "@powerhousedao/reactor-workflow";
1436
+ const SINGLETON_LOST = {
1437
+ status: "unavailable",
1438
+ reason: "workflow-singleton-lost"
1439
+ };
1440
+ async function assertWorkflowPackageLoadable(load = () => import("@powerhousedao/workflow/document-models")) {
1441
+ try {
1442
+ await load();
1443
+ } catch (error) {
1444
+ throw new Error(`Workflows are enabled but ${WORKFLOW_PACKAGE_NAME} could not be loaded`, { cause: error });
1445
+ }
1446
+ }
1447
+ /**
1448
+ * Whether a composition failure was the workflow singleton refusing this
1449
+ * process, rather than something that should take the boot down.
1450
+ *
1451
+ * Matched by NAME: the engine loads lazily, and importing it here for the
1452
+ * constructor would defeat that. The fields the engine's error carries are
1453
+ * typed optional for the same reason.
1454
+ */
1455
+ function isWorkflowSingletonConflict(error) {
1456
+ return error instanceof Error && error.name === "WorkflowSingletonConflictError";
1457
+ }
1458
+ /**
1459
+ * Retries the singleton claim for a host that booted without it, and hands
1460
+ * the runtime over once a claim succeeds.
1461
+ *
1462
+ * Without it a rolling deploy whose slots have different owner names ends
1463
+ * with nobody running workflows: the new pod is refused while the old one
1464
+ * still holds the lease, and nothing retries once the old pod releases it.
1465
+ * Only for a host that never composed; one that lost the lease after
1466
+ * composing stays without workflows until it restarts.
1467
+ */
1468
+ function retryWorkflowSingleton(options) {
1469
+ const intervalMs = options.intervalMs ?? 2e4;
1470
+ let stopped = false;
1471
+ let timer;
1472
+ let attempt;
1473
+ const run = async () => {
1474
+ let workflows;
1475
+ try {
1476
+ workflows = await options.compose();
1477
+ } catch (error) {
1478
+ if (!isWorkflowSingletonConflict(error)) options.logger.error("Composing the workflow runtime after the singleton came free failed: @error", error);
1479
+ schedule();
1480
+ return;
1481
+ }
1482
+ if (stopped) {
1483
+ await workflows.stop();
1484
+ return;
1485
+ }
1486
+ options.logger.info("Claimed the workflow singleton after boot; starting the workflow runtime");
1487
+ try {
1488
+ await options.onComposed(workflows);
1489
+ } catch (error) {
1490
+ options.logger.error("Starting the workflow runtime after the singleton came free failed: @error", error);
1491
+ schedule();
1492
+ }
1493
+ };
1494
+ const schedule = () => {
1495
+ if (stopped) return;
1496
+ timer = setTimeout(() => {
1497
+ timer = void 0;
1498
+ attempt = run().finally(() => {
1499
+ attempt = void 0;
1500
+ });
1501
+ }, intervalMs);
1502
+ timer.unref();
1503
+ };
1504
+ schedule();
1505
+ return { async stop() {
1506
+ stopped = true;
1507
+ if (timer) clearTimeout(timer);
1508
+ timer = void 0;
1509
+ await attempt?.catch(() => void 0);
1510
+ } };
1511
+ }
1512
+ /**
1513
+ * What a host does once its composed runtime has shut down for losing the
1514
+ * workflow singleton.
1515
+ *
1516
+ * Taken over by another claim: that process runs workflows now, so this one
1517
+ * stays without them until it restarts. Unrenewable with no takeover seen (a
1518
+ * database blip): nothing else runs them, so the process goes down through
1519
+ * the fatal shutdown and its supervisor restarts it, which re-claims at boot.
1520
+ * A host with no fatal shutdown installed (embedded) stays without workflows
1521
+ * and says a restart is needed.
1522
+ */
1523
+ function workflowSingletonLossHandler(logger, fatal = triggerFatalShutdown) {
1524
+ return (loss) => {
1525
+ if (loss.reason === "taken") {
1526
+ logger.error(`Another process ("${loss.heldBy ?? "unknown"}") took the workflow singleton. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted; everything else serves normally.`);
1527
+ return;
1528
+ }
1529
+ const error = /* @__PURE__ */ new Error(`The workflow singleton lease could not be renewed for ${Math.round(loss.silentMs)}ms; no other process was seen taking it over`);
1530
+ if (fatal("Workflow singleton lease unrenewable", error)) return;
1531
+ logger.error(`${error.message}. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted.`);
1532
+ };
1533
+ }
1534
+ function modelManifestSource(builder) {
1535
+ return {
1536
+ modelManifest: () => builder.getResolvedModelManifest() ?? [],
1537
+ modelEntries: (documentType) => builder.getImportableEntries(documentType)
1538
+ };
1539
+ }
1540
+ function readAssertion(authorizationService, reactorClient) {
1541
+ const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
1542
+ const hostCanRead = async (identifier, ctx) => {
1543
+ if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
1544
+ if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
1545
+ let documentId;
1546
+ try {
1547
+ documentId = await resolveCanonical(identifier);
1548
+ } catch {
1549
+ throw new ForbiddenError();
1550
+ }
1551
+ if (!await authorizationService.canRead(documentId, ctx.user?.address)) throw new ForbiddenError("to read this document");
1552
+ };
1553
+ return async (identifier, caller) => {
1554
+ const ctx = caller;
1555
+ await hostCanRead(identifier, ctx);
1556
+ let served;
1557
+ try {
1558
+ served = await reactorClient.isServed(identifier, { subject: callerSubject(ctx.user) });
1559
+ } catch {
1560
+ throw new ForbiddenError();
1561
+ }
1562
+ if (!served) throw new ForbiddenError("to read this document");
1563
+ };
1564
+ }
1565
+ /** The same, for a design-time call that writes what it names. */
1566
+ function writeAssertion(authorizationService, reactorClient) {
1567
+ const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
1568
+ return async (identifier, caller) => {
1569
+ const ctx = caller;
1570
+ if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
1571
+ if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
1572
+ let documentId;
1573
+ try {
1574
+ documentId = await resolveCanonical(identifier);
1575
+ } catch {
1576
+ throw new ForbiddenError();
1577
+ }
1578
+ if (!await authorizationService.canWrite(documentId, ctx.user?.address)) throw new ForbiddenError("to write this document");
1579
+ };
1580
+ }
1581
+ /** What the reactor enforces and who it signs as; unknown counts as enforced. */
1582
+ function reactorAccessOf(clientModule) {
1583
+ const flags = clientModule?.reactorModule?.featureFlags;
1584
+ const signer = clientModule?.signer;
1585
+ const key = signer?.app?.key;
1586
+ const identity = key ? {
1587
+ address: signer.user?.address ?? null,
1588
+ key
1589
+ } : null;
1590
+ return {
1591
+ authEnforcement: flags ? flags.authEnforcement : true,
1592
+ authConditions: flags?.authConditions === true,
1593
+ identity
1594
+ };
1595
+ }
1596
+ /**
1597
+ * A piece's read of a read-model index, run in process as the run's user
1598
+ * through the same GraphQL manager that serves the index over HTTP. The
1599
+ * request's caller is the run user's address on the host's own network and
1600
+ * chain, what a Renown bearer for that address would carry; the index's
1601
+ * access declarations decide from the address.
1602
+ *
1603
+ * A run with no user (its publish was unsigned or host-signed) is refused
1604
+ * before this under enforcement. With enforcement off the host acts for such
1605
+ * a run already, signing its writes with its own key, so its index reads are
1606
+ * the host's too: the request's caller is the host's signed-in address. A
1607
+ * host with no signed-in identity reads anonymously, which the
1608
+ * authenticated-caller floor refuses as it would an anonymous HTTP request.
1609
+ *
1610
+ * A caller the policy gives no rows is refused here. The index would answer it
1611
+ * with nothing, which a piece cannot tell from "nothing exists", and an upsert
1612
+ * would then create a duplicate of everything: a granter who left ADMINS must
1613
+ * stop a run, not double its documents.
1614
+ */
1615
+ function indexQueryFor(manager, clientModule, authorization) {
1616
+ const signer = clientModule?.signer;
1617
+ const host = signer?.user;
1618
+ const hostKey = signer?.app?.key ?? "";
1619
+ const chainId = host?.chainId ?? 1;
1620
+ const networkId = host?.networkId ?? "eip155";
1621
+ return async (request, runUser) => {
1622
+ const user = runUser ? {
1623
+ address: runUser.address,
1624
+ chainId,
1625
+ networkId,
1626
+ appKey: runUser.subject.key ?? hostKey
1627
+ } : host?.address ? {
1628
+ address: host.address,
1629
+ chainId,
1630
+ networkId,
1631
+ appKey: hostKey
1632
+ } : void 0;
1633
+ if (authorization?.config.policy === AuthorizationPolicy.ADMIN_ONLY && !authorization.isSupremeAdmin(user?.address)) return {
1634
+ data: null,
1635
+ errors: [{ message: user ? `Forbidden: ${user.address} is not an admin of this host, so it reads no index` : "Forbidden: this run has no person behind it, so it reads no index" }]
1636
+ };
1637
+ const result = await manager.executeSubgraph(request.subgraph, {
1638
+ query: request.query,
1639
+ variables: request.variables,
1640
+ user
1641
+ });
1642
+ return {
1643
+ data: result.data ?? null,
1644
+ ...result.errors ? { errors: result.errors.map((e) => ({ message: e.message })) } : {}
1645
+ };
1646
+ };
1647
+ }
1648
+ /** Whom a run's created documents also grant: the host, as §8 grants it. */
1649
+ function hostPrincipalOf(access) {
1650
+ const identity = access.identity;
1651
+ if (!identity) return void 0;
1652
+ if (access.authConditions) return { match: { eq: [{ attr: "subject.key" }, { lit: identity.key }] } };
1653
+ return identity.address ? { address: identity.address } : void 0;
1654
+ }
1655
+ /** Who the host signs as, so a publish it signs makes no run user. */
1656
+ function hostIdentityOf(access) {
1657
+ const identity = access.identity;
1658
+ if (!identity) return void 0;
1659
+ return identity.address ? {
1660
+ address: identity.address,
1661
+ key: identity.key
1662
+ } : { key: identity.key };
1663
+ }
1664
+ const REFERENCE_INDEX_RETRIES = 8;
1665
+ const REFERENCE_INDEX_RETRY_MS = 250;
1666
+ /** A step reads an attachment the way the download route serves one: when the
1667
+ * run's user may read a document that references it. The candidates are the
1668
+ * documents the run was handed; the reference index can trail the operation
1669
+ * that fired the trigger, so a denial is retried briefly. */
1670
+ function attachmentReadPolicy(access, retryMs = REFERENCE_INDEX_RETRY_MS) {
1671
+ return async (request) => {
1672
+ try {
1673
+ if (parseRef(request.ref).version !== 1) return false;
1674
+ } catch {
1675
+ return false;
1676
+ }
1677
+ if (!access || request.documentIds.length === 0) return false;
1678
+ const subject = request.runUser?.subject;
1679
+ const caller = {
1680
+ ...subject?.address ? { userAddress: subject.address } : {},
1681
+ ...subject?.key ? { appKey: subject.key } : {}
1682
+ };
1683
+ for (let attempt = 0; attempt <= REFERENCE_INDEX_RETRIES; attempt++) {
1684
+ for (const documentId of request.documentIds) if ((await access.canReadAttachment({
1685
+ documentId,
1686
+ attachmentRef: request.ref,
1687
+ ...caller
1688
+ })).kind === "allowed") return true;
1689
+ if (attempt < REFERENCE_INDEX_RETRIES) await new Promise((resolve) => setTimeout(resolve, retryMs));
1690
+ }
1691
+ return false;
1692
+ };
1693
+ }
1694
+ async function registerWorkflowTriggersReadModel(engine, runtime, clientModule, registration) {
1695
+ const reactorModule = clientModule?.reactorModule;
1696
+ if (!reactorModule) return {
1697
+ status: "unavailable",
1698
+ reason: "in-process-reactor-module-unavailable"
1699
+ };
1700
+ const coordinator = reactorModule.readModelCoordinator;
1701
+ if (!supportsLiveReadModelRegistration(coordinator)) return {
1702
+ status: "unavailable",
1703
+ reason: "live-read-model-registration-unsupported"
1704
+ };
1705
+ const readModel = new engine.WorkflowTriggersReadModel(reactorModule.database.withSchema(REACTOR_SCHEMA), reactorModule.operationIndex, reactorModule.writeCache, reactorModule.processorManagerConsistencyTracker, runtime);
1706
+ await readModel.init();
1707
+ if (registration.tornDown) return SINGLETON_LOST;
1708
+ coordinator.addReadModel(readModel, engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE);
1709
+ registration.detach = () => coordinator.removeReadModel(readModel);
1710
+ return { status: "available" };
1711
+ }
1712
+ function bindPackagePieces(registry, source) {
1713
+ const apply = (byPackage) => {
1714
+ registry.setPieces([...byPackage.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).flatMap(([, pieces]) => pieces));
1715
+ };
1716
+ apply(source.getPieces());
1717
+ source.onPiecesChange(apply);
1718
+ }
1719
+ async function composeWorkflowRuntime(deps) {
1720
+ const load = deps.load ?? (() => import("@powerhousedao/reactor-workflow"));
1721
+ let engine;
1722
+ try {
1723
+ engine = await load();
1724
+ } catch (error) {
1725
+ throw new Error("Workflows are enabled but @powerhousedao/reactor-workflow could not be loaded", { cause: error });
1726
+ }
1727
+ const loss = { lost: false };
1728
+ const lease = deps.singletonLease === false ? void 0 : await engine.acquireWorkflowSingletonLease({
1729
+ relationalDb: deps.relationalDb,
1730
+ logger: deps.logger,
1731
+ ...deps.storageId ? { storageId: deps.storageId } : {},
1732
+ selfFence: deps.exclusiveJournal !== true,
1733
+ exclusive: deps.exclusiveJournal === true,
1734
+ onLost: (lost) => {
1735
+ loss.lost = true;
1736
+ if (lost.reason === "taken") loss.heldBy = lost.heldBy;
1737
+ loss.tearDown?.();
1738
+ if (loss.composed) deps.onSingletonLost?.(lost);
1739
+ }
1740
+ });
1741
+ try {
1742
+ const composed = await composeClaimed(engine, deps, lease, loss);
1743
+ if (loss.lost) throw singletonLostError(engine, loss, lease);
1744
+ loss.composed = true;
1745
+ return composed;
1746
+ } catch (error) {
1747
+ loss.tearDown?.();
1748
+ await lease?.release();
1749
+ throw error;
1750
+ }
1751
+ }
1752
+ function singletonLostError(engine, loss, lease) {
1753
+ return new engine.WorkflowSingletonConflictError(loss.heldBy ?? "unknown", "unknown", lease?.owner ?? "unknown");
1754
+ }
1755
+ async function composeClaimed(engine, deps, lease, loss) {
1756
+ engine.setPieceRegistryUrl(deps.pieceRegistryUrl);
1757
+ if (deps.pieces) bindPackagePieces(engine.packagePieces, deps.pieces);
1758
+ if (loss.lost) throw singletonLostError(engine, loss, lease);
1759
+ const access = reactorAccessOf(deps.clientModule);
1760
+ const models = deps.models;
1761
+ const runtime = engine.createWorkflowRuntime({
1762
+ relationalDb: deps.relationalDb,
1763
+ secretsKeyFile: deps.secretsKeyFile,
1764
+ ...deps.oauthApps?.length ? { oauthApps: deps.oauthApps } : {},
1765
+ reactorClient: deps.reactorClient,
1766
+ assertCanRead: readAssertion(deps.authorizationService, deps.reactorClient),
1767
+ subjectOf: (caller) => callerSubject(caller.user),
1768
+ assertCanWrite: writeAssertion(deps.authorizationService, deps.reactorClient),
1769
+ ...deps.clientModule?.reactorModule ? { authEnforcement: access.authEnforcement } : {},
1770
+ hostPrincipal: hostPrincipalOf(access),
1771
+ hostIdentity: hostIdentityOf(access),
1772
+ ...deps.indexQueries ? { queryIndex: indexQueryFor(deps.indexQueries, deps.clientModule, deps.authorizationService) } : {},
1773
+ ...models ? {
1774
+ modelManifest: () => models.modelManifest(),
1775
+ modelEntries: (documentType) => models.modelEntries(documentType)
1776
+ } : {},
1777
+ webhooks: deps.webhooks,
1778
+ waitpointBaseUrl: deps.http ? waitpointBaseUrlOf(deps.http) : void 0,
1779
+ attachments: deps.attachments,
1780
+ canReadAttachmentRef: attachmentReadPolicy(deps.attachmentAccess),
1781
+ logger: deps.logger,
1782
+ ...deps.reactorThreads ? { reactorThreads: deps.reactorThreads } : {},
1783
+ ...deps.telemetry ? { telemetry: deps.telemetry } : {}
1784
+ });
1785
+ const routes = {};
1786
+ const registration = { tornDown: false };
1787
+ const tearDown = () => {
1788
+ if (registration.tornDown) return;
1789
+ registration.tornDown = true;
1790
+ routes.oauthCallback?.dispose();
1791
+ for (const handle of routes.waitpoints ?? []) handle.dispose();
1792
+ runtime.shutdown();
1793
+ registration.detach?.();
1794
+ };
1795
+ loss.tearDown = tearDown;
1796
+ const triggers = await registerWorkflowTriggersReadModel(engine, runtime, deps.clientModule, registration);
1797
+ if (registration.tornDown) throw singletonLostError(engine, loss, lease);
1798
+ if (triggers.status === "available") deps.logger.info(`Workflow trigger read model registered (${engine.WORKFLOW_TRIGGERS_READ_MODEL}, ${engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE})`);
1799
+ else deps.logger.error("Workflow document triggers are NOT armed (@reason): this reactor's read-model coordinator takes no live registration, so no document operation reaches the runtime. Webhook and schedule triggers are unaffected.", triggers.reason);
1800
+ let stopped = false;
1801
+ if (deps.http) {
1802
+ routes.oauthCallback = registerOAuthCallback(deps.http, runtime);
1803
+ routes.waitpoints = registerWaitpointRoutes(deps.http, runtime);
1804
+ }
1805
+ return {
1806
+ subgraph: createWorkflowRuntimeSubgraph(runtime, deps.http ? { callbackUrl: callbackUrlOf(deps.http) } : void 0, access),
1807
+ get triggers() {
1808
+ return loss.lost ? SINGLETON_LOST : triggers;
1809
+ },
1810
+ ...lease ? { singletonOwner: lease.owner } : {},
1811
+ secrets: () => runtime.secrets(),
1812
+ async start() {
1813
+ if (registration.tornDown) return;
1814
+ await runtime.registerWebhookEndpoint();
1815
+ if (loss.lost || stopped) return;
1816
+ runtime.startTriggerSupervisor();
1817
+ runtime.warmPieceSearch();
1818
+ },
1819
+ async stop() {
1820
+ if (stopped) return;
1821
+ stopped = true;
1822
+ tearDown();
1823
+ await lease?.release();
1824
+ }
1825
+ };
1826
+ }
1827
+ //#endregion
1828
+ //#region src/plugins/workflows.mts
1829
+ /** The drive app Workflow Studio registers under (packages/workflow). */
1830
+ const WORKFLOW_STUDIO_EDITOR_ID = "workflow-studio";
1831
+ /** The drive the plugin seeds unless the entry says otherwise. */
1832
+ const DEFAULT_WORKFLOWS_DRIVE = {
1833
+ slug: "workflows",
1834
+ name: "Workflows"
1835
+ };
1836
+ const workflowsDriveSchema = z.strictObject({
1837
+ /** The seeding key and the served `/d/<slug>` path (default "workflows"). */
1838
+ slug: z.string().min(1).optional(),
1839
+ /** Display name (default "Workflows"). */
1840
+ name: z.string().min(1).optional(),
1841
+ /** Fixed id; without one the id is project-hashed like classic `ph vetra`
1842
+ * (`workflows-<sha256(projectPath)[0:8]>`, slug unchanged), so existing
1843
+ * stores keep theirs. `projectHash: true` hashes the served slug as well. */
1844
+ id: z.string().min(1).optional(),
1845
+ projectHash: z.union([z.boolean(), z.literal("id")]).optional(),
1846
+ icon: z.string().optional()
1847
+ });
1848
+ const workflowsPluginConfigSchema = z.strictObject({
1849
+ /** The Workflows drive to seed; `false` runs the runtime without one. */
1850
+ drive: z.union([workflowsDriveSchema, z.literal(false)]).optional() });
1851
+ /** The drive declaration the entry config amounts to (host-core's
1852
+ * DriveDeclaration shape; kept structural here to avoid the import cycle the
1853
+ * Contributions type documents). `undefined` when `drive: false`. */
1854
+ function workflowsDriveDeclaration(config) {
1855
+ if (config.drive === false) return void 0;
1856
+ const drive = config.drive ?? {};
1857
+ return {
1858
+ slug: drive.slug ?? DEFAULT_WORKFLOWS_DRIVE.slug,
1859
+ name: drive.name ?? DEFAULT_WORKFLOWS_DRIVE.name,
1860
+ preferredEditor: WORKFLOW_STUDIO_EDITOR_ID,
1861
+ ...drive.id !== void 0 ? { id: drive.id } : { projectHash: drive.projectHash ?? "id" },
1862
+ ...drive.icon !== void 0 ? { icon: drive.icon } : {}
1863
+ };
1864
+ }
1865
+ function createWorkflowsPlugin(rawConfig = {}) {
1866
+ const drive = workflowsDriveDeclaration(workflowsPluginConfigSchema.parse(rawConfig ?? {}));
1867
+ return {
1868
+ name: "switchboard-workflows",
1869
+ appliesTo: "switchboard",
1870
+ configSchema: workflowsPluginConfigSchema,
1871
+ contributions: { drives: drive ? [drive] : [] },
1872
+ hooks: {
1873
+ transformServerOptions: (options) => {
1874
+ const current = options.workflows;
1875
+ if (current?.enabled === false) return options;
1876
+ return {
1877
+ ...options,
1878
+ workflows: {
1879
+ ...current,
1880
+ enabled: true
1881
+ }
1882
+ };
1883
+ },
1884
+ onSubgraphsRegistering: async (ctx) => {
1885
+ const orchestration = ctx.workflowsOrchestration;
1886
+ if (!orchestration?.enabled) return;
1887
+ const logger = ctx.logger;
1888
+ const lateSubgraphs = ctx.lateSubgraphs;
1889
+ let workflows;
1890
+ let workflowsRetry;
1891
+ try {
1892
+ workflows = await orchestration.composeWorkflows();
1893
+ } catch (error) {
1894
+ if (!isWorkflowSingletonConflict(error)) throw error;
1895
+ logger.warn(`Workflows are enabled but another live process ("${error.owner ?? "unknown"}") holds the workflow singleton until ${error.expiresAt ?? "unknown"}. This Switchboard has booted WITHOUT the workflow runtime: no trigger of any kind fires here, and the workflow GraphQL face is absent. Everything else serves normally. Stop the other owner, or set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the slot that owns workflows. This Switchboard retries the claim and starts workflows once the lease comes free.`);
1896
+ workflowsRetry = retryWorkflowSingleton({
1897
+ compose: orchestration.composeWorkflows,
1898
+ onComposed: async (composed) => {
1899
+ try {
1900
+ await composed.start();
1901
+ } catch (error) {
1902
+ try {
1903
+ await composed.stop();
1904
+ } catch (stopError) {
1905
+ logger.error("Stopping the late workflow runtime failed: @error", stopError);
1906
+ }
1907
+ throw error;
1908
+ }
1909
+ logger.info("Workflow runtime started");
1910
+ ctx.workflows = composed;
1911
+ await orchestration.registerWorkflowSubgraph(composed);
1912
+ try {
1913
+ await orchestration.updateRouter();
1914
+ } catch (error) {
1915
+ orchestration.reportMountFailure(error);
1916
+ }
1917
+ },
1918
+ logger
1919
+ });
1920
+ }
1921
+ ctx.workflowsRetry = workflowsRetry;
1922
+ if (workflows) {
1923
+ ctx.workflows = workflows;
1924
+ lateSubgraphs.push(orchestration.registerWorkflowSubgraph(workflows));
1925
+ const runtime = workflows;
1926
+ await withProgressHeartbeat({
1927
+ logger,
1928
+ label: "Starting the workflow runtime"
1929
+ }, () => runtime.start());
1930
+ logger.info("Workflow runtime started");
1931
+ orchestration.setWorkflowsFact();
1932
+ }
1933
+ },
1934
+ onShutdown: async (ctx) => {
1935
+ await ctx.workflowsRetry?.stop();
1936
+ await ctx.workflows?.stop();
1937
+ }
1938
+ }
1939
+ };
1940
+ }
1941
+ /** The default-config instance: the built-in composition's entry. */
1942
+ const workflowsPlugin = createWorkflowsPlugin({});
1943
+ //#endregion
1944
+ export { triggerFatalShutdown as _, workflowsPlugin as a, WORKFLOW_TELEMETRY_SCOPE as c, isWorkflowSingletonConflict as d, modelManifestSource as f, raiseSigterm as g, installFatalErrorShutdown as h, workflowsDriveDeclaration as i, assertWorkflowPackageLoadable as l, workflowSingletonLossHandler as m, WORKFLOW_STUDIO_EDITOR_ID as n, workflowsPluginConfigSchema as o, retryWorkflowSingleton as p, createWorkflowsPlugin as r, WORKFLOW_PACKAGE_NAME as s, DEFAULT_WORKFLOWS_DRIVE as t, composeWorkflowRuntime as u };
1945
+
1946
+ //# sourceMappingURL=workflows-mdYUh3Us.mjs.map
1947
+ //# debugId=c9a4d238-312b-50e4-86c0-d888f00a2e3d