@rudderhq/server 0.1.0-canary.0

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 (902) hide show
  1. package/LICENSE +14 -0
  2. package/dist/agent-auth-jwt.d.ts +14 -0
  3. package/dist/agent-auth-jwt.d.ts.map +1 -0
  4. package/dist/agent-auth-jwt.js +119 -0
  5. package/dist/agent-auth-jwt.js.map +1 -0
  6. package/dist/agent-runtimes/codex-models.d.ts +4 -0
  7. package/dist/agent-runtimes/codex-models.d.ts.map +1 -0
  8. package/dist/agent-runtimes/codex-models.js +98 -0
  9. package/dist/agent-runtimes/codex-models.js.map +1 -0
  10. package/dist/agent-runtimes/cursor-models.d.ts +13 -0
  11. package/dist/agent-runtimes/cursor-models.d.ts.map +1 -0
  12. package/dist/agent-runtimes/cursor-models.js +148 -0
  13. package/dist/agent-runtimes/cursor-models.js.map +1 -0
  14. package/dist/agent-runtimes/http/execute.d.ts +3 -0
  15. package/dist/agent-runtimes/http/execute.d.ts.map +1 -0
  16. package/dist/agent-runtimes/http/execute.js +39 -0
  17. package/dist/agent-runtimes/http/execute.js.map +1 -0
  18. package/dist/agent-runtimes/http/index.d.ts +3 -0
  19. package/dist/agent-runtimes/http/index.d.ts.map +1 -0
  20. package/dist/agent-runtimes/http/index.js +20 -0
  21. package/dist/agent-runtimes/http/index.js.map +1 -0
  22. package/dist/agent-runtimes/http/test.d.ts +3 -0
  23. package/dist/agent-runtimes/http/test.d.ts.map +1 -0
  24. package/dist/agent-runtimes/http/test.js +106 -0
  25. package/dist/agent-runtimes/http/test.js.map +1 -0
  26. package/dist/agent-runtimes/index.d.ts +4 -0
  27. package/dist/agent-runtimes/index.d.ts.map +1 -0
  28. package/dist/agent-runtimes/index.js +3 -0
  29. package/dist/agent-runtimes/index.js.map +1 -0
  30. package/dist/agent-runtimes/process/execute.d.ts +3 -0
  31. package/dist/agent-runtimes/process/execute.d.ts.map +1 -0
  32. package/dist/agent-runtimes/process/execute.js +63 -0
  33. package/dist/agent-runtimes/process/execute.js.map +1 -0
  34. package/dist/agent-runtimes/process/index.d.ts +3 -0
  35. package/dist/agent-runtimes/process/index.d.ts.map +1 -0
  36. package/dist/agent-runtimes/process/index.js +23 -0
  37. package/dist/agent-runtimes/process/index.js.map +1 -0
  38. package/dist/agent-runtimes/process/test.d.ts +3 -0
  39. package/dist/agent-runtimes/process/test.d.ts.map +1 -0
  40. package/dist/agent-runtimes/process/test.js +77 -0
  41. package/dist/agent-runtimes/process/test.js.map +1 -0
  42. package/dist/agent-runtimes/registry.d.ts +9 -0
  43. package/dist/agent-runtimes/registry.d.ts.map +1 -0
  44. package/dist/agent-runtimes/registry.js +189 -0
  45. package/dist/agent-runtimes/registry.js.map +1 -0
  46. package/dist/agent-runtimes/types.d.ts +2 -0
  47. package/dist/agent-runtimes/types.d.ts.map +1 -0
  48. package/dist/agent-runtimes/types.js +2 -0
  49. package/dist/agent-runtimes/types.js.map +1 -0
  50. package/dist/agent-runtimes/utils.d.ts +10 -0
  51. package/dist/agent-runtimes/utils.d.ts.map +1 -0
  52. package/dist/agent-runtimes/utils.js +14 -0
  53. package/dist/agent-runtimes/utils.js.map +1 -0
  54. package/dist/agent-workspace-key.d.ts +17 -0
  55. package/dist/agent-workspace-key.d.ts.map +1 -0
  56. package/dist/agent-workspace-key.js +49 -0
  57. package/dist/agent-workspace-key.js.map +1 -0
  58. package/dist/app.d.ts +14 -0
  59. package/dist/app.d.ts.map +1 -0
  60. package/dist/app.js +19 -0
  61. package/dist/app.js.map +1 -0
  62. package/dist/attachment-types.d.ts +33 -0
  63. package/dist/attachment-types.d.ts.map +1 -0
  64. package/dist/attachment-types.js +67 -0
  65. package/dist/attachment-types.js.map +1 -0
  66. package/dist/auth/better-auth.d.ts +24 -0
  67. package/dist/auth/better-auth.d.ts.map +1 -0
  68. package/dist/auth/better-auth.js +108 -0
  69. package/dist/auth/better-auth.js.map +1 -0
  70. package/dist/board-claim.d.ts +23 -0
  71. package/dist/board-claim.d.ts.map +1 -0
  72. package/dist/board-claim.js +115 -0
  73. package/dist/board-claim.js.map +1 -0
  74. package/dist/bootstrap/create-http-app.d.ts +6 -0
  75. package/dist/bootstrap/create-http-app.d.ts.map +1 -0
  76. package/dist/bootstrap/create-http-app.js +122 -0
  77. package/dist/bootstrap/create-http-app.js.map +1 -0
  78. package/dist/bootstrap/plugin-host-runtime.d.ts +116 -0
  79. package/dist/bootstrap/plugin-host-runtime.d.ts.map +1 -0
  80. package/dist/bootstrap/plugin-host-runtime.js +121 -0
  81. package/dist/bootstrap/plugin-host-runtime.js.map +1 -0
  82. package/dist/bootstrap/register-api-routes.d.ts +5 -0
  83. package/dist/bootstrap/register-api-routes.d.ts.map +1 -0
  84. package/dist/bootstrap/register-api-routes.js +65 -0
  85. package/dist/bootstrap/register-api-routes.js.map +1 -0
  86. package/dist/bootstrap/types.d.ts +24 -0
  87. package/dist/bootstrap/types.d.ts.map +1 -0
  88. package/dist/bootstrap/types.js +2 -0
  89. package/dist/bootstrap/types.js.map +1 -0
  90. package/dist/config-file.d.ts +5 -0
  91. package/dist/config-file.d.ts.map +1 -0
  92. package/dist/config-file.js +48 -0
  93. package/dist/config-file.js.map +1 -0
  94. package/dist/config.d.ts +45 -0
  95. package/dist/config.d.ts.map +1 -0
  96. package/dist/config.js +233 -0
  97. package/dist/config.js.map +1 -0
  98. package/dist/dev-server-status.d.ts +29 -0
  99. package/dist/dev-server-status.d.ts.map +1 -0
  100. package/dist/dev-server-status.js +75 -0
  101. package/dist/dev-server-status.js.map +1 -0
  102. package/dist/errors.d.ts +12 -0
  103. package/dist/errors.d.ts.map +1 -0
  104. package/dist/errors.js +28 -0
  105. package/dist/errors.js.map +1 -0
  106. package/dist/home-paths.d.ts +50 -0
  107. package/dist/home-paths.d.ts.map +1 -0
  108. package/dist/home-paths.js +183 -0
  109. package/dist/home-paths.js.map +1 -0
  110. package/dist/index.d.ts +69 -0
  111. package/dist/index.d.ts.map +1 -0
  112. package/dist/index.js +827 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/langfuse-transcript.d.ts +32 -0
  115. package/dist/langfuse-transcript.d.ts.map +1 -0
  116. package/dist/langfuse-transcript.js +341 -0
  117. package/dist/langfuse-transcript.js.map +1 -0
  118. package/dist/langfuse.d.ts +93 -0
  119. package/dist/langfuse.d.ts.map +1 -0
  120. package/dist/langfuse.js +412 -0
  121. package/dist/langfuse.js.map +1 -0
  122. package/dist/local-runtime.d.ts +67 -0
  123. package/dist/local-runtime.d.ts.map +1 -0
  124. package/dist/local-runtime.js +302 -0
  125. package/dist/local-runtime.js.map +1 -0
  126. package/dist/log-redaction.d.ts +11 -0
  127. package/dist/log-redaction.d.ts.map +1 -0
  128. package/dist/log-redaction.js +118 -0
  129. package/dist/log-redaction.js.map +1 -0
  130. package/dist/middleware/auth.d.ts +12 -0
  131. package/dist/middleware/auth.d.ts.map +1 -0
  132. package/dist/middleware/auth.js +144 -0
  133. package/dist/middleware/auth.js.map +1 -0
  134. package/dist/middleware/board-mutation-guard.d.ts +3 -0
  135. package/dist/middleware/board-mutation-guard.d.ts.map +1 -0
  136. package/dist/middleware/board-mutation-guard.js +59 -0
  137. package/dist/middleware/board-mutation-guard.js.map +1 -0
  138. package/dist/middleware/error-handler.d.ts +17 -0
  139. package/dist/middleware/error-handler.d.ts.map +1 -0
  140. package/dist/middleware/error-handler.js +37 -0
  141. package/dist/middleware/error-handler.js.map +1 -0
  142. package/dist/middleware/index.d.ts +4 -0
  143. package/dist/middleware/index.d.ts.map +1 -0
  144. package/dist/middleware/index.js +4 -0
  145. package/dist/middleware/index.js.map +1 -0
  146. package/dist/middleware/logger.d.ts +4 -0
  147. package/dist/middleware/logger.d.ts.map +1 -0
  148. package/dist/middleware/logger.js +133 -0
  149. package/dist/middleware/logger.js.map +1 -0
  150. package/dist/middleware/private-hostname-guard.d.ts +11 -0
  151. package/dist/middleware/private-hostname-guard.d.ts.map +1 -0
  152. package/dist/middleware/private-hostname-guard.js +78 -0
  153. package/dist/middleware/private-hostname-guard.js.map +1 -0
  154. package/dist/middleware/validate.d.ts +4 -0
  155. package/dist/middleware/validate.d.ts.map +1 -0
  156. package/dist/middleware/validate.js +7 -0
  157. package/dist/middleware/validate.js.map +1 -0
  158. package/dist/onboarding-assets/ceo/AGENTS.md +33 -0
  159. package/dist/onboarding-assets/ceo/HEARTBEAT.md +77 -0
  160. package/dist/onboarding-assets/ceo/SOUL.md +33 -0
  161. package/dist/onboarding-assets/ceo/TOOLS.md +3 -0
  162. package/dist/onboarding-assets/default/AGENTS.md +9 -0
  163. package/dist/onboarding-assets/default/HEARTBEAT.md +36 -0
  164. package/dist/onboarding-assets/default/SOUL.md +23 -0
  165. package/dist/onboarding-assets/default/TOOLS.md +3 -0
  166. package/dist/paths.d.ts +3 -0
  167. package/dist/paths.d.ts.map +1 -0
  168. package/dist/paths.js +31 -0
  169. package/dist/paths.js.map +1 -0
  170. package/dist/realtime/live-events-ws.d.ts +28 -0
  171. package/dist/realtime/live-events-ws.d.ts.map +1 -0
  172. package/dist/realtime/live-events-ws.js +187 -0
  173. package/dist/realtime/live-events-ws.js.map +1 -0
  174. package/dist/redaction.d.ts +4 -0
  175. package/dist/redaction.d.ts.map +1 -0
  176. package/dist/redaction.js +63 -0
  177. package/dist/redaction.js.map +1 -0
  178. package/dist/routes/access.d.ts +57 -0
  179. package/dist/routes/access.d.ts.map +1 -0
  180. package/dist/routes/access.js +2266 -0
  181. package/dist/routes/access.js.map +1 -0
  182. package/dist/routes/activity.d.ts +3 -0
  183. package/dist/routes/activity.d.ts.map +1 -0
  184. package/dist/routes/activity.js +78 -0
  185. package/dist/routes/activity.js.map +1 -0
  186. package/dist/routes/agents.d.ts +3 -0
  187. package/dist/routes/agents.d.ts.map +1 -0
  188. package/dist/routes/agents.js +1913 -0
  189. package/dist/routes/agents.js.map +1 -0
  190. package/dist/routes/approvals.d.ts +3 -0
  191. package/dist/routes/approvals.d.ts.map +1 -0
  192. package/dist/routes/approvals.js +365 -0
  193. package/dist/routes/approvals.js.map +1 -0
  194. package/dist/routes/assets.d.ts +4 -0
  195. package/dist/routes/assets.d.ts.map +1 -0
  196. package/dist/routes/assets.js +309 -0
  197. package/dist/routes/assets.js.map +1 -0
  198. package/dist/routes/authz.d.ts +16 -0
  199. package/dist/routes/authz.d.ts.map +1 -0
  200. package/dist/routes/authz.js +47 -0
  201. package/dist/routes/authz.js.map +1 -0
  202. package/dist/routes/automations.d.ts +3 -0
  203. package/dist/routes/automations.d.ts.map +1 -0
  204. package/dist/routes/automations.js +277 -0
  205. package/dist/routes/automations.js.map +1 -0
  206. package/dist/routes/chats.d.ts +4 -0
  207. package/dist/routes/chats.d.ts.map +1 -0
  208. package/dist/routes/chats.js +1162 -0
  209. package/dist/routes/chats.js.map +1 -0
  210. package/dist/routes/costs.d.ts +3 -0
  211. package/dist/routes/costs.d.ts.map +1 -0
  212. package/dist/routes/costs.js +268 -0
  213. package/dist/routes/costs.js.map +1 -0
  214. package/dist/routes/dashboard.d.ts +3 -0
  215. package/dist/routes/dashboard.d.ts.map +1 -0
  216. package/dist/routes/dashboard.js +15 -0
  217. package/dist/routes/dashboard.js.map +1 -0
  218. package/dist/routes/execution-workspaces.d.ts +3 -0
  219. package/dist/routes/execution-workspaces.d.ts.map +1 -0
  220. package/dist/routes/execution-workspaces.js +165 -0
  221. package/dist/routes/execution-workspaces.js.map +1 -0
  222. package/dist/routes/goals.d.ts +3 -0
  223. package/dist/routes/goals.d.ts.map +1 -0
  224. package/dist/routes/goals.js +95 -0
  225. package/dist/routes/goals.js.map +1 -0
  226. package/dist/routes/health.d.ts +12 -0
  227. package/dist/routes/health.d.ts.map +1 -0
  228. package/dist/routes/health.js +85 -0
  229. package/dist/routes/health.js.map +1 -0
  230. package/dist/routes/index.d.ts +19 -0
  231. package/dist/routes/index.d.ts.map +1 -0
  232. package/dist/routes/index.js +19 -0
  233. package/dist/routes/index.js.map +1 -0
  234. package/dist/routes/instance-settings.d.ts +6 -0
  235. package/dist/routes/instance-settings.d.ts.map +1 -0
  236. package/dist/routes/instance-settings.js +250 -0
  237. package/dist/routes/instance-settings.js.map +1 -0
  238. package/dist/routes/issues-checkout-wakeup.d.ts +9 -0
  239. package/dist/routes/issues-checkout-wakeup.d.ts.map +1 -0
  240. package/dist/routes/issues-checkout-wakeup.js +12 -0
  241. package/dist/routes/issues-checkout-wakeup.js.map +1 -0
  242. package/dist/routes/issues.d.ts +4 -0
  243. package/dist/routes/issues.d.ts.map +1 -0
  244. package/dist/routes/issues.js +1615 -0
  245. package/dist/routes/issues.js.map +1 -0
  246. package/dist/routes/llms.d.ts +3 -0
  247. package/dist/routes/llms.d.ts.map +1 -0
  248. package/dist/routes/llms.js +78 -0
  249. package/dist/routes/llms.js.map +1 -0
  250. package/dist/routes/messenger.d.ts +3 -0
  251. package/dist/routes/messenger.d.ts.map +1 -0
  252. package/dist/routes/messenger.js +108 -0
  253. package/dist/routes/messenger.js.map +1 -0
  254. package/dist/routes/org-chart-logo.d.ts +2 -0
  255. package/dist/routes/org-chart-logo.d.ts.map +1 -0
  256. package/dist/routes/org-chart-logo.js +2 -0
  257. package/dist/routes/org-chart-logo.js.map +1 -0
  258. package/dist/routes/org-chart-svg.d.ts +25 -0
  259. package/dist/routes/org-chart-svg.d.ts.map +1 -0
  260. package/dist/routes/org-chart-svg.js +652 -0
  261. package/dist/routes/org-chart-svg.js.map +1 -0
  262. package/dist/routes/organization-skills.d.ts +3 -0
  263. package/dist/routes/organization-skills.d.ts.map +1 -0
  264. package/dist/routes/organization-skills.js +253 -0
  265. package/dist/routes/organization-skills.js.map +1 -0
  266. package/dist/routes/orgs.d.ts +4 -0
  267. package/dist/routes/orgs.d.ts.map +1 -0
  268. package/dist/routes/orgs.js +575 -0
  269. package/dist/routes/orgs.js.map +1 -0
  270. package/dist/routes/plugin-ui-static.d.ts +69 -0
  271. package/dist/routes/plugin-ui-static.d.ts.map +1 -0
  272. package/dist/routes/plugin-ui-static.js +411 -0
  273. package/dist/routes/plugin-ui-static.js.map +1 -0
  274. package/dist/routes/plugins.d.ts +120 -0
  275. package/dist/routes/plugins.d.ts.map +1 -0
  276. package/dist/routes/plugins.js +1776 -0
  277. package/dist/routes/plugins.js.map +1 -0
  278. package/dist/routes/projects.d.ts +3 -0
  279. package/dist/routes/projects.d.ts.map +1 -0
  280. package/dist/routes/projects.js +235 -0
  281. package/dist/routes/projects.js.map +1 -0
  282. package/dist/routes/run-intelligence.d.ts +3 -0
  283. package/dist/routes/run-intelligence.d.ts.map +1 -0
  284. package/dist/routes/run-intelligence.js +58 -0
  285. package/dist/routes/run-intelligence.js.map +1 -0
  286. package/dist/routes/secrets.d.ts +3 -0
  287. package/dist/routes/secrets.d.ts.map +1 -0
  288. package/dist/routes/secrets.js +128 -0
  289. package/dist/routes/secrets.js.map +1 -0
  290. package/dist/routes/sidebar-badges.d.ts +3 -0
  291. package/dist/routes/sidebar-badges.d.ts.map +1 -0
  292. package/dist/routes/sidebar-badges.js +70 -0
  293. package/dist/routes/sidebar-badges.js.map +1 -0
  294. package/dist/secrets/external-stub-providers.d.ts +5 -0
  295. package/dist/secrets/external-stub-providers.d.ts.map +1 -0
  296. package/dist/secrets/external-stub-providers.js +21 -0
  297. package/dist/secrets/external-stub-providers.js.map +1 -0
  298. package/dist/secrets/local-encrypted-provider.d.ts +3 -0
  299. package/dist/secrets/local-encrypted-provider.d.ts.map +1 -0
  300. package/dist/secrets/local-encrypted-provider.js +116 -0
  301. package/dist/secrets/local-encrypted-provider.js.map +1 -0
  302. package/dist/secrets/provider-registry.d.ts +5 -0
  303. package/dist/secrets/provider-registry.d.ts.map +1 -0
  304. package/dist/secrets/provider-registry.js +20 -0
  305. package/dist/secrets/provider-registry.js.map +1 -0
  306. package/dist/secrets/types.d.ts +21 -0
  307. package/dist/secrets/types.d.ts.map +1 -0
  308. package/dist/secrets/types.js +2 -0
  309. package/dist/secrets/types.js.map +1 -0
  310. package/dist/services/access.d.ts +113 -0
  311. package/dist/services/access.d.ts.map +1 -0
  312. package/dist/services/access.js +247 -0
  313. package/dist/services/access.js.map +1 -0
  314. package/dist/services/activity-log.d.ts +17 -0
  315. package/dist/services/activity-log.d.ts.map +1 -0
  316. package/dist/services/activity-log.js +109 -0
  317. package/dist/services/activity-log.js.map +1 -0
  318. package/dist/services/activity.d.ts +472 -0
  319. package/dist/services/activity.d.ts.map +1 -0
  320. package/dist/services/activity.js +134 -0
  321. package/dist/services/activity.js.map +1 -0
  322. package/dist/services/agent-enabled-skills.d.ts +9 -0
  323. package/dist/services/agent-enabled-skills.d.ts.map +1 -0
  324. package/dist/services/agent-enabled-skills.js +89 -0
  325. package/dist/services/agent-enabled-skills.js.map +1 -0
  326. package/dist/services/agent-instructions.d.ts +98 -0
  327. package/dist/services/agent-instructions.d.ts.map +1 -0
  328. package/dist/services/agent-instructions.js +596 -0
  329. package/dist/services/agent-instructions.js.map +1 -0
  330. package/dist/services/agent-name-pool.d.ts +10 -0
  331. package/dist/services/agent-name-pool.d.ts.map +1 -0
  332. package/dist/services/agent-name-pool.js +230 -0
  333. package/dist/services/agent-name-pool.js.map +1 -0
  334. package/dist/services/agent-permissions.d.ts +6 -0
  335. package/dist/services/agent-permissions.d.ts.map +1 -0
  336. package/dist/services/agent-permissions.js +18 -0
  337. package/dist/services/agent-permissions.js.map +1 -0
  338. package/dist/services/agent-run-context.d.ts +142 -0
  339. package/dist/services/agent-run-context.d.ts.map +1 -0
  340. package/dist/services/agent-run-context.js +451 -0
  341. package/dist/services/agent-run-context.js.map +1 -0
  342. package/dist/services/agents.d.ts +1713 -0
  343. package/dist/services/agents.d.ts.map +1 -0
  344. package/dist/services/agents.js +750 -0
  345. package/dist/services/agents.js.map +1 -0
  346. package/dist/services/approvals.d.ts +546 -0
  347. package/dist/services/approvals.d.ts.map +1 -0
  348. package/dist/services/approvals.js +212 -0
  349. package/dist/services/approvals.js.map +1 -0
  350. package/dist/services/assets.d.ts +33 -0
  351. package/dist/services/assets.d.ts.map +1 -0
  352. package/dist/services/assets.js +17 -0
  353. package/dist/services/assets.js.map +1 -0
  354. package/dist/services/automations.d.ts +135 -0
  355. package/dist/services/automations.d.ts.map +1 -0
  356. package/dist/services/automations.js +1105 -0
  357. package/dist/services/automations.js.map +1 -0
  358. package/dist/services/board-auth.d.ts +234 -0
  359. package/dist/services/board-auth.d.ts.map +1 -0
  360. package/dist/services/board-auth.js +295 -0
  361. package/dist/services/board-auth.js.map +1 -0
  362. package/dist/services/budgets.d.ts +38 -0
  363. package/dist/services/budgets.d.ts.map +1 -0
  364. package/dist/services/budgets.js +784 -0
  365. package/dist/services/budgets.js.map +1 -0
  366. package/dist/services/chat-assistant.d.ts +62 -0
  367. package/dist/services/chat-assistant.d.ts.map +1 -0
  368. package/dist/services/chat-assistant.js +943 -0
  369. package/dist/services/chat-assistant.js.map +1 -0
  370. package/dist/services/chat-generation-locks.d.ts +3 -0
  371. package/dist/services/chat-generation-locks.d.ts.map +1 -0
  372. package/dist/services/chat-generation-locks.js +16 -0
  373. package/dist/services/chat-generation-locks.js.map +1 -0
  374. package/dist/services/chats.d.ts +723 -0
  375. package/dist/services/chats.d.ts.map +1 -0
  376. package/dist/services/chats.js +1188 -0
  377. package/dist/services/chats.js.map +1 -0
  378. package/dist/services/costs.d.ts +114 -0
  379. package/dist/services/costs.d.ts.map +1 -0
  380. package/dist/services/costs.js +326 -0
  381. package/dist/services/costs.js.map +1 -0
  382. package/dist/services/cron.d.ts +80 -0
  383. package/dist/services/cron.d.ts.map +1 -0
  384. package/dist/services/cron.js +300 -0
  385. package/dist/services/cron.js.map +1 -0
  386. package/dist/services/dashboard.d.ts +26 -0
  387. package/dist/services/dashboard.d.ts.map +1 -0
  388. package/dist/services/dashboard.js +98 -0
  389. package/dist/services/dashboard.js.map +1 -0
  390. package/dist/services/default-agent-instructions.d.ts +9 -0
  391. package/dist/services/default-agent-instructions.d.ts.map +1 -0
  392. package/dist/services/default-agent-instructions.js +20 -0
  393. package/dist/services/default-agent-instructions.js.map +1 -0
  394. package/dist/services/documents.d.ts +164 -0
  395. package/dist/services/documents.d.ts.map +1 -0
  396. package/dist/services/documents.js +382 -0
  397. package/dist/services/documents.js.map +1 -0
  398. package/dist/services/execution-workspace-policy.d.ts +20 -0
  399. package/dist/services/execution-workspace-policy.d.ts.map +1 -0
  400. package/dist/services/execution-workspace-policy.js +172 -0
  401. package/dist/services/execution-workspace-policy.js.map +1 -0
  402. package/dist/services/execution-workspaces.d.ts +19 -0
  403. package/dist/services/execution-workspaces.d.ts.map +1 -0
  404. package/dist/services/execution-workspaces.js +87 -0
  405. package/dist/services/execution-workspaces.js.map +1 -0
  406. package/dist/services/finance.d.ts +93 -0
  407. package/dist/services/finance.d.ts.map +1 -0
  408. package/dist/services/finance.js +120 -0
  409. package/dist/services/finance.js.map +1 -0
  410. package/dist/services/goals.d.ts +433 -0
  411. package/dist/services/goals.d.ts.map +1 -0
  412. package/dist/services/goals.js +54 -0
  413. package/dist/services/goals.js.map +1 -0
  414. package/dist/services/heartbeat-run-summary.d.ts +2 -0
  415. package/dist/services/heartbeat-run-summary.d.ts.map +1 -0
  416. package/dist/services/heartbeat-run-summary.js +131 -0
  417. package/dist/services/heartbeat-run-summary.js.map +1 -0
  418. package/dist/services/heartbeat.d.ts +2 -0
  419. package/dist/services/heartbeat.d.ts.map +1 -0
  420. package/dist/services/heartbeat.js +2 -0
  421. package/dist/services/heartbeat.js.map +1 -0
  422. package/dist/services/hire-hook.d.ts +14 -0
  423. package/dist/services/hire-hook.d.ts.map +1 -0
  424. package/dist/services/hire-hook.js +85 -0
  425. package/dist/services/hire-hook.js.map +1 -0
  426. package/dist/services/index.d.ts +38 -0
  427. package/dist/services/index.d.ts.map +1 -0
  428. package/dist/services/index.js +38 -0
  429. package/dist/services/index.js.map +1 -0
  430. package/dist/services/instance-settings.d.ts +14 -0
  431. package/dist/services/instance-settings.d.ts.map +1 -0
  432. package/dist/services/instance-settings.js +158 -0
  433. package/dist/services/instance-settings.js.map +1 -0
  434. package/dist/services/issue-approvals.d.ts +56 -0
  435. package/dist/services/issue-approvals.d.ts.map +1 -0
  436. package/dist/services/issue-approvals.js +153 -0
  437. package/dist/services/issue-approvals.js.map +1 -0
  438. package/dist/services/issue-assignment-wakeup.d.ts +32 -0
  439. package/dist/services/issue-assignment-wakeup.d.ts.map +1 -0
  440. package/dist/services/issue-assignment-wakeup.js +43 -0
  441. package/dist/services/issue-assignment-wakeup.js.map +1 -0
  442. package/dist/services/issue-goal-fallback.d.ts +15 -0
  443. package/dist/services/issue-goal-fallback.d.ts.map +1 -0
  444. package/dist/services/issue-goal-fallback.js +15 -0
  445. package/dist/services/issue-goal-fallback.js.map +1 -0
  446. package/dist/services/issues.d.ts +580 -0
  447. package/dist/services/issues.d.ts.map +1 -0
  448. package/dist/services/issues.js +1464 -0
  449. package/dist/services/issues.js.map +1 -0
  450. package/dist/services/knowledge-portability/organization-portability.d.ts +23 -0
  451. package/dist/services/knowledge-portability/organization-portability.d.ts.map +1 -0
  452. package/dist/services/knowledge-portability/organization-portability.js +3795 -0
  453. package/dist/services/knowledge-portability/organization-portability.js.map +1 -0
  454. package/dist/services/knowledge-portability/organization-skills.d.ts +105 -0
  455. package/dist/services/knowledge-portability/organization-skills.d.ts.map +1 -0
  456. package/dist/services/knowledge-portability/organization-skills.js +3172 -0
  457. package/dist/services/knowledge-portability/organization-skills.js.map +1 -0
  458. package/dist/services/live-events.d.ts +17 -0
  459. package/dist/services/live-events.d.ts.map +1 -0
  460. package/dist/services/live-events.js +33 -0
  461. package/dist/services/live-events.js.map +1 -0
  462. package/dist/services/messenger.d.ts +111 -0
  463. package/dist/services/messenger.d.ts.map +1 -0
  464. package/dist/services/messenger.js +774 -0
  465. package/dist/services/messenger.js.map +1 -0
  466. package/dist/services/native-path-picker.d.ts +18 -0
  467. package/dist/services/native-path-picker.d.ts.map +1 -0
  468. package/dist/services/native-path-picker.js +119 -0
  469. package/dist/services/native-path-picker.js.map +1 -0
  470. package/dist/services/operator-profile.d.ts +7 -0
  471. package/dist/services/operator-profile.d.ts.map +1 -0
  472. package/dist/services/operator-profile.js +66 -0
  473. package/dist/services/operator-profile.js.map +1 -0
  474. package/dist/services/organization-export-readme.d.ts +17 -0
  475. package/dist/services/organization-export-readme.d.ts.map +1 -0
  476. package/dist/services/organization-export-readme.js +148 -0
  477. package/dist/services/organization-export-readme.js.map +1 -0
  478. package/dist/services/organization-portability.d.ts +2 -0
  479. package/dist/services/organization-portability.d.ts.map +1 -0
  480. package/dist/services/organization-portability.js +2 -0
  481. package/dist/services/organization-portability.js.map +1 -0
  482. package/dist/services/organization-skills.d.ts +2 -0
  483. package/dist/services/organization-skills.d.ts.map +1 -0
  484. package/dist/services/organization-skills.js +2 -0
  485. package/dist/services/organization-skills.js.map +1 -0
  486. package/dist/services/organization-workspace-browser.d.ts +8 -0
  487. package/dist/services/organization-workspace-browser.d.ts.map +1 -0
  488. package/dist/services/organization-workspace-browser.js +229 -0
  489. package/dist/services/organization-workspace-browser.js.map +1 -0
  490. package/dist/services/organization-workspace.d.ts +5 -0
  491. package/dist/services/organization-workspace.d.ts.map +1 -0
  492. package/dist/services/organization-workspace.js +71 -0
  493. package/dist/services/organization-workspace.js.map +1 -0
  494. package/dist/services/orgs.d.ts +163 -0
  495. package/dist/services/orgs.d.ts.map +1 -0
  496. package/dist/services/orgs.js +327 -0
  497. package/dist/services/orgs.js.map +1 -0
  498. package/dist/services/plugin-capability-validator.d.ts +108 -0
  499. package/dist/services/plugin-capability-validator.d.ts.map +1 -0
  500. package/dist/services/plugin-capability-validator.js +268 -0
  501. package/dist/services/plugin-capability-validator.js.map +1 -0
  502. package/dist/services/plugin-config-validator.d.ts +26 -0
  503. package/dist/services/plugin-config-validator.d.ts.map +1 -0
  504. package/dist/services/plugin-config-validator.js +41 -0
  505. package/dist/services/plugin-config-validator.js.map +1 -0
  506. package/dist/services/plugin-dev-watcher.d.ts +30 -0
  507. package/dist/services/plugin-dev-watcher.d.ts.map +1 -0
  508. package/dist/services/plugin-dev-watcher.js +241 -0
  509. package/dist/services/plugin-dev-watcher.js.map +1 -0
  510. package/dist/services/plugin-event-bus.d.ts +149 -0
  511. package/dist/services/plugin-event-bus.d.ts.map +1 -0
  512. package/dist/services/plugin-event-bus.js +258 -0
  513. package/dist/services/plugin-event-bus.js.map +1 -0
  514. package/dist/services/plugin-host-service-cleanup.d.ts +14 -0
  515. package/dist/services/plugin-host-service-cleanup.d.ts.map +1 -0
  516. package/dist/services/plugin-host-service-cleanup.js +37 -0
  517. package/dist/services/plugin-host-service-cleanup.js.map +1 -0
  518. package/dist/services/plugin-host-services.d.ts +13 -0
  519. package/dist/services/plugin-host-services.d.ts.map +1 -0
  520. package/dist/services/plugin-host-services.js +973 -0
  521. package/dist/services/plugin-host-services.js.map +1 -0
  522. package/dist/services/plugin-job-coordinator.d.ts +81 -0
  523. package/dist/services/plugin-job-coordinator.d.ts.map +1 -0
  524. package/dist/services/plugin-job-coordinator.js +172 -0
  525. package/dist/services/plugin-job-coordinator.js.map +1 -0
  526. package/dist/services/plugin-job-scheduler.d.ts +163 -0
  527. package/dist/services/plugin-job-scheduler.d.ts.map +1 -0
  528. package/dist/services/plugin-job-scheduler.js +564 -0
  529. package/dist/services/plugin-job-scheduler.js.map +1 -0
  530. package/dist/services/plugin-job-store.d.ts +208 -0
  531. package/dist/services/plugin-job-store.d.ts.map +1 -0
  532. package/dist/services/plugin-job-store.js +350 -0
  533. package/dist/services/plugin-job-store.js.map +1 -0
  534. package/dist/services/plugin-lifecycle.d.ts +203 -0
  535. package/dist/services/plugin-lifecycle.d.ts.map +1 -0
  536. package/dist/services/plugin-lifecycle.js +476 -0
  537. package/dist/services/plugin-lifecycle.js.map +1 -0
  538. package/dist/services/plugin-loader.d.ts +441 -0
  539. package/dist/services/plugin-loader.d.ts.map +1 -0
  540. package/dist/services/plugin-loader.js +1192 -0
  541. package/dist/services/plugin-loader.js.map +1 -0
  542. package/dist/services/plugin-log-retention.d.ts +20 -0
  543. package/dist/services/plugin-log-retention.d.ts.map +1 -0
  544. package/dist/services/plugin-log-retention.js +63 -0
  545. package/dist/services/plugin-log-retention.js.map +1 -0
  546. package/dist/services/plugin-manifest-validator.d.ts +79 -0
  547. package/dist/services/plugin-manifest-validator.d.ts.map +1 -0
  548. package/dist/services/plugin-manifest-validator.js +84 -0
  549. package/dist/services/plugin-manifest-validator.js.map +1 -0
  550. package/dist/services/plugin-registry.d.ts +2542 -0
  551. package/dist/services/plugin-registry.d.ts.map +1 -0
  552. package/dist/services/plugin-registry.js +539 -0
  553. package/dist/services/plugin-registry.js.map +1 -0
  554. package/dist/services/plugin-runtime-sandbox.d.ts +40 -0
  555. package/dist/services/plugin-runtime-sandbox.d.ts.map +1 -0
  556. package/dist/services/plugin-runtime-sandbox.js +154 -0
  557. package/dist/services/plugin-runtime-sandbox.js.map +1 -0
  558. package/dist/services/plugin-secrets-handler.d.ts +81 -0
  559. package/dist/services/plugin-secrets-handler.d.ts.map +1 -0
  560. package/dist/services/plugin-secrets-handler.js +275 -0
  561. package/dist/services/plugin-secrets-handler.js.map +1 -0
  562. package/dist/services/plugin-state-store.d.ts +92 -0
  563. package/dist/services/plugin-state-store.d.ts.map +1 -0
  564. package/dist/services/plugin-state-store.js +190 -0
  565. package/dist/services/plugin-state-store.js.map +1 -0
  566. package/dist/services/plugin-stream-bus.d.ts +29 -0
  567. package/dist/services/plugin-stream-bus.d.ts.map +1 -0
  568. package/dist/services/plugin-stream-bus.js +48 -0
  569. package/dist/services/plugin-stream-bus.js.map +1 -0
  570. package/dist/services/plugin-tool-dispatcher.d.ts +180 -0
  571. package/dist/services/plugin-tool-dispatcher.d.ts.map +1 -0
  572. package/dist/services/plugin-tool-dispatcher.js +224 -0
  573. package/dist/services/plugin-tool-dispatcher.js.map +1 -0
  574. package/dist/services/plugin-tool-registry.d.ts +192 -0
  575. package/dist/services/plugin-tool-registry.d.ts.map +1 -0
  576. package/dist/services/plugin-tool-registry.js +224 -0
  577. package/dist/services/plugin-tool-registry.js.map +1 -0
  578. package/dist/services/plugin-worker-manager.d.ts +260 -0
  579. package/dist/services/plugin-worker-manager.d.ts.map +1 -0
  580. package/dist/services/plugin-worker-manager.js +835 -0
  581. package/dist/services/plugin-worker-manager.js.map +1 -0
  582. package/dist/services/projects.d.ts +92 -0
  583. package/dist/services/projects.d.ts.map +1 -0
  584. package/dist/services/projects.js +705 -0
  585. package/dist/services/projects.js.map +1 -0
  586. package/dist/services/quota-windows.d.ts +9 -0
  587. package/dist/services/quota-windows.d.ts.map +1 -0
  588. package/dist/services/quota-windows.js +56 -0
  589. package/dist/services/quota-windows.js.map +1 -0
  590. package/dist/services/resource-catalog.d.ts +29 -0
  591. package/dist/services/resource-catalog.d.ts.map +1 -0
  592. package/dist/services/resource-catalog.js +298 -0
  593. package/dist/services/resource-catalog.js.map +1 -0
  594. package/dist/services/run-intelligence.d.ts +31 -0
  595. package/dist/services/run-intelligence.d.ts.map +1 -0
  596. package/dist/services/run-intelligence.js +315 -0
  597. package/dist/services/run-intelligence.js.map +1 -0
  598. package/dist/services/run-log-store.d.ts +36 -0
  599. package/dist/services/run-log-store.d.ts.map +1 -0
  600. package/dist/services/run-log-store.js +114 -0
  601. package/dist/services/run-log-store.js.map +1 -0
  602. package/dist/services/runtime-kernel/heartbeat.d.ts +882 -0
  603. package/dist/services/runtime-kernel/heartbeat.d.ts.map +1 -0
  604. package/dist/services/runtime-kernel/heartbeat.js +4345 -0
  605. package/dist/services/runtime-kernel/heartbeat.js.map +1 -0
  606. package/dist/services/runtime-trace-metadata.d.ts +12 -0
  607. package/dist/services/runtime-trace-metadata.d.ts.map +1 -0
  608. package/dist/services/runtime-trace-metadata.js +13 -0
  609. package/dist/services/runtime-trace-metadata.js.map +1 -0
  610. package/dist/services/secrets.d.ts +511 -0
  611. package/dist/services/secrets.d.ts.map +1 -0
  612. package/dist/services/secrets.js +289 -0
  613. package/dist/services/secrets.js.map +1 -0
  614. package/dist/services/sidebar-badges.d.ts +11 -0
  615. package/dist/services/sidebar-badges.d.ts.map +1 -0
  616. package/dist/services/sidebar-badges.js +43 -0
  617. package/dist/services/sidebar-badges.js.map +1 -0
  618. package/dist/services/work-products.d.ts +14 -0
  619. package/dist/services/work-products.d.ts.map +1 -0
  620. package/dist/services/work-products.js +100 -0
  621. package/dist/services/work-products.js.map +1 -0
  622. package/dist/services/workspace-operation-log-store.d.ts +35 -0
  623. package/dist/services/workspace-operation-log-store.d.ts.map +1 -0
  624. package/dist/services/workspace-operation-log-store.js +115 -0
  625. package/dist/services/workspace-operation-log-store.js.map +1 -0
  626. package/dist/services/workspace-operations.d.ts +46 -0
  627. package/dist/services/workspace-operations.d.ts.map +1 -0
  628. package/dist/services/workspace-operations.js +237 -0
  629. package/dist/services/workspace-operations.js.map +1 -0
  630. package/dist/services/workspace-runtime.d.ts +164 -0
  631. package/dist/services/workspace-runtime.d.ts.map +1 -0
  632. package/dist/services/workspace-runtime.js +1235 -0
  633. package/dist/services/workspace-runtime.js.map +1 -0
  634. package/dist/startup-banner.d.ts +31 -0
  635. package/dist/startup-banner.d.ts.map +1 -0
  636. package/dist/startup-banner.js +121 -0
  637. package/dist/startup-banner.js.map +1 -0
  638. package/dist/storage/index.d.ts +6 -0
  639. package/dist/storage/index.d.ts.map +1 -0
  640. package/dist/storage/index.js +29 -0
  641. package/dist/storage/index.js.map +1 -0
  642. package/dist/storage/local-disk-provider.d.ts +3 -0
  643. package/dist/storage/local-disk-provider.d.ts.map +1 -0
  644. package/dist/storage/local-disk-provider.js +79 -0
  645. package/dist/storage/local-disk-provider.js.map +1 -0
  646. package/dist/storage/provider-registry.d.ts +4 -0
  647. package/dist/storage/provider-registry.d.ts.map +1 -0
  648. package/dist/storage/provider-registry.js +15 -0
  649. package/dist/storage/provider-registry.js.map +1 -0
  650. package/dist/storage/s3-provider.d.ts +11 -0
  651. package/dist/storage/s3-provider.d.ts.map +1 -0
  652. package/dist/storage/s3-provider.js +123 -0
  653. package/dist/storage/s3-provider.js.map +1 -0
  654. package/dist/storage/service.d.ts +3 -0
  655. package/dist/storage/service.d.ts.map +1 -0
  656. package/dist/storage/service.js +120 -0
  657. package/dist/storage/service.js.map +1 -0
  658. package/dist/storage/types.d.ts +55 -0
  659. package/dist/storage/types.d.ts.map +1 -0
  660. package/dist/storage/types.js +2 -0
  661. package/dist/storage/types.js.map +1 -0
  662. package/dist/ui-branding.d.ts +14 -0
  663. package/dist/ui-branding.d.ts.map +1 -0
  664. package/dist/ui-branding.js +201 -0
  665. package/dist/ui-branding.js.map +1 -0
  666. package/dist/version.d.ts +2 -0
  667. package/dist/version.d.ts.map +1 -0
  668. package/dist/version.js +5 -0
  669. package/dist/version.js.map +1 -0
  670. package/package.json +101 -0
  671. package/resources/bundled-skills/para-memory-files/SKILL.md +114 -0
  672. package/resources/bundled-skills/para-memory-files/references/schemas.md +35 -0
  673. package/resources/bundled-skills/rudder/SKILL.md +265 -0
  674. package/resources/bundled-skills/rudder/references/api-reference.md +253 -0
  675. package/resources/bundled-skills/rudder/references/cli-reference.md +67 -0
  676. package/resources/bundled-skills/rudder/references/organization-skills.md +155 -0
  677. package/resources/bundled-skills/rudder-create-agent/SKILL.md +166 -0
  678. package/resources/bundled-skills/rudder-create-agent/references/api-reference.md +172 -0
  679. package/resources/bundled-skills/rudder-create-agent/references/cli-reference.md +126 -0
  680. package/resources/bundled-skills/rudder-create-plugin/SKILL.md +103 -0
  681. package/resources/community-skills/deep-research/README.md +124 -0
  682. package/resources/community-skills/deep-research/SKILL.md +107 -0
  683. package/resources/community-skills/deep-research/reference/continuation.md +169 -0
  684. package/resources/community-skills/deep-research/reference/html-generation.md +103 -0
  685. package/resources/community-skills/deep-research/reference/methodology.md +421 -0
  686. package/resources/community-skills/deep-research/reference/quality-gates.md +197 -0
  687. package/resources/community-skills/deep-research/reference/report-assembly.md +119 -0
  688. package/resources/community-skills/deep-research/reference/weasyprint_guidelines.md +324 -0
  689. package/resources/community-skills/deep-research/requirements.txt +14 -0
  690. package/resources/community-skills/deep-research/scripts/citation_manager.py +177 -0
  691. package/resources/community-skills/deep-research/scripts/md_to_html.py +330 -0
  692. package/resources/community-skills/deep-research/scripts/research_engine.py +582 -0
  693. package/resources/community-skills/deep-research/scripts/source_evaluator.py +292 -0
  694. package/resources/community-skills/deep-research/scripts/validate_report.py +403 -0
  695. package/resources/community-skills/deep-research/scripts/verify_citations.py +426 -0
  696. package/resources/community-skills/deep-research/scripts/verify_html.py +220 -0
  697. package/resources/community-skills/deep-research/templates/mckinsey_report_template.html +443 -0
  698. package/resources/community-skills/deep-research/templates/report_template.md +433 -0
  699. package/resources/community-skills/skill-creator/SKILL.md +9 -0
  700. package/resources/community-skills/software-product-advisor/SKILL.md +290 -0
  701. package/skills/para-memory-files/SKILL.md +114 -0
  702. package/skills/para-memory-files/references/schemas.md +35 -0
  703. package/skills/rudder/SKILL.md +265 -0
  704. package/skills/rudder/references/api-reference.md +253 -0
  705. package/skills/rudder/references/cli-reference.md +67 -0
  706. package/skills/rudder/references/organization-skills.md +155 -0
  707. package/skills/rudder-create-agent/SKILL.md +166 -0
  708. package/skills/rudder-create-agent/references/api-reference.md +172 -0
  709. package/skills/rudder-create-agent/references/cli-reference.md +126 -0
  710. package/skills/rudder-create-plugin/SKILL.md +103 -0
  711. package/ui-dist/android-chrome-192x192.png +0 -0
  712. package/ui-dist/android-chrome-512x512.png +0 -0
  713. package/ui-dist/android-chrome-maskable-512x512.png +0 -0
  714. package/ui-dist/apple-touch-icon.png +0 -0
  715. package/ui-dist/assets/_basePickBy-CjUu04_e.js +1 -0
  716. package/ui-dist/assets/_baseUniq-C9YNlrVG.js +1 -0
  717. package/ui-dist/assets/apl-B4CMkyY2.js +1 -0
  718. package/ui-dist/assets/arc-CSSZfktq.js +1 -0
  719. package/ui-dist/assets/architectureDiagram-2XIMDMQ5-Co78JKUi.js +36 -0
  720. package/ui-dist/assets/asciiarmor-Df11BRmG.js +1 -0
  721. package/ui-dist/assets/asn1-EdZsLKOL.js +1 -0
  722. package/ui-dist/assets/asterisk-B-8jnY81.js +1 -0
  723. package/ui-dist/assets/blockDiagram-WCTKOSBZ-2KUUIzzz.js +132 -0
  724. package/ui-dist/assets/brainfuck-C4LP7Hcl.js +1 -0
  725. package/ui-dist/assets/c4Diagram-IC4MRINW-C6pq8tPP.js +10 -0
  726. package/ui-dist/assets/channel-BEODbRMk.js +1 -0
  727. package/ui-dist/assets/chunk-4BX2VUAB-ojCLkixe.js +1 -0
  728. package/ui-dist/assets/chunk-55IACEB6-MGONqzmz.js +1 -0
  729. package/ui-dist/assets/chunk-FMBD7UC4-CmGuLv2P.js +15 -0
  730. package/ui-dist/assets/chunk-JSJVCQXG-BNBefVr6.js +1 -0
  731. package/ui-dist/assets/chunk-KX2RTZJC-DIGBQLn5.js +1 -0
  732. package/ui-dist/assets/chunk-NQ4KR5QH-_KEutsaQ.js +220 -0
  733. package/ui-dist/assets/chunk-QZHKN3VN-B6pzyuwm.js +1 -0
  734. package/ui-dist/assets/chunk-WL4C6EOR-B8NDzcfm.js +189 -0
  735. package/ui-dist/assets/classDiagram-VBA2DB6C-CsSqaaRj.js +1 -0
  736. package/ui-dist/assets/classDiagram-v2-RAHNMMFH-CsSqaaRj.js +1 -0
  737. package/ui-dist/assets/clike-B9uivgTg.js +1 -0
  738. package/ui-dist/assets/clojure-BMjYHr_A.js +1 -0
  739. package/ui-dist/assets/clone-5oWMCI0u.js +1 -0
  740. package/ui-dist/assets/cmake-BQqOBYOt.js +1 -0
  741. package/ui-dist/assets/cobol-CWcv1MsR.js +1 -0
  742. package/ui-dist/assets/coffeescript-S37ZYGWr.js +1 -0
  743. package/ui-dist/assets/commonlisp-DBKNyK5s.js +1 -0
  744. package/ui-dist/assets/cose-bilkent-S5V4N54A-B1t6ulcV.js +1 -0
  745. package/ui-dist/assets/crystal-SjHAIU92.js +1 -0
  746. package/ui-dist/assets/css-BnMrqG3P.js +1 -0
  747. package/ui-dist/assets/cypher-C_CwsFkJ.js +1 -0
  748. package/ui-dist/assets/cytoscape.esm-BQaXIfA_.js +331 -0
  749. package/ui-dist/assets/d-pRatUO7H.js +1 -0
  750. package/ui-dist/assets/dagre-KLK3FWXG-DWVC5_HJ.js +4 -0
  751. package/ui-dist/assets/defaultLocale-DX6XiGOO.js +1 -0
  752. package/ui-dist/assets/diagram-E7M64L7V-C4ztYLox.js +24 -0
  753. package/ui-dist/assets/diagram-IFDJBPK2-DtWBGLnA.js +43 -0
  754. package/ui-dist/assets/diagram-P4PSJMXO-BiqiI4Df.js +24 -0
  755. package/ui-dist/assets/diff-DbItnlRl.js +1 -0
  756. package/ui-dist/assets/dockerfile-BKs6k2Af.js +1 -0
  757. package/ui-dist/assets/dtd-DF_7sFjM.js +1 -0
  758. package/ui-dist/assets/dylan-DwRh75JA.js +1 -0
  759. package/ui-dist/assets/ebnf-CDyGwa7X.js +1 -0
  760. package/ui-dist/assets/ecl-Cabwm37j.js +1 -0
  761. package/ui-dist/assets/eiffel-CnydiIhH.js +1 -0
  762. package/ui-dist/assets/elm-vLlmbW-K.js +1 -0
  763. package/ui-dist/assets/erDiagram-INFDFZHY-CUhr9rIh.js +70 -0
  764. package/ui-dist/assets/erlang-BNw1qcRV.js +1 -0
  765. package/ui-dist/assets/factor-kuTfRLto.js +1 -0
  766. package/ui-dist/assets/fcl-Kvtd6kyn.js +1 -0
  767. package/ui-dist/assets/flowDiagram-PKNHOUZH-BEqBmNL-.js +162 -0
  768. package/ui-dist/assets/forth-Ffai-XNe.js +1 -0
  769. package/ui-dist/assets/fortran-DYz_wnZ1.js +1 -0
  770. package/ui-dist/assets/ganttDiagram-A5KZAMGK-CdeWhdno.js +292 -0
  771. package/ui-dist/assets/gas-Bneqetm1.js +1 -0
  772. package/ui-dist/assets/gherkin-heZmZLOM.js +1 -0
  773. package/ui-dist/assets/gitGraphDiagram-K3NZZRJ6-CgG66QFg.js +65 -0
  774. package/ui-dist/assets/graph-rmownl79.js +1 -0
  775. package/ui-dist/assets/groovy-D9Dt4D0W.js +1 -0
  776. package/ui-dist/assets/haskell-Cw1EW3IL.js +1 -0
  777. package/ui-dist/assets/haxe-H-WmDvRZ.js +1 -0
  778. package/ui-dist/assets/http-DBlCnlav.js +1 -0
  779. package/ui-dist/assets/idl-BEugSyMb.js +1 -0
  780. package/ui-dist/assets/index-B1YyDqaG.js +1 -0
  781. package/ui-dist/assets/index-B7exNxYd.js +1 -0
  782. package/ui-dist/assets/index-BIuriVDl.js +1 -0
  783. package/ui-dist/assets/index-BT9rfwYt.js +1 -0
  784. package/ui-dist/assets/index-BZhmacJG.js +1 -0
  785. package/ui-dist/assets/index-B_ebS3U_.js +3 -0
  786. package/ui-dist/assets/index-BnQqZOsc.js +1 -0
  787. package/ui-dist/assets/index-BwPbAax6.js +1 -0
  788. package/ui-dist/assets/index-C5i670o5.js +1 -0
  789. package/ui-dist/assets/index-C9KwE7Yr.js +1 -0
  790. package/ui-dist/assets/index-CDId_UjP.js +1 -0
  791. package/ui-dist/assets/index-CI9ydSGM.js +1 -0
  792. package/ui-dist/assets/index-CKpm3WGI.css +1 -0
  793. package/ui-dist/assets/index-CMP_bzP3.js +2 -0
  794. package/ui-dist/assets/index-CRcHIoCW.js +1 -0
  795. package/ui-dist/assets/index-DZqNY-Lg.js +1 -0
  796. package/ui-dist/assets/index-DbDKJhW-.js +7 -0
  797. package/ui-dist/assets/index-Dkg6MwQ_.js +1 -0
  798. package/ui-dist/assets/index-Dn0iitKg.js +1 -0
  799. package/ui-dist/assets/index-GvHywIOA.js +1323 -0
  800. package/ui-dist/assets/index-WtX4Y4Fx.js +13 -0
  801. package/ui-dist/assets/index-iyC5PHC3.js +6 -0
  802. package/ui-dist/assets/index-jMlzlqoV.js +1 -0
  803. package/ui-dist/assets/index-pTIOLGTe.js +1 -0
  804. package/ui-dist/assets/infoDiagram-LFFYTUFH-CEhdbTYQ.js +2 -0
  805. package/ui-dist/assets/init-Gi6I4Gst.js +1 -0
  806. package/ui-dist/assets/ishikawaDiagram-PHBUUO56-g9GiiXI2.js +70 -0
  807. package/ui-dist/assets/javascript-iXu5QeM3.js +1 -0
  808. package/ui-dist/assets/journeyDiagram-4ABVD52K-CheeZzlg.js +139 -0
  809. package/ui-dist/assets/julia-DuME0IfC.js +1 -0
  810. package/ui-dist/assets/kanban-definition-K7BYSVSG-BTpuAgUJ.js +89 -0
  811. package/ui-dist/assets/katex-B1X10hvy.js +261 -0
  812. package/ui-dist/assets/layout-CuBgufef.js +1 -0
  813. package/ui-dist/assets/linear-CnXO6wXw.js +1 -0
  814. package/ui-dist/assets/livescript-BwQOo05w.js +1 -0
  815. package/ui-dist/assets/lua-BgMRiT3U.js +1 -0
  816. package/ui-dist/assets/mathematica-DTrFuWx2.js +1 -0
  817. package/ui-dist/assets/mbox-CNhZ1qSd.js +1 -0
  818. package/ui-dist/assets/mermaid.core-DVaYxfh9.js +255 -0
  819. package/ui-dist/assets/mindmap-definition-YRQLILUH-00nAuexq.js +68 -0
  820. package/ui-dist/assets/mirc-CjQqDB4T.js +1 -0
  821. package/ui-dist/assets/mllike-CXdrOF99.js +1 -0
  822. package/ui-dist/assets/modelica-Dc1JOy9r.js +1 -0
  823. package/ui-dist/assets/mscgen-BA5vi2Kp.js +1 -0
  824. package/ui-dist/assets/mumps-BT43cFF4.js +1 -0
  825. package/ui-dist/assets/nginx-DdIZxoE0.js +1 -0
  826. package/ui-dist/assets/nsis-LdVXkNf5.js +1 -0
  827. package/ui-dist/assets/ntriples-BfvgReVJ.js +1 -0
  828. package/ui-dist/assets/octave-Ck1zUtKM.js +1 -0
  829. package/ui-dist/assets/ordinal-Cboi1Yqb.js +1 -0
  830. package/ui-dist/assets/oz-BzwKVEFT.js +1 -0
  831. package/ui-dist/assets/pascal--L3eBynH.js +1 -0
  832. package/ui-dist/assets/perl-CdXCOZ3F.js +1 -0
  833. package/ui-dist/assets/pieDiagram-SKSYHLDU-NaOgRqIj.js +30 -0
  834. package/ui-dist/assets/pig-CevX1Tat.js +1 -0
  835. package/ui-dist/assets/powershell-CFHJl5sT.js +1 -0
  836. package/ui-dist/assets/properties-C78fOPTZ.js +1 -0
  837. package/ui-dist/assets/protobuf-ChK-085T.js +1 -0
  838. package/ui-dist/assets/pug-DeIclll2.js +1 -0
  839. package/ui-dist/assets/puppet-DMA9R1ak.js +1 -0
  840. package/ui-dist/assets/python-BuPzkPfP.js +1 -0
  841. package/ui-dist/assets/q-pXgVlZs6.js +1 -0
  842. package/ui-dist/assets/quadrantDiagram-337W2JSQ-Bnf9OCW0.js +7 -0
  843. package/ui-dist/assets/r-B6wPVr8A.js +1 -0
  844. package/ui-dist/assets/requirementDiagram-Z7DCOOCP-BiacZTTh.js +73 -0
  845. package/ui-dist/assets/rpm-CTu-6PCP.js +1 -0
  846. package/ui-dist/assets/ruby-B2Rjki9n.js +1 -0
  847. package/ui-dist/assets/sankeyDiagram-WA2Y5GQK-DOuD4D2Q.js +10 -0
  848. package/ui-dist/assets/sas-B4kiWyti.js +1 -0
  849. package/ui-dist/assets/scheme-C41bIUwD.js +1 -0
  850. package/ui-dist/assets/sequenceDiagram-2WXFIKYE-oV3M_w-H.js +145 -0
  851. package/ui-dist/assets/shell-CjFT_Tl9.js +1 -0
  852. package/ui-dist/assets/sieve-C3Gn_uJK.js +1 -0
  853. package/ui-dist/assets/simple-mode-GW_nhZxv.js +1 -0
  854. package/ui-dist/assets/smalltalk-CnHTOXQT.js +1 -0
  855. package/ui-dist/assets/solr-DehyRSwq.js +1 -0
  856. package/ui-dist/assets/sparql-DkYu6x3z.js +1 -0
  857. package/ui-dist/assets/spreadsheet-BCZA_wO0.js +1 -0
  858. package/ui-dist/assets/sql-D0XecflT.js +1 -0
  859. package/ui-dist/assets/stateDiagram-RAJIS63D-CdRc2Pqb.js +1 -0
  860. package/ui-dist/assets/stateDiagram-v2-FVOUBMTO-CIMHFJYg.js +1 -0
  861. package/ui-dist/assets/stex-C3f8Ysf7.js +1 -0
  862. package/ui-dist/assets/stylus-B533Al4x.js +1 -0
  863. package/ui-dist/assets/swift-BzpIVaGY.js +1 -0
  864. package/ui-dist/assets/tcl-DVfN8rqt.js +1 -0
  865. package/ui-dist/assets/textile-CnDTJFAw.js +1 -0
  866. package/ui-dist/assets/tiddlywiki-DO-Gjzrf.js +1 -0
  867. package/ui-dist/assets/tiki-DGYXhP31.js +1 -0
  868. package/ui-dist/assets/timeline-definition-YZTLITO2-BCWQDIwt.js +61 -0
  869. package/ui-dist/assets/toml-Bm5Em-hy.js +1 -0
  870. package/ui-dist/assets/treemap-KZPCXAKY-BvsIxXAi.js +162 -0
  871. package/ui-dist/assets/troff-wAsdV37c.js +1 -0
  872. package/ui-dist/assets/ttcn-CfJYG6tj.js +1 -0
  873. package/ui-dist/assets/ttcn-cfg-B9xdYoR4.js +1 -0
  874. package/ui-dist/assets/turtle-B1tBg_DP.js +1 -0
  875. package/ui-dist/assets/vb-CmGdzxic.js +1 -0
  876. package/ui-dist/assets/vbscript-BuJXcnF6.js +1 -0
  877. package/ui-dist/assets/velocity-D8B20fx6.js +1 -0
  878. package/ui-dist/assets/vennDiagram-LZ73GAT5-BzibHs4r.js +34 -0
  879. package/ui-dist/assets/verilog-C6RDOZhf.js +1 -0
  880. package/ui-dist/assets/vhdl-lSbBsy5d.js +1 -0
  881. package/ui-dist/assets/webidl-ZXfAyPTL.js +1 -0
  882. package/ui-dist/assets/xquery-DzFWVndE.js +1 -0
  883. package/ui-dist/assets/xychartDiagram-JWTSCODW-CX_Xt_y-.js +7 -0
  884. package/ui-dist/assets/yacas-BJ4BC0dw.js +1 -0
  885. package/ui-dist/assets/z80-Hz9HOZM7.js +1 -0
  886. package/ui-dist/brands/opencode-logo-dark-square.svg +18 -0
  887. package/ui-dist/brands/opencode-logo-light-square.svg +18 -0
  888. package/ui-dist/favicon-16x16.png +0 -0
  889. package/ui-dist/favicon-32x32.png +0 -0
  890. package/ui-dist/favicon-dev-16x16.png +0 -0
  891. package/ui-dist/favicon-dev-32x32.png +0 -0
  892. package/ui-dist/favicon-dev.ico +0 -0
  893. package/ui-dist/favicon.ico +0 -0
  894. package/ui-dist/favicon.svg +1 -0
  895. package/ui-dist/index.html +61 -0
  896. package/ui-dist/rudder-logo.png +0 -0
  897. package/ui-dist/site.webmanifest +30 -0
  898. package/ui-dist/sw.js +42 -0
  899. package/ui-dist/worktree-favicon-16x16.png +0 -0
  900. package/ui-dist/worktree-favicon-32x32.png +0 -0
  901. package/ui-dist/worktree-favicon.ico +0 -0
  902. package/ui-dist/worktree-favicon.svg +1 -0
