@powerhousedao/switchboard 6.2.3-dev.9 → 6.2.3-dev.90

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 (306) 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/byte-grants.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
  5. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
  6. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
  7. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  8. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  9. package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
  10. package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-auth-config.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-auth-config.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-desktop-auth.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-desktop-auth.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-env-isolation.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-env-isolation.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-helpers.d.ts +5 -0
  20. package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-mcp-auth.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-mcp-auth.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-port-zero.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-port-zero.test.d.ts.map +1 -0
  29. package/.tsbuild/test/boot-preconditions.test.d.ts +2 -0
  30. package/.tsbuild/test/boot-preconditions.test.d.ts.map +1 -0
  31. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  32. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  33. package/.tsbuild/test/boot-ready-drives.test.d.ts +2 -0
  34. package/.tsbuild/test/boot-ready-drives.test.d.ts.map +1 -0
  35. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  36. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  37. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  38. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  39. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  40. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  41. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  42. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  43. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  44. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  45. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  46. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  47. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  48. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  49. package/.tsbuild/test/config-from-env.test.d.ts +2 -0
  50. package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
  51. package/.tsbuild/test/config-merge.test.d.ts +2 -0
  52. package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
  53. package/.tsbuild/test/config-schema.test.d.ts +2 -0
  54. package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
  55. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  56. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  57. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts +2 -0
  58. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts.map +1 -0
  59. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  60. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  61. package/.tsbuild/test/delegated-publish.test.d.ts +2 -0
  62. package/.tsbuild/test/delegated-publish.test.d.ts.map +1 -0
  63. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  64. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  65. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  66. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  67. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  68. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  69. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
  70. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
  71. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  72. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  73. package/.tsbuild/test/permissions-backfill.test.d.ts +2 -0
  74. package/.tsbuild/test/permissions-backfill.test.d.ts.map +1 -0
  75. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  76. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  77. package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
  78. package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
  79. package/.tsbuild/test/pglite-store.test.d.ts +2 -0
  80. package/.tsbuild/test/pglite-store.test.d.ts.map +1 -0
  81. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  82. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  83. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  84. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  85. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  86. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  87. package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
  88. package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
  89. package/.tsbuild/test/renown-storage-path.test.d.ts +2 -0
  90. package/.tsbuild/test/renown-storage-path.test.d.ts.map +1 -0
  91. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  92. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  93. package/.tsbuild/test/served-schemas.test.d.ts +2 -0
  94. package/.tsbuild/test/served-schemas.test.d.ts.map +1 -0
  95. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  96. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  97. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  98. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  99. package/.tsbuild/test/store-lock.test.d.ts +2 -0
  100. package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
  101. package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
  102. package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
  103. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  104. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  105. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  106. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  107. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts +2 -0
  108. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts.map +1 -0
  109. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  110. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  111. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  112. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  113. package/.tsbuild/test/workflow/runtime-host.test.d.ts +2 -0
  114. package/.tsbuild/test/workflow/runtime-host.test.d.ts.map +1 -0
  115. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts +2 -0
  116. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts.map +1 -0
  117. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts +2 -0
  118. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts.map +1 -0
  119. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  120. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  121. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  122. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  123. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  124. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  125. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  126. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  127. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  128. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  129. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  130. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  131. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  132. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  133. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  134. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  135. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  136. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  137. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  138. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  139. package/.tsbuild/vitest.config.d.ts.map +1 -1
  140. package/Auth.md +144 -2
  141. package/CHANGELOG.md +1206 -0
  142. package/README.md +88 -14
  143. package/dist/boot.d.mts +46 -0
  144. package/dist/boot.d.mts.map +1 -0
  145. package/dist/boot.mjs +67 -0
  146. package/dist/boot.mjs.map +1 -0
  147. package/dist/config/from-env.d.mts +15 -0
  148. package/dist/config/from-env.d.mts.map +1 -0
  149. package/dist/config/from-env.mjs +4 -0
  150. package/dist/config/schema.d.mts +3 -0
  151. package/dist/config/schema.mjs +4 -0
  152. package/dist/from-env-DJ4iQ3QZ.mjs +473 -0
  153. package/dist/from-env-DJ4iQ3QZ.mjs.map +1 -0
  154. package/dist/index.d.mts +2 -1
  155. package/dist/index.mjs +84 -84
  156. package/dist/index.mjs.map +1 -1
  157. package/dist/install-packages.d.mts +2 -1
  158. package/dist/install-packages.mjs +2 -2
  159. package/dist/install-packages.mjs.map +1 -1
  160. package/dist/mcp-SsBK14Jm.mjs +32 -0
  161. package/dist/mcp-SsBK14Jm.mjs.map +1 -0
  162. package/dist/migrate.d.mts +2 -1
  163. package/dist/migrate.mjs +7 -5
  164. package/dist/migrate.mjs.map +1 -1
  165. package/dist/plugin-host-BHEUSn9G.d.mts +46 -0
  166. package/dist/plugin-host-BHEUSn9G.d.mts.map +1 -0
  167. package/dist/plugins/ai.d.mts +37 -0
  168. package/dist/plugins/ai.d.mts.map +1 -0
  169. package/dist/plugins/ai.mjs +400 -0
  170. package/dist/plugins/ai.mjs.map +1 -0
  171. package/dist/plugins/attachments.d.mts +33 -0
  172. package/dist/plugins/attachments.d.mts.map +1 -0
  173. package/dist/plugins/attachments.mjs +4 -0
  174. package/dist/plugins/mcp.d.mts +31 -0
  175. package/dist/plugins/mcp.d.mts.map +1 -0
  176. package/dist/plugins/mcp.mjs +4 -0
  177. package/dist/plugins/privacy.d.mts +22 -0
  178. package/dist/plugins/privacy.d.mts.map +1 -0
  179. package/dist/plugins/privacy.mjs +4 -0
  180. package/dist/plugins/workflows.d.mts +79 -0
  181. package/dist/plugins/workflows.d.mts.map +1 -0
  182. package/dist/plugins/workflows.mjs +4 -0
  183. package/dist/postgres-url-DTDhBjXX.mjs +11 -0
  184. package/dist/postgres-url-DTDhBjXX.mjs.map +1 -0
  185. package/dist/privacy-BO8Q25xI.mjs +44 -0
  186. package/dist/privacy-BO8Q25xI.mjs.map +1 -0
  187. package/dist/privacy-DxIJGH4P.mjs +91 -0
  188. package/dist/privacy-DxIJGH4P.mjs.map +1 -0
  189. package/dist/renown-layers-COZsrGQT.mjs +40 -0
  190. package/dist/renown-layers-COZsrGQT.mjs.map +1 -0
  191. package/dist/schema-1yj85yQD.mjs +326 -0
  192. package/dist/schema-1yj85yQD.mjs.map +1 -0
  193. package/dist/schema-ugrJupVH.d.mts +246 -0
  194. package/dist/schema-ugrJupVH.d.mts.map +1 -0
  195. package/dist/server-CgDvrUqE.mjs +2729 -0
  196. package/dist/server-CgDvrUqE.mjs.map +1 -0
  197. package/dist/server.d.mts +129 -189
  198. package/dist/server.d.mts.map +1 -1
  199. package/dist/server.mjs +5 -5
  200. package/dist/types-DzO3_320.d.mts +308 -0
  201. package/dist/types-DzO3_320.d.mts.map +1 -0
  202. package/dist/utils-Cm0TE6dP.mjs +148 -0
  203. package/dist/utils-Cm0TE6dP.mjs.map +1 -0
  204. package/dist/utils.d.mts +30 -5
  205. package/dist/utils.d.mts.map +1 -1
  206. package/dist/utils.mjs +5 -4
  207. package/dist/worker-pool-gyxJnCxA.mjs +304 -0
  208. package/dist/worker-pool-gyxJnCxA.mjs.map +1 -0
  209. package/dist/workflow-runtime-CF5pc8mt.d.mts +33 -0
  210. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
  211. package/dist/workflows-C9BQlyT0.mjs +1943 -0
  212. package/dist/workflows-C9BQlyT0.mjs.map +1 -0
  213. package/package.json +85 -24
  214. package/scripts/install-packages.sh +0 -0
  215. package/test/ai-gateway.test.ts +612 -0
  216. package/test/attachment-reference-read-model.test.ts +28 -20
  217. package/test/attachments/auth.test.ts +85 -0
  218. package/test/attachments/byte-grants.test.ts +290 -0
  219. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  220. package/test/attachments/download-target.test.ts +211 -32
  221. package/test/attachments/index.test.ts +47 -4
  222. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  223. package/test/attachments/routes-integration.test.ts +60 -4
  224. package/test/attachments/routes.test.ts +297 -35
  225. package/test/attachments/service-config.test.ts +41 -19
  226. package/test/attachments/url-signer.test.ts +105 -0
  227. package/test/boot-auth-config.test.ts +109 -0
  228. package/test/boot-create-signature-policy.test.ts +110 -0
  229. package/test/boot-desktop-auth.test.ts +278 -0
  230. package/test/boot-env-isolation.test.ts +26 -0
  231. package/test/boot-helpers.ts +19 -0
  232. package/test/boot-inspection-enabled.test.ts +140 -0
  233. package/test/boot-mcp-auth.test.ts +449 -0
  234. package/test/boot-mcp-enabled.test.ts +119 -0
  235. package/test/boot-port-zero.test.ts +101 -0
  236. package/test/boot-preconditions.test.ts +213 -0
  237. package/test/boot-privacy.test.ts +232 -0
  238. package/test/boot-ready-drives.test.ts +141 -0
  239. package/test/boot-unsupported-stored-documents.test.ts +214 -0
  240. package/test/boot-without-renown.test.ts +83 -0
  241. package/test/boot-without-require-signatures.test.ts +76 -0
  242. package/test/boot-worker-trust-policy.test.ts +91 -0
  243. package/test/boot-workflow-singleton-conflict.test.ts +109 -0
  244. package/test/boot-workflow-singleton-retry.test.ts +122 -0
  245. package/test/builder-defaults.test.ts +80 -0
  246. package/test/config-from-env.test.ts +942 -0
  247. package/test/config-merge.test.ts +226 -0
  248. package/test/config-schema.test.ts +156 -0
  249. package/test/create-signature-policy.test.ts +69 -0
  250. package/test/default-drive-protocol-versions.test.ts +79 -0
  251. package/test/default-drive-slug.test.ts +265 -0
  252. package/test/delegated-publish.test.ts +435 -0
  253. package/test/durable-node-fs-pg16.test.ts +80 -0
  254. package/test/fatal-shutdown.test.ts +205 -0
  255. package/test/goldens/packages.graphql +797 -0
  256. package/test/goldens/privacy.graphql +853 -0
  257. package/test/goldens/reactor-drive-nodes.graphql +827 -0
  258. package/test/goldens/resolvers.json +327 -0
  259. package/test/goldens/supergraph.graphql +5918 -0
  260. package/test/goldens/workflow-runtime.graphql +1548 -0
  261. package/test/inspection-throttle.test.ts +23 -0
  262. package/test/keyframe-reclaim-store.test.ts +156 -0
  263. package/test/observability-signals.test.ts +131 -0
  264. package/test/permissions-backfill.test.ts +486 -0
  265. package/test/pglite-dialect.test.ts +237 -2
  266. package/test/pglite-preflight.test.ts +313 -0
  267. package/test/pglite-storage-dirs.test.ts +113 -0
  268. package/test/pglite-store.test.ts +441 -0
  269. package/test/pglite-version.test.ts +9 -1
  270. package/test/plugin-config-schemas.test.ts +83 -0
  271. package/test/plugin-presence.test.ts +262 -0
  272. package/test/port-probe.test.ts +45 -0
  273. package/test/processor-timing-log.test.ts +109 -0
  274. package/test/redact-webhook-path.test.ts +9 -0
  275. package/test/renown-storage-path.test.ts +40 -0
  276. package/test/renown-trust-policy.test.ts +313 -0
  277. package/test/served-schemas.test.ts +134 -0
  278. package/test/shutdown.test.ts +278 -0
  279. package/test/snapshot-writer.ts +94 -0
  280. package/test/store-lock.test.ts +65 -0
  281. package/test/two-switchboards.test.ts +146 -0
  282. package/test/unsupported-stored-documents.test.ts +72 -0
  283. package/test/worker-pool.test.ts +27 -1
  284. package/test/workflow/harness.ts +289 -0
  285. package/test/workflow/oauth-apps-config.test.ts +66 -0
  286. package/test/workflow/oauth.test.ts +286 -0
  287. package/test/workflow/resolvers.test.ts +488 -0
  288. package/test/workflow/runtime-host.test.ts +19 -0
  289. package/test/workflow/waitpoint-routes.test.ts +306 -0
  290. package/test/workflow/waitpoint-runtime.test.ts +204 -0
  291. package/test/workflow/webhook-dedupe.test.ts +295 -0
  292. package/test/workflow/webhook-signed.test.ts +509 -0
  293. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  294. package/test/workflow/webhook-unsigned.test.ts +345 -0
  295. package/test/workflow-reactor-access.test.ts +384 -0
  296. package/test/workflow-reactor-enforcement.test.ts +808 -0
  297. package/test/workflow-read-gate.test.ts +213 -0
  298. package/test/workflow-runtime.test.ts +1254 -0
  299. package/test/workflows-plugin-config.test.ts +77 -0
  300. package/tsconfig.json +11 -2
  301. package/tsdown.config.ts +13 -1
  302. package/vitest.config.ts +65 -0
  303. package/dist/server-CiKkVE6g.mjs +0 -1555
  304. package/dist/server-CiKkVE6g.mjs.map +0 -1
  305. package/dist/utils-Baw7rThP.mjs +0 -80
  306. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -0,0 +1,400 @@
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]="2d671121-82f8-589e-b299-962df32df435")}catch(e){}}();
3
+ import { getConfig } from "@powerhousedao/config/node";
4
+ import { AuthorizationPolicy } from "@powerhousedao/reactor-api";
5
+ import path from "node:path";
6
+ import { readFile } from "node:fs/promises";
7
+ import { z } from "zod";
8
+ //#region src/ai/demo-key.mts
9
+ /**
10
+ * The config file's `ai.demoKeyFile`, made absolute from the config file's
11
+ * folder. Unreadable or unset means this host has no demo key.
12
+ */
13
+ function demoKeyFileOf(configPath) {
14
+ let named;
15
+ try {
16
+ named = getConfig(configPath).ai?.demoKeyFile;
17
+ } catch {
18
+ return;
19
+ }
20
+ if (typeof named !== "string" || named === "") return void 0;
21
+ return path.resolve(path.dirname(path.resolve(configPath)), named);
22
+ }
23
+ /** The key in that file, read when asked, so it's in memory only then. */
24
+ async function readDemoKey(file) {
25
+ if (!file) return void 0;
26
+ try {
27
+ const key = (await readFile(file, "utf8")).trim();
28
+ return key === "" ? void 0 : key;
29
+ } catch {
30
+ return;
31
+ }
32
+ }
33
+ //#endregion
34
+ //#region src/ai/key-store.mts
35
+ /**
36
+ * The gateway's settings, held as host secrets (`ownerId: null`) in the
37
+ * workflow runtime's encrypted store and addressed by a fixed label. Host
38
+ * secrets resolve for no document and never appear in the
39
+ * `workflowRuntime.secrets` listing, and no API here returns a value.
40
+ */
41
+ const AI_KEY_LABEL = "ai-gateway/openrouter/api-key";
42
+ /** The model is not secret; it lives here so the gateway needs no table. */
43
+ const AI_MODEL_LABEL = "ai-gateway/openrouter/model";
44
+ function findActive(stats, label) {
45
+ return stats.filter((stat) => stat.label === label && stat.ownerId === null && stat.status === "ACTIVE");
46
+ }
47
+ async function readSetting(store, label) {
48
+ const newest = findActive(await store.list(), label).at(0);
49
+ if (!newest) return void 0;
50
+ return {
51
+ value: await store.get(newest.ref, null),
52
+ setBy: newest.createdBy,
53
+ setAt: newest.updatedAt
54
+ };
55
+ }
56
+ async function writeSetting(store, label, value, actor) {
57
+ const newest = findActive(await store.list(), label).at(0);
58
+ if (newest) {
59
+ await store.rotate(newest.ref, value);
60
+ return;
61
+ }
62
+ await store.create({
63
+ value,
64
+ label,
65
+ ownerId: null,
66
+ createdBy: actor ?? null
67
+ });
68
+ }
69
+ const readKey = (store) => readSetting(store, AI_KEY_LABEL);
70
+ const writeKey = (store, value, actor) => writeSetting(store, AI_KEY_LABEL, value, actor);
71
+ /** Tombstones the key: the value becomes unrecoverable. */
72
+ async function deleteKey(store) {
73
+ const active = findActive(await store.list(), AI_KEY_LABEL);
74
+ for (const stat of active) await store.delete(stat.ref);
75
+ }
76
+ const readModel = async (store) => (await readSetting(store, AI_MODEL_LABEL))?.value;
77
+ const writeModel = (store, model, actor) => writeSetting(store, AI_MODEL_LABEL, model, actor);
78
+ /** `sk-or-v1-…abcd`: the provider prefix and the last four, nothing between. */
79
+ function maskKey(value) {
80
+ const prefix = /^sk-(?:[a-z]+-)*(?:v\d+-)?/i.exec(value)?.[0] ?? "";
81
+ if (value.length - prefix.length < 16) return `${prefix}…`;
82
+ return `${prefix}…${value.slice(-4)}`;
83
+ }
84
+ //#endregion
85
+ //#region src/ai/routes.mts
86
+ /** Requests carry the conversation and base64 images, so more than the default. */
87
+ const MAX_CHAT_BODY_BYTES = 33554432;
88
+ const UPSTREAM_CHECK_TIMEOUT_MS = 15e3;
89
+ const MAX_KEY_CHARS = 512;
90
+ /** What of a chat request reaches the provider; routing overrides do not. */
91
+ const FORWARDED_CHAT_FIELDS = [
92
+ "messages",
93
+ "tools",
94
+ "tool_choice",
95
+ "parallel_tool_calls",
96
+ "temperature",
97
+ "top_p",
98
+ "frequency_penalty",
99
+ "presence_penalty",
100
+ "stop",
101
+ "seed",
102
+ "response_format",
103
+ "stream",
104
+ "stream_options"
105
+ ];
106
+ function errorResponse(status, message, code) {
107
+ return Response.json({ error: {
108
+ message,
109
+ code
110
+ } }, { status });
111
+ }
112
+ /** Removes the stored key, and anything shaped like a credential, from text. */
113
+ function redactSecrets(text, key) {
114
+ return (key ? text.split(key).join("[redacted]") : text).replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/sk-[a-z0-9_-]{8,}/gi, "[redacted]");
115
+ }
116
+ function errorText(error) {
117
+ return error instanceof Error ? error.message : String(error);
118
+ }
119
+ /** Never the request body or the parser's message: V8 quotes the input there. */
120
+ async function readJsonObject(request) {
121
+ try {
122
+ const value = JSON.parse(await request.text());
123
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
124
+ } catch {
125
+ return;
126
+ }
127
+ }
128
+ /**
129
+ * Serves the gateway: the OpenAI-compatible chat and model endpoints, and the
130
+ * key and model administration. Every route is for admins, and the key never
131
+ * leaves this module except as the upstream's bearer.
132
+ */
133
+ function registerAiRoutes(http, deps) {
134
+ const { logger } = deps;
135
+ const fetchImpl = deps.fetchImpl ?? fetch;
136
+ const upstreamHeaders = (key) => ({
137
+ authorization: `Bearer ${key}`,
138
+ "http-referer": deps.appUrl,
139
+ "x-title": deps.appTitle
140
+ });
141
+ const gate = async (ctx) => {
142
+ if (!deps.isAdmin(ctx.user?.address)) return { refused: errorResponse(403, "The assistant is for this host's admins.", "forbidden") };
143
+ let store;
144
+ try {
145
+ store = await deps.secrets();
146
+ } catch (error) {
147
+ logger.error("The AI gateway could not open the secret store: @message", redactSecrets(errorText(error), void 0));
148
+ }
149
+ if (!store) return { refused: errorResponse(503, "The assistant needs the workflow runtime, which is not running on this host.", "unavailable") };
150
+ return { store };
151
+ };
152
+ const currentModel = async (store) => await readModel(store) ?? deps.defaultModel;
153
+ const status = async (store) => {
154
+ const stored = await readKey(store);
155
+ return Response.json({
156
+ configured: stored !== void 0,
157
+ keyHint: stored ? maskKey(stored.value) : null,
158
+ keySetBy: stored?.setBy ?? null,
159
+ keySetAt: stored?.setAt ?? null,
160
+ model: await currentModel(store),
161
+ demoKeyAvailable: await deps.demoKey?.() !== void 0
162
+ });
163
+ };
164
+ /** Keeps the provider's status; the body is rebuilt from its error message. */
165
+ const upstreamFailure = async (upstream, key) => {
166
+ let message = `The AI provider answered HTTP ${upstream.status}.`;
167
+ try {
168
+ const body = await upstream.json();
169
+ if (typeof body.error?.message === "string") message = redactSecrets(body.error.message, key);
170
+ } catch {}
171
+ return errorResponse(upstream.status, message, "upstream_error");
172
+ };
173
+ const unreachable = (error, key) => {
174
+ logger.warn("The AI gateway could not reach the provider: @message", redactSecrets(errorText(error), key));
175
+ return errorResponse(502, "The AI provider could not be reached.", "upstream_unreachable");
176
+ };
177
+ http.route({
178
+ method: "GET",
179
+ path: "ai/status",
180
+ auth: "renown",
181
+ handler: async (_request, ctx) => {
182
+ const gated = await gate(ctx);
183
+ return "refused" in gated ? gated.refused : status(gated.store);
184
+ }
185
+ });
186
+ const testAndStore = async (value, store, ctx) => {
187
+ let check;
188
+ try {
189
+ check = await fetchImpl(`${deps.upstreamUrl}/key`, {
190
+ headers: upstreamHeaders(value),
191
+ signal: AbortSignal.timeout(UPSTREAM_CHECK_TIMEOUT_MS)
192
+ });
193
+ } catch (error) {
194
+ return unreachable(error, value);
195
+ }
196
+ if (!check.ok) {
197
+ await check.body?.cancel();
198
+ return errorResponse(400, `OpenRouter did not accept this key (HTTP ${check.status}).`, "invalid_key");
199
+ }
200
+ await check.body?.cancel();
201
+ await writeKey(store, value, ctx.user?.address);
202
+ logger.info("The AI gateway key was set by @actor", ctx.user?.address);
203
+ return status(store);
204
+ };
205
+ http.route({
206
+ method: "PUT",
207
+ path: "ai/key",
208
+ auth: "renown",
209
+ maxBodyBytes: 4096,
210
+ handler: async (request, ctx) => {
211
+ const gated = await gate(ctx);
212
+ if ("refused" in gated) return gated.refused;
213
+ const body = await readJsonObject(request);
214
+ const value = typeof body?.value === "string" ? body.value.trim() : "";
215
+ if (!value || value.length > MAX_KEY_CHARS || /\s/.test(value)) return errorResponse(400, "Enter an OpenRouter key.", "invalid_key");
216
+ return testAndStore(value, gated.store, ctx);
217
+ }
218
+ });
219
+ http.route({
220
+ method: "PUT",
221
+ path: "ai/key/demo",
222
+ auth: "renown",
223
+ handler: async (_request, ctx) => {
224
+ const gated = await gate(ctx);
225
+ if ("refused" in gated) return gated.refused;
226
+ const value = await deps.demoKey?.();
227
+ if (value === void 0) return errorResponse(404, "This host has no demo key.", "no_demo_key");
228
+ return testAndStore(value, gated.store, ctx);
229
+ }
230
+ });
231
+ http.route({
232
+ method: "DELETE",
233
+ path: "ai/key",
234
+ auth: "renown",
235
+ handler: async (_request, ctx) => {
236
+ const gated = await gate(ctx);
237
+ if ("refused" in gated) return gated.refused;
238
+ await deleteKey(gated.store);
239
+ logger.info("The AI gateway key was reset by @actor", ctx.user?.address);
240
+ return status(gated.store);
241
+ }
242
+ });
243
+ http.route({
244
+ method: "PUT",
245
+ path: "ai/model",
246
+ auth: "renown",
247
+ maxBodyBytes: 4096,
248
+ handler: async (request, ctx) => {
249
+ const gated = await gate(ctx);
250
+ if ("refused" in gated) return gated.refused;
251
+ const body = await readJsonObject(request);
252
+ const model = typeof body?.model === "string" ? body.model.trim() : "";
253
+ if (!model) return errorResponse(400, "Name a model.", "invalid_model");
254
+ let listed;
255
+ try {
256
+ const answer = await fetchImpl(`${deps.upstreamUrl}/models`, { signal: AbortSignal.timeout(UPSTREAM_CHECK_TIMEOUT_MS) });
257
+ if (!answer.ok) throw new Error(`HTTP ${answer.status}`);
258
+ listed = await answer.json();
259
+ } catch (error) {
260
+ return unreachable(error, void 0);
261
+ }
262
+ if (!listed.data?.some((entry) => entry.id === model)) return errorResponse(400, `OpenRouter has no model "${model}".`, "invalid_model");
263
+ await writeModel(gated.store, model, ctx.user?.address);
264
+ return status(gated.store);
265
+ }
266
+ });
267
+ http.route({
268
+ method: "GET",
269
+ path: "ai/v1/models",
270
+ auth: "renown",
271
+ handler: async (_request, ctx) => {
272
+ const gated = await gate(ctx);
273
+ if ("refused" in gated) return gated.refused;
274
+ const stored = await readKey(gated.store);
275
+ if (!stored) return notConfigured();
276
+ let upstream;
277
+ try {
278
+ upstream = await fetchImpl(`${deps.upstreamUrl}/models`, {
279
+ headers: upstreamHeaders(stored.value),
280
+ signal: ctx.signal
281
+ });
282
+ } catch (error) {
283
+ return unreachable(error, stored.value);
284
+ }
285
+ if (!upstream.ok) return upstreamFailure(upstream, stored.value);
286
+ return new Response(upstream.body, {
287
+ status: upstream.status,
288
+ headers: { "content-type": "application/json" }
289
+ });
290
+ }
291
+ });
292
+ http.route({
293
+ method: "POST",
294
+ path: "ai/v1/chat/completions",
295
+ auth: "renown",
296
+ maxBodyBytes: MAX_CHAT_BODY_BYTES,
297
+ handler: async (request, ctx) => {
298
+ const gated = await gate(ctx);
299
+ if ("refused" in gated) return gated.refused;
300
+ const stored = await readKey(gated.store);
301
+ if (!stored) return notConfigured();
302
+ const body = await readJsonObject(request);
303
+ if (!Array.isArray(body?.messages)) return errorResponse(400, "A chat request needs messages.", "invalid_request");
304
+ const forwarded = {};
305
+ for (const field of FORWARDED_CHAT_FIELDS) if (body[field] !== void 0) forwarded[field] = body[field];
306
+ forwarded.model = await currentModel(gated.store);
307
+ const asked = body.max_tokens;
308
+ forwarded.max_tokens = typeof asked === "number" && asked > 0 ? Math.min(asked, deps.maxOutputTokens) : deps.maxOutputTokens;
309
+ let upstream;
310
+ try {
311
+ upstream = await fetchImpl(`${deps.upstreamUrl}/chat/completions`, {
312
+ method: "POST",
313
+ headers: {
314
+ ...upstreamHeaders(stored.value),
315
+ "content-type": "application/json"
316
+ },
317
+ body: JSON.stringify(forwarded),
318
+ signal: ctx.signal
319
+ });
320
+ } catch (error) {
321
+ return unreachable(error, stored.value);
322
+ }
323
+ if (!upstream.ok) return upstreamFailure(upstream, stored.value);
324
+ return new Response(upstream.body, {
325
+ status: upstream.status,
326
+ headers: {
327
+ "content-type": upstream.headers.get("content-type") ?? "text/event-stream",
328
+ "cache-control": "no-cache",
329
+ "x-accel-buffering": "no"
330
+ }
331
+ });
332
+ }
333
+ });
334
+ }
335
+ function notConfigured() {
336
+ return errorResponse(503, "The assistant has no OpenRouter key yet.", "not_configured");
337
+ }
338
+ //#endregion
339
+ //#region src/plugins/ai.mts
340
+ const DEFAULT_AI_UPSTREAM_URL = "https://openrouter.ai/api/v1";
341
+ const aiPluginConfigSchema = z.strictObject({
342
+ /** The model the gateway answers with until an admin picks another. */
343
+ defaultModel: z.string().min(1),
344
+ /** Upper bound on `max_tokens` per request. */
345
+ maxOutputTokens: z.number().int().positive().default(4096),
346
+ /** The OpenAI-compatible provider. Tests point this at a stub. */
347
+ upstreamUrl: z.url().default(DEFAULT_AI_UPSTREAM_URL),
348
+ /** How the host names itself to the provider (OpenRouter's app attribution). */
349
+ appTitle: z.string().min(1).default("Powerhouse"),
350
+ appUrl: z.url().default("https://powerhouse.inc"),
351
+ /**
352
+ * Local development only. Under the OPEN policy everyone is an admin,
353
+ * anonymous callers included, so the gateway does not mount there unless
354
+ * this says so.
355
+ */
356
+ allowWithoutAuth: z.boolean().default(false)
357
+ });
358
+ /**
359
+ * The AI gateway: an OpenAI-compatible endpoint for this host's admins that
360
+ * holds the provider key server side, so the browser's agent runs without
361
+ * one. The key is a host secret in the workflow runtime's encrypted store,
362
+ * reached per request through `ctx.workflows`: the runtime can arrive after
363
+ * boot, and a second opener of the store could race the first over the key
364
+ * file. Without the runtime the routes answer 503.
365
+ */
366
+ function createAiPlugin(rawConfig) {
367
+ const config = aiPluginConfigSchema.parse(rawConfig ?? {});
368
+ return {
369
+ name: "switchboard-ai",
370
+ appliesTo: "switchboard",
371
+ configSchema: aiPluginConfigSchema,
372
+ hooks: { onHttpMounting: (ctx) => {
373
+ const api = ctx.api;
374
+ const logger = ctx.logger;
375
+ const { authorizationService } = api;
376
+ if (authorizationService.config.policy === AuthorizationPolicy.OPEN && !config.allowWithoutAuth) {
377
+ logger.warn("The AI gateway is not mounted: this host has no sign-in, so every caller would be an admin. Enable authentication (AUTH_ENABLED=true with ADMINS), or set allowWithoutAuth for local development.");
378
+ return;
379
+ }
380
+ const { configFile } = ctx.options;
381
+ const demoKeyFile = demoKeyFileOf(configFile ?? path.join(process.cwd(), "powerhouse.config.json"));
382
+ registerAiRoutes(api.httpRoutes.scopeFor("@powerhousedao/switchboard"), {
383
+ isAdmin: (address) => authorizationService.isSupremeAdmin(address),
384
+ demoKey: () => readDemoKey(demoKeyFile),
385
+ secrets: async () => ctx.workflows?.secrets(),
386
+ upstreamUrl: config.upstreamUrl.replace(/\/+$/, ""),
387
+ defaultModel: config.defaultModel,
388
+ maxOutputTokens: config.maxOutputTokens,
389
+ appTitle: config.appTitle,
390
+ appUrl: config.appUrl,
391
+ logger
392
+ });
393
+ } }
394
+ };
395
+ }
396
+ //#endregion
397
+ export { DEFAULT_AI_UPSTREAM_URL, aiPluginConfigSchema, createAiPlugin, createAiPlugin as default };
398
+
399
+ //# sourceMappingURL=ai.mjs.map
400
+ //# debugId=2d671121-82f8-589e-b299-962df32df435
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai.mjs","sources":["../../src/ai/demo-key.mts","../../src/ai/key-store.mts","../../src/ai/routes.mts","../../src/plugins/ai.mts"],"sourcesContent":["import { getConfig } from \"@powerhousedao/config/node\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * The config file's `ai.demoKeyFile`, made absolute from the config file's\n * folder. Unreadable or unset means this host has no demo key.\n */\nexport function demoKeyFileOf(configPath: string): string | undefined {\n let named: unknown;\n try {\n named = (getConfig(configPath) as { ai?: { demoKeyFile?: unknown } }).ai\n ?.demoKeyFile;\n } catch {\n return undefined;\n }\n if (typeof named !== \"string\" || named === \"\") return undefined;\n return path.resolve(path.dirname(path.resolve(configPath)), named);\n}\n\n/** The key in that file, read when asked, so it's in memory only then. */\nexport async function readDemoKey(\n file: string | undefined,\n): Promise<string | undefined> {\n if (!file) return undefined;\n try {\n const key = (await readFile(file, \"utf8\")).trim();\n return key === \"\" ? undefined : key;\n } catch {\n return undefined;\n }\n}\n","import type { ComposedWorkflowRuntime } from \"../workflow-runtime.mjs\";\n\ntype SecretStore = Awaited<ReturnType<ComposedWorkflowRuntime[\"secrets\"]>>;\n\n/**\n * The gateway's settings, held as host secrets (`ownerId: null`) in the\n * workflow runtime's encrypted store and addressed by a fixed label. Host\n * secrets resolve for no document and never appear in the\n * `workflowRuntime.secrets` listing, and no API here returns a value.\n */\nexport const AI_KEY_LABEL = \"ai-gateway/openrouter/api-key\";\n/** The model is not secret; it lives here so the gateway needs no table. */\nexport const AI_MODEL_LABEL = \"ai-gateway/openrouter/model\";\n\nexport type AiSecretStore = Pick<\n SecretStore,\n \"get\" | \"create\" | \"rotate\" | \"list\" | \"delete\"\n>;\n\nexport interface StoredKey {\n value: string;\n setBy: string | null;\n setAt: string;\n}\n\nfunction findActive(\n stats: Awaited<ReturnType<SecretStore[\"list\"]>>,\n label: string,\n) {\n return stats.filter(\n (stat) =>\n stat.label === label && stat.ownerId === null && stat.status === \"ACTIVE\",\n );\n}\n\nasync function readSetting(\n store: AiSecretStore,\n label: string,\n): Promise<StoredKey | undefined> {\n const newest = findActive(await store.list(), label).at(0);\n if (!newest) return undefined;\n return {\n value: await store.get(newest.ref, null),\n setBy: newest.createdBy,\n setAt: newest.updatedAt,\n };\n}\n\nasync function writeSetting(\n store: AiSecretStore,\n label: string,\n value: string,\n actor: string | undefined,\n): Promise<void> {\n const newest = findActive(await store.list(), label).at(0);\n if (newest) {\n await store.rotate(newest.ref, value);\n return;\n }\n await store.create({ value, label, ownerId: null, createdBy: actor ?? null });\n}\n\nexport const readKey = (store: AiSecretStore) =>\n readSetting(store, AI_KEY_LABEL);\n\nexport const writeKey = (\n store: AiSecretStore,\n value: string,\n actor: string | undefined,\n) => writeSetting(store, AI_KEY_LABEL, value, actor);\n\n/** Tombstones the key: the value becomes unrecoverable. */\nexport async function deleteKey(store: AiSecretStore): Promise<void> {\n const active = findActive(await store.list(), AI_KEY_LABEL);\n for (const stat of active) await store.delete(stat.ref);\n}\n\nexport const readModel = async (store: AiSecretStore) =>\n (await readSetting(store, AI_MODEL_LABEL))?.value;\n\nexport const writeModel = (\n store: AiSecretStore,\n model: string,\n actor: string | undefined,\n) => writeSetting(store, AI_MODEL_LABEL, model, actor);\n\n/** `sk-or-v1-…abcd`: the provider prefix and the last four, nothing between. */\nexport function maskKey(value: string): string {\n const prefix = /^sk-(?:[a-z]+-)*(?:v\\d+-)?/i.exec(value)?.[0] ?? \"\";\n // A value this short would be mostly shown by its tail.\n if (value.length - prefix.length < 16) return `${prefix}…`;\n return `${prefix}…${value.slice(-4)}`;\n}\n","import type {\n IHttpScope,\n RouteContext,\n} from \"@powerhousedao/shared/processors\";\nimport type { ILogger } from \"document-model\";\nimport {\n deleteKey,\n maskKey,\n readKey,\n readModel,\n writeKey,\n writeModel,\n type AiSecretStore,\n} from \"./key-store.mjs\";\n\n/** Requests carry the conversation and base64 images, so more than the default. */\nconst MAX_CHAT_BODY_BYTES = 32 * 1024 * 1024;\nconst UPSTREAM_CHECK_TIMEOUT_MS = 15_000;\nconst MAX_KEY_CHARS = 512;\n\n/** What of a chat request reaches the provider; routing overrides do not. */\nconst FORWARDED_CHAT_FIELDS = [\n \"messages\",\n \"tools\",\n \"tool_choice\",\n \"parallel_tool_calls\",\n \"temperature\",\n \"top_p\",\n \"frequency_penalty\",\n \"presence_penalty\",\n \"stop\",\n \"seed\",\n \"response_format\",\n \"stream\",\n \"stream_options\",\n] as const;\n\nexport interface AiRoutesDeps {\n /** Whether this caller may use and manage the gateway. */\n isAdmin(address: string | undefined): boolean;\n /** Undefined while the workflow runtime is absent. */\n secrets(): Promise<AiSecretStore | undefined>;\n /** The host's demo key, which stays on the server; undefined without one. */\n demoKey?(): Promise<string | undefined>;\n /** OpenAI-compatible base, without a trailing slash. */\n upstreamUrl: string;\n defaultModel: string;\n maxOutputTokens: number;\n appTitle: string;\n appUrl: string;\n logger: ILogger;\n fetchImpl?: typeof fetch;\n}\n\nfunction errorResponse(status: number, message: string, code: string) {\n // OpenAI's error shape, which OpenAI-compatible clients surface as is.\n return Response.json({ error: { message, code } }, { status });\n}\n\n/** Removes the stored key, and anything shaped like a credential, from text. */\nexport function redactSecrets(text: string, key: string | undefined): string {\n const named = key ? text.split(key).join(\"[redacted]\") : text;\n return named\n .replace(/Bearer\\s+\\S+/gi, \"Bearer [redacted]\")\n .replace(/sk-[a-z0-9_-]{8,}/gi, \"[redacted]\");\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Never the request body or the parser's message: V8 quotes the input there. */\nasync function readJsonObject(\n request: Request,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const value: unknown = JSON.parse(await request.text());\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Serves the gateway: the OpenAI-compatible chat and model endpoints, and the\n * key and model administration. Every route is for admins, and the key never\n * leaves this module except as the upstream's bearer.\n */\nexport function registerAiRoutes(http: IHttpScope, deps: AiRoutesDeps): void {\n const { logger } = deps;\n const fetchImpl = deps.fetchImpl ?? fetch;\n\n const upstreamHeaders = (key: string) => ({\n authorization: `Bearer ${key}`,\n \"http-referer\": deps.appUrl,\n \"x-title\": deps.appTitle,\n });\n\n type Gate = { store: AiSecretStore } | { refused: Response };\n\n const gate = async (ctx: RouteContext): Promise<Gate> => {\n if (!deps.isAdmin(ctx.user?.address)) {\n return {\n refused: errorResponse(\n 403,\n \"The assistant is for this host's admins.\",\n \"forbidden\",\n ),\n };\n }\n let store: AiSecretStore | undefined;\n try {\n store = await deps.secrets();\n } catch (error) {\n logger.error(\n \"The AI gateway could not open the secret store: @message\",\n redactSecrets(errorText(error), undefined),\n );\n }\n if (!store) {\n return {\n refused: errorResponse(\n 503,\n \"The assistant needs the workflow runtime, which is not running on this host.\",\n \"unavailable\",\n ),\n };\n }\n return { store };\n };\n\n const currentModel = async (store: AiSecretStore) =>\n (await readModel(store)) ?? deps.defaultModel;\n\n const status = async (store: AiSecretStore) => {\n const stored = await readKey(store);\n return Response.json({\n configured: stored !== undefined,\n keyHint: stored ? maskKey(stored.value) : null,\n keySetBy: stored?.setBy ?? null,\n keySetAt: stored?.setAt ?? null,\n model: await currentModel(store),\n demoKeyAvailable: (await deps.demoKey?.()) !== undefined,\n });\n };\n\n /** Keeps the provider's status; the body is rebuilt from its error message. */\n const upstreamFailure = async (upstream: Response, key: string) => {\n let message = `The AI provider answered HTTP ${upstream.status}.`;\n try {\n const body = (await upstream.json()) as {\n error?: { message?: unknown };\n };\n if (typeof body.error?.message === \"string\") {\n message = redactSecrets(body.error.message, key);\n }\n } catch {\n // Not JSON: the status line above says as much as we can repeat.\n }\n return errorResponse(upstream.status, message, \"upstream_error\");\n };\n\n const unreachable = (error: unknown, key: string | undefined) => {\n logger.warn(\n \"The AI gateway could not reach the provider: @message\",\n redactSecrets(errorText(error), key),\n );\n return errorResponse(\n 502,\n \"The AI provider could not be reached.\",\n \"upstream_unreachable\",\n );\n };\n\n http.route({\n method: \"GET\",\n path: \"ai/status\",\n auth: \"renown\",\n handler: async (_request, ctx) => {\n const gated = await gate(ctx);\n return \"refused\" in gated ? gated.refused : status(gated.store);\n },\n });\n\n // Tested before it is stored, so a typo cannot replace a working key.\n const testAndStore = async (\n value: string,\n store: AiSecretStore,\n ctx: RouteContext,\n ) => {\n let check: Response;\n try {\n check = await fetchImpl(`${deps.upstreamUrl}/key`, {\n headers: upstreamHeaders(value),\n signal: AbortSignal.timeout(UPSTREAM_CHECK_TIMEOUT_MS),\n });\n } catch (error) {\n return unreachable(error, value);\n }\n if (!check.ok) {\n await check.body?.cancel();\n return errorResponse(\n 400,\n `OpenRouter did not accept this key (HTTP ${check.status}).`,\n \"invalid_key\",\n );\n }\n await check.body?.cancel();\n await writeKey(store, value, ctx.user?.address);\n logger.info(\"The AI gateway key was set by @actor\", ctx.user?.address);\n return status(store);\n };\n\n http.route({\n method: \"PUT\",\n path: \"ai/key\",\n auth: \"renown\",\n maxBodyBytes: 4096,\n handler: async (request, ctx) => {\n const gated = await gate(ctx);\n if (\"refused\" in gated) return gated.refused;\n const body = await readJsonObject(request);\n const value = typeof body?.value === \"string\" ? body.value.trim() : \"\";\n if (!value || value.length > MAX_KEY_CHARS || /\\s/.test(value)) {\n return errorResponse(400, \"Enter an OpenRouter key.\", \"invalid_key\");\n }\n return testAndStore(value, gated.store, ctx);\n },\n });\n\n // The browser only asks: the key goes from the host's file to its store.\n http.route({\n method: \"PUT\",\n path: \"ai/key/demo\",\n auth: \"renown\",\n handler: async (_request, ctx) => {\n const gated = await gate(ctx);\n if (\"refused\" in gated) return gated.refused;\n const value = await deps.demoKey?.();\n if (value === undefined) {\n return errorResponse(404, \"This host has no demo key.\", \"no_demo_key\");\n }\n return testAndStore(value, gated.store, ctx);\n },\n });\n\n http.route({\n method: \"DELETE\",\n path: \"ai/key\",\n auth: \"renown\",\n handler: async (_request, ctx) => {\n const gated = await gate(ctx);\n if (\"refused\" in gated) return gated.refused;\n await deleteKey(gated.store);\n logger.info(\"The AI gateway key was reset by @actor\", ctx.user?.address);\n return status(gated.store);\n },\n });\n\n http.route({\n method: \"PUT\",\n path: \"ai/model\",\n auth: \"renown\",\n maxBodyBytes: 4096,\n handler: async (request, ctx) => {\n const gated = await gate(ctx);\n if (\"refused\" in gated) return gated.refused;\n const body = await readJsonObject(request);\n const model = typeof body?.model === \"string\" ? body.model.trim() : \"\";\n if (!model) {\n return errorResponse(400, \"Name a model.\", \"invalid_model\");\n }\n let listed: { data?: { id?: unknown }[] };\n try {\n const answer = await fetchImpl(`${deps.upstreamUrl}/models`, {\n signal: AbortSignal.timeout(UPSTREAM_CHECK_TIMEOUT_MS),\n });\n if (!answer.ok) throw new Error(`HTTP ${answer.status}`);\n listed = (await answer.json()) as typeof listed;\n } catch (error) {\n return unreachable(error, undefined);\n }\n if (!listed.data?.some((entry) => entry.id === model)) {\n return errorResponse(\n 400,\n `OpenRouter has no model \"${model}\".`,\n \"invalid_model\",\n );\n }\n await writeModel(gated.store, model, ctx.user?.address);\n return status(gated.store);\n },\n });\n\n http.route({\n method: \"GET\",\n path: \"ai/v1/models\",\n auth: \"renown\",\n handler: async (_request, ctx) => {\n const gated = await gate(ctx);\n if (\"refused\" in gated) return gated.refused;\n const stored = await readKey(gated.store);\n if (!stored) return notConfigured();\n let upstream: Response;\n try {\n upstream = await fetchImpl(`${deps.upstreamUrl}/models`, {\n headers: upstreamHeaders(stored.value),\n signal: ctx.signal,\n });\n } catch (error) {\n return unreachable(error, stored.value);\n }\n if (!upstream.ok) return upstreamFailure(upstream, stored.value);\n return new Response(upstream.body, {\n status: upstream.status,\n headers: { \"content-type\": \"application/json\" },\n });\n },\n });\n\n http.route({\n method: \"POST\",\n path: \"ai/v1/chat/completions\",\n auth: \"renown\",\n maxBodyBytes: MAX_CHAT_BODY_BYTES,\n handler: async (request, ctx) => {\n const gated = await gate(ctx);\n if (\"refused\" in gated) return gated.refused;\n const stored = await readKey(gated.store);\n if (!stored) return notConfigured();\n const body = await readJsonObject(request);\n if (!Array.isArray(body?.messages)) {\n return errorResponse(\n 400,\n \"A chat request needs messages.\",\n \"invalid_request\",\n );\n }\n\n const forwarded: Record<string, unknown> = {};\n for (const field of FORWARDED_CHAT_FIELDS) {\n if (body[field] !== undefined) forwarded[field] = body[field];\n }\n // The host's model, whatever the client named: cost is the host's call.\n forwarded.model = await currentModel(gated.store);\n const asked = body.max_tokens;\n forwarded.max_tokens =\n typeof asked === \"number\" && asked > 0\n ? Math.min(asked, deps.maxOutputTokens)\n : deps.maxOutputTokens;\n\n let upstream: Response;\n try {\n upstream = await fetchImpl(`${deps.upstreamUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n ...upstreamHeaders(stored.value),\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(forwarded),\n // A closed tab stops spending.\n signal: ctx.signal,\n });\n } catch (error) {\n return unreachable(error, stored.value);\n }\n if (!upstream.ok) return upstreamFailure(upstream, stored.value);\n return new Response(upstream.body, {\n status: upstream.status,\n headers: {\n \"content-type\":\n upstream.headers.get(\"content-type\") ?? \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n \"x-accel-buffering\": \"no\",\n },\n });\n },\n });\n}\n\nfunction notConfigured() {\n return errorResponse(\n 503,\n \"The assistant has no OpenRouter key yet.\",\n \"not_configured\",\n );\n}\n","import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport { AuthorizationPolicy, type API } from \"@powerhousedao/reactor-api\";\nimport type { ILogger } from \"document-model\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { demoKeyFileOf, readDemoKey } from \"../ai/demo-key.mjs\";\nimport { registerAiRoutes } from \"../ai/routes.mjs\";\nimport type { SwitchboardHostContext } from \"../plugin-host.mjs\";\nimport type { ComposedWorkflowRuntime } from \"../workflow-runtime.mjs\";\n\nexport const DEFAULT_AI_UPSTREAM_URL = \"https://openrouter.ai/api/v1\";\n\nexport const aiPluginConfigSchema = z.strictObject({\n /** The model the gateway answers with until an admin picks another. */\n defaultModel: z.string().min(1),\n /** Upper bound on `max_tokens` per request. */\n maxOutputTokens: z.number().int().positive().default(4096),\n /** The OpenAI-compatible provider. Tests point this at a stub. */\n upstreamUrl: z.url().default(DEFAULT_AI_UPSTREAM_URL),\n /** How the host names itself to the provider (OpenRouter's app attribution). */\n appTitle: z.string().min(1).default(\"Powerhouse\"),\n appUrl: z.url().default(\"https://powerhouse.inc\"),\n /**\n * Local development only. Under the OPEN policy everyone is an admin,\n * anonymous callers included, so the gateway does not mount there unless\n * this says so.\n */\n allowWithoutAuth: z.boolean().default(false),\n});\n\nexport type AiPluginConfig = z.infer<typeof aiPluginConfigSchema>;\n\n/** What a host.js entry writes (typed-host-configs 1.4). */\nexport type AiPluginConfigInput = z.input<typeof aiPluginConfigSchema>;\n\ndeclare global {\n interface PHPluginConfigs {\n \"@powerhousedao/switchboard/plugins/ai\": AiPluginConfigInput;\n }\n}\n\nexport type AiPlugin = HostPlugin<\n { onHttpMounting: (ctx: SwitchboardHostContext) => void },\n AiPluginConfig\n>;\n\n/**\n * The AI gateway: an OpenAI-compatible endpoint for this host's admins that\n * holds the provider key server side, so the browser's agent runs without\n * one. The key is a host secret in the workflow runtime's encrypted store,\n * reached per request through `ctx.workflows`: the runtime can arrive after\n * boot, and a second opener of the store could race the first over the key\n * file. Without the runtime the routes answer 503.\n */\nexport function createAiPlugin(rawConfig: unknown): AiPlugin {\n const config = aiPluginConfigSchema.parse(rawConfig ?? {});\n return {\n name: \"switchboard-ai\",\n appliesTo: \"switchboard\",\n configSchema: aiPluginConfigSchema,\n hooks: {\n onHttpMounting: (ctx) => {\n const api = ctx.api as API;\n const logger = ctx.logger as ILogger;\n const { authorizationService } = api;\n // A warning, not a refused boot: a host composition is shared by\n // stacks that run with and without sign-in (desktop has none).\n if (\n authorizationService.config.policy === AuthorizationPolicy.OPEN &&\n !config.allowWithoutAuth\n ) {\n logger.warn(\n \"The AI gateway is not mounted: this host has no sign-in, so every caller would be an admin. Enable authentication (AUTH_ENABLED=true with ADMINS), or set allowWithoutAuth for local development.\",\n );\n return;\n }\n const { configFile } = ctx.options as { configFile?: string };\n const demoKeyFile = demoKeyFileOf(\n configFile ?? path.join(process.cwd(), \"powerhouse.config.json\"),\n );\n registerAiRoutes(\n api.httpRoutes.scopeFor(\"@powerhousedao/switchboard\"),\n {\n isAdmin: (address) => authorizationService.isSupremeAdmin(address),\n demoKey: () => readDemoKey(demoKeyFile),\n secrets: async () =>\n (ctx.workflows as ComposedWorkflowRuntime | undefined)?.secrets(),\n upstreamUrl: config.upstreamUrl.replace(/\\/+$/, \"\"),\n defaultModel: config.defaultModel,\n maxOutputTokens: config.maxOutputTokens,\n appTitle: config.appTitle,\n appUrl: config.appUrl,\n logger,\n },\n );\n },\n },\n };\n}\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default createAiPlugin;\n"],"names":[],"mappings":";;;;;;;;;;;;AAQA,SAAgB,cAAc,YAAwC;CACpE,IAAI;CACJ,IAAI;EACF,QAAS,UAAU,UAAU,CAAC,CAAwC,IAClE;CACN,QAAQ;EACN;CACF;CACA,IAAI,OAAO,UAAU,YAAY,UAAU,IAAI,OAAO,KAAA;CACtD,OAAO,KAAK,QAAQ,KAAK,QAAQ,KAAK,QAAQ,UAAU,CAAC,GAAG,KAAK;AACnE;;AAGA,eAAsB,YACpB,MAC6B;CAC7B,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,IAAI;EACF,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM,EAAA,CAAG,KAAK;EAChD,OAAO,QAAQ,KAAK,KAAA,IAAY;CAClC,QAAQ;EACN;CACF;AACF;;;;;;;;;ACrBA,MAAa,eAAe;;AAE5B,MAAa,iBAAiB;AAa9B,SAAS,WACP,OACA,OACA;CACA,OAAO,MAAM,QACV,SACC,KAAK,UAAU,SAAS,KAAK,YAAY,QAAQ,KAAK,WAAW,QACrE;AACF;AAEA,eAAe,YACb,OACA,OACgC;CAChC,MAAM,SAAS,WAAW,MAAM,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC;CACzD,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,OAAO;EACL,OAAO,MAAM,MAAM,IAAI,OAAO,KAAK,IAAI;EACvC,OAAO,OAAO;EACd,OAAO,OA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{ z } from "zod";
3
+ import { HostPlugin } from "@powerhousedao/host-core";
4
+ //#region src/plugins/attachments.d.mts
5
+ /** No entry config: presence is the whole activation. A typo'd config key
6
+ * fails at resolution instead of being silently ignored. */
7
+ export declare const attachmentsPluginConfigSchema: z.ZodObject<{}, z.core.$strict>;
8
+ export type AttachmentsPluginConfig = z.input<typeof attachmentsPluginConfigSchema>;
9
+ declare global {
10
+ interface PHPluginConfigs {
11
+ "@powerhousedao/switchboard/plugins/attachments": AttachmentsPluginConfig;
12
+ }
13
+ }
14
+ /**
15
+ * R2.3 — the attachments subsystem as a built-in plugin: the six /attachments
16
+ * routes mount at onHttpMounting and the remote attachment service is created
17
+ * for the returned handle. Presence is activation — removed from the
18
+ * composition, the routes and service do not exist. NOT yet carved: the
19
+ * attachment-reference read model registered inside reactor construction
20
+ * (carve map: server.mts initializeClient) — it follows with the
21
+ * onReadModelsRegistering step in R2 step 2; until then it registers on both
22
+ * paths (a dormant read model when the plugin is absent, harmless).
23
+ *
24
+ * Inputs (carve map): api (routes), config.attachments (signing, TTL),
25
+ * options.attachmentServiceUrl / https + serverPort + renown (service config).
26
+ */
27
+ export declare const attachmentsPlugin: HostPlugin<{
28
+ onHttpMounting: (ctx: SwitchboardHostContext) => void;
29
+ }>;
30
+ //#endregion
31
+ export { attachmentsPlugin as default };
32
+ export {};
33
+ //# sourceMappingURL=attachments.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachments.d.mts","names":[],"sources":["../../src/plugins/attachments.mts"],"mappings":";;;;;;qBAUa,+BAA6B,EAAA,cAAA,EAAA,KAAA;YAE9B,0BAA0B,EAAE,aAC/B;QAGD;YACI;IACR,kDAAkD;;;;;;;;;;;;;;;;qBAiBzC,mBAAmB;EAC9B,iBAAiB,KAAK"}
@@ -0,0 +1,4 @@
1
+ import { c as attachmentsPlugin, l as attachmentsPluginConfigSchema } from "../server-CgDvrUqE.mjs";
2
+ export { attachmentsPlugin, attachmentsPlugin as default, attachmentsPluginConfigSchema };
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]="da20b830-acdf-5b53-81db-75d2a261edcc")}catch(e){}}();
4
+ //# debugId=da20b830-acdf-5b53-81db-75d2a261edcc
@@ -0,0 +1,31 @@
1
+ import { t as SwitchboardHostContext } from "../plugin-host-BHEUSn9G.mjs";
2
+ import { z } from "zod";
3
+ import { HostPlugin } from "@powerhousedao/host-core";
4
+ //#region src/plugins/mcp.d.mts
5
+ /** No entry config: presence is the whole activation. A typo'd config key
6
+ * fails at resolution instead of being silently ignored. */
7
+ export declare const mcpPluginConfigSchema: z.ZodObject<{}, z.core.$strict>;
8
+ export type McpPluginConfig = z.input<typeof mcpPluginConfigSchema>;
9
+ declare global {
10
+ interface PHPluginConfigs {
11
+ "@powerhousedao/switchboard/plugins/mcp": McpPluginConfig;
12
+ }
13
+ }
14
+ /**
15
+ * R2.2 — the MCP subsystem as a built-in plugin. Flag-on semantics: PRESENCE
16
+ * IS ACTIVATION — listed (built-in default) means the /mcp endpoint mounts;
17
+ * removed from the composition means it does not exist. The MCP_ENABLED env
18
+ * flag governs the classic/flag-off path only (resolveMcpEnabled, which
19
+ * still runs and whose result this transform overrides flag-on).
20
+ *
21
+ * The mount itself lives inside reactor-api's initializeAndStartAPI (carve
22
+ * map: reactor-api server.ts:1282-1294) and is driven by options.mcp — the
23
+ * plugin's whole job is owning that option.
24
+ */
25
+ export declare const mcpPlugin: HostPlugin<{
26
+ transformServerOptions: (options: Record<string, unknown>, ctx: SwitchboardHostContext) => Record<string, unknown>;
27
+ }>;
28
+ //#endregion
29
+ export { mcpPlugin as default };
30
+ export {};
31
+ //# sourceMappingURL=mcp.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.d.mts","names":[],"sources":["../../src/plugins/mcp.mts"],"mappings":";;;;;;qBAMa,uBAAqB,EAAA,cAAA,EAAA,KAAA;YAEtB,kBAAkB,EAAE,aAAa;QAErC;YACI;IACR,0CAA0C;;;;;;;;;;;;;;qBAejC,WAAW;EACtB,yBACE,SAAS,yBACT,KAAK,2BACF"}
@@ -0,0 +1,4 @@
1
+ import { n as mcpPluginConfigSchema, t as mcpPlugin } from "../mcp-SsBK14Jm.mjs";
2
+ export { mcpPlugin as default, mcpPlugin, mcpPluginConfigSchema };
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]="dba18a22-a12c-5f1b-8475-f41ceb845bef")}catch(e){}}();
4
+ //# debugId=dba18a22-a12c-5f1b-8475-f41ceb845bef
@@ -0,0 +1,22 @@
1
+ import { t as SwitchboardHostContext } from "../plugin-host-BHEUSn9G.mjs";
2
+ import { z } from "zod";
3
+ import { HostPlugin } from "@powerhousedao/host-core";
4
+ //#region src/plugins/privacy.d.mts
5
+ /** No entry config: presence is the whole activation. A typo'd config key
6
+ * fails at resolution instead of being silently ignored. */
7
+ export declare const privacyPluginConfigSchema: z.ZodObject<{}, z.core.$strict>;
8
+ export type PrivacyPluginConfig = z.input<typeof privacyPluginConfigSchema>;
9
+ declare global {
10
+ interface PHPluginConfigs {
11
+ "@powerhousedao/switchboard/plugins/privacy": PrivacyPluginConfig;
12
+ }
13
+ }
14
+ export declare const privacyPlugin: HostPlugin<{
15
+ transformServerOptions: (options: Record<string, unknown>, ctx: SwitchboardHostContext) => Record<string, unknown>;
16
+ onSubgraphsRegistering: (ctx: SwitchboardHostContext) => Promise<void>;
17
+ onShutdown: (ctx: SwitchboardHostContext) => Promise<void>;
18
+ }>;
19
+ //#endregion
20
+ export { privacyPlugin as default };
21
+ export {};
22
+ //# sourceMappingURL=privacy.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"privacy.d.mts","names":[],"sources":["../../src/plugins/privacy.mts"],"mappings":";;;;;;qBAea,2BAAyB,EAAA,cAAA,EAAA,KAAA;YAE1B,sBAAsB,EAAE,aAAa;QAEzC;YACI;IACR,8CAA8C;;;qBAuBrC,eAAe;EAC1B,yBACE,SAAS,yBACT,KAAK,2BACF;EACL,yBAAyB,KAAK,2BAA2B;EACzD,aAAa,KAAK,2BAA2B"}
@@ -0,0 +1,4 @@
1
+ import { n as privacyPluginConfigSchema, t as privacyPlugin } from "../privacy-BO8Q25xI.mjs";
2
+ export { privacyPlugin as default, privacyPlugin, privacyPluginConfigSchema };
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]="af72d555-6d6a-516e-8ed1-2d5f46f39dda")}catch(e){}}();
4
+ //# debugId=af72d555-6d6a-516e-8ed1-2d5f46f39dda