@powerhousedao/switchboard 6.2.3 → 6.3.0-dev.10

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 +1122 -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,224 @@
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]="f2fea0fd-6621-5985-b4bc-34293d9647f0")}catch(e){}}();
3
+ import { metrics } from "@opentelemetry/api";
4
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
5
+ import { ExpressInstrumentation } from "@opentelemetry/instrumentation-express";
6
+ import { GraphQLInstrumentation } from "@opentelemetry/instrumentation-graphql";
7
+ import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";
8
+ import { PgInstrumentation } from "@opentelemetry/instrumentation-pg";
9
+ import { UndiciInstrumentation } from "@opentelemetry/instrumentation-undici";
10
+ import { resourceFromAttributes } from "@opentelemetry/resources";
11
+ import { NodeSDK } from "@opentelemetry/sdk-node";
12
+ import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
13
+ import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
14
+ import { registerEventLoopInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
15
+ import * as Sentry from "@sentry/node";
16
+ import { SentryPropagator, SentrySpanProcessor } from "@sentry/opentelemetry";
17
+ import { childLogger } from "document-model";
18
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
19
+ import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
20
+ //#region src/metrics.ts
21
+ const logger$1 = childLogger(["switchboard", "metrics"]);
22
+ function createMeterProviderFromEnv(env) {
23
+ const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;
24
+ if (!endpoint) return void 0;
25
+ const parsed = parseInt(env.OTEL_METRIC_EXPORT_INTERVAL ?? "", 10);
26
+ const exportIntervalMillis = Number.isFinite(parsed) && parsed > 0 ? parsed : 5e3;
27
+ const base = endpoint.replace(/\/$/, "");
28
+ const exporterUrl = base.endsWith("/v1/metrics") ? base : `${base}/v1/metrics`;
29
+ logger$1.info(`Initializing OpenTelemetry metrics exporter at: ${endpoint}`);
30
+ const meterProvider = new MeterProvider({
31
+ resource: resourceFromAttributes({ "service.name": env.OTEL_SERVICE_NAME ?? "switchboard" }),
32
+ readers: [new PeriodicExportingMetricReader({
33
+ exporter: new OTLPMetricExporter({ url: exporterUrl }),
34
+ exportIntervalMillis,
35
+ exportTimeoutMillis: Math.max(exportIntervalMillis - 250, 1)
36
+ })]
37
+ });
38
+ logger$1.info(`Metrics export enabled (interval: ${exportIntervalMillis}ms)`);
39
+ return meterProvider;
40
+ }
41
+ //#endregion
42
+ //#region src/observability-signals.mts
43
+ /**
44
+ * Flushes telemetry on SIGINT/SIGTERM, then exits only when no other module
45
+ * has claimed a failing exit.
46
+ *
47
+ * Exit ownership, decided here on purpose:
48
+ *
49
+ * - Ordinary signal (process.exitCode unset or 0): this handler exits with
50
+ * the current exit code after the flush settles (the flush bounds itself,
51
+ * see shutdown() in observability.mts). When the reactor builder's drain
52
+ * handler is also attached it runs first (prependListener) and swaps
53
+ * process.exit for a recording shim before this handler's exit call, so
54
+ * the drain still finishes and performs the real exit; when the builder is
55
+ * not attached (startup, signalHandlers: false), this exit is what
56
+ * terminates the process, with code 0.
57
+ *
58
+ * - Fatal shutdown in progress (process.exitCode already non-zero):
59
+ * fatal-shutdown.mts sets exitCode = 1 and arms a 15s forced exit BEFORE
60
+ * raising SIGTERM, precisely so the builder's drain can flush the PGlite
61
+ * snapshots. Calling exit here would lower that code to 0 (supervisors
62
+ * would see a crash as success) and, whenever the builder's shim is not in
63
+ * place, cut the drain off at this handler's shorter flush budget. So this
64
+ * handler never exits once a non-zero code is set: the exit belongs to the
65
+ * builder's drain, or failing that to fatal-shutdown's 15s backstop, both
66
+ * of which preserve code 1.
67
+ */
68
+ function installObservabilitySignalHandlers(flush, proc = process) {
69
+ const onSignal = () => {
70
+ flush().finally(() => {
71
+ const code = proc.exitCode;
72
+ if (code !== void 0 && code !== 0) return;
73
+ proc.exit(code ?? 0);
74
+ });
75
+ };
76
+ proc.on("SIGINT", onSignal);
77
+ proc.on("SIGTERM", onSignal);
78
+ }
79
+ //#endregion
80
+ //#region src/redact-webhook-path.ts
81
+ const TOKEN_SEGMENTS = ["/webhooks/", "/waitpoints/"];
82
+ /**
83
+ * Strips a webhook's delivery token out of a request path.
84
+ *
85
+ * The token is the endpoint's whole credential and it sits in the path, so it
86
+ * must not reach a log line or a span attribute that ships off-box. The family
87
+ * mounts under the host's base path, so the segment can sit at any depth.
88
+ */
89
+ function redactWebhookPath(url) {
90
+ if (!url) return "";
91
+ const path = url.split("?")[0] ?? url;
92
+ for (const segment of TOKEN_SEGMENTS) {
93
+ const at = path.indexOf(segment);
94
+ if (at === -1) continue;
95
+ if (path.length === at + segment.length) return url;
96
+ return `${path.slice(0, at)}${segment}[redacted]`;
97
+ }
98
+ return url;
99
+ }
100
+ //#endregion
101
+ //#region src/observability.mts
102
+ const logger = childLogger(["switchboard", "observability"]);
103
+ const SERVICE_NAME = process.env.OTEL_SERVICE_NAME || "switchboard";
104
+ const SERVICE_VERSION = process.env.npm_package_version || "unknown";
105
+ const TENANT_ID = process.env.TENANT_ID || "default";
106
+ const DEPLOY_ENV = process.env.NODE_ENV || "development";
107
+ const TEMPO_ENDPOINT = process.env.TEMPO_ENDPOINT;
108
+ const SENTRY_DSN = process.env.SENTRY_DSN;
109
+ const SENTRY_TRACING_TO_SENTRY = Boolean(SENTRY_DSN) && process.env.SENTRY_TRACING_ENABLED !== "false";
110
+ const TRACING_REQUESTED = process.env.ENABLE_TRACING === "true" || process.env.NODE_ENV === "production";
111
+ const HAS_TRACE_DESTINATION = Boolean(TEMPO_ENDPOINT) || Boolean(SENTRY_DSN);
112
+ const TRACING_ENABLED = TRACING_REQUESTED && HAS_TRACE_DESTINATION;
113
+ if (TRACING_REQUESTED && !HAS_TRACE_DESTINATION) logger.warn("Tracing was requested (NODE_ENV=production or ENABLE_TRACING=true) but no destination is configured — instrumentation will not run. Set TEMPO_ENDPOINT (e.g. http://tempo.monitoring.svc.cluster.local:4318/v1/traces) to export OTLP spans, and/or SENTRY_DSN to forward spans to Sentry.");
114
+ const SENTRY_TRACES_SAMPLE_RATE = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE ?? "0.1");
115
+ if (SENTRY_DSN) {
116
+ logger.info("Initialized Sentry with env: @env", process.env.SENTRY_ENV);
117
+ Sentry.init({
118
+ dsn: SENTRY_DSN,
119
+ environment: process.env.SENTRY_ENV,
120
+ release: process.env.SENTRY_RELEASE || (process.env.npm_package_version ? `v${process.env.npm_package_version}` : void 0),
121
+ tracesSampleRate: SENTRY_TRACING_TO_SENTRY ? SENTRY_TRACES_SAMPLE_RATE : 0,
122
+ skipOpenTelemetrySetup: TRACING_ENABLED
123
+ });
124
+ }
125
+ const meterProvider = createMeterProviderFromEnv({
126
+ OTEL_EXPORTER_OTLP_ENDPOINT: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
127
+ OTEL_METRIC_EXPORT_INTERVAL: process.env.OTEL_METRIC_EXPORT_INTERVAL,
128
+ OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME
129
+ });
130
+ let eventLoopInstrumentation;
131
+ if (meterProvider) {
132
+ metrics.setGlobalMeterProvider(meterProvider);
133
+ eventLoopInstrumentation = registerEventLoopInstrumentation();
134
+ }
135
+ let sdk;
136
+ if (TRACING_ENABLED) {
137
+ logger.info(`Initializing OpenTelemetry tracing for ${SERVICE_NAME}`);
138
+ if (TEMPO_ENDPOINT) logger.info(` Tempo endpoint: ${TEMPO_ENDPOINT}`);
139
+ if (SENTRY_DSN) logger.info(` Sentry span forwarding: enabled`);
140
+ logger.info(` Tenant: ${TENANT_ID}`);
141
+ const resource = resourceFromAttributes({
142
+ [ATTR_SERVICE_NAME]: SERVICE_NAME,
143
+ [ATTR_SERVICE_VERSION]: SERVICE_VERSION,
144
+ "tenant.id": TENANT_ID,
145
+ "deployment.environment": DEPLOY_ENV
146
+ });
147
+ const spanProcessors = [];
148
+ if (TEMPO_ENDPOINT) spanProcessors.push(new BatchSpanProcessor(new OTLPTraceExporter({ url: TEMPO_ENDPOINT })));
149
+ if (SENTRY_TRACING_TO_SENTRY) spanProcessors.push(new SentrySpanProcessor());
150
+ sdk = new NodeSDK({
151
+ resource,
152
+ spanProcessors,
153
+ textMapPropagator: SENTRY_TRACING_TO_SENTRY ? new SentryPropagator() : void 0,
154
+ instrumentations: [
155
+ new HttpInstrumentation({
156
+ ignoreIncomingRequestHook: (req) => req.url === "/health" || req.url === "/ready",
157
+ requireParentforIncomingSpans: false,
158
+ requireParentforOutgoingSpans: false,
159
+ requestHook: (span, request) => {
160
+ span.setAttribute("http.route", redactWebhookPath(request.url));
161
+ },
162
+ responseHook: (span, response) => {
163
+ if (response.statusCode) span.setAttribute("http.status_code", response.statusCode);
164
+ }
165
+ }),
166
+ new ExpressInstrumentation({ requestHook: (span, info) => {
167
+ if (info.route) span.setAttribute("http.route", info.route);
168
+ } }),
169
+ new UndiciInstrumentation(),
170
+ new GraphQLInstrumentation({
171
+ mergeItems: true,
172
+ allowValues: true
173
+ }),
174
+ new PgInstrumentation({
175
+ enhancedDatabaseReporting: true,
176
+ requireParentSpan: true
177
+ })
178
+ ]
179
+ });
180
+ sdk.start();
181
+ if (SENTRY_TRACING_TO_SENTRY && typeof Sentry.validateOpenTelemetrySetup === "function") Sentry.validateOpenTelemetrySetup();
182
+ logger.info("OpenTelemetry tracing initialized");
183
+ }
184
+ async function shutdown() {
185
+ eventLoopInstrumentation?.stop();
186
+ await Promise.race([Promise.all([meterProvider?.shutdown().catch(() => void 0), sdk?.shutdown().catch(() => void 0)]), new Promise((resolve) => setTimeout(resolve, 5e3))]);
187
+ }
188
+ let flushing;
189
+ /** Flushes and stops telemetry, once: a signal and a runner's shutdown may
190
+ * both ask. */
191
+ function flushObservability() {
192
+ return flushing ??= shutdown();
193
+ }
194
+ let signalHandlersInstalled = false;
195
+ /**
196
+ * Installs the SIGINT/SIGTERM flush, once. The bin does it at load
197
+ * (observability-bin.mts). Under `ph run` the switchboard runner does it, and
198
+ * only when no compound owns the signals: these handlers exit the process.
199
+ *
200
+ * Exit-code and drain coordination with fatal-shutdown.mts and the reactor
201
+ * builder lives in observability-signals.mts; the earlier inline handlers
202
+ * exited with a literal 0, which turned a fatal crash (exitCode = 1) into a
203
+ * success in the supervisor's eyes and could cut the snapshot drain short.
204
+ */
205
+ function installObservabilitySignals() {
206
+ if (signalHandlersInstalled) return;
207
+ signalHandlersInstalled = true;
208
+ installObservabilitySignalHandlers(flushObservability);
209
+ }
210
+ /**
211
+ * A failed boot as the bin reports it: captured, then flushed before the
212
+ * caller exits. A stored-documents refusal was already reported to the
213
+ * operator. Matched by name: importing the error would load the reactor
214
+ * ahead of the hooks above.
215
+ */
216
+ async function reportBootFailure(error) {
217
+ if (!(error instanceof Error && error.name === "StoredDocumentsRefusedError")) Sentry.captureException(error);
218
+ await Sentry.flush(2e3).catch(() => void 0);
219
+ }
220
+ //#endregion
221
+ export { sdk as a, reportBootFailure as i, installObservabilitySignals as n, meterProvider as r, flushObservability as t };
222
+
223
+ //# sourceMappingURL=observability-CldagyT_.mjs.map
224
+ //# debugId=f2fea0fd-6621-5985-b4bc-34293d9647f0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observability-CldagyT_.mjs","sources":["../src/metrics.ts","../src/observability-signals.mts","../src/redact-webhook-path.ts","../src/observability.mts"],"sourcesContent":["import { OTLPMetricExporter } from \"@opentelemetry/exporter-metrics-otlp-http\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport {\n MeterProvider,\n PeriodicExportingMetricReader,\n} from \"@opentelemetry/sdk-metrics\";\nimport { childLogger } from \"document-model\";\n\nconst logger = childLogger([\"switchboard\", \"metrics\"]);\n\nexport function createMeterProviderFromEnv(env: {\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_METRIC_EXPORT_INTERVAL?: string;\n OTEL_SERVICE_NAME?: string;\n}): MeterProvider | undefined {\n const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;\n if (!endpoint) return undefined;\n\n const parsed = parseInt(env.OTEL_METRIC_EXPORT_INTERVAL ?? \"\", 10);\n const exportIntervalMillis =\n Number.isFinite(parsed) && parsed > 0 ? parsed : 5_000;\n\n const base = endpoint.replace(/\\/$/, \"\");\n const exporterUrl = base.endsWith(\"/v1/metrics\")\n ? base\n : `${base}/v1/metrics`;\n\n logger.info(`Initializing OpenTelemetry metrics exporter at: ${endpoint}`);\n const meterProvider = new MeterProvider({\n resource: resourceFromAttributes({\n \"service.name\": env.OTEL_SERVICE_NAME ?? \"switchboard\",\n }),\n readers: [\n new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporter({\n url: exporterUrl,\n }),\n exportIntervalMillis,\n exportTimeoutMillis: Math.max(exportIntervalMillis - 250, 1),\n }),\n ],\n });\n logger.info(`Metrics export enabled (interval: ${exportIntervalMillis}ms)`);\n return meterProvider;\n}\n","// Signal handling for the observability bootstrap, split out of\n// observability.mts so tests can exercise it without importing the module\n// whose load-time side effects start Sentry and OpenTelemetry.\n\ntype SignalProcess = Pick<NodeJS.Process, \"on\" | \"exit\"> & {\n exitCode?: NodeJS.Process[\"exitCode\"];\n};\n\n/**\n * Flushes telemetry on SIGINT/SIGTERM, then exits only when no other module\n * has claimed a failing exit.\n *\n * Exit ownership, decided here on purpose:\n *\n * - Ordinary signal (process.exitCode unset or 0): this handler exits with\n * the current exit code after the flush settles (the flush bounds itself,\n * see shutdown() in observability.mts). When the reactor builder's drain\n * handler is also attached it runs first (prependListener) and swaps\n * process.exit for a recording shim before this handler's exit call, so\n * the drain still finishes and performs the real exit; when the builder is\n * not attached (startup, signalHandlers: false), this exit is what\n * terminates the process, with code 0.\n *\n * - Fatal shutdown in progress (process.exitCode already non-zero):\n * fatal-shutdown.mts sets exitCode = 1 and arms a 15s forced exit BEFORE\n * raising SIGTERM, precisely so the builder's drain can flush the PGlite\n * snapshots. Calling exit here would lower that code to 0 (supervisors\n * would see a crash as success) and, whenever the builder's shim is not in\n * place, cut the drain off at this handler's shorter flush budget. So this\n * handler never exits once a non-zero code is set: the exit belongs to the\n * builder's drain, or failing that to fatal-shutdown's 15s backstop, both\n * of which preserve code 1.\n */\nexport function installObservabilitySignalHandlers(\n flush: () => Promise<void>,\n proc: SignalProcess = process,\n): void {\n const onSignal = () => {\n void flush().finally(() => {\n const code = proc.exitCode;\n if (code !== undefined && code !== 0) {\n return;\n }\n proc.exit(code ?? 0);\n });\n };\n proc.on(\"SIGINT\", onSignal);\n proc.on(\"SIGTERM\", onSignal);\n}\n","// Segments followed by a token that is the request's whole credential:\n// a webhook's delivery token, a waitpoint's resume token.\nconst TOKEN_SEGMENTS = [\"/webhooks/\", \"/waitpoints/\"];\n\n/**\n * Strips a webhook's delivery token out of a request path.\n *\n * The token is the endpoint's whole credential and it sits in the path, so it\n * must not reach a log line or a span attribute that ships off-box. The family\n * mounts under the host's base path, so the segment can sit at any depth.\n */\nexport function redactWebhookPath(url: string | undefined): string {\n if (!url) return \"\";\n // Dropped with the token: `http.route` is meant to be a template, and a\n // query string is another place a sender can put a credential.\n const path = url.split(\"?\")[0] ?? url;\n for (const segment of TOKEN_SEGMENTS) {\n const at = path.indexOf(segment);\n if (at === -1) continue;\n // Nothing after the segment is nothing to redact.\n if (path.length === at + segment.length) return url;\n return `${path.slice(0, at)}${segment}[redacted]`;\n }\n return url;\n}\n","// Single observability bootstrap: Sentry + OpenTelemetry (tracing + metrics).\n//\n// MUST be imported as the very first module in apps/switchboard/src/index.mts\n// (through observability-bin.mts, which also installs the signal handlers).\n// OpenTelemetry instrumentations register require-time hooks at module load,\n// so http/express/pg/graphql must not be imported (transitively) before this\n// file runs. `ph run` imports it the same way, as\n// `@powerhousedao/switchboard/observability`, before it loads a host.\n//\n// Replaces three legacy bootstrap sites:\n// - apps/switchboard/src/server.mts top-level Sentry.init\n// - apps/switchboard/src/metrics.ts standalone MeterProvider (still exported\n// here via createMeterProviderFromEnv so its tests keep passing)\n// - packages/reactor-api/src/tracing.ts side-effect NodeSDK\nimport { metrics } from \"@opentelemetry/api\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { ExpressInstrumentation } from \"@opentelemetry/instrumentation-express\";\nimport { GraphQLInstrumentation } from \"@opentelemetry/instrumentation-graphql\";\nimport { HttpInstrumentation } from \"@opentelemetry/instrumentation-http\";\nimport { PgInstrumentation } from \"@opentelemetry/instrumentation-pg\";\nimport { UndiciInstrumentation } from \"@opentelemetry/instrumentation-undici\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport type { MeterProvider } from \"@opentelemetry/sdk-metrics\";\nimport { NodeSDK } from \"@opentelemetry/sdk-node\";\nimport {\n BatchSpanProcessor,\n type SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n} from \"@opentelemetry/semantic-conventions\";\nimport {\n registerEventLoopInstrumentation,\n type EventLoopInstrumentation,\n} from \"@powerhousedao/opentelemetry-instrumentation-reactor\";\nimport * as Sentry from \"@sentry/node\";\nimport { SentryPropagator, SentrySpanProcessor } from \"@sentry/opentelemetry\";\nimport { childLogger } from \"document-model\";\nimport type { IncomingMessage } from \"node:http\";\nimport { createMeterProviderFromEnv } from \"./metrics.js\";\nimport { installObservabilitySignalHandlers } from \"./observability-signals.mjs\";\nimport { redactWebhookPath } from \"./redact-webhook-path.js\";\n\nconst logger = childLogger([\"switchboard\", \"observability\"]);\n\nconst SERVICE_NAME = process.env.OTEL_SERVICE_NAME || \"switchboard\";\nconst SERVICE_VERSION = process.env.npm_package_version || \"unknown\";\nconst TENANT_ID = process.env.TENANT_ID || \"default\";\nconst DEPLOY_ENV = process.env.NODE_ENV || \"development\";\n\nconst TEMPO_ENDPOINT = process.env.TEMPO_ENDPOINT;\nconst SENTRY_DSN = process.env.SENTRY_DSN;\n\n// Whether to forward TRANSACTIONS (spans) to Sentry. Errors are always sent\n// when SENTRY_DSN is set — this flag only gates APM/tracing into Sentry.\n// Default on (back-compat). Set SENTRY_TRACING_ENABLED=false for an\n// \"errors-only\" deployment: errors still go to Sentry, traces still go to\n// Tempo, but no transactions hit Sentry (no Kafka/ClickHouse/nodestore\n// cost). This is the recommended mode for tenant workloads at scale —\n// Sentry's value there is error grouping; traces live in Tempo.\nconst SENTRY_TRACING_TO_SENTRY =\n Boolean(SENTRY_DSN) && process.env.SENTRY_TRACING_ENABLED !== \"false\";\n\nconst TRACING_REQUESTED =\n process.env.ENABLE_TRACING === \"true\" ||\n process.env.NODE_ENV === \"production\";\nconst HAS_TRACE_DESTINATION = Boolean(TEMPO_ENDPOINT) || Boolean(SENTRY_DSN);\nconst TRACING_ENABLED = TRACING_REQUESTED && HAS_TRACE_DESTINATION;\n\nif (TRACING_REQUESTED && !HAS_TRACE_DESTINATION) {\n logger.warn(\n \"Tracing was requested (NODE_ENV=production or ENABLE_TRACING=true) but \" +\n \"no destination is configured — instrumentation will not run. Set \" +\n \"TEMPO_ENDPOINT (e.g. http://tempo.monitoring.svc.cluster.local:4318/v1/traces) \" +\n \"to export OTLP spans, and/or SENTRY_DSN to forward spans to Sentry.\",\n );\n}\n\n// APM sampling for the Sentry-SDK-managed path (i.e. when TRACING is OFF and\n// @sentry/node runs its own bundled OTel — see skipOpenTelemetrySetup below).\n//\n// IMPORTANT: when TRACING_ENABLED, this value does NOT govern span volume.\n// Our NodeSDK (below) owns the pipeline and is constructed with no explicit\n// `sampler`, so @opentelemetry/sdk-node falls back to buildSamplerFromEnv()\n// and the REAL head-sampling knob is the standard OTEL_TRACES_SAMPLER /\n// OTEL_TRACES_SAMPLER_ARG env (set per-deploy in the k8s chart). That head\n// decision gates spans before any processor runs, so it bounds BOTH the\n// SentrySpanProcessor (→ Sentry transactions) and the Tempo OTLP export.\n// (Wiring @sentry/opentelemetry's SentrySampler here would let this rate\n// drive both backends and make DSC/sample_rand propagation spec-correct, but\n// that only matters for Sentry server-side dynamic sampling — a SaaS feature\n// our self-hosted install doesn't run — so it's intentionally deferred.)\nconst SENTRY_TRACES_SAMPLE_RATE = parseFloat(\n process.env.SENTRY_TRACES_SAMPLE_RATE ?? \"0.1\",\n);\n\nif (SENTRY_DSN) {\n logger.info(\"Initialized Sentry with env: @env\", process.env.SENTRY_ENV);\n Sentry.init({\n dsn: SENTRY_DSN,\n environment: process.env.SENTRY_ENV,\n // Match the version tag uploaded by release-branch.yml so source maps\n // resolve. Populated by the CI (WORKSPACE_VERSION) or npm at runtime.\n release:\n process.env.SENTRY_RELEASE ||\n (process.env.npm_package_version\n ? `v${process.env.npm_package_version}`\n : undefined),\n // 0 in errors-only mode so even @sentry/node's bundled auto-OTel path\n // (used when TRACING_ENABLED is false) produces no transactions.\n tracesSampleRate: SENTRY_TRACING_TO_SENTRY ? SENTRY_TRACES_SAMPLE_RATE : 0,\n // When tracing is on, our NodeSDK below owns the OTel globals and Sentry\n // receives spans via SentrySpanProcessor. Skipping Sentry's bundled OTel\n // setup avoids two TracerProviders fighting over setGlobalTracerProvider.\n // When tracing is off, leave the flag unset so @sentry/node's default\n // auto-OTel still records HTTP transactions for the APM dashboard.\n skipOpenTelemetrySetup: TRACING_ENABLED,\n });\n}\n\nconst meterProvider: MeterProvider | undefined = createMeterProviderFromEnv({\n OTEL_EXPORTER_OTLP_ENDPOINT: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,\n OTEL_METRIC_EXPORT_INTERVAL: process.env.OTEL_METRIC_EXPORT_INTERVAL,\n OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME,\n});\nlet eventLoopInstrumentation: EventLoopInstrumentation | undefined;\nif (meterProvider) {\n // One-way door: must register before any code calls metrics.getMeter() —\n // most notably ReactorInstrumentation inside the reactor module.\n metrics.setGlobalMeterProvider(meterProvider);\n // Host event-loop and CPU gauges (reactor.host.eventloop.*,\n // reactor.host.cpu.utilization). The bench sweep identified the host event\n // loop, not the executor, as the binding constraint on write throughput\n // (bench/test/integration/BASELINE.md, Run 10) — these are the production\n // counterpart of the metrics that finding was made from. Must come after\n // setGlobalMeterProvider or the gauges bind to a no-op meter.\n eventLoopInstrumentation = registerEventLoopInstrumentation();\n}\n\nlet sdk: NodeSDK | undefined;\n\nif (TRACING_ENABLED) {\n logger.info(`Initializing OpenTelemetry tracing for ${SERVICE_NAME}`);\n if (TEMPO_ENDPOINT) logger.info(` Tempo endpoint: ${TEMPO_ENDPOINT}`);\n if (SENTRY_DSN) logger.info(` Sentry span forwarding: enabled`);\n logger.info(` Tenant: ${TENANT_ID}`);\n\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: SERVICE_NAME,\n [ATTR_SERVICE_VERSION]: SERVICE_VERSION,\n \"tenant.id\": TENANT_ID,\n \"deployment.environment\": DEPLOY_ENV,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n if (TEMPO_ENDPOINT) {\n spanProcessors.push(\n new BatchSpanProcessor(new OTLPTraceExporter({ url: TEMPO_ENDPOINT })),\n );\n }\n if (SENTRY_TRACING_TO_SENTRY) {\n // Fan the same OTel spans into Sentry — same trace IDs as Tempo, so\n // Sentry transactions cross-link to traces in Grafana. Skipped in\n // errors-only mode (SENTRY_TRACING_ENABLED=false): spans still flow to\n // Tempo via the BatchSpanProcessor above, just not to Sentry.\n spanProcessors.push(new SentrySpanProcessor());\n }\n\n sdk = new NodeSDK({\n resource,\n spanProcessors,\n textMapPropagator: SENTRY_TRACING_TO_SENTRY\n ? new SentryPropagator()\n : undefined,\n instrumentations: [\n new HttpInstrumentation({\n ignoreIncomingRequestHook: (req) =>\n req.url === \"/health\" || req.url === \"/ready\",\n requireParentforIncomingSpans: false,\n requireParentforOutgoingSpans: false,\n requestHook: (span, request) => {\n span.setAttribute(\n \"http.route\",\n redactWebhookPath((request as IncomingMessage).url),\n );\n },\n responseHook: (span, response) => {\n if (response.statusCode) {\n span.setAttribute(\"http.status_code\", response.statusCode);\n }\n },\n }),\n new ExpressInstrumentation({\n requestHook: (span, info) => {\n if (info.route) span.setAttribute(\"http.route\", info.route);\n },\n }),\n // HttpInstrumentation only patches node:http/https; outbound global\n // fetch() goes through undici and is otherwise untraced — e.g. the\n // per-request Renown credential check in AuthService.verifyCredentialExists.\n new UndiciInstrumentation(),\n new GraphQLInstrumentation({ mergeItems: true, allowValues: true }),\n // requireParentSpan: only trace DB queries that run inside a request\n // (HTTP/GraphQL) span. Parentless queries — the management\n // switchboard's background polling loops (vetra-cloud-observability\n // reconcile @60s + clint pull-worker @15s, each writing\n // environment_pods / clint_runtime_endpoints) — would otherwise each\n // become a standalone root transaction. That volume scales O(tenant\n // count) and was ~70% of all Sentry transactions before this change.\n // Dropping it at the instrumentation layer (no span created at all) is\n // cheaper and cleaner than sampling it away downstream.\n new PgInstrumentation({\n enhancedDatabaseReporting: true,\n requireParentSpan: true,\n }),\n ],\n });\n sdk.start();\n if (\n SENTRY_TRACING_TO_SENTRY &&\n typeof Sentry.validateOpenTelemetrySetup === \"function\"\n ) {\n Sentry.validateOpenTelemetrySetup();\n }\n logger.info(\"OpenTelemetry tracing initialized\");\n}\n\nasync function shutdown() {\n // Detach the observable callback before the provider drains, so the final\n // export does not fire a gauge callback against a shutting-down meter.\n eventLoopInstrumentation?.stop();\n await Promise.race([\n Promise.all([\n meterProvider?.shutdown().catch(() => undefined),\n sdk?.shutdown().catch(() => undefined),\n ]),\n new Promise<void>((resolve) => setTimeout(resolve, 5_000)),\n ]);\n}\n\nlet flushing: Promise<void> | undefined;\n\n/** Flushes and stops telemetry, once: a signal and a runner's shutdown may\n * both ask. */\nexport function flushObservability(): Promise<void> {\n return (flushing ??= shutdown());\n}\n\nlet signalHandlersInstalled = false;\n\n/**\n * Installs the SIGINT/SIGTERM flush, once. The bin does it at load\n * (observability-bin.mts). Under `ph run` the switchboard runner does it, and\n * only when no compound owns the signals: these handlers exit the process.\n *\n * Exit-code and drain coordination with fatal-shutdown.mts and the reactor\n * builder lives in observability-signals.mts; the earlier inline handlers\n * exited with a literal 0, which turned a fatal crash (exitCode = 1) into a\n * success in the supervisor's eyes and could cut the snapshot drain short.\n */\nexport function installObservabilitySignals(): void {\n if (signalHandlersInstalled) return;\n signalHandlersInstalled = true;\n installObservabilitySignalHandlers(flushObservability);\n}\n\n/**\n * A failed boot as the bin reports it: captured, then flushed before the\n * caller exits. A stored-documents refusal was already reported to the\n * operator. Matched by name: importing the error would load the reactor\n * ahead of the hooks above.\n */\nexport async function reportBootFailure(error: unknown): Promise<void> {\n if (\n !(error instanceof Error && error.name === \"StoredDocumentsRefusedError\")\n ) {\n Sentry.captureException(error);\n }\n await Sentry.flush(2000).catch(() => undefined);\n}\n\nexport { meterProvider, sdk };\n"],"names":["logger"],"mappings":";;;;;;;;;;;;;;;;;;;;AAQA,MAAMA,WAAS,YAAY,CAAC,eAAe,SAAS,CAAC;AAErD,SAAgB,2BAA2B,KAIb;CAC5B,MAAM,WAAW,IAAI;CACrB,IAAI,CAAC,UAAU,OAAO,KAAA;CAEtB,MAAM,SAAS,SAAS,IAAI,+BAA+B,IAAI,EAAE;CACjE,MAAM,uBACJ,OAAO,SAAS,MAAM,KAAK,SAAS,IAAI,SAAS;CAEnD,MAAM,OAAO,SAAS,QAAQ,OAAO,EAAE;CACvC,MAAM,cAAc,KAAK,SAAS,aAAa,IAC3C,OACA,GAAG,KAAK;CAEZ,SAAO,KAAK,mDAAmD,UAAU;CACzE,MAAM,gBAAgB,IAAI,cAAc;EACtC,UAAU,uBAAuB,EAC/B,gBAAgB,IAAI,qBAAqB,cAC3C,CAAC;EACD,SAAS,CACP,IAAI,8BAA8B;GAChC,UAAU,IAAI,mBAAmB,EAC/B,KAAK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AAM,OAAO,MAAM,GAAI,CAAC,CAAC,YAAY,KAAA,CAAS;AAChD","debug_id":"f2fea0fd-6621-5985-b4bc-34293d9647f0"}
@@ -0,0 +1,30 @@
1
+ import { NodeSDK } from "@opentelemetry/sdk-node";
2
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
3
+ //#region src/observability.d.mts
4
+ declare const meterProvider: MeterProvider | undefined;
5
+ declare let sdk: NodeSDK | undefined;
6
+ /** Flushes and stops telemetry, once: a signal and a runner's shutdown may
7
+ * both ask. */
8
+ export declare function flushObservability(): Promise<void>;
9
+ /**
10
+ * Installs the SIGINT/SIGTERM flush, once. The bin does it at load
11
+ * (observability-bin.mts). Under `ph run` the switchboard runner does it, and
12
+ * only when no compound owns the signals: these handlers exit the process.
13
+ *
14
+ * Exit-code and drain coordination with fatal-shutdown.mts and the reactor
15
+ * builder lives in observability-signals.mts; the earlier inline handlers
16
+ * exited with a literal 0, which turned a fatal crash (exitCode = 1) into a
17
+ * success in the supervisor's eyes and could cut the snapshot drain short.
18
+ */
19
+ export declare function installObservabilitySignals(): void;
20
+ /**
21
+ * A failed boot as the bin reports it: captured, then flushed before the
22
+ * caller exits. A stored-documents refusal was already reported to the
23
+ * operator. Matched by name: importing the error would load the reactor
24
+ * ahead of the hooks above.
25
+ */
26
+ export declare function reportBootFailure(error: unknown): Promise<void>;
27
+ //#endregion
28
+ export { meterProvider, sdk };
29
+ export {};
30
+ //# sourceMappingURL=observability.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observability.d.mts","names":[],"sources":["../src/observability.mts"],"mappings":";;;cAyHM,eAAe;YAmBjB,KAAK;;;wBAyGO,sBAAsB;;;;;;;;;;;wBAgBtB;;;;;;;wBAYM,kBAAkB,iBAAiB"}
@@ -0,0 +1,4 @@
1
+ import { a as sdk, i as reportBootFailure, n as installObservabilitySignals, r as meterProvider, t as flushObservability } from "./observability-CldagyT_.mjs";
2
+ export { flushObservability, installObservabilitySignals, meterProvider, reportBootFailure, sdk };
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4076c5a5-d0ba-5320-903e-f1d2f6cc7b06")}catch(e){}}();
4
+ //# debugId=4076c5a5-d0ba-5320-903e-f1d2f6cc7b06
@@ -0,0 +1,46 @@
1
+ import { i as SwitchboardConfig } from "./schema-w1lShimw.mjs";
2
+ import { HostPlugin, MergedContribution, ResolvedPlugin } from "@powerhousedao/host-core";
3
+ //#region src/plugin-host.d.mts
4
+ /**
5
+ * The context plugins receive. Fields are populated as the boot spine reaches
6
+ * them (api/client/graphqlManager are undefined before stage 17); concrete
7
+ * types stay in server.mts — subsystem carves tighten their own slices.
8
+ */
9
+ interface SwitchboardHostContext {
10
+ /** The switchboard's ILogger; typed loosely here to avoid pinning the
11
+ * logger package in the scaffold — subsystem carves use it as-is. */
12
+ logger: unknown;
13
+ options: Record<string, unknown>;
14
+ /** The parsed config the switchboard booted with. */
15
+ config?: SwitchboardConfig;
16
+ renown: unknown;
17
+ serverPort?: number;
18
+ /** Set by the attachments plugin at onHttpMounting; the boot reads it for
19
+ * the returned handle. */
20
+ attachmentService?: unknown;
21
+ /** Privacy plugin state: config resolved at transformServerOptions
22
+ * (fail-fast), the running subsystem set at onSubgraphsRegistering. */
23
+ privacyConfig?: unknown;
24
+ privacy?: unknown;
25
+ /** Workflows plugin: wiring closures handed in by server.mts, runtime +
26
+ * retry handles stored by the plugin. */
27
+ workflowsOrchestration?: unknown;
28
+ workflows?: unknown;
29
+ workflowsRetry?: unknown;
30
+ api?: unknown;
31
+ /** @deprecated The facade; plugins that have moved take `read` and `write`. */
32
+ client?: unknown;
33
+ /** The reactor's read half (IReactorReadClient), set at onReactorReady. */
34
+ read?: unknown;
35
+ /** The reactor's write half (IReactorWriteClient), set at onReactorReady. */
36
+ write?: unknown;
37
+ graphqlManager?: unknown;
38
+ reactorClientModule?: unknown;
39
+ /** Late subgraph registrations drain before the readiness router update. */
40
+ lateSubgraphs?: Promise<unknown>[];
41
+ contributions: Record<string, MergedContribution[]>;
42
+ }
43
+ //#endregion
44
+ export { SwitchboardHostContext as t };
45
+ export {};
46
+ //# sourceMappingURL=plugin-host-tTjDTNz0.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-host-tTjDTNz0.d.mts","names":[],"sources":["../src/plugin-host.mts"],"mappings":";;;;;;;;UAgDiB;;;EAGf;EACA,SAAS;;EAET,SAAS;EACT;EACA;;;EAGA;;;EAGA;EACA;;;EAGA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB;EAChB,eAAe,eAAe"}
@@ -0,0 +1,37 @@
1
+ import { t as SwitchboardHostContext } from "../plugin-host-tTjDTNz0.mjs";
2
+ import { z } from "zod";
3
+ import { HostPlugin } from "@powerhousedao/host-core";
4
+ //#region src/plugins/ai.d.mts
5
+ export declare const DEFAULT_AI_UPSTREAM_URL = "https://openrouter.ai/api/v1";
6
+ export declare const aiPluginConfigSchema: z.ZodObject<{
7
+ defaultModel: z.ZodString;
8
+ maxOutputTokens: z.ZodDefault<z.ZodNumber>;
9
+ upstreamUrl: z.ZodDefault<z.ZodURL>;
10
+ appTitle: z.ZodDefault<z.ZodString>;
11
+ appUrl: z.ZodDefault<z.ZodURL>;
12
+ allowWithoutAuth: z.ZodDefault<z.ZodBoolean>;
13
+ }, z.core.$strict>;
14
+ export type AiPluginConfig = z.infer<typeof aiPluginConfigSchema>;
15
+ /** What a host.js entry writes (typed-host-configs 1.4). */
16
+ export type AiPluginConfigInput = z.input<typeof aiPluginConfigSchema>;
17
+ declare global {
18
+ interface PHPluginConfigs {
19
+ "@powerhousedao/switchboard/plugins/ai": AiPluginConfigInput;
20
+ }
21
+ }
22
+ export type AiPlugin = HostPlugin<{
23
+ onHttpMounting: (ctx: SwitchboardHostContext) => void;
24
+ }, AiPluginConfig>;
25
+ /**
26
+ * The AI gateway: an OpenAI-compatible endpoint for this host's admins that
27
+ * holds the provider key server side, so the browser's agent runs without
28
+ * one. The key is a host secret in the workflow runtime's encrypted store,
29
+ * reached per request through `ctx.workflows`: the runtime can arrive after
30
+ * boot, and a second opener of the store could race the first over the key
31
+ * file. Without the runtime the routes answer 503.
32
+ */
33
+ export declare function createAiPlugin(rawConfig: unknown): AiPlugin;
34
+ //#endregion
35
+ export { createAiPlugin as default };
36
+ export {};
37
+ //# sourceMappingURL=ai.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai.d.mts","names":[],"sources":["../../src/plugins/ai.mts"],"mappings":";;;;qBAUa;qBAEA,sBAAoB,EAAA;;;;;;;GAgB/B,EAAA,KAAA;YAEU,iBAAiB,EAAE,aAAa;;YAGhC,sBAAsB,EAAE,aAAa;QAEzC;YACI;IACR,yCAAyC;;;YAIjC,WAAW;EACnB,iBAAiB,KAAK;GACxB;;;;;;;;;wBAWc,eAAe,qBAAqB"}