@@ -0,0 +1,2266 @@
1
+ import { createHash, generateKeyPairSync, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { Router } from "express";
6
+ import { and, eq, isNull, desc } from "drizzle-orm";
7
+ import { agentApiKeys, authUsers, invites, joinRequests } from "@rudderhq/db";
8
+ import { acceptInviteSchema, createCliAuthChallengeSchema, claimJoinRequestApiKeySchema, createCompanyInviteSchema, createOpenClawInvitePromptSchema, listJoinRequestsQuerySchema, resolveCliAuthChallengeSchema, updateMemberPermissionsSchema, updateUserCompanyAccessSchema, PERMISSION_KEYS } from "@rudderhq/shared";
9
+ import { forbidden, conflict, notFound, unauthorized, badRequest } from "../errors.js";
10
+ import { logger } from "../middleware/logger.js";
11
+ import { validate } from "../middleware/validate.js";
12
+ import { accessService, agentService, boardAuthService, deduplicateAgentName, logActivity, notifyHireApproved } from "../services/index.js";
13
+ import { assertCompanyAccess } from "./authz.js";
14
+ import { claimBoardOwnership, inspectBoardClaimChallenge } from "../board-claim.js";
15
+ function hashToken(token) {
16
+ return createHash("sha256").update(token).digest("hex");
17
+ }
18
+ const INVITE_TOKEN_PREFIX = "pcp_invite_";
19
+ const INVITE_TOKEN_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
20
+ const INVITE_TOKEN_SUFFIX_LENGTH = 8;
21
+ const INVITE_TOKEN_MAX_RETRIES = 5;
22
+ const COMPANY_INVITE_TTL_MS = 10 * 60 * 1000;
23
+ function createInviteToken() {
24
+ const bytes = randomBytes(INVITE_TOKEN_SUFFIX_LENGTH);
25
+ let suffix = "";
26
+ for (let idx = 0; idx < INVITE_TOKEN_SUFFIX_LENGTH; idx += 1) {
27
+ suffix += INVITE_TOKEN_ALPHABET[bytes[idx] % INVITE_TOKEN_ALPHABET.length];
28
+ }
29
+ return `${INVITE_TOKEN_PREFIX}${suffix}`;
30
+ }
31
+ function createClaimSecret() {
32
+ return `pcp_claim_${randomBytes(24).toString("hex")}`;
33
+ }
34
+ export function companyInviteExpiresAt(nowMs = Date.now()) {
35
+ return new Date(nowMs + COMPANY_INVITE_TTL_MS);
36
+ }
37
+ function tokenHashesMatch(left, right) {
38
+ const leftBytes = Buffer.from(left, "utf8");
39
+ const rightBytes = Buffer.from(right, "utf8");
40
+ return (leftBytes.length === rightBytes.length &&
41
+ timingSafeEqual(leftBytes, rightBytes));
42
+ }
43
+ function requestBaseUrl(req) {
44
+ const forwardedProto = req.header("x-forwarded-proto");
45
+ const proto = forwardedProto?.split(",")[0]?.trim() || req.protocol || "http";
46
+ const host = req.header("x-forwarded-host")?.split(",")[0]?.trim() || req.header("host");
47
+ if (!host)
48
+ return "";
49
+ return `${proto}://${host}`;
50
+ }
51
+ function buildCliAuthApprovalPath(challengeId, token) {
52
+ return `/cli-auth/${challengeId}?token=${encodeURIComponent(token)}`;
53
+ }
54
+ function readSkillMarkdown(skillName) {
55
+ const normalized = skillName.trim().toLowerCase();
56
+ if (normalized !== "rudder" &&
57
+ normalized !== "rudder-create-agent" &&
58
+ // TODO 2026-04-12 15:42:09: disabled: not used yet; will be re-enabled when plugin scaffold is ready
59
+ // normalized !== "rudder-create-plugin" &&
60
+ normalized !== "para-memory-files")
61
+ return null;
62
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
63
+ const candidates = [
64
+ path.resolve(moduleDir, "../../resources/bundled-skills", normalized, "SKILL.md"), // published: dist/routes/ -> server/resources/bundled-skills/
65
+ path.resolve(process.cwd(), "server/resources/bundled-skills", normalized, "SKILL.md"), // cwd (e.g. monorepo root)
66
+ path.resolve(moduleDir, "../../../server/resources/bundled-skills", normalized, "SKILL.md"), // dev: src/routes/ -> repo root/server/resources/bundled-skills/
67
+ path.resolve(moduleDir, "../../.agents/skills", normalized, "SKILL.md"), // legacy published fallback
68
+ path.resolve(process.cwd(), ".agents/skills", normalized, "SKILL.md"), // legacy cwd fallback
69
+ path.resolve(moduleDir, "../../../.agents/skills", normalized, "SKILL.md"), // legacy dev fallback
70
+ path.resolve(moduleDir, "../../skills", normalized, "SKILL.md"), // legacy fallback
71
+ path.resolve(process.cwd(), "skills", normalized, "SKILL.md"), // legacy fallback
72
+ path.resolve(moduleDir, "../../../skills", normalized, "SKILL.md"), // legacy fallback
73
+ ];
74
+ for (const skillPath of candidates) {
75
+ try {
76
+ return fs.readFileSync(skillPath, "utf8");
77
+ }
78
+ catch {
79
+ // Continue to next candidate.
80
+ }
81
+ }
82
+ return null;
83
+ }
84
+ /** Resolve the Rudder repo skill directory (built-in / managed skills). */
85
+ function resolveRudderSkillsDir() {
86
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
87
+ const candidates = [
88
+ path.resolve(moduleDir, "../../resources/bundled-skills"), // published
89
+ path.resolve(process.cwd(), "server/resources/bundled-skills"), // cwd (monorepo root)
90
+ path.resolve(moduleDir, "../../../server/resources/bundled-skills"), // dev
91
+ path.resolve(moduleDir, "../../.agents/skills"), // legacy published fallback
92
+ path.resolve(process.cwd(), ".agents/skills"), // legacy cwd fallback
93
+ path.resolve(moduleDir, "../../../.agents/skills"), // legacy dev fallback
94
+ path.resolve(moduleDir, "../../skills"), // legacy fallback
95
+ path.resolve(process.cwd(), "skills"), // legacy fallback
96
+ path.resolve(moduleDir, "../../../skills"), // legacy fallback
97
+ ];
98
+ for (const candidate of candidates) {
99
+ try {
100
+ if (fs.statSync(candidate).isDirectory())
101
+ return candidate;
102
+ }
103
+ catch { /* skip */ }
104
+ }
105
+ return null;
106
+ }
107
+ /** Parse YAML frontmatter from a SKILL.md file to extract the description. */
108
+ function parseSkillFrontmatter(markdown) {
109
+ const match = markdown.match(/^---\n([\s\S]*?)\n---/);
110
+ if (!match)
111
+ return { description: "" };
112
+ const yaml = match[1];
113
+ // Extract description — handles both single-line and multi-line YAML values
114
+ const descMatch = yaml.match(/^description:\s*(?:>\s*\n((?:\s{2,}[^\n]*\n?)+)|[|]\s*\n((?:\s{2,}[^\n]*\n?)+)|["']?(.*?)["']?\s*$)/m);
115
+ if (!descMatch)
116
+ return { description: "" };
117
+ const raw = descMatch[1] ?? descMatch[2] ?? descMatch[3] ?? "";
118
+ return {
119
+ description: raw
120
+ .split("\n")
121
+ .map((l) => l.trim())
122
+ .filter(Boolean)
123
+ .join(" ")
124
+ .trim(),
125
+ };
126
+ }
127
+ /** Discover user-installed Claude Code skills from ~/.claude/skills/. */
128
+ function listAvailableSkills() {
129
+ const homeDir = process.env.HOME || process.env.USERPROFILE || "";
130
+ const claudeSkillsDir = path.join(homeDir, ".claude", "skills");
131
+ const rudderSkillsDir = resolveRudderSkillsDir();
132
+ // Build set of Rudder-managed skill names
133
+ const rudderSkillNames = new Set();
134
+ if (rudderSkillsDir) {
135
+ try {
136
+ for (const entry of fs.readdirSync(rudderSkillsDir, { withFileTypes: true })) {
137
+ if (entry.isDirectory())
138
+ rudderSkillNames.add(entry.name);
139
+ }
140
+ }
141
+ catch { /* skip */ }
142
+ }
143
+ const skills = [];
144
+ try {
145
+ const entries = fs.readdirSync(claudeSkillsDir, { withFileTypes: true });
146
+ for (const entry of entries) {
147
+ if (!entry.isDirectory() && !entry.isSymbolicLink())
148
+ continue;
149
+ if (entry.name.startsWith("."))
150
+ continue;
151
+ const skillMdPath = path.join(claudeSkillsDir, entry.name, "SKILL.md");
152
+ let description = "";
153
+ try {
154
+ const md = fs.readFileSync(skillMdPath, "utf8");
155
+ description = parseSkillFrontmatter(md).description;
156
+ }
157
+ catch { /* no SKILL.md or unreadable */ }
158
+ skills.push({
159
+ name: entry.name,
160
+ description,
161
+ isRudderManaged: rudderSkillNames.has(entry.name),
162
+ });
163
+ }
164
+ }
165
+ catch { /* ~/.claude/skills/ doesn't exist */ }
166
+ skills.sort((a, b) => a.name.localeCompare(b.name));
167
+ return skills;
168
+ }
169
+ function toJoinRequestResponse(row) {
170
+ const { claimSecretHash: _claimSecretHash, ...safe } = row;
171
+ return safe;
172
+ }
173
+ function isPlainObject(value) {
174
+ return typeof value === "object" && value !== null && !Array.isArray(value);
175
+ }
176
+ function isLoopbackHost(hostname) {
177
+ const value = hostname.trim().toLowerCase();
178
+ return value === "localhost" || value === "127.0.0.1" || value === "::1";
179
+ }
180
+ function normalizeHostname(value) {
181
+ if (!value)
182
+ return null;
183
+ const trimmed = value.trim();
184
+ if (!trimmed)
185
+ return null;
186
+ if (trimmed.startsWith("[")) {
187
+ const end = trimmed.indexOf("]");
188
+ return end > 1
189
+ ? trimmed.slice(1, end).toLowerCase()
190
+ : trimmed.toLowerCase();
191
+ }
192
+ const firstColon = trimmed.indexOf(":");
193
+ if (firstColon > -1)
194
+ return trimmed.slice(0, firstColon).toLowerCase();
195
+ return trimmed.toLowerCase();
196
+ }
197
+ function normalizeHeaderValue(value, depth = 0) {
198
+ const direct = nonEmptyTrimmedString(value);
199
+ if (direct)
200
+ return direct;
201
+ if (!isPlainObject(value) || depth >= 3)
202
+ return null;
203
+ const candidateKeys = [
204
+ "value",
205
+ "token",
206
+ "secret",
207
+ "apiKey",
208
+ "api_key",
209
+ "auth",
210
+ "authToken",
211
+ "auth_token",
212
+ "accessToken",
213
+ "access_token",
214
+ "authorization",
215
+ "bearer",
216
+ "header",
217
+ "raw",
218
+ "text",
219
+ "string"
220
+ ];
221
+ for (const key of candidateKeys) {
222
+ if (!Object.prototype.hasOwnProperty.call(value, key))
223
+ continue;
224
+ const normalized = normalizeHeaderValue(value[key], depth + 1);
225
+ if (normalized)
226
+ return normalized;
227
+ }
228
+ const entries = Object.entries(value);
229
+ if (entries.length === 1) {
230
+ const [singleKey, singleValue] = entries[0];
231
+ const normalizedKey = singleKey.trim().toLowerCase();
232
+ if (normalizedKey !== "type" &&
233
+ normalizedKey !== "version" &&
234
+ normalizedKey !== "secretid" &&
235
+ normalizedKey !== "secret_id") {
236
+ const normalized = normalizeHeaderValue(singleValue, depth + 1);
237
+ if (normalized)
238
+ return normalized;
239
+ }
240
+ }
241
+ return null;
242
+ }
243
+ function extractHeaderEntries(input) {
244
+ if (isPlainObject(input)) {
245
+ return Object.entries(input);
246
+ }
247
+ if (!Array.isArray(input)) {
248
+ return [];
249
+ }
250
+ const entries = [];
251
+ for (const item of input) {
252
+ if (Array.isArray(item)) {
253
+ const key = nonEmptyTrimmedString(item[0]);
254
+ if (!key)
255
+ continue;
256
+ entries.push([key, item[1]]);
257
+ continue;
258
+ }
259
+ if (!isPlainObject(item))
260
+ continue;
261
+ const mapped = item;
262
+ const explicitKey = nonEmptyTrimmedString(mapped.key) ??
263
+ nonEmptyTrimmedString(mapped.name) ??
264
+ nonEmptyTrimmedString(mapped.header);
265
+ if (explicitKey) {
266
+ const explicitValue = Object.prototype.hasOwnProperty.call(mapped, "value")
267
+ ? mapped.value
268
+ : Object.prototype.hasOwnProperty.call(mapped, "token")
269
+ ? mapped.token
270
+ : Object.prototype.hasOwnProperty.call(mapped, "secret")
271
+ ? mapped.secret
272
+ : mapped;
273
+ entries.push([explicitKey, explicitValue]);
274
+ continue;
275
+ }
276
+ const singleEntry = Object.entries(mapped);
277
+ if (singleEntry.length === 1) {
278
+ entries.push(singleEntry[0]);
279
+ }
280
+ }
281
+ return entries;
282
+ }
283
+ function normalizeHeaderMap(input) {
284
+ const entries = extractHeaderEntries(input);
285
+ if (entries.length === 0)
286
+ return undefined;
287
+ const out = {};
288
+ for (const [key, value] of entries) {
289
+ const normalizedValue = normalizeHeaderValue(value);
290
+ if (!normalizedValue)
291
+ continue;
292
+ const trimmedKey = key.trim();
293
+ const trimmedValue = normalizedValue.trim();
294
+ if (!trimmedKey || !trimmedValue)
295
+ continue;
296
+ out[trimmedKey] = trimmedValue;
297
+ }
298
+ return Object.keys(out).length > 0 ? out : undefined;
299
+ }
300
+ function nonEmptyTrimmedString(value) {
301
+ if (typeof value !== "string")
302
+ return null;
303
+ const trimmed = value.trim();
304
+ return trimmed.length > 0 ? trimmed : null;
305
+ }
306
+ function headerMapHasKeyIgnoreCase(headers, targetKey) {
307
+ const normalizedTarget = targetKey.trim().toLowerCase();
308
+ return Object.keys(headers).some((key) => key.trim().toLowerCase() === normalizedTarget);
309
+ }
310
+ function headerMapGetIgnoreCase(headers, targetKey) {
311
+ const normalizedTarget = targetKey.trim().toLowerCase();
312
+ const key = Object.keys(headers).find((candidate) => candidate.trim().toLowerCase() === normalizedTarget);
313
+ if (!key)
314
+ return null;
315
+ const value = headers[key];
316
+ return typeof value === "string" ? value : null;
317
+ }
318
+ function tokenFromAuthorizationHeader(rawHeader) {
319
+ const trimmed = nonEmptyTrimmedString(rawHeader);
320
+ if (!trimmed)
321
+ return null;
322
+ const bearerMatch = trimmed.match(/^bearer\s+(.+)$/i);
323
+ if (bearerMatch?.[1]) {
324
+ return nonEmptyTrimmedString(bearerMatch[1]);
325
+ }
326
+ return trimmed;
327
+ }
328
+ function parseBooleanLike(value) {
329
+ if (typeof value === "boolean")
330
+ return value;
331
+ if (typeof value !== "string")
332
+ return null;
333
+ const normalized = value.trim().toLowerCase();
334
+ if (normalized === "true" || normalized === "1")
335
+ return true;
336
+ if (normalized === "false" || normalized === "0")
337
+ return false;
338
+ return null;
339
+ }
340
+ function generateEd25519PrivateKeyPem() {
341
+ const generated = generateKeyPairSync("ed25519");
342
+ return generated.privateKey
343
+ .export({ type: "pkcs8", format: "pem" })
344
+ .toString();
345
+ }
346
+ export function buildJoinDefaultsPayloadForAccept(input) {
347
+ if (input.agentRuntimeType !== "openclaw_gateway") {
348
+ return input.defaultsPayload;
349
+ }
350
+ const merged = isPlainObject(input.defaultsPayload)
351
+ ? { ...input.defaultsPayload }
352
+ : {};
353
+ if (!nonEmptyTrimmedString(merged.rudderApiUrl)) {
354
+ const legacyPaperclipApiUrl = nonEmptyTrimmedString(input.paperclipApiUrl);
355
+ if (legacyPaperclipApiUrl)
356
+ merged.rudderApiUrl = legacyPaperclipApiUrl;
357
+ }
358
+ const mergedHeaders = normalizeHeaderMap(merged.headers) ?? {};
359
+ const inboundOpenClawAuthHeader = nonEmptyTrimmedString(input.inboundOpenClawAuthHeader);
360
+ const inboundOpenClawTokenHeader = nonEmptyTrimmedString(input.inboundOpenClawTokenHeader);
361
+ if (inboundOpenClawTokenHeader &&
362
+ !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-token")) {
363
+ mergedHeaders["x-openclaw-token"] = inboundOpenClawTokenHeader;
364
+ }
365
+ if (inboundOpenClawAuthHeader &&
366
+ !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-auth")) {
367
+ mergedHeaders["x-openclaw-auth"] = inboundOpenClawAuthHeader;
368
+ }
369
+ if (Object.keys(mergedHeaders).length > 0) {
370
+ merged.headers = mergedHeaders;
371
+ }
372
+ else {
373
+ delete merged.headers;
374
+ }
375
+ const discoveredToken = headerMapGetIgnoreCase(mergedHeaders, "x-openclaw-token") ??
376
+ headerMapGetIgnoreCase(mergedHeaders, "x-openclaw-auth") ??
377
+ tokenFromAuthorizationHeader(headerMapGetIgnoreCase(mergedHeaders, "authorization"));
378
+ if (discoveredToken &&
379
+ !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-token")) {
380
+ mergedHeaders["x-openclaw-token"] = discoveredToken;
381
+ }
382
+ return Object.keys(merged).length > 0 ? merged : null;
383
+ }
384
+ export function mergeJoinDefaultsPayloadForReplay(existingDefaultsPayload, nextDefaultsPayload) {
385
+ if (!isPlainObject(existingDefaultsPayload) &&
386
+ !isPlainObject(nextDefaultsPayload)) {
387
+ return nextDefaultsPayload ?? existingDefaultsPayload;
388
+ }
389
+ if (!isPlainObject(existingDefaultsPayload)) {
390
+ return nextDefaultsPayload;
391
+ }
392
+ if (!isPlainObject(nextDefaultsPayload)) {
393
+ return existingDefaultsPayload;
394
+ }
395
+ const merged = {
396
+ ...existingDefaultsPayload,
397
+ ...nextDefaultsPayload
398
+ };
399
+ const existingHeaders = normalizeHeaderMap(existingDefaultsPayload.headers);
400
+ const nextHeaders = normalizeHeaderMap(nextDefaultsPayload.headers);
401
+ if (existingHeaders || nextHeaders) {
402
+ merged.headers = {
403
+ ...(existingHeaders ?? {}),
404
+ ...(nextHeaders ?? {})
405
+ };
406
+ }
407
+ else if (Object.prototype.hasOwnProperty.call(merged, "headers")) {
408
+ delete merged.headers;
409
+ }
410
+ return merged;
411
+ }
412
+ export function canReplayOpenClawGatewayInviteAccept(input) {
413
+ if (input.requestType !== "agent" ||
414
+ input.agentRuntimeType !== "openclaw_gateway") {
415
+ return false;
416
+ }
417
+ if (!input.existingJoinRequest) {
418
+ return false;
419
+ }
420
+ if (input.existingJoinRequest.requestType !== "agent" ||
421
+ input.existingJoinRequest.agentRuntimeType !== "openclaw_gateway") {
422
+ return false;
423
+ }
424
+ return (input.existingJoinRequest.status === "pending_approval" ||
425
+ input.existingJoinRequest.status === "approved");
426
+ }
427
+ function summarizeSecretForLog(value) {
428
+ const trimmed = nonEmptyTrimmedString(value);
429
+ if (!trimmed)
430
+ return null;
431
+ return {
432
+ present: true,
433
+ length: trimmed.length,
434
+ sha256Prefix: hashToken(trimmed).slice(0, 12)
435
+ };
436
+ }
437
+ function summarizeOpenClawGatewayDefaultsForLog(defaultsPayload) {
438
+ const defaults = isPlainObject(defaultsPayload)
439
+ ? defaultsPayload
440
+ : null;
441
+ const headers = defaults ? normalizeHeaderMap(defaults.headers) : undefined;
442
+ const gatewayTokenValue = headers
443
+ ? headerMapGetIgnoreCase(headers, "x-openclaw-token") ??
444
+ headerMapGetIgnoreCase(headers, "x-openclaw-auth") ??
445
+ tokenFromAuthorizationHeader(headerMapGetIgnoreCase(headers, "authorization"))
446
+ : null;
447
+ return {
448
+ present: Boolean(defaults),
449
+ keys: defaults ? Object.keys(defaults).sort() : [],
450
+ url: defaults ? nonEmptyTrimmedString(defaults.url) : null,
451
+ rudderApiUrl: defaults
452
+ ? nonEmptyTrimmedString(defaults.rudderApiUrl)
453
+ : null,
454
+ headerKeys: headers ? Object.keys(headers).sort() : [],
455
+ sessionKeyStrategy: defaults
456
+ ? nonEmptyTrimmedString(defaults.sessionKeyStrategy)
457
+ : null,
458
+ disableDeviceAuth: defaults
459
+ ? parseBooleanLike(defaults.disableDeviceAuth)
460
+ : null,
461
+ waitTimeoutMs: defaults && typeof defaults.waitTimeoutMs === "number"
462
+ ? defaults.waitTimeoutMs
463
+ : null,
464
+ devicePrivateKeyPem: defaults
465
+ ? summarizeSecretForLog(defaults.devicePrivateKeyPem)
466
+ : null,
467
+ gatewayToken: summarizeSecretForLog(gatewayTokenValue)
468
+ };
469
+ }
470
+ export function normalizeAgentDefaultsForJoin(input) {
471
+ const fatalErrors = [];
472
+ const diagnostics = [];
473
+ if (input.agentRuntimeType !== "openclaw_gateway") {
474
+ const normalized = isPlainObject(input.defaultsPayload)
475
+ ? input.defaultsPayload
476
+ : null;
477
+ return { normalized, diagnostics, fatalErrors };
478
+ }
479
+ if (!isPlainObject(input.defaultsPayload)) {
480
+ diagnostics.push({
481
+ code: "openclaw_gateway_defaults_missing",
482
+ level: "warn",
483
+ message: "No OpenClaw gateway config was provided in agentDefaultsPayload.",
484
+ hint: "Include agentDefaultsPayload.url and headers.x-openclaw-token for OpenClaw gateway joins."
485
+ });
486
+ fatalErrors.push("agentDefaultsPayload is required for agentRuntimeType=openclaw_gateway");
487
+ return {
488
+ normalized: null,
489
+ diagnostics,
490
+ fatalErrors
491
+ };
492
+ }
493
+ const defaults = input.defaultsPayload;
494
+ const normalized = {};
495
+ let gatewayUrl = null;
496
+ const rawGatewayUrl = nonEmptyTrimmedString(defaults.url);
497
+ if (!rawGatewayUrl) {
498
+ diagnostics.push({
499
+ code: "openclaw_gateway_url_missing",
500
+ level: "warn",
501
+ message: "OpenClaw gateway URL is missing.",
502
+ hint: "Set agentDefaultsPayload.url to ws:// or wss:// gateway URL."
503
+ });
504
+ fatalErrors.push("agentDefaultsPayload.url is required");
505
+ }
506
+ else {
507
+ try {
508
+ gatewayUrl = new URL(rawGatewayUrl);
509
+ if (gatewayUrl.protocol !== "ws:" && gatewayUrl.protocol !== "wss:") {
510
+ diagnostics.push({
511
+ code: "openclaw_gateway_url_protocol",
512
+ level: "warn",
513
+ message: `OpenClaw gateway URL must use ws:// or wss:// (got ${gatewayUrl.protocol}).`
514
+ });
515
+ fatalErrors.push("agentDefaultsPayload.url must use ws:// or wss:// for openclaw_gateway");
516
+ }
517
+ else {
518
+ normalized.url = gatewayUrl.toString();
519
+ diagnostics.push({
520
+ code: "openclaw_gateway_url_configured",
521
+ level: "info",
522
+ message: `Gateway endpoint set to ${gatewayUrl.toString()}`
523
+ });
524
+ }
525
+ }
526
+ catch {
527
+ diagnostics.push({
528
+ code: "openclaw_gateway_url_invalid",
529
+ level: "warn",
530
+ message: `Invalid OpenClaw gateway URL: ${rawGatewayUrl}`
531
+ });
532
+ fatalErrors.push("agentDefaultsPayload.url is not a valid URL");
533
+ }
534
+ }
535
+ const headers = normalizeHeaderMap(defaults.headers) ?? {};
536
+ const gatewayToken = headerMapGetIgnoreCase(headers, "x-openclaw-token") ??
537
+ headerMapGetIgnoreCase(headers, "x-openclaw-auth") ??
538
+ tokenFromAuthorizationHeader(headerMapGetIgnoreCase(headers, "authorization"));
539
+ if (gatewayToken && !headerMapHasKeyIgnoreCase(headers, "x-openclaw-token")) {
540
+ headers["x-openclaw-token"] = gatewayToken;
541
+ }
542
+ if (Object.keys(headers).length > 0) {
543
+ normalized.headers = headers;
544
+ }
545
+ if (!gatewayToken) {
546
+ diagnostics.push({
547
+ code: "openclaw_gateway_auth_header_missing",
548
+ level: "warn",
549
+ message: "Gateway auth token is missing from agent defaults.",
550
+ hint: "Set agentDefaultsPayload.headers.x-openclaw-token (or legacy x-openclaw-auth)."
551
+ });
552
+ fatalErrors.push("agentDefaultsPayload.headers.x-openclaw-token (or x-openclaw-auth) is required");
553
+ }
554
+ else if (gatewayToken.trim().length < 16) {
555
+ diagnostics.push({
556
+ code: "openclaw_gateway_auth_header_too_short",
557
+ level: "warn",
558
+ message: `Gateway auth token appears too short (${gatewayToken.trim().length} chars).`,
559
+ hint: "Use the full gateway auth token from ~/.openclaw/openclaw.json (typically long random string)."
560
+ });
561
+ fatalErrors.push("agentDefaultsPayload.headers.x-openclaw-token is too short; expected a full gateway token");
562
+ }
563
+ else {
564
+ diagnostics.push({
565
+ code: "openclaw_gateway_auth_header_configured",
566
+ level: "info",
567
+ message: "Gateway auth token configured."
568
+ });
569
+ }
570
+ if (isPlainObject(defaults.payloadTemplate)) {
571
+ normalized.payloadTemplate = defaults.payloadTemplate;
572
+ }
573
+ const parsedDisableDeviceAuth = parseBooleanLike(defaults.disableDeviceAuth);
574
+ const disableDeviceAuth = parsedDisableDeviceAuth === true;
575
+ if (parsedDisableDeviceAuth !== null) {
576
+ normalized.disableDeviceAuth = parsedDisableDeviceAuth;
577
+ }
578
+ const configuredDevicePrivateKeyPem = nonEmptyTrimmedString(defaults.devicePrivateKeyPem);
579
+ if (configuredDevicePrivateKeyPem) {
580
+ normalized.devicePrivateKeyPem = configuredDevicePrivateKeyPem;
581
+ diagnostics.push({
582
+ code: "openclaw_gateway_device_key_configured",
583
+ level: "info",
584
+ message: "Gateway device key configured. Pairing approvals should persist for this agent."
585
+ });
586
+ }
587
+ else if (!disableDeviceAuth) {
588
+ try {
589
+ normalized.devicePrivateKeyPem = generateEd25519PrivateKeyPem();
590
+ diagnostics.push({
591
+ code: "openclaw_gateway_device_key_generated",
592
+ level: "info",
593
+ message: "Generated persistent gateway device key for this join. Pairing approvals should persist for this agent."
594
+ });
595
+ }
596
+ catch (err) {
597
+ diagnostics.push({
598
+ code: "openclaw_gateway_device_key_generate_failed",
599
+ level: "warn",
600
+ message: `Failed to generate gateway device key: ${err instanceof Error ? err.message : String(err)}`,
601
+ hint: "Set agentDefaultsPayload.devicePrivateKeyPem explicitly or set disableDeviceAuth=true."
602
+ });
603
+ fatalErrors.push("Failed to generate gateway device key. Set devicePrivateKeyPem or disableDeviceAuth=true.");
604
+ }
605
+ }
606
+ const waitTimeoutMs = typeof defaults.waitTimeoutMs === "number" &&
607
+ Number.isFinite(defaults.waitTimeoutMs)
608
+ ? Math.floor(defaults.waitTimeoutMs)
609
+ : typeof defaults.waitTimeoutMs === "string"
610
+ ? Number.parseInt(defaults.waitTimeoutMs.trim(), 10)
611
+ : NaN;
612
+ if (Number.isFinite(waitTimeoutMs) && waitTimeoutMs > 0) {
613
+ normalized.waitTimeoutMs = waitTimeoutMs;
614
+ }
615
+ const timeoutSec = typeof defaults.timeoutSec === "number" && Number.isFinite(defaults.timeoutSec)
616
+ ? Math.floor(defaults.timeoutSec)
617
+ : typeof defaults.timeoutSec === "string"
618
+ ? Number.parseInt(defaults.timeoutSec.trim(), 10)
619
+ : NaN;
620
+ if (Number.isFinite(timeoutSec) && timeoutSec > 0) {
621
+ normalized.timeoutSec = timeoutSec;
622
+ }
623
+ const sessionKeyStrategy = nonEmptyTrimmedString(defaults.sessionKeyStrategy);
624
+ if (sessionKeyStrategy === "fixed" ||
625
+ sessionKeyStrategy === "issue" ||
626
+ sessionKeyStrategy === "run") {
627
+ normalized.sessionKeyStrategy = sessionKeyStrategy;
628
+ }
629
+ const sessionKey = nonEmptyTrimmedString(defaults.sessionKey);
630
+ if (sessionKey) {
631
+ normalized.sessionKey = sessionKey;
632
+ }
633
+ const role = nonEmptyTrimmedString(defaults.role);
634
+ if (role) {
635
+ normalized.role = role;
636
+ }
637
+ if (Array.isArray(defaults.scopes)) {
638
+ const scopes = defaults.scopes
639
+ .filter((entry) => typeof entry === "string")
640
+ .map((entry) => entry.trim())
641
+ .filter(Boolean);
642
+ if (scopes.length > 0) {
643
+ normalized.scopes = scopes;
644
+ }
645
+ }
646
+ const rawPaperclipApiUrl = typeof defaults.rudderApiUrl === "string"
647
+ ? defaults.rudderApiUrl.trim()
648
+ : "";
649
+ if (rawPaperclipApiUrl) {
650
+ try {
651
+ const parsedPaperclipApiUrl = new URL(rawPaperclipApiUrl);
652
+ if (parsedPaperclipApiUrl.protocol !== "http:" &&
653
+ parsedPaperclipApiUrl.protocol !== "https:") {
654
+ diagnostics.push({
655
+ code: "openclaw_gateway_paperclip_api_url_protocol",
656
+ level: "warn",
657
+ message: `rudderApiUrl must use http:// or https:// (got ${parsedPaperclipApiUrl.protocol}).`
658
+ });
659
+ }
660
+ else {
661
+ normalized.rudderApiUrl = parsedPaperclipApiUrl.toString();
662
+ diagnostics.push({
663
+ code: "openclaw_gateway_paperclip_api_url_configured",
664
+ level: "info",
665
+ message: `rudderApiUrl set to ${parsedPaperclipApiUrl.toString()}`
666
+ });
667
+ }
668
+ }
669
+ catch {
670
+ diagnostics.push({
671
+ code: "openclaw_gateway_paperclip_api_url_invalid",
672
+ level: "warn",
673
+ message: `Invalid rudderApiUrl: ${rawPaperclipApiUrl}`
674
+ });
675
+ }
676
+ }
677
+ return { normalized, diagnostics, fatalErrors };
678
+ }
679
+ function toInviteSummaryResponse(req, token, invite) {
680
+ const baseUrl = requestBaseUrl(req);
681
+ const onboardingPath = `/api/invites/${token}/onboarding`;
682
+ const onboardingTextPath = `/api/invites/${token}/onboarding.txt`;
683
+ const inviteMessage = extractInviteMessage(invite);
684
+ return {
685
+ id: invite.id,
686
+ orgId: invite.orgId,
687
+ inviteType: invite.inviteType,
688
+ allowedJoinTypes: invite.allowedJoinTypes,
689
+ expiresAt: invite.expiresAt,
690
+ onboardingPath,
691
+ onboardingUrl: baseUrl ? `${baseUrl}${onboardingPath}` : onboardingPath,
692
+ onboardingTextPath,
693
+ onboardingTextUrl: baseUrl
694
+ ? `${baseUrl}${onboardingTextPath}`
695
+ : onboardingTextPath,
696
+ skillIndexPath: "/api/skills/index",
697
+ skillIndexUrl: baseUrl
698
+ ? `${baseUrl}/api/skills/index`
699
+ : "/api/skills/index",
700
+ inviteMessage
701
+ };
702
+ }
703
+ function buildOnboardingDiscoveryDiagnostics(input) {
704
+ const diagnostics = [];
705
+ let apiHost = null;
706
+ if (input.apiBaseUrl) {
707
+ try {
708
+ apiHost = normalizeHostname(new URL(input.apiBaseUrl).hostname);
709
+ }
710
+ catch {
711
+ apiHost = null;
712
+ }
713
+ }
714
+ const bindHost = normalizeHostname(input.bindHost);
715
+ const allowSet = new Set(input.allowedHostnames
716
+ .map((entry) => normalizeHostname(entry))
717
+ .filter((entry) => Boolean(entry)));
718
+ if (apiHost && isLoopbackHost(apiHost)) {
719
+ diagnostics.push({
720
+ code: "openclaw_onboarding_api_loopback",
721
+ level: "warn",
722
+ message: "Onboarding URL resolves to loopback hostname. Remote OpenClaw agents cannot reach localhost on your Rudder host.",
723
+ hint: "Use a reachable hostname/IP (for example Tailscale hostname, Docker host alias, or public domain)."
724
+ });
725
+ }
726
+ if (input.deploymentMode === "authenticated" &&
727
+ input.deploymentExposure === "private" &&
728
+ (!bindHost || isLoopbackHost(bindHost))) {
729
+ diagnostics.push({
730
+ code: "openclaw_onboarding_private_loopback_bind",
731
+ level: "warn",
732
+ message: "Rudder is bound to loopback in authenticated/private mode.",
733
+ hint: "Run with a reachable bind host or use pnpm dev --tailscale-auth for private-network onboarding."
734
+ });
735
+ }
736
+ if (input.deploymentMode === "authenticated" &&
737
+ input.deploymentExposure === "private" &&
738
+ apiHost &&
739
+ !isLoopbackHost(apiHost) &&
740
+ allowSet.size > 0 &&
741
+ !allowSet.has(apiHost)) {
742
+ diagnostics.push({
743
+ code: "openclaw_onboarding_private_host_not_allowed",
744
+ level: "warn",
745
+ message: `Onboarding host "${apiHost}" is not in allowed hostnames for authenticated/private mode.`,
746
+ hint: `Run pnpm rudder allowed-hostname ${apiHost}`
747
+ });
748
+ }
749
+ return diagnostics;
750
+ }
751
+ function buildOnboardingConnectionCandidates(input) {
752
+ let base = null;
753
+ try {
754
+ if (input.apiBaseUrl) {
755
+ base = new URL(input.apiBaseUrl);
756
+ }
757
+ }
758
+ catch {
759
+ base = null;
760
+ }
761
+ const protocol = base?.protocol ?? "http:";
762
+ const port = base?.port ? `:${base.port}` : "";
763
+ const candidates = new Set();
764
+ if (base) {
765
+ candidates.add(base.origin);
766
+ }
767
+ const bindHost = normalizeHostname(input.bindHost);
768
+ if (bindHost && !isLoopbackHost(bindHost)) {
769
+ candidates.add(`${protocol}//${bindHost}${port}`);
770
+ }
771
+ for (const rawHost of input.allowedHostnames) {
772
+ const host = normalizeHostname(rawHost);
773
+ if (!host)
774
+ continue;
775
+ candidates.add(`${protocol}//${host}${port}`);
776
+ }
777
+ if (base && isLoopbackHost(base.hostname)) {
778
+ candidates.add(`${protocol}//host.docker.internal${port}`);
779
+ }
780
+ return Array.from(candidates);
781
+ }
782
+ function buildInviteOnboardingManifest(req, token, invite, opts) {
783
+ const baseUrl = requestBaseUrl(req);
784
+ const skillPath = "/api/skills/rudder";
785
+ const skillUrl = baseUrl ? `${baseUrl}${skillPath}` : skillPath;
786
+ const registrationEndpointPath = `/api/invites/${token}/accept`;
787
+ const registrationEndpointUrl = baseUrl
788
+ ? `${baseUrl}${registrationEndpointPath}`
789
+ : registrationEndpointPath;
790
+ const onboardingTextPath = `/api/invites/${token}/onboarding.txt`;
791
+ const onboardingTextUrl = baseUrl
792
+ ? `${baseUrl}${onboardingTextPath}`
793
+ : onboardingTextPath;
794
+ const discoveryDiagnostics = buildOnboardingDiscoveryDiagnostics({
795
+ apiBaseUrl: baseUrl,
796
+ deploymentMode: opts.deploymentMode,
797
+ deploymentExposure: opts.deploymentExposure,
798
+ bindHost: opts.bindHost,
799
+ allowedHostnames: opts.allowedHostnames
800
+ });
801
+ const connectionCandidates = buildOnboardingConnectionCandidates({
802
+ apiBaseUrl: baseUrl,
803
+ bindHost: opts.bindHost,
804
+ allowedHostnames: opts.allowedHostnames
805
+ });
806
+ return {
807
+ invite: toInviteSummaryResponse(req, token, invite),
808
+ onboarding: {
809
+ instructions: "Join as an OpenClaw Gateway agent, save your one-time claim secret, wait for board approval, then claim your API key. Save the claim response token to ~/.openclaw/workspace/rudder-claimed-api-key.json and load RUDDER_API_KEY from that file before starting heartbeat loops. You MUST submit agentRuntimeType='openclaw_gateway', set agentDefaultsPayload.url to your ws:// or wss:// OpenClaw gateway endpoint, and include agentDefaultsPayload.headers.x-openclaw-token (or legacy x-openclaw-auth).",
810
+ inviteMessage: extractInviteMessage(invite),
811
+ recommendedAdapterType: "openclaw_gateway",
812
+ requiredFields: {
813
+ requestType: "agent",
814
+ agentName: "Display name for this agent",
815
+ agentRuntimeType: "Use 'openclaw_gateway' for OpenClaw Gateway agents",
816
+ capabilities: "Optional capability summary",
817
+ agentDefaultsPayload: "Adapter config for OpenClaw gateway. MUST include url (ws:// or wss://) and headers.x-openclaw-token (or legacy x-openclaw-auth). Optional fields: rudderApiUrl, waitTimeoutMs, sessionKeyStrategy, sessionKey, role, scopes, disableDeviceAuth, devicePrivateKeyPem."
818
+ },
819
+ registrationEndpoint: {
820
+ method: "POST",
821
+ path: registrationEndpointPath,
822
+ url: registrationEndpointUrl
823
+ },
824
+ claimEndpointTemplate: {
825
+ method: "POST",
826
+ path: "/api/join-requests/{requestId}/claim-api-key",
827
+ body: {
828
+ claimSecret: "one-time claim secret returned when the join request is created"
829
+ }
830
+ },
831
+ connectivity: {
832
+ deploymentMode: opts.deploymentMode,
833
+ deploymentExposure: opts.deploymentExposure,
834
+ bindHost: opts.bindHost,
835
+ allowedHostnames: opts.allowedHostnames,
836
+ connectionCandidates,
837
+ diagnostics: discoveryDiagnostics,
838
+ guidance: opts.deploymentMode === "authenticated" &&
839
+ opts.deploymentExposure === "private"
840
+ ? "If OpenClaw runs on another machine, ensure the Rudder hostname is reachable and allowed via `pnpm rudder allowed-hostname <host>`."
841
+ : "Ensure OpenClaw can reach this Rudder API base URL for invite, claim, and skill bootstrap calls."
842
+ },
843
+ textInstructions: {
844
+ path: onboardingTextPath,
845
+ url: onboardingTextUrl,
846
+ contentType: "text/plain"
847
+ },
848
+ skill: {
849
+ name: "rudder",
850
+ path: skillPath,
851
+ url: skillUrl,
852
+ installPath: "~/.openclaw/skills/rudder/SKILL.md"
853
+ }
854
+ }
855
+ };
856
+ }
857
+ export function buildInviteOnboardingTextDocument(req, token, invite, opts) {
858
+ const manifest = buildInviteOnboardingManifest(req, token, invite, opts);
859
+ const onboarding = manifest.onboarding;
860
+ const diagnostics = Array.isArray(onboarding.connectivity?.diagnostics)
861
+ ? onboarding.connectivity.diagnostics
862
+ : [];
863
+ const lines = [];
864
+ const appendBlock = (block) => {
865
+ const trimmed = block.replace(/^\n/, "").replace(/\n\s*$/, "");
866
+ const lineIndentation = trimmed
867
+ .split("\n")
868
+ .filter((line) => line.trim().length > 0)
869
+ .map((line) => line.match(/^(\s*)/)?.[0].length ?? 0);
870
+ const minIndent = lineIndentation.length > 0 ? Math.min(...lineIndentation) : 0;
871
+ for (const line of trimmed.split("\n")) {
872
+ lines.push(line.slice(minIndent));
873
+ }
874
+ };
875
+ appendBlock(`
876
+ # Rudder OpenClaw Gateway Onboarding
877
+
878
+ This document is meant to be readable by both humans and agents.
879
+
880
+ ## Invite
881
+ - inviteType: ${invite.inviteType}
882
+ - allowedJoinTypes: ${invite.allowedJoinTypes}
883
+ - expiresAt: ${invite.expiresAt.toISOString()}
884
+ `);
885
+ if (onboarding.inviteMessage) {
886
+ appendBlock(`
887
+ ## Message from inviter
888
+ ${onboarding.inviteMessage}
889
+ `);
890
+ }
891
+ appendBlock(`
892
+ ## Step 0
893
+
894
+ Get the OpenClaw gateway auth token (THIS MUST BE SENT)
895
+ Token lives in:
896
+
897
+ ~/.openclaw/openclaw.json -> gateway.auth.token
898
+ Extract:
899
+
900
+ TOKEN="$(node -p 'require(process.env.HOME+\"/.openclaw/openclaw.json\").gateway.auth.token')"
901
+ test -n "$TOKEN" || (echo "Missing TOKEN" && exit 1)
902
+ test "\${#TOKEN}" -ge 16 || (echo "Gateway token unexpectedly short (\${#TOKEN})" && exit 1)
903
+
904
+ 3) IMPORTANT: Don't accidentally drop the token when generating JSON
905
+ If you build JSON with Node, pass the token explicitly (argv), don't rely on an un-exported env var.
906
+
907
+ Safe payload build looks sort of like this (substitute where necessary):
908
+
909
+ BODY="$(node -e '
910
+ const token = process.argv[1];
911
+ if (!token) process.exit(2);
912
+ const body = {
913
+ requestType: "agent",
914
+ agentName: "OpenClaw",
915
+ agentRuntimeType: "openclaw_gateway",
916
+ capabilities: "OpenClaw agent adapter",
917
+ agentDefaultsPayload: {
918
+ url: "ws://127.0.0.1:18789",
919
+ rudderApiUrl: "http://host.docker.internal:3100",
920
+ headers: { "x-openclaw-token": token },
921
+ waitTimeoutMs: 120000,
922
+ sessionKeyStrategy: "issue",
923
+ role: "operator",
924
+ scopes: ["operator.admin"]
925
+ }
926
+ };
927
+ process.stdout.write(JSON.stringify(body));
928
+ ' "$TOKEN")"
929
+
930
+ ## Step 1: Submit agent join request
931
+ ${onboarding.registrationEndpoint.method} ${onboarding.registrationEndpoint.url}
932
+
933
+ IMPORTANT: You MUST include agentDefaultsPayload.headers.x-openclaw-token with your gateway token.
934
+ Legacy x-openclaw-auth is also accepted, but x-openclaw-token is preferred.
935
+ Use agentRuntimeType "openclaw_gateway" and a ws:// or wss:// gateway URL.
936
+ Pairing mode requirement:
937
+ - Keep device auth enabled (recommended). If devicePrivateKeyPem is omitted, Rudder generates and persists one during join so pairing approvals are stable.
938
+ - You may set disableDeviceAuth=true only for special environments that cannot support pairing.
939
+ - First run may return "pairing required" once; approve the pending pairing request in OpenClaw, then retry.
940
+ Do NOT use /v1/responses or /hooks/* in this gateway join flow.
941
+
942
+ Body (JSON):
943
+ {
944
+ "requestType": "agent",
945
+ "agentName": "My OpenClaw Agent",
946
+ "agentRuntimeType": "openclaw_gateway",
947
+ "capabilities": "Optional summary",
948
+ "agentDefaultsPayload": {
949
+ "url": "wss://your-openclaw-gateway.example",
950
+ "rudderApiUrl": "https://rudder-hostname-your-agent-can-reach:3100",
951
+ "headers": { "x-openclaw-token": "replace-me" },
952
+ "waitTimeoutMs": 120000,
953
+ "sessionKeyStrategy": "issue",
954
+ "role": "operator",
955
+ "scopes": ["operator.admin"]
956
+ }
957
+ }
958
+
959
+ Expected response includes:
960
+ - request id
961
+ - one-time claimSecret
962
+ - claimApiKeyPath
963
+
964
+ ## Step 2: Wait for board approval
965
+ The board approves the join request in Rudder before key claim is allowed.
966
+
967
+ ## Step 3: Claim API key (one-time)
968
+ ${onboarding.claimEndpointTemplate.method} /api/join-requests/{requestId}/claim-api-key
969
+
970
+ Body (JSON):
971
+ {
972
+ "claimSecret": "<one-time-claim-secret>"
973
+ }
974
+
975
+ On successful claim, save the full JSON response to:
976
+
977
+ - ~/.openclaw/workspace/rudder-claimed-api-key.json
978
+ chmod 600 ~/.openclaw/workspace/rudder-claimed-api-key.json
979
+
980
+ And set the RUDDER_API_KEY and RUDDER_API_URL in your environment variables as specified here:
981
+ https://docs.openclaw.ai/help/environment
982
+
983
+ e.g.
984
+
985
+ {
986
+ env: {
987
+ RUDDER_API_KEY: "...",
988
+ RUDDER_API_URL: "...",
989
+ },
990
+ }
991
+
992
+ Then set RUDDER_API_KEY and RUDDER_API_URL from the saved token field for every heartbeat run.
993
+
994
+ Important:
995
+ - claim secrets expire
996
+ - claim secrets are single-use
997
+ - claim fails before board approval
998
+
999
+ ## Step 4: Install Rudder skill in OpenClaw
1000
+ GET ${onboarding.skill.url}
1001
+ Install path: ${onboarding.skill.installPath}
1002
+
1003
+ Be sure to prepend your RUDDER_API_URL to the top of your skill and note the path to your RUDDER_API_URL
1004
+
1005
+ ## Text onboarding URL
1006
+ ${onboarding.textInstructions.url}
1007
+
1008
+ ## Connectivity guidance
1009
+ ${onboarding.connectivity?.guidance ??
1010
+ "Ensure Rudder is reachable from your OpenClaw runtime."}
1011
+ `);
1012
+ const connectionCandidates = Array.isArray(onboarding.connectivity?.connectionCandidates)
1013
+ ? onboarding.connectivity.connectionCandidates.filter((entry) => Boolean(entry))
1014
+ : [];
1015
+ if (connectionCandidates.length > 0) {
1016
+ lines.push("## Suggested Rudder base URLs to try");
1017
+ for (const candidate of connectionCandidates) {
1018
+ lines.push(`- ${candidate}`);
1019
+ }
1020
+ appendBlock(`
1021
+
1022
+ Test each candidate with:
1023
+ - GET <candidate>/api/health
1024
+ - set the first reachable candidate as agentDefaultsPayload.rudderApiUrl when submitting your join request
1025
+
1026
+ If none are reachable: ask your human operator for a reachable hostname/address and help them update network configuration.
1027
+ For authenticated/private mode, they may need:
1028
+ - pnpm rudder allowed-hostname <host>
1029
+ - then restart Rudder and retry onboarding.
1030
+ `);
1031
+ }
1032
+ if (diagnostics.length > 0) {
1033
+ lines.push("## Connectivity diagnostics");
1034
+ for (const diag of diagnostics) {
1035
+ lines.push(`- [${diag.level}] ${diag.message}`);
1036
+ if (diag.hint)
1037
+ lines.push(` hint: ${diag.hint}`);
1038
+ }
1039
+ }
1040
+ appendBlock(`
1041
+
1042
+ ## Helpful endpoints
1043
+ ${onboarding.registrationEndpoint.path}
1044
+ ${onboarding.claimEndpointTemplate.path}
1045
+ ${onboarding.skill.path}
1046
+ ${manifest.invite.onboardingPath}
1047
+ `);
1048
+ return `${lines.join("\n")}\n`;
1049
+ }
1050
+ function extractInviteMessage(invite) {
1051
+ const rawDefaults = invite.defaultsPayload;
1052
+ if (!rawDefaults ||
1053
+ typeof rawDefaults !== "object" ||
1054
+ Array.isArray(rawDefaults)) {
1055
+ return null;
1056
+ }
1057
+ const rawMessage = rawDefaults.agentMessage;
1058
+ if (typeof rawMessage !== "string") {
1059
+ return null;
1060
+ }
1061
+ const trimmed = rawMessage.trim();
1062
+ return trimmed.length ? trimmed : null;
1063
+ }
1064
+ function mergeInviteDefaults(defaultsPayload, agentMessage) {
1065
+ const merged = defaultsPayload && typeof defaultsPayload === "object"
1066
+ ? { ...defaultsPayload }
1067
+ : {};
1068
+ if (agentMessage) {
1069
+ merged.agentMessage = agentMessage;
1070
+ }
1071
+ return Object.keys(merged).length ? merged : null;
1072
+ }
1073
+ function requestIp(req) {
1074
+ const forwarded = req.header("x-forwarded-for");
1075
+ if (forwarded) {
1076
+ const first = forwarded.split(",")[0]?.trim();
1077
+ if (first)
1078
+ return first;
1079
+ }
1080
+ return req.ip || "unknown";
1081
+ }
1082
+ function inviteExpired(invite) {
1083
+ return invite.expiresAt.getTime() <= Date.now();
1084
+ }
1085
+ function isLocalImplicit(req) {
1086
+ return req.actor.type === "board" && req.actor.source === "local_implicit";
1087
+ }
1088
+ async function resolveActorEmail(db, req) {
1089
+ if (isLocalImplicit(req))
1090
+ return "local@rudder.local";
1091
+ const userId = req.actor.userId;
1092
+ if (!userId)
1093
+ return null;
1094
+ const user = await db
1095
+ .select({ email: authUsers.email })
1096
+ .from(authUsers)
1097
+ .where(eq(authUsers.id, userId))
1098
+ .then((rows) => rows[0] ?? null);
1099
+ return user?.email ?? null;
1100
+ }
1101
+ function grantsFromDefaults(defaultsPayload, key) {
1102
+ if (!defaultsPayload || typeof defaultsPayload !== "object")
1103
+ return [];
1104
+ const scoped = defaultsPayload[key];
1105
+ if (!scoped || typeof scoped !== "object")
1106
+ return [];
1107
+ const grants = scoped.grants;
1108
+ if (!Array.isArray(grants))
1109
+ return [];
1110
+ const validPermissionKeys = new Set(PERMISSION_KEYS);
1111
+ const result = [];
1112
+ for (const item of grants) {
1113
+ if (!item || typeof item !== "object")
1114
+ continue;
1115
+ const record = item;
1116
+ if (typeof record.permissionKey !== "string")
1117
+ continue;
1118
+ if (!validPermissionKeys.has(record.permissionKey))
1119
+ continue;
1120
+ result.push({
1121
+ permissionKey: record.permissionKey,
1122
+ scope: record.scope &&
1123
+ typeof record.scope === "object" &&
1124
+ !Array.isArray(record.scope)
1125
+ ? record.scope
1126
+ : null
1127
+ });
1128
+ }
1129
+ return result;
1130
+ }
1131
+ export function resolveJoinRequestAgentManagerId(candidates) {
1132
+ const ceoCandidates = candidates.filter((candidate) => candidate.role === "ceo");
1133
+ if (ceoCandidates.length === 0)
1134
+ return null;
1135
+ const rootCeo = ceoCandidates.find((candidate) => candidate.reportsTo === null);
1136
+ return (rootCeo ?? ceoCandidates[0] ?? null)?.id ?? null;
1137
+ }
1138
+ function isInviteTokenHashCollisionError(error) {
1139
+ const candidates = [
1140
+ error,
1141
+ error?.cause ?? null
1142
+ ];
1143
+ for (const candidate of candidates) {
1144
+ if (!candidate || typeof candidate !== "object")
1145
+ continue;
1146
+ const code = "code" in candidate && typeof candidate.code === "string"
1147
+ ? candidate.code
1148
+ : null;
1149
+ const message = "message" in candidate && typeof candidate.message === "string"
1150
+ ? candidate.message
1151
+ : "";
1152
+ const constraint = "constraint" in candidate && typeof candidate.constraint === "string"
1153
+ ? candidate.constraint
1154
+ : null;
1155
+ if (code !== "23505")
1156
+ continue;
1157
+ if (constraint === "invites_token_hash_unique_idx")
1158
+ return true;
1159
+ if (message.includes("invites_token_hash_unique_idx"))
1160
+ return true;
1161
+ }
1162
+ return false;
1163
+ }
1164
+ function isAbortError(error) {
1165
+ return error instanceof Error && error.name === "AbortError";
1166
+ }
1167
+ async function probeInviteResolutionTarget(url, timeoutMs) {
1168
+ const startedAt = Date.now();
1169
+ const controller = new AbortController();
1170
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
1171
+ try {
1172
+ const response = await fetch(url, {
1173
+ method: "HEAD",
1174
+ redirect: "manual",
1175
+ signal: controller.signal
1176
+ });
1177
+ const durationMs = Date.now() - startedAt;
1178
+ if (response.ok ||
1179
+ response.status === 401 ||
1180
+ response.status === 403 ||
1181
+ response.status === 404 ||
1182
+ response.status === 405 ||
1183
+ response.status === 422 ||
1184
+ response.status === 500 ||
1185
+ response.status === 501) {
1186
+ return {
1187
+ status: "reachable",
1188
+ method: "HEAD",
1189
+ durationMs,
1190
+ httpStatus: response.status,
1191
+ message: `Webhook endpoint responded to HEAD with HTTP ${response.status}.`
1192
+ };
1193
+ }
1194
+ return {
1195
+ status: "unreachable",
1196
+ method: "HEAD",
1197
+ durationMs,
1198
+ httpStatus: response.status,
1199
+ message: `Webhook endpoint probe returned HTTP ${response.status}.`
1200
+ };
1201
+ }
1202
+ catch (error) {
1203
+ const durationMs = Date.now() - startedAt;
1204
+ if (isAbortError(error)) {
1205
+ return {
1206
+ status: "timeout",
1207
+ method: "HEAD",
1208
+ durationMs,
1209
+ httpStatus: null,
1210
+ message: `Webhook endpoint probe timed out after ${timeoutMs}ms.`
1211
+ };
1212
+ }
1213
+ return {
1214
+ status: "unreachable",
1215
+ method: "HEAD",
1216
+ durationMs,
1217
+ httpStatus: null,
1218
+ message: error instanceof Error
1219
+ ? error.message
1220
+ : "Webhook endpoint probe failed."
1221
+ };
1222
+ }
1223
+ finally {
1224
+ clearTimeout(timeout);
1225
+ }
1226
+ }
1227
+ export function accessRoutes(db, opts) {
1228
+ const router = Router();
1229
+ const access = accessService(db);
1230
+ const boardAuth = boardAuthService(db);
1231
+ const agents = agentService(db);
1232
+ async function assertInstanceAdmin(req) {
1233
+ if (req.actor.type !== "board")
1234
+ throw unauthorized();
1235
+ if (isLocalImplicit(req))
1236
+ return;
1237
+ const allowed = await access.isInstanceAdmin(req.actor.userId);
1238
+ if (!allowed)
1239
+ throw forbidden("Instance admin required");
1240
+ }
1241
+ router.get("/board-claim/:token", async (req, res) => {
1242
+ const token = req.params.token.trim();
1243
+ const code = typeof req.query.code === "string" ? req.query.code.trim() : undefined;
1244
+ if (!token)
1245
+ throw notFound("Board claim challenge not found");
1246
+ const challenge = inspectBoardClaimChallenge(token, code);
1247
+ if (challenge.status === "invalid")
1248
+ throw notFound("Board claim challenge not found");
1249
+ res.json(challenge);
1250
+ });
1251
+ router.post("/board-claim/:token/claim", async (req, res) => {
1252
+ const token = req.params.token.trim();
1253
+ const code = typeof req.body?.code === "string" ? req.body.code.trim() : undefined;
1254
+ if (!token)
1255
+ throw notFound("Board claim challenge not found");
1256
+ if (!code)
1257
+ throw badRequest("Claim code is required");
1258
+ if (req.actor.type !== "board" ||
1259
+ req.actor.source !== "session" ||
1260
+ !req.actor.userId) {
1261
+ throw unauthorized("Sign in before claiming board ownership");
1262
+ }
1263
+ const claimed = await claimBoardOwnership(db, {
1264
+ token,
1265
+ code,
1266
+ userId: req.actor.userId
1267
+ });
1268
+ if (claimed.status === "invalid")
1269
+ throw notFound("Board claim challenge not found");
1270
+ if (claimed.status === "expired")
1271
+ throw conflict("Board claim challenge expired. Restart server to generate a new one.");
1272
+ if (claimed.status === "claimed") {
1273
+ res.json({
1274
+ claimed: true,
1275
+ userId: claimed.claimedByUserId ?? req.actor.userId
1276
+ });
1277
+ return;
1278
+ }
1279
+ throw conflict("Board claim challenge is no longer available");
1280
+ });
1281
+ router.post("/cli-auth/challenges", validate(createCliAuthChallengeSchema), async (req, res) => {
1282
+ const created = await boardAuth.createCliAuthChallenge(req.body);
1283
+ const approvalPath = buildCliAuthApprovalPath(created.challenge.id, created.challengeSecret);
1284
+ const baseUrl = requestBaseUrl(req);
1285
+ res.status(201).json({
1286
+ id: created.challenge.id,
1287
+ token: created.challengeSecret,
1288
+ boardApiToken: created.pendingBoardToken,
1289
+ approvalPath,
1290
+ approvalUrl: baseUrl ? `${baseUrl}${approvalPath}` : null,
1291
+ pollPath: `/cli-auth/challenges/${created.challenge.id}`,
1292
+ expiresAt: created.challenge.expiresAt.toISOString(),
1293
+ suggestedPollIntervalMs: 1000,
1294
+ });
1295
+ });
1296
+ router.get("/cli-auth/challenges/:id", async (req, res) => {
1297
+ const id = req.params.id.trim();
1298
+ const token = typeof req.query.token === "string" ? req.query.token.trim() : "";
1299
+ if (!id || !token)
1300
+ throw notFound("CLI auth challenge not found");
1301
+ const challenge = await boardAuth.describeCliAuthChallenge(id, token);
1302
+ if (!challenge)
1303
+ throw notFound("CLI auth challenge not found");
1304
+ const isSignedInBoardUser = req.actor.type === "board" &&
1305
+ (req.actor.source === "session" || isLocalImplicit(req)) &&
1306
+ Boolean(req.actor.userId);
1307
+ const canApprove = isSignedInBoardUser &&
1308
+ (challenge.requestedAccess !== "instance_admin_required" ||
1309
+ isLocalImplicit(req) ||
1310
+ Boolean(req.actor.isInstanceAdmin));
1311
+ res.json({
1312
+ ...challenge,
1313
+ requiresSignIn: !isSignedInBoardUser,
1314
+ canApprove,
1315
+ currentUserId: req.actor.type === "board" ? req.actor.userId ?? null : null,
1316
+ });
1317
+ });
1318
+ router.post("/cli-auth/challenges/:id/approve", validate(resolveCliAuthChallengeSchema), async (req, res) => {
1319
+ const id = req.params.id.trim();
1320
+ if (req.actor.type !== "board" ||
1321
+ (!req.actor.userId && !isLocalImplicit(req))) {
1322
+ throw unauthorized("Sign in before approving CLI access");
1323
+ }
1324
+ const userId = req.actor.userId ?? "local-board";
1325
+ const approved = await boardAuth.approveCliAuthChallenge(id, req.body.token, userId);
1326
+ if (approved.status === "approved") {
1327
+ const orgIds = await boardAuth.resolveBoardActivityCompanyIds({
1328
+ userId,
1329
+ requestedCompanyId: approved.challenge.requestedCompanyId,
1330
+ boardApiKeyId: approved.challenge.boardApiKeyId,
1331
+ });
1332
+ for (const orgId of orgIds) {
1333
+ await logActivity(db, {
1334
+ orgId,
1335
+ actorType: "user",
1336
+ actorId: userId,
1337
+ action: "board_api_key.created",
1338
+ entityType: "user",
1339
+ entityId: userId,
1340
+ details: {
1341
+ boardApiKeyId: approved.challenge.boardApiKeyId,
1342
+ requestedAccess: approved.challenge.requestedAccess,
1343
+ requestedCompanyId: approved.challenge.requestedCompanyId,
1344
+ challengeId: approved.challenge.id,
1345
+ },
1346
+ });
1347
+ }
1348
+ }
1349
+ res.json({
1350
+ approved: approved.status === "approved",
1351
+ status: approved.status,
1352
+ userId,
1353
+ keyId: approved.challenge.boardApiKeyId ?? null,
1354
+ expiresAt: approved.challenge.expiresAt.toISOString(),
1355
+ });
1356
+ });
1357
+ router.post("/cli-auth/challenges/:id/cancel", validate(resolveCliAuthChallengeSchema), async (req, res) => {
1358
+ const id = req.params.id.trim();
1359
+ const cancelled = await boardAuth.cancelCliAuthChallenge(id, req.body.token);
1360
+ res.json({
1361
+ status: cancelled.status,
1362
+ cancelled: cancelled.status === "cancelled",
1363
+ });
1364
+ });
1365
+ router.get("/cli-auth/me", async (req, res) => {
1366
+ if (req.actor.type !== "board" || !req.actor.userId) {
1367
+ throw unauthorized("Board authentication required");
1368
+ }
1369
+ const accessSnapshot = await boardAuth.resolveBoardAccess(req.actor.userId);
1370
+ res.json({
1371
+ user: accessSnapshot.user,
1372
+ userId: req.actor.userId,
1373
+ isInstanceAdmin: accessSnapshot.isInstanceAdmin || isLocalImplicit(req),
1374
+ orgIds: accessSnapshot.orgIds,
1375
+ source: req.actor.source ?? "none",
1376
+ keyId: req.actor.source === "board_key" ? req.actor.keyId ?? null : null,
1377
+ });
1378
+ });
1379
+ router.post("/cli-auth/revoke-current", async (req, res) => {
1380
+ if (req.actor.type !== "board" || req.actor.source !== "board_key") {
1381
+ throw badRequest("Current board API key context is required");
1382
+ }
1383
+ const key = await boardAuth.assertCurrentBoardKey(req.actor.keyId, req.actor.userId);
1384
+ await boardAuth.revokeBoardApiKey(key.id);
1385
+ const orgIds = await boardAuth.resolveBoardActivityCompanyIds({
1386
+ userId: key.userId,
1387
+ boardApiKeyId: key.id,
1388
+ });
1389
+ for (const orgId of orgIds) {
1390
+ await logActivity(db, {
1391
+ orgId,
1392
+ actorType: "user",
1393
+ actorId: key.userId,
1394
+ action: "board_api_key.revoked",
1395
+ entityType: "user",
1396
+ entityId: key.userId,
1397
+ details: {
1398
+ boardApiKeyId: key.id,
1399
+ revokedVia: "cli_auth_logout",
1400
+ },
1401
+ });
1402
+ }
1403
+ res.json({ revoked: true, keyId: key.id });
1404
+ });
1405
+ async function assertCompanyPermission(req, orgId, permissionKey) {
1406
+ assertCompanyAccess(req, orgId);
1407
+ if (req.actor.type === "agent") {
1408
+ if (!req.actor.agentId)
1409
+ throw forbidden();
1410
+ const allowed = await access.hasPermission(orgId, "agent", req.actor.agentId, permissionKey);
1411
+ if (!allowed)
1412
+ throw forbidden("Permission denied");
1413
+ return;
1414
+ }
1415
+ if (req.actor.type !== "board")
1416
+ throw unauthorized();
1417
+ if (isLocalImplicit(req))
1418
+ return;
1419
+ const allowed = await access.canUser(orgId, req.actor.userId, permissionKey);
1420
+ if (!allowed)
1421
+ throw forbidden("Permission denied");
1422
+ }
1423
+ async function assertCanGenerateOpenClawInvitePrompt(req, orgId) {
1424
+ assertCompanyAccess(req, orgId);
1425
+ if (req.actor.type === "agent") {
1426
+ if (!req.actor.agentId)
1427
+ throw forbidden("Agent authentication required");
1428
+ const actorAgent = await agents.getById(req.actor.agentId);
1429
+ if (!actorAgent || actorAgent.orgId !== orgId) {
1430
+ throw forbidden("Agent key cannot access another organization");
1431
+ }
1432
+ if (actorAgent.role !== "ceo") {
1433
+ throw forbidden("Only CEO agents can generate OpenClaw invite prompts");
1434
+ }
1435
+ return;
1436
+ }
1437
+ if (req.actor.type !== "board")
1438
+ throw unauthorized();
1439
+ if (isLocalImplicit(req))
1440
+ return;
1441
+ const allowed = await access.canUser(orgId, req.actor.userId, "users:invite");
1442
+ if (!allowed)
1443
+ throw forbidden("Permission denied");
1444
+ }
1445
+ async function createCompanyInviteForCompany(input) {
1446
+ const normalizedAgentMessage = typeof input.agentMessage === "string"
1447
+ ? input.agentMessage.trim() || null
1448
+ : null;
1449
+ const insertValues = {
1450
+ orgId: input.orgId,
1451
+ inviteType: "company_join",
1452
+ allowedJoinTypes: input.allowedJoinTypes,
1453
+ defaultsPayload: mergeInviteDefaults(input.defaultsPayload ?? null, normalizedAgentMessage),
1454
+ expiresAt: companyInviteExpiresAt(),
1455
+ invitedByUserId: input.req.actor.userId ?? null
1456
+ };
1457
+ let token = null;
1458
+ let created = null;
1459
+ for (let attempt = 0; attempt < INVITE_TOKEN_MAX_RETRIES; attempt += 1) {
1460
+ const candidateToken = createInviteToken();
1461
+ try {
1462
+ const row = await db
1463
+ .insert(invites)
1464
+ .values({
1465
+ ...insertValues,
1466
+ tokenHash: hashToken(candidateToken)
1467
+ })
1468
+ .returning()
1469
+ .then((rows) => rows[0]);
1470
+ token = candidateToken;
1471
+ created = row;
1472
+ break;
1473
+ }
1474
+ catch (error) {
1475
+ if (!isInviteTokenHashCollisionError(error)) {
1476
+ throw error;
1477
+ }
1478
+ }
1479
+ }
1480
+ if (!token || !created) {
1481
+ throw conflict("Failed to generate a unique invite token. Please retry.");
1482
+ }
1483
+ return { token, created, normalizedAgentMessage };
1484
+ }
1485
+ router.get("/skills/available", (_req, res) => {
1486
+ res.json({ skills: listAvailableSkills() });
1487
+ });
1488
+ router.get("/skills/index", (_req, res) => {
1489
+ res.json({
1490
+ skills: [
1491
+ { name: "rudder", path: "/api/skills/rudder" },
1492
+ {
1493
+ name: "para-memory-files",
1494
+ path: "/api/skills/para-memory-files"
1495
+ },
1496
+ {
1497
+ name: "rudder-create-agent",
1498
+ path: "/api/skills/rudder-create-agent"
1499
+ }
1500
+ ]
1501
+ });
1502
+ });
1503
+ router.get("/skills/:skillName", (req, res) => {
1504
+ const skillName = req.params.skillName.trim().toLowerCase();
1505
+ const markdown = readSkillMarkdown(skillName);
1506
+ if (!markdown)
1507
+ throw notFound("Skill not found");
1508
+ res.type("text/markdown").send(markdown);
1509
+ });
1510
+ router.post("/orgs/:orgId/invites", validate(createCompanyInviteSchema), async (req, res) => {
1511
+ const orgId = req.params.orgId;
1512
+ await assertCompanyPermission(req, orgId, "users:invite");
1513
+ const { token, created, normalizedAgentMessage } = await createCompanyInviteForCompany({
1514
+ req,
1515
+ orgId,
1516
+ allowedJoinTypes: req.body.allowedJoinTypes,
1517
+ defaultsPayload: req.body.defaultsPayload ?? null,
1518
+ agentMessage: req.body.agentMessage ?? null
1519
+ });
1520
+ await logActivity(db, {
1521
+ orgId,
1522
+ actorType: req.actor.type === "agent" ? "agent" : "user",
1523
+ actorId: req.actor.type === "agent"
1524
+ ? req.actor.agentId ?? "unknown-agent"
1525
+ : req.actor.userId ?? "board",
1526
+ action: "invite.created",
1527
+ entityType: "invite",
1528
+ entityId: created.id,
1529
+ details: {
1530
+ inviteType: created.inviteType,
1531
+ allowedJoinTypes: created.allowedJoinTypes,
1532
+ expiresAt: created.expiresAt.toISOString(),
1533
+ hasAgentMessage: Boolean(normalizedAgentMessage)
1534
+ }
1535
+ });
1536
+ const inviteSummary = toInviteSummaryResponse(req, token, created);
1537
+ res.status(201).json({
1538
+ ...created,
1539
+ token,
1540
+ inviteUrl: `/invite/${token}`,
1541
+ onboardingTextPath: inviteSummary.onboardingTextPath,
1542
+ onboardingTextUrl: inviteSummary.onboardingTextUrl,
1543
+ inviteMessage: inviteSummary.inviteMessage
1544
+ });
1545
+ });
1546
+ router.post("/orgs/:orgId/openclaw/invite-prompt", validate(createOpenClawInvitePromptSchema), async (req, res) => {
1547
+ const orgId = req.params.orgId;
1548
+ await assertCanGenerateOpenClawInvitePrompt(req, orgId);
1549
+ const { token, created, normalizedAgentMessage } = await createCompanyInviteForCompany({
1550
+ req,
1551
+ orgId,
1552
+ allowedJoinTypes: "agent",
1553
+ defaultsPayload: null,
1554
+ agentMessage: req.body.agentMessage ?? null
1555
+ });
1556
+ await logActivity(db, {
1557
+ orgId,
1558
+ actorType: req.actor.type === "agent" ? "agent" : "user",
1559
+ actorId: req.actor.type === "agent"
1560
+ ? req.actor.agentId ?? "unknown-agent"
1561
+ : req.actor.userId ?? "board",
1562
+ action: "invite.openclaw_prompt_created",
1563
+ entityType: "invite",
1564
+ entityId: created.id,
1565
+ details: {
1566
+ inviteType: created.inviteType,
1567
+ allowedJoinTypes: created.allowedJoinTypes,
1568
+ expiresAt: created.expiresAt.toISOString(),
1569
+ hasAgentMessage: Boolean(normalizedAgentMessage)
1570
+ }
1571
+ });
1572
+ const inviteSummary = toInviteSummaryResponse(req, token, created);
1573
+ res.status(201).json({
1574
+ ...created,
1575
+ token,
1576
+ inviteUrl: `/invite/${token}`,
1577
+ onboardingTextPath: inviteSummary.onboardingTextPath,
1578
+ onboardingTextUrl: inviteSummary.onboardingTextUrl,
1579
+ inviteMessage: inviteSummary.inviteMessage
1580
+ });
1581
+ });
1582
+ router.get("/invites/:token", async (req, res) => {
1583
+ const token = req.params.token.trim();
1584
+ if (!token)
1585
+ throw notFound("Invite not found");
1586
+ const invite = await db
1587
+ .select()
1588
+ .from(invites)
1589
+ .where(eq(invites.tokenHash, hashToken(token)))
1590
+ .then((rows) => rows[0] ?? null);
1591
+ if (!invite ||
1592
+ invite.revokedAt ||
1593
+ invite.acceptedAt ||
1594
+ inviteExpired(invite)) {
1595
+ throw notFound("Invite not found");
1596
+ }
1597
+ res.json(toInviteSummaryResponse(req, token, invite));
1598
+ });
1599
+ router.get("/invites/:token/onboarding", async (req, res) => {
1600
+ const token = req.params.token.trim();
1601
+ if (!token)
1602
+ throw notFound("Invite not found");
1603
+ const invite = await db
1604
+ .select()
1605
+ .from(invites)
1606
+ .where(eq(invites.tokenHash, hashToken(token)))
1607
+ .then((rows) => rows[0] ?? null);
1608
+ if (!invite || invite.revokedAt || inviteExpired(invite)) {
1609
+ throw notFound("Invite not found");
1610
+ }
1611
+ res.json(buildInviteOnboardingManifest(req, token, invite, opts));
1612
+ });
1613
+ router.get("/invites/:token/onboarding.txt", async (req, res) => {
1614
+ const token = req.params.token.trim();
1615
+ if (!token)
1616
+ throw notFound("Invite not found");
1617
+ const invite = await db
1618
+ .select()
1619
+ .from(invites)
1620
+ .where(eq(invites.tokenHash, hashToken(token)))
1621
+ .then((rows) => rows[0] ?? null);
1622
+ if (!invite || invite.revokedAt || inviteExpired(invite)) {
1623
+ throw notFound("Invite not found");
1624
+ }
1625
+ res
1626
+ .type("text/plain; charset=utf-8")
1627
+ .send(buildInviteOnboardingTextDocument(req, token, invite, opts));
1628
+ });
1629
+ router.get("/invites/:token/test-resolution", async (req, res) => {
1630
+ const token = req.params.token.trim();
1631
+ if (!token)
1632
+ throw notFound("Invite not found");
1633
+ const invite = await db
1634
+ .select()
1635
+ .from(invites)
1636
+ .where(eq(invites.tokenHash, hashToken(token)))
1637
+ .then((rows) => rows[0] ?? null);
1638
+ if (!invite || invite.revokedAt || inviteExpired(invite)) {
1639
+ throw notFound("Invite not found");
1640
+ }
1641
+ const rawUrl = typeof req.query.url === "string" ? req.query.url.trim() : "";
1642
+ if (!rawUrl)
1643
+ throw badRequest("url query parameter is required");
1644
+ let target;
1645
+ try {
1646
+ target = new URL(rawUrl);
1647
+ }
1648
+ catch {
1649
+ throw badRequest("url must be an absolute http(s) URL");
1650
+ }
1651
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
1652
+ throw badRequest("url must use http or https");
1653
+ }
1654
+ const parsedTimeoutMs = typeof req.query.timeoutMs === "string"
1655
+ ? Number(req.query.timeoutMs)
1656
+ : NaN;
1657
+ const timeoutMs = Number.isFinite(parsedTimeoutMs)
1658
+ ? Math.max(1000, Math.min(15000, Math.floor(parsedTimeoutMs)))
1659
+ : 5000;
1660
+ const probe = await probeInviteResolutionTarget(target, timeoutMs);
1661
+ res.json({
1662
+ inviteId: invite.id,
1663
+ testResolutionPath: `/api/invites/${token}/test-resolution`,
1664
+ requestedUrl: target.toString(),
1665
+ timeoutMs,
1666
+ ...probe
1667
+ });
1668
+ });
1669
+ router.post("/invites/:token/accept", validate(acceptInviteSchema), async (req, res) => {
1670
+ const token = req.params.token.trim();
1671
+ if (!token)
1672
+ throw notFound("Invite not found");
1673
+ const invite = await db
1674
+ .select()
1675
+ .from(invites)
1676
+ .where(eq(invites.tokenHash, hashToken(token)))
1677
+ .then((rows) => rows[0] ?? null);
1678
+ if (!invite || invite.revokedAt || inviteExpired(invite)) {
1679
+ throw notFound("Invite not found");
1680
+ }
1681
+ const inviteAlreadyAccepted = Boolean(invite.acceptedAt);
1682
+ const existingJoinRequestForInvite = inviteAlreadyAccepted
1683
+ ? await db
1684
+ .select()
1685
+ .from(joinRequests)
1686
+ .where(eq(joinRequests.inviteId, invite.id))
1687
+ .then((rows) => rows[0] ?? null)
1688
+ : null;
1689
+ if (invite.inviteType === "bootstrap_ceo") {
1690
+ if (inviteAlreadyAccepted)
1691
+ throw notFound("Invite not found");
1692
+ if (req.body.requestType !== "human") {
1693
+ throw badRequest("Bootstrap invite requires human request type");
1694
+ }
1695
+ if (req.actor.type !== "board" ||
1696
+ (!req.actor.userId && !isLocalImplicit(req))) {
1697
+ throw unauthorized("Authenticated user required for bootstrap acceptance");
1698
+ }
1699
+ const userId = req.actor.userId ?? "local-board";
1700
+ const existingAdmin = await access.isInstanceAdmin(userId);
1701
+ if (!existingAdmin) {
1702
+ await access.promoteInstanceAdmin(userId);
1703
+ }
1704
+ const updatedInvite = await db
1705
+ .update(invites)
1706
+ .set({ acceptedAt: new Date(), updatedAt: new Date() })
1707
+ .where(eq(invites.id, invite.id))
1708
+ .returning()
1709
+ .then((rows) => rows[0] ?? invite);
1710
+ res.status(202).json({
1711
+ inviteId: updatedInvite.id,
1712
+ inviteType: updatedInvite.inviteType,
1713
+ bootstrapAccepted: true,
1714
+ userId
1715
+ });
1716
+ return;
1717
+ }
1718
+ const requestType = req.body.requestType;
1719
+ const orgId = invite.orgId;
1720
+ if (!orgId)
1721
+ throw conflict("Invite is missing organization scope");
1722
+ if (invite.allowedJoinTypes !== "both" &&
1723
+ invite.allowedJoinTypes !== requestType) {
1724
+ throw badRequest(`Invite does not allow ${requestType} joins`);
1725
+ }
1726
+ if (requestType === "human" && req.actor.type !== "board") {
1727
+ throw unauthorized("Human invite acceptance requires authenticated user");
1728
+ }
1729
+ if (requestType === "human" &&
1730
+ !req.actor.userId &&
1731
+ !isLocalImplicit(req)) {
1732
+ throw unauthorized("Authenticated user is required");
1733
+ }
1734
+ if (requestType === "agent" && !req.body.agentName) {
1735
+ if (!inviteAlreadyAccepted ||
1736
+ !existingJoinRequestForInvite?.agentName) {
1737
+ throw badRequest("agentName is required for agent join requests");
1738
+ }
1739
+ }
1740
+ const agentRuntimeType = req.body.agentRuntimeType ?? null;
1741
+ if (inviteAlreadyAccepted &&
1742
+ !canReplayOpenClawGatewayInviteAccept({
1743
+ requestType,
1744
+ agentRuntimeType,
1745
+ existingJoinRequest: existingJoinRequestForInvite
1746
+ })) {
1747
+ throw notFound("Invite not found");
1748
+ }
1749
+ const replayJoinRequestId = inviteAlreadyAccepted
1750
+ ? existingJoinRequestForInvite?.id ?? null
1751
+ : null;
1752
+ if (inviteAlreadyAccepted && !replayJoinRequestId) {
1753
+ throw conflict("Join request not found");
1754
+ }
1755
+ const replayMergedDefaults = inviteAlreadyAccepted
1756
+ ? mergeJoinDefaultsPayloadForReplay(existingJoinRequestForInvite?.agentDefaultsPayload ?? null, req.body.agentDefaultsPayload ?? null)
1757
+ : req.body.agentDefaultsPayload ?? null;
1758
+ const gatewayDefaultsPayload = requestType === "agent"
1759
+ ? buildJoinDefaultsPayloadForAccept({
1760
+ agentRuntimeType,
1761
+ defaultsPayload: replayMergedDefaults,
1762
+ rudderApiUrl: req.body.rudderApiUrl ?? null,
1763
+ inboundOpenClawAuthHeader: req.header("x-openclaw-auth") ?? null,
1764
+ inboundOpenClawTokenHeader: req.header("x-openclaw-token") ?? null
1765
+ })
1766
+ : null;
1767
+ const joinDefaults = requestType === "agent"
1768
+ ? normalizeAgentDefaultsForJoin({
1769
+ agentRuntimeType,
1770
+ defaultsPayload: gatewayDefaultsPayload,
1771
+ deploymentMode: opts.deploymentMode,
1772
+ deploymentExposure: opts.deploymentExposure,
1773
+ bindHost: opts.bindHost,
1774
+ allowedHostnames: opts.allowedHostnames
1775
+ })
1776
+ : {
1777
+ normalized: null,
1778
+ diagnostics: [],
1779
+ fatalErrors: []
1780
+ };
1781
+ if (requestType === "agent" && joinDefaults.fatalErrors.length > 0) {
1782
+ throw badRequest(joinDefaults.fatalErrors.join("; "));
1783
+ }
1784
+ if (requestType === "agent" && agentRuntimeType === "openclaw_gateway") {
1785
+ logger.info({
1786
+ inviteId: invite.id,
1787
+ joinRequestDiagnostics: joinDefaults.diagnostics.map((diag) => ({
1788
+ code: diag.code,
1789
+ level: diag.level
1790
+ })),
1791
+ normalizedAgentDefaults: summarizeOpenClawGatewayDefaultsForLog(joinDefaults.normalized)
1792
+ }, "invite accept normalized OpenClaw gateway defaults");
1793
+ }
1794
+ const claimSecret = requestType === "agent" && !inviteAlreadyAccepted
1795
+ ? createClaimSecret()
1796
+ : null;
1797
+ const claimSecretHash = claimSecret ? hashToken(claimSecret) : null;
1798
+ const claimSecretExpiresAt = claimSecret
1799
+ ? new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
1800
+ : null;
1801
+ const actorEmail = requestType === "human" ? await resolveActorEmail(db, req) : null;
1802
+ const created = !inviteAlreadyAccepted
1803
+ ? await db.transaction(async (tx) => {
1804
+ await tx
1805
+ .update(invites)
1806
+ .set({ acceptedAt: new Date(), updatedAt: new Date() })
1807
+ .where(and(eq(invites.id, invite.id), isNull(invites.acceptedAt), isNull(invites.revokedAt)));
1808
+ const row = await tx
1809
+ .insert(joinRequests)
1810
+ .values({
1811
+ inviteId: invite.id,
1812
+ orgId,
1813
+ requestType,
1814
+ status: "pending_approval",
1815
+ requestIp: requestIp(req),
1816
+ requestingUserId: requestType === "human"
1817
+ ? req.actor.userId ?? "local-board"
1818
+ : null,
1819
+ requestEmailSnapshot: requestType === "human" ? actorEmail : null,
1820
+ agentName: requestType === "agent" ? req.body.agentName : null,
1821
+ agentRuntimeType: requestType === "agent" ? agentRuntimeType : null,
1822
+ capabilities: requestType === "agent"
1823
+ ? req.body.capabilities ?? null
1824
+ : null,
1825
+ agentDefaultsPayload: requestType === "agent" ? joinDefaults.normalized : null,
1826
+ claimSecretHash,
1827
+ claimSecretExpiresAt
1828
+ })
1829
+ .returning()
1830
+ .then((rows) => rows[0]);
1831
+ return row;
1832
+ })
1833
+ : await db
1834
+ .update(joinRequests)
1835
+ .set({
1836
+ requestIp: requestIp(req),
1837
+ agentName: requestType === "agent"
1838
+ ? req.body.agentName ??
1839
+ existingJoinRequestForInvite?.agentName ??
1840
+ null
1841
+ : null,
1842
+ capabilities: requestType === "agent"
1843
+ ? req.body.capabilities ??
1844
+ existingJoinRequestForInvite?.capabilities ??
1845
+ null
1846
+ : null,
1847
+ agentRuntimeType: requestType === "agent" ? agentRuntimeType : null,
1848
+ agentDefaultsPayload: requestType === "agent" ? joinDefaults.normalized : null,
1849
+ updatedAt: new Date()
1850
+ })
1851
+ .where(eq(joinRequests.id, replayJoinRequestId))
1852
+ .returning()
1853
+ .then((rows) => rows[0]);
1854
+ if (!created) {
1855
+ throw conflict("Join request not found");
1856
+ }
1857
+ if (inviteAlreadyAccepted &&
1858
+ requestType === "agent" &&
1859
+ agentRuntimeType === "openclaw_gateway" &&
1860
+ created.status === "approved" &&
1861
+ created.createdAgentId) {
1862
+ const existingAgent = await agents.getById(created.createdAgentId);
1863
+ if (!existingAgent) {
1864
+ throw conflict("Approved join request agent not found");
1865
+ }
1866
+ const existingAdapterConfig = isPlainObject(existingAgent.agentRuntimeConfig)
1867
+ ? existingAgent.agentRuntimeConfig
1868
+ : {};
1869
+ const nextAdapterConfig = {
1870
+ ...existingAdapterConfig,
1871
+ ...(joinDefaults.normalized ?? {})
1872
+ };
1873
+ const updatedAgent = await agents.update(created.createdAgentId, {
1874
+ agentRuntimeType,
1875
+ agentRuntimeConfig: nextAdapterConfig
1876
+ });
1877
+ if (!updatedAgent) {
1878
+ throw conflict("Approved join request agent not found");
1879
+ }
1880
+ await logActivity(db, {
1881
+ orgId,
1882
+ actorType: req.actor.type === "agent" ? "agent" : "user",
1883
+ actorId: req.actor.type === "agent"
1884
+ ? req.actor.agentId ?? "invite-agent"
1885
+ : req.actor.userId ?? "board",
1886
+ action: "agent.updated_from_join_replay",
1887
+ entityType: "agent",
1888
+ entityId: updatedAgent.id,
1889
+ details: { inviteId: invite.id, joinRequestId: created.id }
1890
+ });
1891
+ }
1892
+ if (requestType === "agent" && agentRuntimeType === "openclaw_gateway") {
1893
+ const expectedDefaults = summarizeOpenClawGatewayDefaultsForLog(joinDefaults.normalized);
1894
+ const persistedDefaults = summarizeOpenClawGatewayDefaultsForLog(created.agentDefaultsPayload);
1895
+ const missingPersistedFields = [];
1896
+ if (expectedDefaults.url && !persistedDefaults.url)
1897
+ missingPersistedFields.push("url");
1898
+ if (expectedDefaults.rudderApiUrl &&
1899
+ !persistedDefaults.rudderApiUrl) {
1900
+ missingPersistedFields.push("rudderApiUrl");
1901
+ }
1902
+ if (expectedDefaults.gatewayToken && !persistedDefaults.gatewayToken) {
1903
+ missingPersistedFields.push("headers.x-openclaw-token");
1904
+ }
1905
+ if (expectedDefaults.devicePrivateKeyPem &&
1906
+ !persistedDefaults.devicePrivateKeyPem) {
1907
+ missingPersistedFields.push("devicePrivateKeyPem");
1908
+ }
1909
+ if (expectedDefaults.headerKeys.length > 0 &&
1910
+ persistedDefaults.headerKeys.length === 0) {
1911
+ missingPersistedFields.push("headers");
1912
+ }
1913
+ logger.info({
1914
+ inviteId: invite.id,
1915
+ joinRequestId: created.id,
1916
+ joinRequestStatus: created.status,
1917
+ expectedDefaults,
1918
+ persistedDefaults,
1919
+ diagnostics: joinDefaults.diagnostics.map((diag) => ({
1920
+ code: diag.code,
1921
+ level: diag.level,
1922
+ message: diag.message,
1923
+ hint: diag.hint ?? null
1924
+ }))
1925
+ }, "invite accept persisted OpenClaw gateway join request");
1926
+ if (missingPersistedFields.length > 0) {
1927
+ logger.warn({
1928
+ inviteId: invite.id,
1929
+ joinRequestId: created.id,
1930
+ missingPersistedFields
1931
+ }, "invite accept detected missing persisted OpenClaw gateway defaults");
1932
+ }
1933
+ }
1934
+ await logActivity(db, {
1935
+ orgId,
1936
+ actorType: req.actor.type === "agent" ? "agent" : "user",
1937
+ actorId: req.actor.type === "agent"
1938
+ ? req.actor.agentId ?? "invite-agent"
1939
+ : req.actor.userId ??
1940
+ (requestType === "agent" ? "invite-anon" : "board"),
1941
+ action: inviteAlreadyAccepted
1942
+ ? "join.request_replayed"
1943
+ : "join.requested",
1944
+ entityType: "join_request",
1945
+ entityId: created.id,
1946
+ details: {
1947
+ requestType,
1948
+ requestIp: created.requestIp,
1949
+ inviteReplay: inviteAlreadyAccepted
1950
+ }
1951
+ });
1952
+ const response = toJoinRequestResponse(created);
1953
+ if (claimSecret) {
1954
+ const onboardingManifest = buildInviteOnboardingManifest(req, token, invite, opts);
1955
+ res.status(202).json({
1956
+ ...response,
1957
+ claimSecret,
1958
+ claimApiKeyPath: `/api/join-requests/${created.id}/claim-api-key`,
1959
+ onboarding: onboardingManifest.onboarding,
1960
+ diagnostics: joinDefaults.diagnostics
1961
+ });
1962
+ return;
1963
+ }
1964
+ res.status(202).json({
1965
+ ...response,
1966
+ ...(joinDefaults.diagnostics.length > 0
1967
+ ? { diagnostics: joinDefaults.diagnostics }
1968
+ : {})
1969
+ });
1970
+ });
1971
+ router.post("/invites/:inviteId/revoke", async (req, res) => {
1972
+ const id = req.params.inviteId;
1973
+ const invite = await db
1974
+ .select()
1975
+ .from(invites)
1976
+ .where(eq(invites.id, id))
1977
+ .then((rows) => rows[0] ?? null);
1978
+ if (!invite)
1979
+ throw notFound("Invite not found");
1980
+ if (invite.inviteType === "bootstrap_ceo") {
1981
+ await assertInstanceAdmin(req);
1982
+ }
1983
+ else {
1984
+ if (!invite.orgId)
1985
+ throw conflict("Invite is missing organization scope");
1986
+ await assertCompanyPermission(req, invite.orgId, "users:invite");
1987
+ }
1988
+ if (invite.acceptedAt)
1989
+ throw conflict("Invite already consumed");
1990
+ if (invite.revokedAt)
1991
+ return res.json(invite);
1992
+ const revoked = await db
1993
+ .update(invites)
1994
+ .set({ revokedAt: new Date(), updatedAt: new Date() })
1995
+ .where(eq(invites.id, id))
1996
+ .returning()
1997
+ .then((rows) => rows[0]);
1998
+ if (invite.orgId) {
1999
+ await logActivity(db, {
2000
+ orgId: invite.orgId,
2001
+ actorType: req.actor.type === "agent" ? "agent" : "user",
2002
+ actorId: req.actor.type === "agent"
2003
+ ? req.actor.agentId ?? "unknown-agent"
2004
+ : req.actor.userId ?? "board",
2005
+ action: "invite.revoked",
2006
+ entityType: "invite",
2007
+ entityId: id
2008
+ });
2009
+ }
2010
+ res.json(revoked);
2011
+ });
2012
+ router.get("/orgs/:orgId/join-requests", async (req, res) => {
2013
+ const orgId = req.params.orgId;
2014
+ await assertCompanyPermission(req, orgId, "joins:approve");
2015
+ const query = listJoinRequestsQuerySchema.parse(req.query);
2016
+ const all = await db
2017
+ .select()
2018
+ .from(joinRequests)
2019
+ .where(eq(joinRequests.orgId, orgId))
2020
+ .orderBy(desc(joinRequests.createdAt));
2021
+ const filtered = all.filter((row) => {
2022
+ if (query.status && row.status !== query.status)
2023
+ return false;
2024
+ if (query.requestType && row.requestType !== query.requestType)
2025
+ return false;
2026
+ return true;
2027
+ });
2028
+ res.json(filtered.map(toJoinRequestResponse));
2029
+ });
2030
+ router.post("/orgs/:orgId/join-requests/:requestId/approve", async (req, res) => {
2031
+ const orgId = req.params.orgId;
2032
+ const requestId = req.params.requestId;
2033
+ await assertCompanyPermission(req, orgId, "joins:approve");
2034
+ const existing = await db
2035
+ .select()
2036
+ .from(joinRequests)
2037
+ .where(and(eq(joinRequests.orgId, orgId), eq(joinRequests.id, requestId)))
2038
+ .then((rows) => rows[0] ?? null);
2039
+ if (!existing)
2040
+ throw notFound("Join request not found");
2041
+ if (existing.status !== "pending_approval")
2042
+ throw conflict("Join request is not pending");
2043
+ const invite = await db
2044
+ .select()
2045
+ .from(invites)
2046
+ .where(eq(invites.id, existing.inviteId))
2047
+ .then((rows) => rows[0] ?? null);
2048
+ if (!invite)
2049
+ throw notFound("Invite not found");
2050
+ let createdAgentId = existing.createdAgentId ?? null;
2051
+ if (existing.requestType === "human") {
2052
+ if (!existing.requestingUserId)
2053
+ throw conflict("Join request missing user identity");
2054
+ await access.ensureMembership(orgId, "user", existing.requestingUserId, "member", "active");
2055
+ const grants = grantsFromDefaults(invite.defaultsPayload, "human");
2056
+ await access.setPrincipalGrants(orgId, "user", existing.requestingUserId, grants, req.actor.userId ?? null);
2057
+ }
2058
+ else {
2059
+ const existingAgents = await agents.list(orgId);
2060
+ const managerId = resolveJoinRequestAgentManagerId(existingAgents);
2061
+ if (!managerId) {
2062
+ throw conflict("Join request cannot be approved because this organization has no active CEO");
2063
+ }
2064
+ const agentName = deduplicateAgentName(existing.agentName ?? "New Agent", existingAgents.map((a) => ({
2065
+ id: a.id,
2066
+ name: a.name,
2067
+ status: a.status
2068
+ })));
2069
+ const created = await agents.create(orgId, {
2070
+ name: agentName,
2071
+ role: "general",
2072
+ title: null,
2073
+ status: "idle",
2074
+ reportsTo: managerId,
2075
+ capabilities: existing.capabilities ?? null,
2076
+ agentRuntimeType: existing.agentRuntimeType ?? "process",
2077
+ agentRuntimeConfig: existing.agentDefaultsPayload &&
2078
+ typeof existing.agentDefaultsPayload === "object"
2079
+ ? existing.agentDefaultsPayload
2080
+ : {},
2081
+ runtimeConfig: {},
2082
+ budgetMonthlyCents: 0,
2083
+ spentMonthlyCents: 0,
2084
+ permissions: {},
2085
+ lastHeartbeatAt: null,
2086
+ metadata: null
2087
+ });
2088
+ createdAgentId = created.id;
2089
+ await access.ensureMembership(orgId, "agent", created.id, "member", "active");
2090
+ await access.setPrincipalPermission(orgId, "agent", created.id, "tasks:assign", true, req.actor.userId ?? null);
2091
+ const grants = grantsFromDefaults(invite.defaultsPayload, "agent");
2092
+ await access.setPrincipalGrants(orgId, "agent", created.id, grants, req.actor.userId ?? null);
2093
+ }
2094
+ const approved = await db
2095
+ .update(joinRequests)
2096
+ .set({
2097
+ status: "approved",
2098
+ approvedByUserId: req.actor.userId ?? (isLocalImplicit(req) ? "local-board" : null),
2099
+ approvedAt: new Date(),
2100
+ createdAgentId,
2101
+ updatedAt: new Date()
2102
+ })
2103
+ .where(eq(joinRequests.id, requestId))
2104
+ .returning()
2105
+ .then((rows) => rows[0]);
2106
+ await logActivity(db, {
2107
+ orgId,
2108
+ actorType: "user",
2109
+ actorId: req.actor.userId ?? "board",
2110
+ action: "join.approved",
2111
+ entityType: "join_request",
2112
+ entityId: requestId,
2113
+ details: { requestType: existing.requestType, createdAgentId }
2114
+ });
2115
+ if (createdAgentId) {
2116
+ void notifyHireApproved(db, {
2117
+ orgId,
2118
+ agentId: createdAgentId,
2119
+ source: "join_request",
2120
+ sourceId: requestId,
2121
+ approvedAt: new Date()
2122
+ }).catch(() => { });
2123
+ }
2124
+ res.json(toJoinRequestResponse(approved));
2125
+ });
2126
+ router.post("/orgs/:orgId/join-requests/:requestId/reject", async (req, res) => {
2127
+ const orgId = req.params.orgId;
2128
+ const requestId = req.params.requestId;
2129
+ await assertCompanyPermission(req, orgId, "joins:approve");
2130
+ const existing = await db
2131
+ .select()
2132
+ .from(joinRequests)
2133
+ .where(and(eq(joinRequests.orgId, orgId), eq(joinRequests.id, requestId)))
2134
+ .then((rows) => rows[0] ?? null);
2135
+ if (!existing)
2136
+ throw notFound("Join request not found");
2137
+ if (existing.status !== "pending_approval")
2138
+ throw conflict("Join request is not pending");
2139
+ const rejected = await db
2140
+ .update(joinRequests)
2141
+ .set({
2142
+ status: "rejected",
2143
+ rejectedByUserId: req.actor.userId ?? (isLocalImplicit(req) ? "local-board" : null),
2144
+ rejectedAt: new Date(),
2145
+ updatedAt: new Date()
2146
+ })
2147
+ .where(eq(joinRequests.id, requestId))
2148
+ .returning()
2149
+ .then((rows) => rows[0]);
2150
+ await logActivity(db, {
2151
+ orgId,
2152
+ actorType: "user",
2153
+ actorId: req.actor.userId ?? "board",
2154
+ action: "join.rejected",
2155
+ entityType: "join_request",
2156
+ entityId: requestId,
2157
+ details: { requestType: existing.requestType }
2158
+ });
2159
+ res.json(toJoinRequestResponse(rejected));
2160
+ });
2161
+ router.post("/join-requests/:requestId/claim-api-key", validate(claimJoinRequestApiKeySchema), async (req, res) => {
2162
+ const requestId = req.params.requestId;
2163
+ const presentedClaimSecretHash = hashToken(req.body.claimSecret);
2164
+ const joinRequest = await db
2165
+ .select()
2166
+ .from(joinRequests)
2167
+ .where(eq(joinRequests.id, requestId))
2168
+ .then((rows) => rows[0] ?? null);
2169
+ if (!joinRequest)
2170
+ throw notFound("Join request not found");
2171
+ if (joinRequest.requestType !== "agent")
2172
+ throw badRequest("Only agent join requests can claim API keys");
2173
+ if (joinRequest.status !== "approved")
2174
+ throw conflict("Join request must be approved before key claim");
2175
+ if (!joinRequest.createdAgentId)
2176
+ throw conflict("Join request has no created agent");
2177
+ if (!joinRequest.claimSecretHash)
2178
+ throw conflict("Join request is missing claim secret metadata");
2179
+ if (!tokenHashesMatch(joinRequest.claimSecretHash, presentedClaimSecretHash)) {
2180
+ throw forbidden("Invalid claim secret");
2181
+ }
2182
+ if (joinRequest.claimSecretExpiresAt &&
2183
+ joinRequest.claimSecretExpiresAt.getTime() <= Date.now()) {
2184
+ throw conflict("Claim secret expired");
2185
+ }
2186
+ if (joinRequest.claimSecretConsumedAt)
2187
+ throw conflict("Claim secret already used");
2188
+ const existingKey = await db
2189
+ .select({ id: agentApiKeys.id })
2190
+ .from(agentApiKeys)
2191
+ .where(eq(agentApiKeys.agentId, joinRequest.createdAgentId))
2192
+ .then((rows) => rows[0] ?? null);
2193
+ if (existingKey)
2194
+ throw conflict("API key already claimed");
2195
+ const consumed = await db
2196
+ .update(joinRequests)
2197
+ .set({ claimSecretConsumedAt: new Date(), updatedAt: new Date() })
2198
+ .where(and(eq(joinRequests.id, requestId), isNull(joinRequests.claimSecretConsumedAt)))
2199
+ .returning({ id: joinRequests.id })
2200
+ .then((rows) => rows[0] ?? null);
2201
+ if (!consumed)
2202
+ throw conflict("Claim secret already used");
2203
+ const created = await agents.createApiKey(joinRequest.createdAgentId, "initial-join-key");
2204
+ await logActivity(db, {
2205
+ orgId: joinRequest.orgId,
2206
+ actorType: "system",
2207
+ actorId: "join-claim",
2208
+ action: "agent_api_key.claimed",
2209
+ entityType: "agent_api_key",
2210
+ entityId: created.id,
2211
+ details: {
2212
+ agentId: joinRequest.createdAgentId,
2213
+ joinRequestId: requestId
2214
+ }
2215
+ });
2216
+ res.status(201).json({
2217
+ keyId: created.id,
2218
+ token: created.token,
2219
+ agentId: joinRequest.createdAgentId,
2220
+ createdAt: created.createdAt
2221
+ });
2222
+ });
2223
+ router.get("/orgs/:orgId/members", async (req, res) => {
2224
+ const orgId = req.params.orgId;
2225
+ await assertCompanyPermission(req, orgId, "users:manage_permissions");
2226
+ const members = await access.listMembers(orgId);
2227
+ res.json(members);
2228
+ });
2229
+ router.patch("/orgs/:orgId/members/:memberId/permissions", validate(updateMemberPermissionsSchema), async (req, res) => {
2230
+ const orgId = req.params.orgId;
2231
+ const memberId = req.params.memberId;
2232
+ await assertCompanyPermission(req, orgId, "users:manage_permissions");
2233
+ const updated = await access.setMemberPermissions(orgId, memberId, req.body.grants ?? [], req.actor.userId ?? null);
2234
+ if (!updated)
2235
+ throw notFound("Member not found");
2236
+ res.json(updated);
2237
+ });
2238
+ router.post("/admin/users/:userId/promote-instance-admin", async (req, res) => {
2239
+ await assertInstanceAdmin(req);
2240
+ const userId = req.params.userId;
2241
+ const result = await access.promoteInstanceAdmin(userId);
2242
+ res.status(201).json(result);
2243
+ });
2244
+ router.post("/admin/users/:userId/demote-instance-admin", async (req, res) => {
2245
+ await assertInstanceAdmin(req);
2246
+ const userId = req.params.userId;
2247
+ const removed = await access.demoteInstanceAdmin(userId);
2248
+ if (!removed)
2249
+ throw notFound("Instance admin role not found");
2250
+ res.json(removed);
2251
+ });
2252
+ router.get("/admin/users/:userId/organization-access", async (req, res) => {
2253
+ await assertInstanceAdmin(req);
2254
+ const userId = req.params.userId;
2255
+ const memberships = await access.listUserCompanyAccess(userId);
2256
+ res.json(memberships);
2257
+ });
2258
+ router.put("/admin/users/:userId/organization-access", validate(updateUserCompanyAccessSchema), async (req, res) => {
2259
+ await assertInstanceAdmin(req);
2260
+ const userId = req.params.userId;
2261
+ const memberships = await access.setUserCompanyAccess(userId, req.body.orgIds ?? []);
2262
+ res.json(memberships);
2263
+ });
2264
+ return router;
2265
+ }
2266
+ //# sourceMappingURL=access.js.map