corporateai 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (704) hide show
  1. package/.dockerignore +10 -0
  2. package/.env.example +3 -0
  3. package/.github/workflows/publish-cli.yml +49 -0
  4. package/.mailmap +1 -0
  5. package/AGENTS.md +148 -0
  6. package/CONTRIBUTING.md +75 -0
  7. package/Dockerfile +59 -0
  8. package/Dockerfile.onboard-smoke +42 -0
  9. package/LICENSE +21 -0
  10. package/README.md +93 -0
  11. package/cli/esbuild.config.mjs +11 -0
  12. package/cli/package.json +24 -0
  13. package/cli/scripts/build-cli.mjs +5 -0
  14. package/cli/src/index.ts +27 -0
  15. package/docker-compose.quickstart.yml +18 -0
  16. package/docker-compose.untrusted-review.yml +33 -0
  17. package/docker-compose.yml +38 -0
  18. package/package.json +56 -0
  19. package/patches/embedded-postgres@18.1.0-beta.16.patch +0 -0
  20. package/pnpm-workspace.yaml +4 -0
  21. package/releases/.gitkeep +0 -0
  22. package/releases/v0.0.1.md +36 -0
  23. package/releases/v0.2.7.md +15 -0
  24. package/releases/v0.3.0.md +54 -0
  25. package/releases/v0.3.1.md +55 -0
  26. package/releases/v2026.318.0.md +66 -0
  27. package/releases/v2026.325.0.md +78 -0
  28. package/report/2026-03-13-08-46-token-optimization-implementation.md +48 -0
  29. package/scripts/backup-db.sh +17 -0
  30. package/scripts/build-npm.sh +80 -0
  31. package/scripts/check-forbidden-tokens.mjs +115 -0
  32. package/scripts/clean-onboard-git.sh +14 -0
  33. package/scripts/clean-onboard-npm.sh +13 -0
  34. package/scripts/clean-onboard-ref.sh +86 -0
  35. package/scripts/create-github-release.sh +99 -0
  36. package/scripts/dev-runner-paths.mjs +38 -0
  37. package/scripts/dev-runner.mjs +606 -0
  38. package/scripts/docker-onboard-smoke.sh +306 -0
  39. package/scripts/ensure-plugin-build-deps.mjs +47 -0
  40. package/scripts/generate-company-assets.ts +365 -0
  41. package/scripts/generate-npm-package-json.mjs +113 -0
  42. package/scripts/generate-org-chart-images.ts +694 -0
  43. package/scripts/generate-org-chart-satori-comparison.ts +225 -0
  44. package/scripts/generate-ui-package-json.mjs +31 -0
  45. package/scripts/kill-dev.sh +71 -0
  46. package/scripts/migrate-inline-env-secrets.ts +126 -0
  47. package/scripts/prepare-server-ui-dist.sh +22 -0
  48. package/scripts/provision-worktree.sh +333 -0
  49. package/scripts/release-lib.sh +306 -0
  50. package/scripts/release-package-map.mjs +169 -0
  51. package/scripts/release.sh +312 -0
  52. package/scripts/rollback-latest.sh +111 -0
  53. package/scripts/smoke/openclaw-docker-ui.sh +329 -0
  54. package/scripts/smoke/openclaw-gateway-e2e.sh +954 -0
  55. package/scripts/smoke/openclaw-join.sh +295 -0
  56. package/scripts/smoke/openclaw-sse-standalone.sh +146 -0
  57. package/scripts/workspace-compat.mjs +60 -0
  58. package/server/CHANGELOG.md +130 -0
  59. package/server/package.json +96 -0
  60. package/server/scripts/copy-onboarding-assets.mjs +10 -0
  61. package/server/scripts/dev-watch.ts +33 -0
  62. package/server/src/__tests__/activity-routes.test.ts +70 -0
  63. package/server/src/__tests__/adapter-models.test.ts +105 -0
  64. package/server/src/__tests__/adapter-session-codecs.test.ts +194 -0
  65. package/server/src/__tests__/agent-auth-jwt.test.ts +79 -0
  66. package/server/src/__tests__/agent-instructions-routes.test.ts +318 -0
  67. package/server/src/__tests__/agent-instructions-service.test.ts +361 -0
  68. package/server/src/__tests__/agent-permissions-routes.test.ts +275 -0
  69. package/server/src/__tests__/agent-shortname-collision.test.ts +69 -0
  70. package/server/src/__tests__/agent-skill-contract.test.ts +50 -0
  71. package/server/src/__tests__/agent-skills-routes.test.ts +462 -0
  72. package/server/src/__tests__/app-hmr-port.test.ts +19 -0
  73. package/server/src/__tests__/approval-routes-idempotency.test.ts +110 -0
  74. package/server/src/__tests__/approvals-service.test.ts +107 -0
  75. package/server/src/__tests__/assets.test.ts +250 -0
  76. package/server/src/__tests__/attachment-types.test.ts +97 -0
  77. package/server/src/__tests__/board-mutation-guard.test.ts +105 -0
  78. package/server/src/__tests__/budgets-service.test.ts +311 -0
  79. package/server/src/__tests__/claude-local-adapter-environment.test.ts +92 -0
  80. package/server/src/__tests__/claude-local-adapter.test.ts +31 -0
  81. package/server/src/__tests__/claude-local-skill-sync.test.ts +111 -0
  82. package/server/src/__tests__/cli-auth-routes.test.ts +230 -0
  83. package/server/src/__tests__/codex-local-adapter-environment.test.ts +143 -0
  84. package/server/src/__tests__/codex-local-adapter.test.ts +253 -0
  85. package/server/src/__tests__/codex-local-execute.test.ts +391 -0
  86. package/server/src/__tests__/codex-local-skill-injection.test.ts +175 -0
  87. package/server/src/__tests__/codex-local-skill-sync.test.ts +123 -0
  88. package/server/src/__tests__/companies-route-path-guard.test.ts +56 -0
  89. package/server/src/__tests__/company-branding-route.test.ts +196 -0
  90. package/server/src/__tests__/company-portability-routes.test.ts +175 -0
  91. package/server/src/__tests__/company-portability.test.ts +2186 -0
  92. package/server/src/__tests__/company-skills-routes.test.ts +113 -0
  93. package/server/src/__tests__/company-skills.test.ts +229 -0
  94. package/server/src/__tests__/costs-service.test.ts +226 -0
  95. package/server/src/__tests__/cursor-local-adapter-environment.test.ts +196 -0
  96. package/server/src/__tests__/cursor-local-adapter.test.ts +406 -0
  97. package/server/src/__tests__/cursor-local-execute.test.ts +263 -0
  98. package/server/src/__tests__/cursor-local-skill-injection.test.ts +104 -0
  99. package/server/src/__tests__/cursor-local-skill-sync.test.ts +145 -0
  100. package/server/src/__tests__/dev-runner-paths.test.ts +25 -0
  101. package/server/src/__tests__/dev-server-status.test.ts +66 -0
  102. package/server/src/__tests__/dev-watch-ignore.test.ts +42 -0
  103. package/server/src/__tests__/documents.test.ts +29 -0
  104. package/server/src/__tests__/error-handler.test.ts +53 -0
  105. package/server/src/__tests__/execution-workspace-policy.test.ts +170 -0
  106. package/server/src/__tests__/forbidden-tokens.test.ts +77 -0
  107. package/server/src/__tests__/gemini-local-adapter-environment.test.ts +135 -0
  108. package/server/src/__tests__/gemini-local-adapter.test.ts +190 -0
  109. package/server/src/__tests__/gemini-local-execute.test.ts +172 -0
  110. package/server/src/__tests__/gemini-local-skill-sync.test.ts +90 -0
  111. package/server/src/__tests__/health.test.ts +16 -0
  112. package/server/src/__tests__/heartbeat-process-recovery.test.ts +256 -0
  113. package/server/src/__tests__/heartbeat-run-summary.test.ts +33 -0
  114. package/server/src/__tests__/heartbeat-workspace-session.test.ts +334 -0
  115. package/server/src/__tests__/helpers/embedded-postgres.ts +7 -0
  116. package/server/src/__tests__/hire-hook.test.ts +181 -0
  117. package/server/src/__tests__/instance-settings-routes.test.ts +156 -0
  118. package/server/src/__tests__/invite-accept-gateway-defaults.test.ts +119 -0
  119. package/server/src/__tests__/invite-accept-replay.test.ts +92 -0
  120. package/server/src/__tests__/invite-expiry.test.ts +10 -0
  121. package/server/src/__tests__/invite-join-grants.test.ts +57 -0
  122. package/server/src/__tests__/invite-join-manager.test.ts +33 -0
  123. package/server/src/__tests__/invite-onboarding-text.test.ts +116 -0
  124. package/server/src/__tests__/issue-comment-reopen-routes.test.ts +146 -0
  125. package/server/src/__tests__/issue-goal-fallback.test.ts +99 -0
  126. package/server/src/__tests__/issues-checkout-wakeup.test.ts +48 -0
  127. package/server/src/__tests__/issues-goal-context-routes.test.ts +187 -0
  128. package/server/src/__tests__/issues-service.test.ts +317 -0
  129. package/server/src/__tests__/issues-user-context.test.ts +113 -0
  130. package/server/src/__tests__/log-redaction.test.ts +74 -0
  131. package/server/src/__tests__/monthly-spend-service.test.ts +90 -0
  132. package/server/src/__tests__/normalize-agent-mention-token.test.ts +41 -0
  133. package/server/src/__tests__/openclaw-gateway-adapter.test.ts +626 -0
  134. package/server/src/__tests__/openclaw-invite-prompt-route.test.ts +192 -0
  135. package/server/src/__tests__/opencode-local-adapter-environment.test.ts +97 -0
  136. package/server/src/__tests__/opencode-local-adapter.test.ts +226 -0
  137. package/server/src/__tests__/opencode-local-skill-sync.test.ts +91 -0
  138. package/server/src/__tests__/paperclip-env.test.ts +58 -0
  139. package/server/src/__tests__/paperclip-skill-utils.test.ts +63 -0
  140. package/server/src/__tests__/pi-local-adapter-environment.test.ts +102 -0
  141. package/server/src/__tests__/pi-local-skill-sync.test.ts +95 -0
  142. package/server/src/__tests__/plugin-dev-watcher.test.ts +68 -0
  143. package/server/src/__tests__/plugin-worker-manager.test.ts +43 -0
  144. package/server/src/__tests__/private-hostname-guard.test.ts +56 -0
  145. package/server/src/__tests__/project-shortname-resolution.test.ts +45 -0
  146. package/server/src/__tests__/quota-windows-service.test.ts +56 -0
  147. package/server/src/__tests__/quota-windows.test.ts +1109 -0
  148. package/server/src/__tests__/redaction.test.ts +66 -0
  149. package/server/src/__tests__/routines-e2e.test.ts +276 -0
  150. package/server/src/__tests__/routines-routes.test.ts +271 -0
  151. package/server/src/__tests__/routines-service.test.ts +424 -0
  152. package/server/src/__tests__/storage-local-provider.test.ts +78 -0
  153. package/server/src/__tests__/ui-branding.test.ts +82 -0
  154. package/server/src/__tests__/work-products.test.ts +95 -0
  155. package/server/src/__tests__/workspace-runtime.test.ts +1131 -0
  156. package/server/src/__tests__/worktree-config.test.ts +426 -0
  157. package/server/src/adapters/codex-models.ts +105 -0
  158. package/server/src/adapters/cursor-models.ts +171 -0
  159. package/server/src/adapters/http/execute.ts +42 -0
  160. package/server/src/adapters/http/index.ts +21 -0
  161. package/server/src/adapters/http/test.ts +116 -0
  162. package/server/src/adapters/index.ts +18 -0
  163. package/server/src/adapters/process/execute.ts +77 -0
  164. package/server/src/adapters/process/index.ts +24 -0
  165. package/server/src/adapters/process/test.ts +89 -0
  166. package/server/src/adapters/registry.ts +225 -0
  167. package/server/src/adapters/server-utils-compat.ts +57 -0
  168. package/server/src/adapters/types.ts +30 -0
  169. package/server/src/adapters/utils.ts +48 -0
  170. package/server/src/agent-auth-jwt.ts +141 -0
  171. package/server/src/app.ts +321 -0
  172. package/server/src/attachment-types.ts +74 -0
  173. package/server/src/auth/better-auth.ts +148 -0
  174. package/server/src/board-claim.ts +150 -0
  175. package/server/src/config-file.ts +17 -0
  176. package/server/src/config.ts +260 -0
  177. package/server/src/dev-server-status.ts +103 -0
  178. package/server/src/dev-watch-ignore.ts +36 -0
  179. package/server/src/errors.ts +34 -0
  180. package/server/src/home-paths.ts +95 -0
  181. package/server/src/index.ts +799 -0
  182. package/server/src/log-redaction.ts +146 -0
  183. package/server/src/middleware/auth.ts +178 -0
  184. package/server/src/middleware/board-mutation-guard.ts +66 -0
  185. package/server/src/middleware/error-handler.ts +71 -0
  186. package/server/src/middleware/index.ts +3 -0
  187. package/server/src/middleware/logger.ts +90 -0
  188. package/server/src/middleware/private-hostname-guard.ts +92 -0
  189. package/server/src/middleware/validate.ts +9 -0
  190. package/server/src/onboarding-assets/ceo/AGENTS.md +54 -0
  191. package/server/src/onboarding-assets/ceo/HEARTBEAT.md +72 -0
  192. package/server/src/onboarding-assets/ceo/SOUL.md +33 -0
  193. package/server/src/onboarding-assets/ceo/TOOLS.md +3 -0
  194. package/server/src/onboarding-assets/default/AGENTS.md +3 -0
  195. package/server/src/paths.ts +34 -0
  196. package/server/src/realtime/live-events-ws.ts +274 -0
  197. package/server/src/redaction.ts +59 -0
  198. package/server/src/routes/access.ts +2888 -0
  199. package/server/src/routes/activity.ts +89 -0
  200. package/server/src/routes/agents.ts +2313 -0
  201. package/server/src/routes/approvals.ts +346 -0
  202. package/server/src/routes/assets.ts +341 -0
  203. package/server/src/routes/authz.ts +52 -0
  204. package/server/src/routes/companies.ts +343 -0
  205. package/server/src/routes/company-skills.ts +300 -0
  206. package/server/src/routes/costs.ts +335 -0
  207. package/server/src/routes/dashboard.ts +19 -0
  208. package/server/src/routes/execution-workspaces.ts +182 -0
  209. package/server/src/routes/goals.ts +107 -0
  210. package/server/src/routes/health.ts +94 -0
  211. package/server/src/routes/index.ts +17 -0
  212. package/server/src/routes/instance-settings.ts +95 -0
  213. package/server/src/routes/issues-checkout-wakeup.ts +14 -0
  214. package/server/src/routes/issues.ts +1680 -0
  215. package/server/src/routes/llms.ts +86 -0
  216. package/server/src/routes/org-chart-svg.ts +777 -0
  217. package/server/src/routes/plugin-ui-static.ts +497 -0
  218. package/server/src/routes/plugins.ts +2220 -0
  219. package/server/src/routes/projects.ts +295 -0
  220. package/server/src/routes/routines.ts +300 -0
  221. package/server/src/routes/secrets.ts +166 -0
  222. package/server/src/routes/sidebar-badges.ts +52 -0
  223. package/server/src/secrets/external-stub-providers.ts +32 -0
  224. package/server/src/secrets/local-encrypted-provider.ts +135 -0
  225. package/server/src/secrets/provider-registry.ts +31 -0
  226. package/server/src/secrets/types.ts +23 -0
  227. package/server/src/services/access.ts +381 -0
  228. package/server/src/services/activity-log.ts +95 -0
  229. package/server/src/services/activity.ts +164 -0
  230. package/server/src/services/agent-instructions.ts +735 -0
  231. package/server/src/services/agent-permissions.ts +27 -0
  232. package/server/src/services/agents.ts +694 -0
  233. package/server/src/services/approvals.ts +273 -0
  234. package/server/src/services/assets.ts +23 -0
  235. package/server/src/services/board-auth.ts +355 -0
  236. package/server/src/services/budgets.ts +959 -0
  237. package/server/src/services/companies.ts +313 -0
  238. package/server/src/services/company-export-readme.ts +173 -0
  239. package/server/src/services/company-portability.ts +4263 -0
  240. package/server/src/services/company-skills.ts +2356 -0
  241. package/server/src/services/costs.ts +365 -0
  242. package/server/src/services/cron.ts +373 -0
  243. package/server/src/services/dashboard.ts +110 -0
  244. package/server/src/services/default-agent-instructions.ts +27 -0
  245. package/server/src/services/documents.ts +434 -0
  246. package/server/src/services/execution-workspace-policy.ts +210 -0
  247. package/server/src/services/execution-workspaces.ts +100 -0
  248. package/server/src/services/finance.ts +135 -0
  249. package/server/src/services/goals.ts +81 -0
  250. package/server/src/services/heartbeat-run-summary.ts +35 -0
  251. package/server/src/services/heartbeat.ts +3863 -0
  252. package/server/src/services/hire-hook.ts +114 -0
  253. package/server/src/services/index.ts +32 -0
  254. package/server/src/services/instance-settings.ts +138 -0
  255. package/server/src/services/issue-approvals.ts +175 -0
  256. package/server/src/services/issue-assignment-wakeup.ts +48 -0
  257. package/server/src/services/issue-goal-fallback.ts +56 -0
  258. package/server/src/services/issues.ts +1828 -0
  259. package/server/src/services/live-events.ts +55 -0
  260. package/server/src/services/plugin-capability-validator.ts +450 -0
  261. package/server/src/services/plugin-config-validator.ts +55 -0
  262. package/server/src/services/plugin-dev-watcher.ts +339 -0
  263. package/server/src/services/plugin-event-bus.ts +413 -0
  264. package/server/src/services/plugin-host-service-cleanup.ts +59 -0
  265. package/server/src/services/plugin-host-services.ts +1132 -0
  266. package/server/src/services/plugin-job-coordinator.ts +261 -0
  267. package/server/src/services/plugin-job-scheduler.ts +753 -0
  268. package/server/src/services/plugin-job-store.ts +466 -0
  269. package/server/src/services/plugin-lifecycle.ts +822 -0
  270. package/server/src/services/plugin-loader.ts +1955 -0
  271. package/server/src/services/plugin-log-retention.ts +87 -0
  272. package/server/src/services/plugin-manifest-validator.ts +164 -0
  273. package/server/src/services/plugin-registry.ts +683 -0
  274. package/server/src/services/plugin-runtime-sandbox.ts +222 -0
  275. package/server/src/services/plugin-secrets-handler.ts +355 -0
  276. package/server/src/services/plugin-state-store.ts +238 -0
  277. package/server/src/services/plugin-stream-bus.ts +81 -0
  278. package/server/src/services/plugin-tool-dispatcher.ts +449 -0
  279. package/server/src/services/plugin-tool-registry.ts +450 -0
  280. package/server/src/services/plugin-worker-manager.ts +1343 -0
  281. package/server/src/services/projects.ts +860 -0
  282. package/server/src/services/quota-windows.ts +65 -0
  283. package/server/src/services/routines.ts +1269 -0
  284. package/server/src/services/run-log-store.ts +156 -0
  285. package/server/src/services/secrets.ts +370 -0
  286. package/server/src/services/sidebar-badges.ts +56 -0
  287. package/server/src/services/work-products.ts +124 -0
  288. package/server/src/services/workspace-operation-log-store.ts +156 -0
  289. package/server/src/services/workspace-operations.ts +262 -0
  290. package/server/src/services/workspace-runtime.ts +1565 -0
  291. package/server/src/startup-banner.ts +176 -0
  292. package/server/src/storage/index.ts +35 -0
  293. package/server/src/storage/local-disk-provider.ts +89 -0
  294. package/server/src/storage/provider-registry.ts +18 -0
  295. package/server/src/storage/s3-provider.ts +153 -0
  296. package/server/src/storage/service.ts +131 -0
  297. package/server/src/storage/types.ts +63 -0
  298. package/server/src/ui-branding.ts +217 -0
  299. package/server/src/version.ts +10 -0
  300. package/server/src/worktree-config.ts +468 -0
  301. package/server/tsconfig.json +9 -0
  302. package/server/vitest.config.ts +7 -0
  303. package/skills/paperclip/SKILL.md +365 -0
  304. package/skills/paperclip/references/api-reference.md +647 -0
  305. package/skills/paperclip/references/company-skills.md +193 -0
  306. package/skills/paperclip-create-agent/SKILL.md +142 -0
  307. package/skills/paperclip-create-agent/references/api-reference.md +105 -0
  308. package/skills/paperclip-create-plugin/SKILL.md +102 -0
  309. package/skills/para-memory-files/SKILL.md +104 -0
  310. package/skills/para-memory-files/references/schemas.md +35 -0
  311. package/tests/e2e/onboarding.spec.ts +142 -0
  312. package/tests/e2e/playwright.config.ts +35 -0
  313. package/tests/release-smoke/docker-auth-onboarding.spec.ts +141 -0
  314. package/tests/release-smoke/playwright.config.ts +28 -0
  315. package/tsconfig.base.json +18 -0
  316. package/tsconfig.json +18 -0
  317. package/ui/README.md +12 -0
  318. package/ui/components.json +21 -0
  319. package/ui/index.html +47 -0
  320. package/ui/package.json +73 -0
  321. package/ui/public/android-chrome-192x192.png +0 -0
  322. package/ui/public/android-chrome-512x512.png +0 -0
  323. package/ui/public/apple-touch-icon.png +0 -0
  324. package/ui/public/brands/opencode-logo-dark-square.svg +18 -0
  325. package/ui/public/brands/opencode-logo-light-square.svg +18 -0
  326. package/ui/public/favicon-16x16.png +0 -0
  327. package/ui/public/favicon-32x32.png +0 -0
  328. package/ui/public/favicon.ico +0 -0
  329. package/ui/public/favicon.svg +9 -0
  330. package/ui/public/site.webmanifest +30 -0
  331. package/ui/public/sprites/1-D-1.png +0 -0
  332. package/ui/public/sprites/1-D-2.png +0 -0
  333. package/ui/public/sprites/1-D-3.png +0 -0
  334. package/ui/public/sprites/1-L-1.png +0 -0
  335. package/ui/public/sprites/1-R-1.png +0 -0
  336. package/ui/public/sprites/10-D-1.png +0 -0
  337. package/ui/public/sprites/10-D-2.png +0 -0
  338. package/ui/public/sprites/10-D-3.png +0 -0
  339. package/ui/public/sprites/10-L-1.png +0 -0
  340. package/ui/public/sprites/10-R-1.png +0 -0
  341. package/ui/public/sprites/11-D-1.png +0 -0
  342. package/ui/public/sprites/11-D-2.png +0 -0
  343. package/ui/public/sprites/11-D-3.png +0 -0
  344. package/ui/public/sprites/11-L-1.png +0 -0
  345. package/ui/public/sprites/11-R-1.png +0 -0
  346. package/ui/public/sprites/12-D-1.png +0 -0
  347. package/ui/public/sprites/12-D-2.png +0 -0
  348. package/ui/public/sprites/12-D-3.png +0 -0
  349. package/ui/public/sprites/12-L-1.png +0 -0
  350. package/ui/public/sprites/12-R-1.png +0 -0
  351. package/ui/public/sprites/13-D-1.png +0 -0
  352. package/ui/public/sprites/13-D-2.png +0 -0
  353. package/ui/public/sprites/13-D-3.png +0 -0
  354. package/ui/public/sprites/13-L-1.png +0 -0
  355. package/ui/public/sprites/13-R-1.png +0 -0
  356. package/ui/public/sprites/14-D-1.png +0 -0
  357. package/ui/public/sprites/14-D-2.png +0 -0
  358. package/ui/public/sprites/14-D-3.png +0 -0
  359. package/ui/public/sprites/14-L-1.png +0 -0
  360. package/ui/public/sprites/14-R-1.png +0 -0
  361. package/ui/public/sprites/2-D-1.png +0 -0
  362. package/ui/public/sprites/2-D-2.png +0 -0
  363. package/ui/public/sprites/2-D-3.png +0 -0
  364. package/ui/public/sprites/2-L-1.png +0 -0
  365. package/ui/public/sprites/2-R-1.png +0 -0
  366. package/ui/public/sprites/3-D-1.png +0 -0
  367. package/ui/public/sprites/3-D-2.png +0 -0
  368. package/ui/public/sprites/3-D-3.png +0 -0
  369. package/ui/public/sprites/3-L-1.png +0 -0
  370. package/ui/public/sprites/3-R-1.png +0 -0
  371. package/ui/public/sprites/4-D-1.png +0 -0
  372. package/ui/public/sprites/4-D-2.png +0 -0
  373. package/ui/public/sprites/4-D-3.png +0 -0
  374. package/ui/public/sprites/4-L-1.png +0 -0
  375. package/ui/public/sprites/4-R-1.png +0 -0
  376. package/ui/public/sprites/5-D-1.png +0 -0
  377. package/ui/public/sprites/5-D-2.png +0 -0
  378. package/ui/public/sprites/5-D-3.png +0 -0
  379. package/ui/public/sprites/5-L-1.png +0 -0
  380. package/ui/public/sprites/5-R-1.png +0 -0
  381. package/ui/public/sprites/6-D-1.png +0 -0
  382. package/ui/public/sprites/6-D-2.png +0 -0
  383. package/ui/public/sprites/6-D-3.png +0 -0
  384. package/ui/public/sprites/6-L-1.png +0 -0
  385. package/ui/public/sprites/6-R-1.png +0 -0
  386. package/ui/public/sprites/7-D-1.png +0 -0
  387. package/ui/public/sprites/7-D-2.png +0 -0
  388. package/ui/public/sprites/7-D-3.png +0 -0
  389. package/ui/public/sprites/7-L-1.png +0 -0
  390. package/ui/public/sprites/7-R-1.png +0 -0
  391. package/ui/public/sprites/8-D-1.png +0 -0
  392. package/ui/public/sprites/8-D-2.png +0 -0
  393. package/ui/public/sprites/8-D-3.png +0 -0
  394. package/ui/public/sprites/8-L-1.png +0 -0
  395. package/ui/public/sprites/8-R-1.png +0 -0
  396. package/ui/public/sprites/9-D-1.png +0 -0
  397. package/ui/public/sprites/9-D-2.png +0 -0
  398. package/ui/public/sprites/9-D-3.png +0 -0
  399. package/ui/public/sprites/9-L-1.png +0 -0
  400. package/ui/public/sprites/9-R-1.png +0 -0
  401. package/ui/public/sprites/ceo-lobster.png +0 -0
  402. package/ui/public/sw.js +42 -0
  403. package/ui/public/worktree-favicon-16x16.png +0 -0
  404. package/ui/public/worktree-favicon-32x32.png +0 -0
  405. package/ui/public/worktree-favicon.ico +0 -0
  406. package/ui/public/worktree-favicon.svg +9 -0
  407. package/ui/src/App.tsx +354 -0
  408. package/ui/src/adapters/claude-local/config-fields.tsx +138 -0
  409. package/ui/src/adapters/claude-local/index.ts +13 -0
  410. package/ui/src/adapters/codex-local/config-fields.tsx +104 -0
  411. package/ui/src/adapters/codex-local/index.ts +13 -0
  412. package/ui/src/adapters/cursor/config-fields.tsx +49 -0
  413. package/ui/src/adapters/cursor/index.ts +13 -0
  414. package/ui/src/adapters/gemini-local/config-fields.tsx +51 -0
  415. package/ui/src/adapters/gemini-local/index.ts +13 -0
  416. package/ui/src/adapters/http/build-config.ts +9 -0
  417. package/ui/src/adapters/http/config-fields.tsx +38 -0
  418. package/ui/src/adapters/http/index.ts +12 -0
  419. package/ui/src/adapters/http/parse-stdout.ts +5 -0
  420. package/ui/src/adapters/index.ts +9 -0
  421. package/ui/src/adapters/local-workspace-runtime-fields.tsx +5 -0
  422. package/ui/src/adapters/openclaw-gateway/config-fields.tsx +237 -0
  423. package/ui/src/adapters/openclaw-gateway/index.ts +13 -0
  424. package/ui/src/adapters/opencode-local/config-fields.tsx +72 -0
  425. package/ui/src/adapters/opencode-local/index.ts +13 -0
  426. package/ui/src/adapters/pi-local/config-fields.tsx +49 -0
  427. package/ui/src/adapters/pi-local/index.ts +13 -0
  428. package/ui/src/adapters/process/build-config.ts +18 -0
  429. package/ui/src/adapters/process/config-fields.tsx +77 -0
  430. package/ui/src/adapters/process/index.ts +12 -0
  431. package/ui/src/adapters/process/parse-stdout.ts +5 -0
  432. package/ui/src/adapters/registry.ts +34 -0
  433. package/ui/src/adapters/runtime-json-fields.tsx +122 -0
  434. package/ui/src/adapters/transcript.test.ts +30 -0
  435. package/ui/src/adapters/transcript.ts +62 -0
  436. package/ui/src/adapters/types.ts +34 -0
  437. package/ui/src/api/access.ts +160 -0
  438. package/ui/src/api/activity.ts +37 -0
  439. package/ui/src/api/agents.ts +194 -0
  440. package/ui/src/api/approvals.ts +25 -0
  441. package/ui/src/api/assets.ts +30 -0
  442. package/ui/src/api/auth.ts +74 -0
  443. package/ui/src/api/budgets.ts +21 -0
  444. package/ui/src/api/client.ts +50 -0
  445. package/ui/src/api/companies.ts +59 -0
  446. package/ui/src/api/companySkills.ts +55 -0
  447. package/ui/src/api/costs.ts +60 -0
  448. package/ui/src/api/dashboard.ts +7 -0
  449. package/ui/src/api/execution-workspaces.ts +27 -0
  450. package/ui/src/api/goals.ts +12 -0
  451. package/ui/src/api/health.ts +41 -0
  452. package/ui/src/api/heartbeats.ts +62 -0
  453. package/ui/src/api/index.ts +18 -0
  454. package/ui/src/api/instanceSettings.ts +19 -0
  455. package/ui/src/api/issues.ts +115 -0
  456. package/ui/src/api/plugins.ts +424 -0
  457. package/ui/src/api/projects.ts +34 -0
  458. package/ui/src/api/routines.ts +59 -0
  459. package/ui/src/api/secrets.ts +26 -0
  460. package/ui/src/api/sidebarBadges.ts +7 -0
  461. package/ui/src/components/AccountingModelCard.tsx +69 -0
  462. package/ui/src/components/ActiveAgentsPanel.tsx +157 -0
  463. package/ui/src/components/ActivityCharts.tsx +264 -0
  464. package/ui/src/components/ActivityRow.tsx +147 -0
  465. package/ui/src/components/AgentActionButtons.tsx +51 -0
  466. package/ui/src/components/AgentConfigForm.tsx +1468 -0
  467. package/ui/src/components/AgentIconPicker.tsx +81 -0
  468. package/ui/src/components/AgentProperties.tsx +107 -0
  469. package/ui/src/components/ApprovalCard.tsx +107 -0
  470. package/ui/src/components/ApprovalPayload.tsx +134 -0
  471. package/ui/src/components/AsciiArtAnimation.tsx +355 -0
  472. package/ui/src/components/BillerSpendCard.tsx +146 -0
  473. package/ui/src/components/BreadcrumbBar.tsx +113 -0
  474. package/ui/src/components/BudgetIncidentCard.tsx +101 -0
  475. package/ui/src/components/BudgetPolicyCard.tsx +220 -0
  476. package/ui/src/components/BudgetSidebarMarker.tsx +13 -0
  477. package/ui/src/components/ClaudeSubscriptionPanel.tsx +141 -0
  478. package/ui/src/components/CodexSubscriptionPanel.tsx +158 -0
  479. package/ui/src/components/CommandPalette.tsx +239 -0
  480. package/ui/src/components/CommentThread.tsx +503 -0
  481. package/ui/src/components/CompanyPatternIcon.tsx +212 -0
  482. package/ui/src/components/CompanyRail.tsx +329 -0
  483. package/ui/src/components/CompanySwitcher.tsx +81 -0
  484. package/ui/src/components/CopyText.tsx +56 -0
  485. package/ui/src/components/DevRestartBanner.tsx +89 -0
  486. package/ui/src/components/EmptyState.tsx +27 -0
  487. package/ui/src/components/EntityRow.tsx +69 -0
  488. package/ui/src/components/FilterBar.tsx +39 -0
  489. package/ui/src/components/FinanceBillerCard.tsx +45 -0
  490. package/ui/src/components/FinanceKindCard.tsx +44 -0
  491. package/ui/src/components/FinanceTimelineCard.tsx +72 -0
  492. package/ui/src/components/GoalProperties.tsx +165 -0
  493. package/ui/src/components/GoalTree.tsx +118 -0
  494. package/ui/src/components/Identity.tsx +39 -0
  495. package/ui/src/components/InlineEditor.tsx +248 -0
  496. package/ui/src/components/InlineEntitySelector.tsx +206 -0
  497. package/ui/src/components/InstanceSidebar.tsx +53 -0
  498. package/ui/src/components/IssueDocumentsSection.tsx +892 -0
  499. package/ui/src/components/IssueProperties.tsx +621 -0
  500. package/ui/src/components/IssueRow.tsx +149 -0
  501. package/ui/src/components/IssueWorkspaceCard.tsx +404 -0
  502. package/ui/src/components/IssuesList.tsx +889 -0
  503. package/ui/src/components/JsonSchemaForm.tsx +1048 -0
  504. package/ui/src/components/KanbanBoard.tsx +275 -0
  505. package/ui/src/components/Layout.tsx +441 -0
  506. package/ui/src/components/LiveRunWidget.tsx +160 -0
  507. package/ui/src/components/MarkdownBody.test.tsx +50 -0
  508. package/ui/src/components/MarkdownBody.tsx +152 -0
  509. package/ui/src/components/MarkdownEditor.tsx +622 -0
  510. package/ui/src/components/MetricCard.tsx +53 -0
  511. package/ui/src/components/MobileBottomNav.tsx +123 -0
  512. package/ui/src/components/NewAgentDialog.tsx +223 -0
  513. package/ui/src/components/NewGoalDialog.tsx +283 -0
  514. package/ui/src/components/NewIssueDialog.tsx +1473 -0
  515. package/ui/src/components/NewProjectDialog.tsx +451 -0
  516. package/ui/src/components/OnboardingWizard.tsx +1392 -0
  517. package/ui/src/components/OpenCodeLogoIcon.tsx +22 -0
  518. package/ui/src/components/PackageFileTree.tsx +318 -0
  519. package/ui/src/components/PageSkeleton.tsx +180 -0
  520. package/ui/src/components/PageTabBar.tsx +45 -0
  521. package/ui/src/components/PathInstructionsModal.tsx +143 -0
  522. package/ui/src/components/PriorityIcon.tsx +77 -0
  523. package/ui/src/components/ProjectProperties.tsx +1127 -0
  524. package/ui/src/components/PropertiesPanel.tsx +29 -0
  525. package/ui/src/components/ProviderQuotaCard.tsx +417 -0
  526. package/ui/src/components/QuotaBar.tsx +65 -0
  527. package/ui/src/components/ReportsToPicker.tsx +127 -0
  528. package/ui/src/components/ScheduleEditor.tsx +344 -0
  529. package/ui/src/components/ScrollToBottom.tsx +79 -0
  530. package/ui/src/components/Sidebar.tsx +130 -0
  531. package/ui/src/components/SidebarAgents.tsx +146 -0
  532. package/ui/src/components/SidebarNavItem.tsx +92 -0
  533. package/ui/src/components/SidebarProjects.tsx +234 -0
  534. package/ui/src/components/SidebarSection.tsx +17 -0
  535. package/ui/src/components/StatusBadge.tsx +15 -0
  536. package/ui/src/components/StatusIcon.tsx +71 -0
  537. package/ui/src/components/SwipeToArchive.tsx +152 -0
  538. package/ui/src/components/ToastViewport.tsx +99 -0
  539. package/ui/src/components/WorktreeBanner.tsx +25 -0
  540. package/ui/src/components/agent-config-defaults.ts +31 -0
  541. package/ui/src/components/agent-config-primitives.tsx +476 -0
  542. package/ui/src/components/transcript/RunTranscriptView.test.tsx +84 -0
  543. package/ui/src/components/transcript/RunTranscriptView.tsx +1015 -0
  544. package/ui/src/components/transcript/useLiveRunTranscripts.ts +297 -0
  545. package/ui/src/components/ui/avatar.tsx +107 -0
  546. package/ui/src/components/ui/badge.tsx +48 -0
  547. package/ui/src/components/ui/breadcrumb.tsx +109 -0
  548. package/ui/src/components/ui/button.tsx +64 -0
  549. package/ui/src/components/ui/card.tsx +92 -0
  550. package/ui/src/components/ui/checkbox.tsx +32 -0
  551. package/ui/src/components/ui/collapsible.tsx +33 -0
  552. package/ui/src/components/ui/command.tsx +194 -0
  553. package/ui/src/components/ui/dialog.tsx +156 -0
  554. package/ui/src/components/ui/dropdown-menu.tsx +257 -0
  555. package/ui/src/components/ui/input.tsx +21 -0
  556. package/ui/src/components/ui/label.tsx +22 -0
  557. package/ui/src/components/ui/popover.tsx +88 -0
  558. package/ui/src/components/ui/scroll-area.tsx +56 -0
  559. package/ui/src/components/ui/select.tsx +188 -0
  560. package/ui/src/components/ui/separator.tsx +28 -0
  561. package/ui/src/components/ui/sheet.tsx +143 -0
  562. package/ui/src/components/ui/skeleton.tsx +13 -0
  563. package/ui/src/components/ui/tabs.tsx +89 -0
  564. package/ui/src/components/ui/textarea.tsx +18 -0
  565. package/ui/src/components/ui/tooltip.tsx +57 -0
  566. package/ui/src/components/visual-office/AgentAvatar.tsx +99 -0
  567. package/ui/src/components/visual-office/OfficeViewExact.tsx +417 -0
  568. package/ui/src/components/visual-office/i18n.ts +52 -0
  569. package/ui/src/components/visual-office/office-view/CliUsagePanel.tsx +240 -0
  570. package/ui/src/components/visual-office/office-view/VirtualPadOverlay.tsx +104 -0
  571. package/ui/src/components/visual-office/office-view/buildScene-break-room.ts +248 -0
  572. package/ui/src/components/visual-office/office-view/buildScene-ceo-hallway.ts +345 -0
  573. package/ui/src/components/visual-office/office-view/buildScene-department-agent.ts +242 -0
  574. package/ui/src/components/visual-office/office-view/buildScene-departments.ts +360 -0
  575. package/ui/src/components/visual-office/office-view/buildScene-final-layers.ts +113 -0
  576. package/ui/src/components/visual-office/office-view/buildScene-types.ts +91 -0
  577. package/ui/src/components/visual-office/office-view/buildScene.ts +232 -0
  578. package/ui/src/components/visual-office/office-view/drawing-core.ts +374 -0
  579. package/ui/src/components/visual-office/office-view/drawing-furniture-a.ts +338 -0
  580. package/ui/src/components/visual-office/office-view/drawing-furniture-b.ts +241 -0
  581. package/ui/src/components/visual-office/office-view/model.ts +301 -0
  582. package/ui/src/components/visual-office/office-view/officeTicker.ts +455 -0
  583. package/ui/src/components/visual-office/office-view/officeTickerRoomAndDelivery.ts +133 -0
  584. package/ui/src/components/visual-office/office-view/themes-locale.ts +460 -0
  585. package/ui/src/components/visual-office/office-view/useCliUsage.ts +37 -0
  586. package/ui/src/components/visual-office/office-view/useOfficeDeliveryEffects.ts +465 -0
  587. package/ui/src/components/visual-office/office-view/useOfficePixiRuntime.ts +282 -0
  588. package/ui/src/components/visual-office/types.ts +123 -0
  589. package/ui/src/context/BreadcrumbContext.tsx +44 -0
  590. package/ui/src/context/CompanyContext.tsx +151 -0
  591. package/ui/src/context/DialogContext.tsx +135 -0
  592. package/ui/src/context/LiveUpdatesProvider.test.ts +119 -0
  593. package/ui/src/context/LiveUpdatesProvider.tsx +760 -0
  594. package/ui/src/context/PanelContext.tsx +73 -0
  595. package/ui/src/context/SidebarContext.tsx +43 -0
  596. package/ui/src/context/ThemeContext.tsx +83 -0
  597. package/ui/src/context/ToastContext.tsx +172 -0
  598. package/ui/src/fixtures/runTranscriptFixtures.ts +226 -0
  599. package/ui/src/hooks/useAgentOrder.ts +105 -0
  600. package/ui/src/hooks/useAutosaveIndicator.ts +72 -0
  601. package/ui/src/hooks/useCompanyPageMemory.test.ts +90 -0
  602. package/ui/src/hooks/useCompanyPageMemory.ts +79 -0
  603. package/ui/src/hooks/useDateRange.ts +120 -0
  604. package/ui/src/hooks/useInboxBadge.ts +132 -0
  605. package/ui/src/hooks/useKeyboardShortcuts.ts +40 -0
  606. package/ui/src/hooks/useProjectOrder.ts +106 -0
  607. package/ui/src/index.css +770 -0
  608. package/ui/src/lib/agent-icons.ts +99 -0
  609. package/ui/src/lib/agent-order.ts +107 -0
  610. package/ui/src/lib/agent-skills-state.test.ts +90 -0
  611. package/ui/src/lib/agent-skills-state.ts +41 -0
  612. package/ui/src/lib/assignees.test.ts +92 -0
  613. package/ui/src/lib/assignees.ts +82 -0
  614. package/ui/src/lib/color-contrast.ts +107 -0
  615. package/ui/src/lib/company-export-selection.test.ts +41 -0
  616. package/ui/src/lib/company-export-selection.ts +57 -0
  617. package/ui/src/lib/company-page-memory.ts +65 -0
  618. package/ui/src/lib/company-portability-sidebar.test.ts +101 -0
  619. package/ui/src/lib/company-portability-sidebar.ts +62 -0
  620. package/ui/src/lib/company-routes.ts +88 -0
  621. package/ui/src/lib/company-selection.test.ts +34 -0
  622. package/ui/src/lib/company-selection.ts +18 -0
  623. package/ui/src/lib/groupBy.ts +11 -0
  624. package/ui/src/lib/inbox.test.ts +404 -0
  625. package/ui/src/lib/inbox.ts +292 -0
  626. package/ui/src/lib/instance-settings.test.ts +26 -0
  627. package/ui/src/lib/instance-settings.ts +25 -0
  628. package/ui/src/lib/issueDetailBreadcrumb.ts +24 -0
  629. package/ui/src/lib/legacy-agent-config.test.ts +40 -0
  630. package/ui/src/lib/legacy-agent-config.ts +17 -0
  631. package/ui/src/lib/mention-aware-link-node.test.ts +50 -0
  632. package/ui/src/lib/mention-aware-link-node.ts +67 -0
  633. package/ui/src/lib/mention-chips.ts +168 -0
  634. package/ui/src/lib/mention-deletion.test.ts +87 -0
  635. package/ui/src/lib/mention-deletion.ts +143 -0
  636. package/ui/src/lib/model-utils.ts +16 -0
  637. package/ui/src/lib/onboarding-goal.test.ts +22 -0
  638. package/ui/src/lib/onboarding-goal.ts +18 -0
  639. package/ui/src/lib/onboarding-launch.test.ts +131 -0
  640. package/ui/src/lib/onboarding-launch.ts +54 -0
  641. package/ui/src/lib/onboarding-route.test.ts +80 -0
  642. package/ui/src/lib/onboarding-route.ts +51 -0
  643. package/ui/src/lib/portable-files.ts +42 -0
  644. package/ui/src/lib/project-order.ts +71 -0
  645. package/ui/src/lib/queryKeys.ts +140 -0
  646. package/ui/src/lib/recent-assignees.ts +36 -0
  647. package/ui/src/lib/router.tsx +76 -0
  648. package/ui/src/lib/routine-trigger-patch.test.ts +72 -0
  649. package/ui/src/lib/routine-trigger-patch.ts +31 -0
  650. package/ui/src/lib/status-colors.ts +108 -0
  651. package/ui/src/lib/timeAgo.ts +31 -0
  652. package/ui/src/lib/utils.ts +168 -0
  653. package/ui/src/lib/worktree-branding.ts +65 -0
  654. package/ui/src/lib/zip.test.ts +289 -0
  655. package/ui/src/lib/zip.ts +284 -0
  656. package/ui/src/main.tsx +67 -0
  657. package/ui/src/pages/Activity.tsx +141 -0
  658. package/ui/src/pages/AgentDetail.tsx +4053 -0
  659. package/ui/src/pages/Agents.tsx +415 -0
  660. package/ui/src/pages/ApprovalDetail.tsx +369 -0
  661. package/ui/src/pages/Approvals.tsx +132 -0
  662. package/ui/src/pages/Auth.tsx +180 -0
  663. package/ui/src/pages/BoardClaim.tsx +125 -0
  664. package/ui/src/pages/CliAuth.tsx +184 -0
  665. package/ui/src/pages/Companies.tsx +297 -0
  666. package/ui/src/pages/CompanyExport.tsx +1019 -0
  667. package/ui/src/pages/CompanyImport.tsx +1355 -0
  668. package/ui/src/pages/CompanySettings.tsx +661 -0
  669. package/ui/src/pages/CompanySkills.tsx +1171 -0
  670. package/ui/src/pages/Costs.tsx +1103 -0
  671. package/ui/src/pages/Dashboard.tsx +388 -0
  672. package/ui/src/pages/DesignGuide.tsx +1330 -0
  673. package/ui/src/pages/ExecutionWorkspaceDetail.tsx +82 -0
  674. package/ui/src/pages/GoalDetail.tsx +197 -0
  675. package/ui/src/pages/Goals.tsx +63 -0
  676. package/ui/src/pages/Inbox.tsx +1291 -0
  677. package/ui/src/pages/InstanceExperimentalSettings.tsx +139 -0
  678. package/ui/src/pages/InstanceGeneralSettings.tsx +104 -0
  679. package/ui/src/pages/InstanceSettings.tsx +284 -0
  680. package/ui/src/pages/InviteLanding.tsx +320 -0
  681. package/ui/src/pages/IssueDetail.tsx +1201 -0
  682. package/ui/src/pages/Issues.tsx +116 -0
  683. package/ui/src/pages/MyIssues.tsx +72 -0
  684. package/ui/src/pages/NewAgent.tsx +353 -0
  685. package/ui/src/pages/NotFound.tsx +66 -0
  686. package/ui/src/pages/Org.tsx +132 -0
  687. package/ui/src/pages/OrgChart.tsx +447 -0
  688. package/ui/src/pages/PluginManager.tsx +510 -0
  689. package/ui/src/pages/PluginPage.tsx +156 -0
  690. package/ui/src/pages/PluginSettings.tsx +836 -0
  691. package/ui/src/pages/ProjectDetail.tsx +633 -0
  692. package/ui/src/pages/Projects.tsx +87 -0
  693. package/ui/src/pages/RoutineDetail.tsx +1022 -0
  694. package/ui/src/pages/Routines.tsx +661 -0
  695. package/ui/src/pages/RunTranscriptUxLab.tsx +334 -0
  696. package/ui/src/pages/VisualOffice.tsx +243 -0
  697. package/ui/src/plugins/bridge-init.ts +69 -0
  698. package/ui/src/plugins/bridge.ts +476 -0
  699. package/ui/src/plugins/launchers.tsx +834 -0
  700. package/ui/src/plugins/slots.tsx +855 -0
  701. package/ui/tsconfig.json +21 -0
  702. package/ui/vite.config.ts +23 -0
  703. package/ui/vitest.config.ts +14 -0
  704. package/vitest.config.ts +11 -0
@@ -0,0 +1,1955 @@
1
+ /**
2
+ * PluginLoader — discovery, installation, and runtime activation of plugins.
3
+ *
4
+ * This service is the entry point for the plugin system's I/O boundary:
5
+ *
6
+ * 1. **Discovery** — Scans the local plugin directory
7
+ * (`~/.paperclip/plugins/`) and `node_modules` for packages matching
8
+ * the `paperclip-plugin-*` naming convention. Aggregates results with
9
+ * path-based deduplication.
10
+ *
11
+ * 2. **Installation** — `installPlugin()` downloads from npm (or reads a
12
+ * local path), validates the manifest, checks capability consistency,
13
+ * and persists the install record.
14
+ *
15
+ * 3. **Runtime activation** — `activatePlugin()` wires up a loaded plugin
16
+ * with all runtime services: resolves its entrypoint, builds
17
+ * capability-gated host handlers, spawns a worker process, syncs job
18
+ * declarations, registers event subscriptions, and discovers tools.
19
+ *
20
+ * 4. **Shutdown** — `shutdownAll()` gracefully stops all active workers
21
+ * and unregisters runtime hooks.
22
+ *
23
+ * @see PLUGIN_SPEC.md §8 — Plugin Discovery
24
+ * @see PLUGIN_SPEC.md §10 — Package Contract
25
+ * @see PLUGIN_SPEC.md §12 — Process Model
26
+ */
27
+ import { existsSync } from "node:fs";
28
+ import { readdir, readFile, rm, stat } from "node:fs/promises";
29
+ import { execFile } from "node:child_process";
30
+ import os from "node:os";
31
+ import path from "node:path";
32
+ import { fileURLToPath } from "node:url";
33
+ import { promisify } from "node:util";
34
+ import type { Db } from "@corporateai/db";
35
+ import type {
36
+ PaperclipPluginManifestV1,
37
+ PluginLauncherDeclaration,
38
+ PluginRecord,
39
+ PluginUiSlotDeclaration,
40
+ } from "@corporateai/shared";
41
+ import { logger } from "../middleware/logger.js";
42
+ import { pluginManifestValidator } from "./plugin-manifest-validator.js";
43
+ import { pluginCapabilityValidator } from "./plugin-capability-validator.js";
44
+ import { pluginRegistryService } from "./plugin-registry.js";
45
+ import type { PluginWorkerManager, WorkerStartOptions, WorkerToHostHandlers } from "./plugin-worker-manager.js";
46
+ import type { PluginEventBus } from "./plugin-event-bus.js";
47
+ import type { PluginJobScheduler } from "./plugin-job-scheduler.js";
48
+ import type { PluginJobStore } from "./plugin-job-store.js";
49
+ import type { PluginToolDispatcher } from "./plugin-tool-dispatcher.js";
50
+ import type { PluginLifecycleManager } from "./plugin-lifecycle.js";
51
+
52
+ const execFileAsync = promisify(execFile);
53
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
54
+
55
+ // ---------------------------------------------------------------------------
56
+ // Constants
57
+ // ---------------------------------------------------------------------------
58
+
59
+ /**
60
+ * Naming convention for npm-published Paperclip plugins.
61
+ * Packages matching this pattern are considered Paperclip plugins.
62
+ *
63
+ * @see PLUGIN_SPEC.md §10 — Package Contract
64
+ */
65
+ export const NPM_PLUGIN_PACKAGE_PREFIX = "paperclip-plugin-";
66
+
67
+ /**
68
+ * Default local plugin directory. The loader scans this directory for
69
+ * locally-installed plugin packages.
70
+ *
71
+ * @see PLUGIN_SPEC.md §8.1 — On-Disk Layout
72
+ */
73
+ export const DEFAULT_LOCAL_PLUGIN_DIR = path.join(
74
+ os.homedir(),
75
+ ".paperclip",
76
+ "plugins",
77
+ );
78
+
79
+ const DEV_TSX_LOADER_PATH = path.resolve(__dirname, "../../../cli/node_modules/tsx/dist/loader.mjs");
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // Discovery result types
83
+ // ---------------------------------------------------------------------------
84
+
85
+ /**
86
+ * A plugin package found during discovery from any source.
87
+ */
88
+ export interface DiscoveredPlugin {
89
+ /** Absolute path to the root of the npm package directory. */
90
+ packagePath: string;
91
+ /** The npm package name as declared in package.json. */
92
+ packageName: string;
93
+ /** Semver version from package.json. */
94
+ version: string;
95
+ /** Source that found this package. */
96
+ source: PluginSource;
97
+ /** The parsed and validated manifest if available, null if discovery-only. */
98
+ manifest: PaperclipPluginManifestV1 | null;
99
+ }
100
+
101
+ /**
102
+ * Sources from which plugins can be discovered.
103
+ *
104
+ * @see PLUGIN_SPEC.md §8.1 — On-Disk Layout
105
+ */
106
+ export type PluginSource =
107
+ | "local-filesystem" // ~/.paperclip/plugins/ local directory
108
+ | "npm" // npm packages matching paperclip-plugin-* convention
109
+ | "registry"; // future: remote plugin registry URL
110
+
111
+ type ParsedSemver = {
112
+ major: number;
113
+ minor: number;
114
+ patch: number;
115
+ prerelease: string[];
116
+ };
117
+
118
+ /**
119
+ * Result of a discovery scan.
120
+ */
121
+ export interface PluginDiscoveryResult {
122
+ /** Plugins successfully discovered and validated. */
123
+ discovered: DiscoveredPlugin[];
124
+ /** Packages found but with validation errors. */
125
+ errors: Array<{ packagePath: string; packageName: string; error: string }>;
126
+ /** Source(s) that were scanned. */
127
+ sources: PluginSource[];
128
+ }
129
+
130
+ function getDeclaredPageRoutePaths(manifest: PaperclipPluginManifestV1): string[] {
131
+ return (manifest.ui?.slots ?? [])
132
+ .filter((slot): slot is PluginUiSlotDeclaration => slot.type === "page" && typeof slot.routePath === "string" && slot.routePath.length > 0)
133
+ .map((slot) => slot.routePath!);
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // Loader options
138
+ // ---------------------------------------------------------------------------
139
+
140
+ /**
141
+ * Options for the plugin loader service.
142
+ */
143
+ export interface PluginLoaderOptions {
144
+ /**
145
+ * Path to the local plugin directory to scan.
146
+ * Defaults to ~/.paperclip/plugins/
147
+ */
148
+ localPluginDir?: string;
149
+
150
+ /**
151
+ * Whether to scan the local filesystem directory for plugins.
152
+ * Defaults to true.
153
+ */
154
+ enableLocalFilesystem?: boolean;
155
+
156
+ /**
157
+ * Whether to discover installed npm packages matching the paperclip-plugin-*
158
+ * naming convention.
159
+ * Defaults to true.
160
+ */
161
+ enableNpmDiscovery?: boolean;
162
+
163
+ /**
164
+ * Future: URL of the remote plugin registry to query.
165
+ * When set, the loader will also fetch available plugins from this endpoint.
166
+ * Registry support is not yet implemented; this field is reserved.
167
+ */
168
+ registryUrl?: string;
169
+ }
170
+
171
+ // ---------------------------------------------------------------------------
172
+ // Install options
173
+ // ---------------------------------------------------------------------------
174
+
175
+ /**
176
+ * Options for installing a single plugin package.
177
+ */
178
+ export interface PluginInstallOptions {
179
+ /**
180
+ * npm package name to install (e.g. "paperclip-plugin-linear" or "@acme/plugin-linear").
181
+ * Either packageName or localPath must be set.
182
+ */
183
+ packageName?: string;
184
+
185
+ /**
186
+ * Absolute or relative path to a local plugin directory for development installs.
187
+ * When set, the plugin is loaded from this path without npm install.
188
+ * Either packageName or localPath must be set.
189
+ */
190
+ localPath?: string;
191
+
192
+ /**
193
+ * Version specifier passed to npm install (e.g. "^1.2.0", "latest").
194
+ * Ignored when localPath is set.
195
+ */
196
+ version?: string;
197
+
198
+ /**
199
+ * Plugin install directory where packages are managed.
200
+ * Defaults to the localPluginDir configured on the service.
201
+ */
202
+ installDir?: string;
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // Runtime options — services needed for initializing loaded plugins
207
+ // ---------------------------------------------------------------------------
208
+
209
+ /**
210
+ * Runtime services passed to the loader for plugin initialization.
211
+ *
212
+ * When these are provided, the loader can fully activate plugins (spawn
213
+ * workers, register event subscriptions, sync jobs, register tools).
214
+ * When omitted, the loader operates in discovery/install-only mode.
215
+ *
216
+ * @see PLUGIN_SPEC.md §8.3 — Install Process
217
+ * @see PLUGIN_SPEC.md §12 — Process Model
218
+ */
219
+ export interface PluginRuntimeServices {
220
+ /** Worker process manager for spawning and managing plugin workers. */
221
+ workerManager: PluginWorkerManager;
222
+ /** Event bus for registering plugin event subscriptions. */
223
+ eventBus: PluginEventBus;
224
+ /** Job scheduler for registering plugin cron jobs. */
225
+ jobScheduler: PluginJobScheduler;
226
+ /** Job store for syncing manifest job declarations to the DB. */
227
+ jobStore: PluginJobStore;
228
+ /** Tool dispatcher for registering plugin-contributed agent tools. */
229
+ toolDispatcher: PluginToolDispatcher;
230
+ /** Lifecycle manager for state transitions and worker lifecycle events. */
231
+ lifecycleManager: PluginLifecycleManager;
232
+ /**
233
+ * Factory that creates worker-to-host RPC handlers for a given plugin.
234
+ *
235
+ * The returned handlers service worker→host calls (e.g. state.get,
236
+ * events.emit, config.get). Each plugin gets its own set of handlers
237
+ * scoped to its capabilities and plugin ID.
238
+ */
239
+ buildHostHandlers: (pluginId: string, manifest: PaperclipPluginManifestV1) => WorkerToHostHandlers;
240
+ /**
241
+ * Host instance information passed to the worker during initialization.
242
+ * Includes the instance ID and host version.
243
+ */
244
+ instanceInfo: {
245
+ instanceId: string;
246
+ hostVersion: string;
247
+ };
248
+ }
249
+
250
+ // ---------------------------------------------------------------------------
251
+ // Load results
252
+ // ---------------------------------------------------------------------------
253
+
254
+ /**
255
+ * Result of activating (loading) a single plugin at runtime.
256
+ *
257
+ * Contains the plugin record, activation status, and any error that
258
+ * occurred during the process.
259
+ */
260
+ export interface PluginLoadResult {
261
+ /** The plugin record from the database. */
262
+ plugin: PluginRecord;
263
+ /** Whether the plugin was successfully activated. */
264
+ success: boolean;
265
+ /** Error message if activation failed. */
266
+ error?: string;
267
+ /** Which subsystems were registered during activation. */
268
+ registered: {
269
+ /** True if the worker process was started. */
270
+ worker: boolean;
271
+ /** Number of event subscriptions registered (from manifest event declarations). */
272
+ eventSubscriptions: number;
273
+ /** Number of job declarations synced to the database. */
274
+ jobs: number;
275
+ /** Number of webhook endpoints declared in manifest. */
276
+ webhooks: number;
277
+ /** Number of agent tools registered. */
278
+ tools: number;
279
+ };
280
+ }
281
+
282
+ /**
283
+ * Result of activating all ready plugins at server startup.
284
+ */
285
+ export interface PluginLoadAllResult {
286
+ /** Total number of plugins that were attempted. */
287
+ total: number;
288
+ /** Number of plugins successfully activated. */
289
+ succeeded: number;
290
+ /** Number of plugins that failed to activate. */
291
+ failed: number;
292
+ /** Per-plugin results. */
293
+ results: PluginLoadResult[];
294
+ }
295
+
296
+ /**
297
+ * Normalized UI contribution metadata extracted from a plugin manifest.
298
+ *
299
+ * The host serves all plugin UI bundles from the manifest's `entrypoints.ui`
300
+ * directory and currently expects the bundle entry module to be `index.js`.
301
+ */
302
+ export interface PluginUiContributionMetadata {
303
+ uiEntryFile: string;
304
+ slots: PluginUiSlotDeclaration[];
305
+ launchers: PluginLauncherDeclaration[];
306
+ }
307
+
308
+ // ---------------------------------------------------------------------------
309
+ // Service interface
310
+ // ---------------------------------------------------------------------------
311
+
312
+ export interface PluginLoader {
313
+ /**
314
+ * Discover all available plugins from configured sources.
315
+ *
316
+ * This performs a non-destructive scan of all enabled sources and returns
317
+ * the discovered plugins with their parsed manifests. No installs or DB
318
+ * writes happen during discovery.
319
+ *
320
+ * @param npmSearchDirs - Optional override for node_modules directories to search.
321
+ * Passed through to discoverFromNpm. When omitted the defaults are used.
322
+ *
323
+ * @see PLUGIN_SPEC.md §8.1 — On-Disk Layout
324
+ * @see PLUGIN_SPEC.md §8.3 — Install Process
325
+ */
326
+ discoverAll(npmSearchDirs?: string[]): Promise<PluginDiscoveryResult>;
327
+
328
+ /**
329
+ * Scan the local filesystem plugin directory for installed plugin packages.
330
+ *
331
+ * Reads the plugin directory, attempts to load each subdirectory as an npm
332
+ * package, and validates the plugin manifest.
333
+ *
334
+ * @param dir - Directory to scan (defaults to configured localPluginDir).
335
+ */
336
+ discoverFromLocalFilesystem(dir?: string): Promise<PluginDiscoveryResult>;
337
+
338
+ /**
339
+ * Discover Paperclip plugins installed as npm packages in the current
340
+ * Node.js environment matching the "paperclip-plugin-*" naming convention.
341
+ *
342
+ * Looks for packages in node_modules that match the naming convention.
343
+ *
344
+ * @param searchDirs - node_modules directories to search (defaults to process cwd resolution).
345
+ */
346
+ discoverFromNpm(searchDirs?: string[]): Promise<PluginDiscoveryResult>;
347
+
348
+ /**
349
+ * Load and parse the plugin manifest from a package directory.
350
+ *
351
+ * Reads the package.json, finds the manifest entrypoint declared under
352
+ * the "paperclipPlugin.manifest" key, loads the manifest module, and
353
+ * validates it against the plugin manifest schema.
354
+ *
355
+ * Returns null if the package is not a Paperclip plugin.
356
+ * Throws if the package is a Paperclip plugin but the manifest is invalid.
357
+ *
358
+ * @see PLUGIN_SPEC.md §10 — Package Contract
359
+ */
360
+ loadManifest(packagePath: string): Promise<PaperclipPluginManifestV1 | null>;
361
+
362
+ /**
363
+ * Install a plugin package and register it in the database.
364
+ *
365
+ * Follows the install process described in PLUGIN_SPEC.md §8.3:
366
+ * 1. Resolve npm package / local path.
367
+ * 2. Install into the plugin directory (npm install).
368
+ * 3. Read and validate plugin manifest.
369
+ * 4. Reject incompatible plugin API versions.
370
+ * 5. Validate manifest capabilities.
371
+ * 6. Persist install record in Postgres.
372
+ * 7. Return the discovered plugin for the caller to use.
373
+ *
374
+ * Worker spawning and lifecycle management are handled by the caller
375
+ * (pluginLifecycleManager and the server startup orchestration).
376
+ *
377
+ * @see PLUGIN_SPEC.md §8.3 — Install Process
378
+ */
379
+ installPlugin(options: PluginInstallOptions): Promise<DiscoveredPlugin>;
380
+
381
+ /**
382
+ * Upgrade an already-installed plugin to a newer version.
383
+ *
384
+ * Similar to installPlugin, but:
385
+ * 1. Requires the plugin to already exist in the database.
386
+ * 2. Uses the existing packageName if not provided in options.
387
+ * 3. Updates the existing plugin record instead of creating a new one.
388
+ * 4. Returns the old and new manifests for capability comparison.
389
+ *
390
+ * @see PLUGIN_SPEC.md §25.3 — Upgrade Lifecycle
391
+ */
392
+ upgradePlugin(pluginId: string, options: Omit<PluginInstallOptions, "installDir">): Promise<{
393
+ oldManifest: PaperclipPluginManifestV1;
394
+ newManifest: PaperclipPluginManifestV1;
395
+ discovered: DiscoveredPlugin;
396
+ }>;
397
+
398
+ /**
399
+ * Check whether a plugin API version is supported by this host.
400
+ */
401
+ isSupportedApiVersion(apiVersion: number): boolean;
402
+
403
+ /**
404
+ * Remove runtime-managed on-disk install artifacts for a plugin.
405
+ *
406
+ * This only cleans files under the managed local plugin directory. Local-path
407
+ * source checkouts outside that directory are intentionally left alone.
408
+ */
409
+ cleanupInstallArtifacts(plugin: PluginRecord): Promise<void>;
410
+
411
+ /**
412
+ * Get the local plugin directory this loader is configured to use.
413
+ */
414
+ getLocalPluginDir(): string;
415
+
416
+ // -----------------------------------------------------------------------
417
+ // Runtime initialization (requires PluginRuntimeServices)
418
+ // -----------------------------------------------------------------------
419
+
420
+ /**
421
+ * Load and activate all plugins that are in `ready` status.
422
+ *
423
+ * This is the main server-startup orchestration method. For each plugin
424
+ * that is persisted as `ready`, it:
425
+ * 1. Resolves the worker entrypoint from the manifest.
426
+ * 2. Spawns the worker process via the worker manager.
427
+ * 3. Syncs job declarations from the manifest to the `plugin_jobs` table.
428
+ * 4. Registers the plugin with the job scheduler.
429
+ * 5. Registers event subscriptions declared in the manifest (scoped via the event bus).
430
+ * 6. Registers agent tools from the manifest via the tool dispatcher.
431
+ *
432
+ * Plugins that fail to activate are marked as `error` in the database.
433
+ * Activation failures are non-fatal — other plugins continue loading.
434
+ *
435
+ * **Requires** `PluginRuntimeServices` to have been provided at construction.
436
+ * Throws if runtime services are not available.
437
+ *
438
+ * @returns Aggregated results for all attempted plugin loads.
439
+ *
440
+ * @see PLUGIN_SPEC.md §8.4 — Server-Start Plugin Loading
441
+ * @see PLUGIN_SPEC.md §12 — Process Model
442
+ */
443
+ loadAll(): Promise<PluginLoadAllResult>;
444
+
445
+ /**
446
+ * Activate a single plugin that is in `installed` or `ready` status.
447
+ *
448
+ * Used after a fresh install (POST /api/plugins/install) or after
449
+ * enabling a previously disabled plugin. Performs the same subsystem
450
+ * registration as `loadAll()` but for a single plugin.
451
+ *
452
+ * If the plugin is in `installed` status, transitions it to `ready`
453
+ * via the lifecycle manager before spawning the worker.
454
+ *
455
+ * **Requires** `PluginRuntimeServices` to have been provided at construction.
456
+ *
457
+ * @param pluginId - UUID of the plugin to activate
458
+ * @returns The activation result for this plugin
459
+ *
460
+ * @see PLUGIN_SPEC.md §8.3 — Install Process
461
+ */
462
+ loadSingle(pluginId: string): Promise<PluginLoadResult>;
463
+
464
+ /**
465
+ * Deactivate a single plugin — stop its worker and unregister all
466
+ * subsystem registrations (events, jobs, tools).
467
+ *
468
+ * Used during plugin disable, uninstall, and before upgrade. Does NOT
469
+ * change the plugin's status in the database — that is the caller's
470
+ * responsibility (via the lifecycle manager).
471
+ *
472
+ * **Requires** `PluginRuntimeServices` to have been provided at construction.
473
+ *
474
+ * @param pluginId - UUID of the plugin to deactivate
475
+ * @param pluginKey - The plugin key (manifest ID) for scoped cleanup
476
+ *
477
+ * @see PLUGIN_SPEC.md §8.5 — Uninstall Process
478
+ */
479
+ unloadSingle(pluginId: string, pluginKey: string): Promise<void>;
480
+
481
+ /**
482
+ * Stop all managed plugin workers. Called during server shutdown.
483
+ *
484
+ * Stops the job scheduler and then stops all workers via the worker
485
+ * manager. Does NOT change plugin statuses in the database — plugins
486
+ * remain in `ready` so they are restarted on next boot.
487
+ *
488
+ * **Requires** `PluginRuntimeServices` to have been provided at construction.
489
+ */
490
+ shutdownAll(): Promise<void>;
491
+
492
+ /**
493
+ * Whether runtime services are available for plugin activation.
494
+ */
495
+ hasRuntimeServices(): boolean;
496
+ }
497
+
498
+ // ---------------------------------------------------------------------------
499
+ // Helpers
500
+ // ---------------------------------------------------------------------------
501
+
502
+ /**
503
+ * Check whether a package name matches the Paperclip plugin naming convention.
504
+ * Accepts both the "paperclip-plugin-" prefix and scoped "@scope/plugin-" packages.
505
+ *
506
+ * @see PLUGIN_SPEC.md §10 — Package Contract
507
+ */
508
+ export function isPluginPackageName(name: string): boolean {
509
+ if (name.startsWith(NPM_PLUGIN_PACKAGE_PREFIX)) return true;
510
+ // Also accept scoped packages like @acme/plugin-linear or @corporateai/plugin-*
511
+ if (name.includes("/")) {
512
+ const localPart = name.split("/")[1] ?? "";
513
+ return localPart.startsWith("plugin-");
514
+ }
515
+ return false;
516
+ }
517
+
518
+ /**
519
+ * Read and parse a package.json from a directory path.
520
+ * Returns null if no package.json exists.
521
+ */
522
+ async function readPackageJson(
523
+ dir: string,
524
+ ): Promise<Record<string, unknown> | null> {
525
+ const pkgPath = path.join(dir, "package.json");
526
+ if (!existsSync(pkgPath)) return null;
527
+
528
+ try {
529
+ const raw = await readFile(pkgPath, "utf-8");
530
+ return JSON.parse(raw) as Record<string, unknown>;
531
+ } catch {
532
+ return null;
533
+ }
534
+ }
535
+
536
+ /**
537
+ * Resolve the manifest entrypoint from a package.json and package root.
538
+ *
539
+ * The spec defines a "paperclipPlugin" key in package.json with a "manifest"
540
+ * subkey pointing to the manifest module. This helper resolves the path.
541
+ *
542
+ * @see PLUGIN_SPEC.md §10 — Package Contract
543
+ */
544
+ function resolveManifestPath(
545
+ packageRoot: string,
546
+ pkgJson: Record<string, unknown>,
547
+ ): string | null {
548
+ const paperclipPlugin = pkgJson["paperclipPlugin"];
549
+ if (
550
+ paperclipPlugin !== null &&
551
+ typeof paperclipPlugin === "object" &&
552
+ !Array.isArray(paperclipPlugin)
553
+ ) {
554
+ const manifestRelPath = (paperclipPlugin as Record<string, unknown>)[
555
+ "manifest"
556
+ ];
557
+ if (typeof manifestRelPath === "string") {
558
+ // NOTE: the resolved path is returned as-is even if the file does not yet
559
+ // exist on disk (e.g. the package has not been built). Callers MUST guard
560
+ // with existsSync() before passing the path to loadManifestFromPath().
561
+ return path.resolve(packageRoot, manifestRelPath);
562
+ }
563
+ }
564
+
565
+ // Fallback: look for dist/manifest.js as a convention
566
+ const conventionalPath = path.join(packageRoot, "dist", "manifest.js");
567
+ if (existsSync(conventionalPath)) {
568
+ return conventionalPath;
569
+ }
570
+
571
+ // Fallback: look for manifest.js at package root
572
+ const rootManifestPath = path.join(packageRoot, "manifest.js");
573
+ if (existsSync(rootManifestPath)) {
574
+ return rootManifestPath;
575
+ }
576
+
577
+ return null;
578
+ }
579
+
580
+ function parseSemver(version: string): ParsedSemver | null {
581
+ const match = version.match(
582
+ /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,
583
+ );
584
+ if (!match) return null;
585
+
586
+ return {
587
+ major: Number(match[1]),
588
+ minor: Number(match[2]),
589
+ patch: Number(match[3]),
590
+ prerelease: match[4] ? match[4].split(".") : [],
591
+ };
592
+ }
593
+
594
+ function compareIdentifiers(left: string, right: string): number {
595
+ const leftIsNumeric = /^\d+$/.test(left);
596
+ const rightIsNumeric = /^\d+$/.test(right);
597
+
598
+ if (leftIsNumeric && rightIsNumeric) {
599
+ return Number(left) - Number(right);
600
+ }
601
+
602
+ if (leftIsNumeric) return -1;
603
+ if (rightIsNumeric) return 1;
604
+ return left.localeCompare(right);
605
+ }
606
+
607
+ function compareSemver(left: string, right: string): number {
608
+ const leftParsed = parseSemver(left);
609
+ const rightParsed = parseSemver(right);
610
+
611
+ if (!leftParsed || !rightParsed) {
612
+ throw new Error(`Invalid semver comparison: '${left}' vs '${right}'`);
613
+ }
614
+
615
+ const coreOrder = (
616
+ ["major", "minor", "patch"] as const
617
+ ).map((key) => leftParsed[key] - rightParsed[key]).find((delta) => delta !== 0);
618
+ if (coreOrder) {
619
+ return coreOrder;
620
+ }
621
+
622
+ if (leftParsed.prerelease.length === 0 && rightParsed.prerelease.length === 0) {
623
+ return 0;
624
+ }
625
+ if (leftParsed.prerelease.length === 0) return 1;
626
+ if (rightParsed.prerelease.length === 0) return -1;
627
+
628
+ const maxLength = Math.max(leftParsed.prerelease.length, rightParsed.prerelease.length);
629
+ for (let index = 0; index < maxLength; index += 1) {
630
+ const leftId = leftParsed.prerelease[index];
631
+ const rightId = rightParsed.prerelease[index];
632
+ if (leftId === undefined) return -1;
633
+ if (rightId === undefined) return 1;
634
+
635
+ const diff = compareIdentifiers(leftId, rightId);
636
+ if (diff !== 0) return diff;
637
+ }
638
+
639
+ return 0;
640
+ }
641
+
642
+ function getMinimumHostVersion(manifest: PaperclipPluginManifestV1): string | undefined {
643
+ return manifest.minimumHostVersion ?? manifest.minimumPaperclipVersion;
644
+ }
645
+
646
+ /**
647
+ * Extract UI contribution metadata from a manifest for route serialization.
648
+ *
649
+ * Returns `null` when the plugin does not declare any UI slots or launchers.
650
+ * Launcher declarations are aggregated from both the legacy top-level
651
+ * `launchers` field and the preferred `ui.launchers` field.
652
+ */
653
+ export function getPluginUiContributionMetadata(
654
+ manifest: PaperclipPluginManifestV1,
655
+ ): PluginUiContributionMetadata | null {
656
+ const slots = manifest.ui?.slots ?? [];
657
+ const launchers = [
658
+ ...(manifest.launchers ?? []),
659
+ ...(manifest.ui?.launchers ?? []),
660
+ ];
661
+
662
+ if (slots.length === 0 && launchers.length === 0) {
663
+ return null;
664
+ }
665
+
666
+ return {
667
+ uiEntryFile: "index.js",
668
+ slots,
669
+ launchers,
670
+ };
671
+ }
672
+
673
+ // ---------------------------------------------------------------------------
674
+ // Factory
675
+ // ---------------------------------------------------------------------------
676
+
677
+ /**
678
+ * Create a PluginLoader service.
679
+ *
680
+ * The loader is responsible for plugin discovery, installation, and runtime
681
+ * activation. It reads plugin packages from the local filesystem and npm,
682
+ * validates their manifests, registers them in the database, and — when
683
+ * runtime services are provided — initialises worker processes, event
684
+ * subscriptions, job schedules, webhook endpoints, and agent tools.
685
+ *
686
+ * Usage (discovery & install only):
687
+ * ```ts
688
+ * const loader = pluginLoader(db, { enableLocalFilesystem: true });
689
+ *
690
+ * // Discover all available plugins
691
+ * const result = await loader.discoverAll();
692
+ * for (const plugin of result.discovered) {
693
+ * console.log(plugin.packageName, plugin.manifest?.id);
694
+ * }
695
+ *
696
+ * // Install a specific plugin
697
+ * const discovered = await loader.installPlugin({
698
+ * packageName: "paperclip-plugin-linear",
699
+ * version: "^1.0.0",
700
+ * });
701
+ * ```
702
+ *
703
+ * Usage (full runtime activation at server startup):
704
+ * ```ts
705
+ * const loader = pluginLoader(db, loaderOpts, {
706
+ * workerManager,
707
+ * eventBus,
708
+ * jobScheduler,
709
+ * jobStore,
710
+ * toolDispatcher,
711
+ * lifecycleManager,
712
+ * buildHostHandlers: (pluginId, manifest) => ({ ... }),
713
+ * instanceInfo: { instanceId: "inst-1", hostVersion: "1.0.0" },
714
+ * });
715
+ *
716
+ * // Load all ready plugins at startup
717
+ * const loadResult = await loader.loadAll();
718
+ * console.log(`Loaded ${loadResult.succeeded}/${loadResult.total} plugins`);
719
+ *
720
+ * // Load a single plugin after install
721
+ * const singleResult = await loader.loadSingle(pluginId);
722
+ *
723
+ * // Shutdown all plugin workers on server exit
724
+ * await loader.shutdownAll();
725
+ * ```
726
+ *
727
+ * @see PLUGIN_SPEC.md §8.1 — On-Disk Layout
728
+ * @see PLUGIN_SPEC.md §8.3 — Install Process
729
+ * @see PLUGIN_SPEC.md §12 — Process Model
730
+ */
731
+ export function pluginLoader(
732
+ db: Db,
733
+ options: PluginLoaderOptions = {},
734
+ runtimeServices?: PluginRuntimeServices,
735
+ ): PluginLoader {
736
+ const {
737
+ localPluginDir = DEFAULT_LOCAL_PLUGIN_DIR,
738
+ enableLocalFilesystem = true,
739
+ enableNpmDiscovery = true,
740
+ } = options;
741
+
742
+ const registry = pluginRegistryService(db);
743
+ const manifestValidator = pluginManifestValidator();
744
+ const capabilityValidator = pluginCapabilityValidator();
745
+ const log = logger.child({ service: "plugin-loader" });
746
+ const hostVersion = runtimeServices?.instanceInfo.hostVersion;
747
+
748
+ async function assertPageRoutePathsAvailable(manifest: PaperclipPluginManifestV1): Promise<void> {
749
+ const requestedRoutePaths = getDeclaredPageRoutePaths(manifest);
750
+ if (requestedRoutePaths.length === 0) return;
751
+
752
+ const uniqueRequested = new Set(requestedRoutePaths);
753
+ if (uniqueRequested.size !== requestedRoutePaths.length) {
754
+ throw new Error(`Plugin ${manifest.id} declares duplicate page routePath values`);
755
+ }
756
+
757
+ const installedPlugins = await registry.listInstalled();
758
+ for (const plugin of installedPlugins) {
759
+ if (plugin.pluginKey === manifest.id) continue;
760
+ const installedManifest = plugin.manifestJson as PaperclipPluginManifestV1 | null;
761
+ if (!installedManifest) continue;
762
+ const installedRoutePaths = new Set(getDeclaredPageRoutePaths(installedManifest));
763
+ const conflictingRoute = requestedRoutePaths.find((routePath) => installedRoutePaths.has(routePath));
764
+ if (conflictingRoute) {
765
+ throw new Error(
766
+ `Plugin ${manifest.id} routePath "${conflictingRoute}" conflicts with installed plugin ${plugin.pluginKey}`,
767
+ );
768
+ }
769
+ }
770
+ }
771
+
772
+ // -------------------------------------------------------------------------
773
+ // Internal helpers
774
+ // -------------------------------------------------------------------------
775
+
776
+ /**
777
+ * Fetch a plugin from npm or local path, then parse and validate its manifest.
778
+ *
779
+ * This internal helper encapsulates the core plugin retrieval and validation
780
+ * logic used by both install and upgrade operations. It handles:
781
+ * 1. Resolving the package from npm or local filesystem.
782
+ * 2. Installing the package via npm if necessary.
783
+ * 3. Reading and parsing the plugin manifest.
784
+ * 4. Validating API version compatibility.
785
+ * 5. Validating manifest capabilities.
786
+ *
787
+ * @param installOptions - Options specifying the package to fetch.
788
+ * @returns A `DiscoveredPlugin` object containing the validated manifest.
789
+ */
790
+ async function fetchAndValidate(
791
+ installOptions: PluginInstallOptions,
792
+ ): Promise<DiscoveredPlugin> {
793
+ const { packageName, localPath, version, installDir } = installOptions;
794
+
795
+ if (!packageName && !localPath) {
796
+ throw new Error("Either packageName or localPath must be provided");
797
+ }
798
+
799
+ const targetInstallDir = installDir ?? localPluginDir;
800
+
801
+ // Step 1 & 2: Resolve and install package
802
+ let resolvedPackagePath: string;
803
+ let resolvedPackageName: string;
804
+
805
+ if (localPath) {
806
+ // Local path install — validate the directory exists
807
+ const absLocalPath = path.resolve(localPath);
808
+ if (!existsSync(absLocalPath)) {
809
+ throw new Error(`Local plugin path does not exist: ${absLocalPath}`);
810
+ }
811
+ resolvedPackagePath = absLocalPath;
812
+ const pkgJson = await readPackageJson(absLocalPath);
813
+ resolvedPackageName =
814
+ typeof pkgJson?.["name"] === "string"
815
+ ? pkgJson["name"]
816
+ : path.basename(absLocalPath);
817
+
818
+ log.info(
819
+ { localPath: absLocalPath, packageName: resolvedPackageName },
820
+ "plugin-loader: fetching plugin from local path",
821
+ );
822
+ } else {
823
+ // npm install
824
+ const spec = version ? `${packageName}@${version}` : packageName!;
825
+
826
+ log.info(
827
+ { spec, installDir: targetInstallDir },
828
+ "plugin-loader: fetching plugin from npm",
829
+ );
830
+
831
+ try {
832
+ // Use execFile (not exec) to avoid shell injection from package name/version.
833
+ // --ignore-scripts prevents preinstall/install/postinstall hooks from
834
+ // executing arbitrary code on the host before manifest validation.
835
+ await execFileAsync(
836
+ "npm",
837
+ ["install", spec, "--prefix", targetInstallDir, "--save", "--ignore-scripts"],
838
+ { timeout: 120_000 }, // 2 minute timeout for npm install
839
+ );
840
+ } catch (err) {
841
+ throw new Error(`npm install failed for ${spec}: ${String(err)}`);
842
+ }
843
+
844
+ // Resolve the package path after installation
845
+ const nodeModulesPath = path.join(targetInstallDir, "node_modules");
846
+ resolvedPackageName = packageName!;
847
+
848
+ // Handle scoped packages
849
+ if (resolvedPackageName.startsWith("@")) {
850
+ const [scope, name] = resolvedPackageName.split("/");
851
+ resolvedPackagePath = path.join(nodeModulesPath, scope!, name!);
852
+ } else {
853
+ resolvedPackagePath = path.join(nodeModulesPath, resolvedPackageName);
854
+ }
855
+
856
+ if (!existsSync(resolvedPackagePath)) {
857
+ throw new Error(
858
+ `Package directory not found after installation: ${resolvedPackagePath}`,
859
+ );
860
+ }
861
+ }
862
+
863
+ // Step 3: Read and validate plugin manifest
864
+ // Note: this.loadManifest (used via current context)
865
+ const pkgJson = await readPackageJson(resolvedPackagePath);
866
+ if (!pkgJson) throw new Error(`Missing package.json at ${resolvedPackagePath}`);
867
+
868
+ const manifestPath = resolveManifestPath(resolvedPackagePath, pkgJson);
869
+ if (!manifestPath || !existsSync(manifestPath)) {
870
+ throw new Error(
871
+ `Package ${resolvedPackageName} at ${resolvedPackagePath} does not appear to be a Paperclip plugin (no manifest found).`,
872
+ );
873
+ }
874
+
875
+ const manifest = await loadManifestFromPath(manifestPath);
876
+
877
+ // Step 4: Reject incompatible plugin API versions
878
+ if (!manifestValidator.getSupportedVersions().includes(manifest.apiVersion)) {
879
+ throw new Error(
880
+ `Plugin ${manifest.id} declares apiVersion ${manifest.apiVersion} which is not supported by this host. ` +
881
+ `Supported versions: ${manifestValidator.getSupportedVersions().join(", ")}`,
882
+ );
883
+ }
884
+
885
+ // Step 5: Validate manifest capabilities are consistent
886
+ const capResult = capabilityValidator.validateManifestCapabilities(manifest);
887
+ if (!capResult.allowed) {
888
+ throw new Error(
889
+ `Plugin ${manifest.id} manifest has inconsistent capabilities. ` +
890
+ `Missing required capabilities for declared features: ${capResult.missing.join(", ")}`,
891
+ );
892
+ }
893
+
894
+ await assertPageRoutePathsAvailable(manifest);
895
+
896
+ // Step 6: Reject plugins that require a newer host than the running server
897
+ const minimumHostVersion = getMinimumHostVersion(manifest);
898
+ if (minimumHostVersion && hostVersion) {
899
+ if (compareSemver(hostVersion, minimumHostVersion) < 0) {
900
+ throw new Error(
901
+ `Plugin ${manifest.id} requires host version ${minimumHostVersion} or newer, ` +
902
+ `but this server is running ${hostVersion}`,
903
+ );
904
+ }
905
+ }
906
+
907
+ // Use the version declared in the manifest (required field per the spec)
908
+ const resolvedVersion = manifest.version;
909
+
910
+ return {
911
+ packagePath: resolvedPackagePath,
912
+ packageName: resolvedPackageName,
913
+ version: resolvedVersion,
914
+ source: localPath ? "local-filesystem" : "npm",
915
+ manifest,
916
+ };
917
+ }
918
+
919
+ /**
920
+ * Attempt to load and validate a plugin manifest from a resolved path.
921
+ * Returns the manifest on success or throws with a descriptive error.
922
+ */
923
+ async function loadManifestFromPath(
924
+ manifestPath: string,
925
+ ): Promise<PaperclipPluginManifestV1> {
926
+ let raw: unknown;
927
+
928
+ try {
929
+ // Dynamic import works for both .js (ESM) and .cjs (CJS) manifests
930
+ const mod = await import(manifestPath) as Record<string, unknown>;
931
+ // The manifest may be the default export or the module itself
932
+ raw = mod["default"] ?? mod;
933
+ } catch (err) {
934
+ throw new Error(
935
+ `Failed to load manifest module at ${manifestPath}: ${String(err)}`,
936
+ );
937
+ }
938
+
939
+ return manifestValidator.parseOrThrow(raw);
940
+ }
941
+
942
+ /**
943
+ * Build a DiscoveredPlugin from a resolved package directory, or null
944
+ * if the package is not a Paperclip plugin.
945
+ */
946
+ async function buildDiscoveredPlugin(
947
+ packagePath: string,
948
+ source: PluginSource,
949
+ ): Promise<DiscoveredPlugin | null> {
950
+ const pkgJson = await readPackageJson(packagePath);
951
+ if (!pkgJson) return null;
952
+
953
+ const packageName = typeof pkgJson["name"] === "string" ? pkgJson["name"] : "";
954
+ const version = typeof pkgJson["version"] === "string" ? pkgJson["version"] : "0.0.0";
955
+
956
+ // Determine if this is a plugin package at all
957
+ const hasPaperclipPlugin = "paperclipPlugin" in pkgJson;
958
+ const nameMatchesConvention = isPluginPackageName(packageName);
959
+
960
+ if (!hasPaperclipPlugin && !nameMatchesConvention) {
961
+ return null;
962
+ }
963
+
964
+ const manifestPath = resolveManifestPath(packagePath, pkgJson);
965
+ if (!manifestPath || !existsSync(manifestPath)) {
966
+ // Found a potential plugin package but no manifest entry point — treat
967
+ // as a discovery-only result with no manifest
968
+ return {
969
+ packagePath,
970
+ packageName,
971
+ version,
972
+ source,
973
+ manifest: null,
974
+ };
975
+ }
976
+
977
+ try {
978
+ const manifest = await loadManifestFromPath(manifestPath);
979
+ return {
980
+ packagePath,
981
+ packageName,
982
+ version,
983
+ source,
984
+ manifest,
985
+ };
986
+ } catch (err) {
987
+ // Rethrow with context — callers catch and route to the errors array
988
+ throw new Error(
989
+ `Plugin ${packageName}: ${String(err)}`,
990
+ );
991
+ }
992
+ }
993
+
994
+ // -------------------------------------------------------------------------
995
+ // Public API
996
+ // -------------------------------------------------------------------------
997
+
998
+ return {
999
+ // -----------------------------------------------------------------------
1000
+ // discoverAll
1001
+ // -----------------------------------------------------------------------
1002
+
1003
+ async discoverAll(npmSearchDirs?: string[]): Promise<PluginDiscoveryResult> {
1004
+ const allDiscovered: DiscoveredPlugin[] = [];
1005
+ const allErrors: Array<{ packagePath: string; packageName: string; error: string }> = [];
1006
+ const sources: PluginSource[] = [];
1007
+
1008
+ if (enableLocalFilesystem) {
1009
+ sources.push("local-filesystem");
1010
+ const fsResult = await this.discoverFromLocalFilesystem();
1011
+ allDiscovered.push(...fsResult.discovered);
1012
+ allErrors.push(...fsResult.errors);
1013
+ }
1014
+
1015
+ if (enableNpmDiscovery) {
1016
+ sources.push("npm");
1017
+ const npmResult = await this.discoverFromNpm(npmSearchDirs);
1018
+ // Deduplicate against already-discovered packages (same package path)
1019
+ const existingPaths = new Set(allDiscovered.map((d) => d.packagePath));
1020
+ for (const plugin of npmResult.discovered) {
1021
+ if (!existingPaths.has(plugin.packagePath)) {
1022
+ allDiscovered.push(plugin);
1023
+ }
1024
+ }
1025
+ allErrors.push(...npmResult.errors);
1026
+ }
1027
+
1028
+ // Future: registry source (options.registryUrl)
1029
+ if (options.registryUrl) {
1030
+ sources.push("registry");
1031
+ log.warn(
1032
+ { registryUrl: options.registryUrl },
1033
+ "plugin-loader: remote registry discovery is not yet implemented",
1034
+ );
1035
+ }
1036
+
1037
+ log.info(
1038
+ {
1039
+ discovered: allDiscovered.length,
1040
+ errors: allErrors.length,
1041
+ sources,
1042
+ },
1043
+ "plugin-loader: discovery complete",
1044
+ );
1045
+
1046
+ return { discovered: allDiscovered, errors: allErrors, sources };
1047
+ },
1048
+
1049
+ // -----------------------------------------------------------------------
1050
+ // discoverFromLocalFilesystem
1051
+ // -----------------------------------------------------------------------
1052
+
1053
+ async discoverFromLocalFilesystem(dir?: string): Promise<PluginDiscoveryResult> {
1054
+ const scanDir = dir ?? localPluginDir;
1055
+ const discovered: DiscoveredPlugin[] = [];
1056
+ const errors: Array<{ packagePath: string; packageName: string; error: string }> = [];
1057
+
1058
+ if (!existsSync(scanDir)) {
1059
+ log.debug(
1060
+ { dir: scanDir },
1061
+ "plugin-loader: local plugin directory does not exist, skipping",
1062
+ );
1063
+ return { discovered, errors, sources: ["local-filesystem"] };
1064
+ }
1065
+
1066
+ let entries: string[];
1067
+ try {
1068
+ entries = await readdir(scanDir);
1069
+ } catch (err) {
1070
+ log.warn({ dir: scanDir, err }, "plugin-loader: failed to read local plugin directory");
1071
+ return { discovered, errors, sources: ["local-filesystem"] };
1072
+ }
1073
+
1074
+ for (const entry of entries) {
1075
+ const entryPath = path.join(scanDir, entry);
1076
+
1077
+ // Check if entry is a directory
1078
+ let entryStat;
1079
+ try {
1080
+ entryStat = await stat(entryPath);
1081
+ } catch {
1082
+ continue;
1083
+ }
1084
+ if (!entryStat.isDirectory()) continue;
1085
+
1086
+ // Handle scoped packages: @scope/plugin-name is a subdirectory
1087
+ if (entry.startsWith("@")) {
1088
+ let scopedEntries: string[];
1089
+ try {
1090
+ scopedEntries = await readdir(entryPath);
1091
+ } catch {
1092
+ continue;
1093
+ }
1094
+ for (const scopedEntry of scopedEntries) {
1095
+ const scopedPath = path.join(entryPath, scopedEntry);
1096
+ try {
1097
+ const scopedStat = await stat(scopedPath);
1098
+ if (!scopedStat.isDirectory()) continue;
1099
+ const plugin = await buildDiscoveredPlugin(scopedPath, "local-filesystem");
1100
+ if (plugin) discovered.push(plugin);
1101
+ } catch (err) {
1102
+ errors.push({
1103
+ packagePath: scopedPath,
1104
+ packageName: `${entry}/${scopedEntry}`,
1105
+ error: String(err),
1106
+ });
1107
+ }
1108
+ }
1109
+ continue;
1110
+ }
1111
+
1112
+ try {
1113
+ const plugin = await buildDiscoveredPlugin(entryPath, "local-filesystem");
1114
+ if (plugin) discovered.push(plugin);
1115
+ } catch (err) {
1116
+ const pkgJson = await readPackageJson(entryPath);
1117
+ const packageName =
1118
+ typeof pkgJson?.["name"] === "string" ? pkgJson["name"] : entry;
1119
+ errors.push({ packagePath: entryPath, packageName, error: String(err) });
1120
+ }
1121
+ }
1122
+
1123
+ log.debug(
1124
+ { dir: scanDir, discovered: discovered.length, errors: errors.length },
1125
+ "plugin-loader: local filesystem scan complete",
1126
+ );
1127
+
1128
+ return { discovered, errors, sources: ["local-filesystem"] };
1129
+ },
1130
+
1131
+ // -----------------------------------------------------------------------
1132
+ // discoverFromNpm
1133
+ // -----------------------------------------------------------------------
1134
+
1135
+ async discoverFromNpm(searchDirs?: string[]): Promise<PluginDiscoveryResult> {
1136
+ const discovered: DiscoveredPlugin[] = [];
1137
+ const errors: Array<{ packagePath: string; packageName: string; error: string }> = [];
1138
+
1139
+ // Determine the node_modules directories to search.
1140
+ // When searchDirs is undefined OR empty, fall back to the conventional
1141
+ // defaults (cwd/node_modules and localPluginDir/node_modules).
1142
+ // To search nowhere explicitly, pass a non-empty array of non-existent paths.
1143
+ const dirsToSearch: string[] = searchDirs && searchDirs.length > 0 ? searchDirs : [];
1144
+
1145
+ if (dirsToSearch.length === 0) {
1146
+ // Default: search node_modules relative to the process working directory
1147
+ // and also the local plugin dir's node_modules
1148
+ const cwdNodeModules = path.join(process.cwd(), "node_modules");
1149
+ const localNodeModules = path.join(localPluginDir, "node_modules");
1150
+
1151
+ if (existsSync(cwdNodeModules)) dirsToSearch.push(cwdNodeModules);
1152
+ if (existsSync(localNodeModules)) dirsToSearch.push(localNodeModules);
1153
+ }
1154
+
1155
+ for (const nodeModulesDir of dirsToSearch) {
1156
+ if (!existsSync(nodeModulesDir)) continue;
1157
+
1158
+ let entries: string[];
1159
+ try {
1160
+ entries = await readdir(nodeModulesDir);
1161
+ } catch {
1162
+ continue;
1163
+ }
1164
+
1165
+ for (const entry of entries) {
1166
+ const entryPath = path.join(nodeModulesDir, entry);
1167
+
1168
+ // Handle scoped packages (@scope/*)
1169
+ if (entry.startsWith("@")) {
1170
+ let scopedEntries: string[];
1171
+ try {
1172
+ scopedEntries = await readdir(entryPath);
1173
+ } catch {
1174
+ continue;
1175
+ }
1176
+ for (const scopedEntry of scopedEntries) {
1177
+ const fullName = `${entry}/${scopedEntry}`;
1178
+ if (!isPluginPackageName(fullName)) continue;
1179
+
1180
+ const scopedPath = path.join(entryPath, scopedEntry);
1181
+ try {
1182
+ const plugin = await buildDiscoveredPlugin(scopedPath, "npm");
1183
+ if (plugin) discovered.push(plugin);
1184
+ } catch (err) {
1185
+ errors.push({
1186
+ packagePath: scopedPath,
1187
+ packageName: fullName,
1188
+ error: String(err),
1189
+ });
1190
+ }
1191
+ }
1192
+ continue;
1193
+ }
1194
+
1195
+ // Non-scoped packages: check naming convention
1196
+ if (!isPluginPackageName(entry)) continue;
1197
+
1198
+ let entryStat;
1199
+ try {
1200
+ entryStat = await stat(entryPath);
1201
+ } catch {
1202
+ continue;
1203
+ }
1204
+ if (!entryStat.isDirectory()) continue;
1205
+
1206
+ try {
1207
+ const plugin = await buildDiscoveredPlugin(entryPath, "npm");
1208
+ if (plugin) discovered.push(plugin);
1209
+ } catch (err) {
1210
+ const pkgJson = await readPackageJson(entryPath);
1211
+ const packageName =
1212
+ typeof pkgJson?.["name"] === "string" ? pkgJson["name"] : entry;
1213
+ errors.push({ packagePath: entryPath, packageName, error: String(err) });
1214
+ }
1215
+ }
1216
+ }
1217
+
1218
+ log.debug(
1219
+ { searchDirs: dirsToSearch, discovered: discovered.length, errors: errors.length },
1220
+ "plugin-loader: npm discovery scan complete",
1221
+ );
1222
+
1223
+ return { discovered, errors, sources: ["npm"] };
1224
+ },
1225
+
1226
+ // -----------------------------------------------------------------------
1227
+ // loadManifest
1228
+ // -----------------------------------------------------------------------
1229
+
1230
+ async loadManifest(packagePath: string): Promise<PaperclipPluginManifestV1 | null> {
1231
+ const pkgJson = await readPackageJson(packagePath);
1232
+ if (!pkgJson) return null;
1233
+
1234
+ const hasPaperclipPlugin = "paperclipPlugin" in pkgJson;
1235
+ const packageName = typeof pkgJson["name"] === "string" ? pkgJson["name"] : "";
1236
+ const nameMatchesConvention = isPluginPackageName(packageName);
1237
+
1238
+ if (!hasPaperclipPlugin && !nameMatchesConvention) {
1239
+ return null;
1240
+ }
1241
+
1242
+ const manifestPath = resolveManifestPath(packagePath, pkgJson);
1243
+ if (!manifestPath || !existsSync(manifestPath)) return null;
1244
+
1245
+ return loadManifestFromPath(manifestPath);
1246
+ },
1247
+
1248
+ // -----------------------------------------------------------------------
1249
+ // installPlugin
1250
+ // -----------------------------------------------------------------------
1251
+
1252
+ async installPlugin(installOptions: PluginInstallOptions): Promise<DiscoveredPlugin> {
1253
+ const discovered = await fetchAndValidate(installOptions);
1254
+
1255
+ // Step 6: Persist install record in Postgres (include packagePath for local installs so the worker can be resolved)
1256
+ await registry.install(
1257
+ {
1258
+ packageName: discovered.packageName,
1259
+ packagePath: discovered.source === "local-filesystem" ? discovered.packagePath : undefined,
1260
+ },
1261
+ discovered.manifest!,
1262
+ );
1263
+
1264
+ log.info(
1265
+ {
1266
+ pluginId: discovered.manifest!.id,
1267
+ packageName: discovered.packageName,
1268
+ version: discovered.version,
1269
+ capabilities: discovered.manifest!.capabilities,
1270
+ },
1271
+ "plugin-loader: plugin installed successfully",
1272
+ );
1273
+
1274
+ return discovered;
1275
+ },
1276
+
1277
+ // -----------------------------------------------------------------------
1278
+ // upgradePlugin
1279
+ // -----------------------------------------------------------------------
1280
+
1281
+ /**
1282
+ * Upgrade an already-installed plugin to a newer version.
1283
+ *
1284
+ * This method:
1285
+ * 1. Fetches and validates the new plugin package using `fetchAndValidate`.
1286
+ * 2. Ensures the new manifest ID matches the existing plugin ID for safety.
1287
+ * 3. Updates the plugin record in the registry with the new version and manifest.
1288
+ *
1289
+ * @param pluginId - The UUID of the plugin to upgrade.
1290
+ * @param upgradeOptions - Options for the upgrade (packageName, localPath, version).
1291
+ * @returns The old and new manifests, along with the discovery metadata.
1292
+ * @throws {Error} If the plugin is not found or if the new manifest ID differs.
1293
+ */
1294
+ async upgradePlugin(
1295
+ pluginId: string,
1296
+ upgradeOptions: Omit<PluginInstallOptions, "installDir">,
1297
+ ): Promise<{
1298
+ oldManifest: PaperclipPluginManifestV1;
1299
+ newManifest: PaperclipPluginManifestV1;
1300
+ discovered: DiscoveredPlugin;
1301
+ }> {
1302
+ const plugin = (await registry.getById(pluginId)) as {
1303
+ id: string;
1304
+ packageName: string;
1305
+ packagePath: string | null;
1306
+ manifestJson: PaperclipPluginManifestV1;
1307
+ } | null;
1308
+ if (!plugin) throw new Error(`Plugin not found: ${pluginId}`);
1309
+
1310
+ const oldManifest = plugin.manifestJson;
1311
+ const {
1312
+ packageName = plugin.packageName,
1313
+ // For local-path installs, fall back to the stored packagePath so
1314
+ // `upgradePlugin` can re-read the manifest from disk without needing
1315
+ // the caller to re-supply the path every time.
1316
+ localPath = plugin.packagePath ?? undefined,
1317
+ version,
1318
+ } = upgradeOptions;
1319
+
1320
+ log.info(
1321
+ { pluginId, packageName, version, localPath },
1322
+ "plugin-loader: upgrading plugin",
1323
+ );
1324
+
1325
+ // 1. Fetch/Install the new version
1326
+ const discovered = await fetchAndValidate({
1327
+ packageName,
1328
+ localPath,
1329
+ version,
1330
+ installDir: localPluginDir,
1331
+ });
1332
+
1333
+ const newManifest = discovered.manifest!;
1334
+
1335
+ // 2. Validate it's the same plugin ID
1336
+ if (newManifest.id !== oldManifest.id) {
1337
+ throw new Error(
1338
+ `Upgrade failed: new manifest ID '${newManifest.id}' does not match existing plugin ID '${oldManifest.id}'`,
1339
+ );
1340
+ }
1341
+
1342
+ // 3. Detect capability escalation — new capabilities not in the old manifest
1343
+ const oldCaps = new Set(oldManifest.capabilities ?? []);
1344
+ const newCaps = newManifest.capabilities ?? [];
1345
+ const escalated = newCaps.filter((c) => !oldCaps.has(c));
1346
+
1347
+ if (escalated.length > 0) {
1348
+ log.warn(
1349
+ { pluginId, escalated, oldVersion: oldManifest.version, newVersion: newManifest.version },
1350
+ "plugin-loader: upgrade introduces new capabilities — requires admin approval",
1351
+ );
1352
+ throw new Error(
1353
+ `Upgrade for "${pluginId}" introduces new capabilities that require approval: ${escalated.join(", ")}. ` +
1354
+ `The previous version declared [${[...oldCaps].join(", ")}]. ` +
1355
+ `Please review and approve the capability escalation before upgrading.`,
1356
+ );
1357
+ }
1358
+
1359
+ // 4. Update the existing record
1360
+ await registry.update(pluginId, {
1361
+ packageName: discovered.packageName,
1362
+ version: discovered.version,
1363
+ manifest: newManifest,
1364
+ });
1365
+
1366
+ return {
1367
+ oldManifest,
1368
+ newManifest,
1369
+ discovered,
1370
+ };
1371
+ },
1372
+
1373
+ // -----------------------------------------------------------------------
1374
+ // isSupportedApiVersion
1375
+ // -----------------------------------------------------------------------
1376
+
1377
+ isSupportedApiVersion(apiVersion: number): boolean {
1378
+ return manifestValidator.getSupportedVersions().includes(apiVersion);
1379
+ },
1380
+
1381
+ // -----------------------------------------------------------------------
1382
+ // cleanupInstallArtifacts
1383
+ // -----------------------------------------------------------------------
1384
+
1385
+ async cleanupInstallArtifacts(plugin: PluginRecord): Promise<void> {
1386
+ const managedTargets = new Set<string>();
1387
+ const managedNodeModulesDir = resolveManagedInstallPackageDir(localPluginDir, plugin.packageName);
1388
+ const directManagedDir = path.join(localPluginDir, plugin.packageName);
1389
+
1390
+ managedTargets.add(managedNodeModulesDir);
1391
+ if (isPathInsideDir(directManagedDir, localPluginDir)) {
1392
+ managedTargets.add(directManagedDir);
1393
+ }
1394
+ if (plugin.packagePath && isPathInsideDir(plugin.packagePath, localPluginDir)) {
1395
+ managedTargets.add(path.resolve(plugin.packagePath));
1396
+ }
1397
+
1398
+ const packageJsonPath = path.join(localPluginDir, "package.json");
1399
+ if (existsSync(packageJsonPath)) {
1400
+ try {
1401
+ await execFileAsync(
1402
+ "npm",
1403
+ ["uninstall", plugin.packageName, "--prefix", localPluginDir, "--ignore-scripts"],
1404
+ { timeout: 120_000 },
1405
+ );
1406
+ } catch (err) {
1407
+ log.warn(
1408
+ {
1409
+ pluginId: plugin.id,
1410
+ pluginKey: plugin.pluginKey,
1411
+ packageName: plugin.packageName,
1412
+ err: err instanceof Error ? err.message : String(err),
1413
+ },
1414
+ "plugin-loader: npm uninstall failed during cleanup, falling back to direct removal",
1415
+ );
1416
+ }
1417
+ }
1418
+
1419
+ for (const target of managedTargets) {
1420
+ if (!existsSync(target)) continue;
1421
+ await rm(target, { recursive: true, force: true });
1422
+ }
1423
+ },
1424
+
1425
+ // -----------------------------------------------------------------------
1426
+ // getLocalPluginDir
1427
+ // -----------------------------------------------------------------------
1428
+
1429
+ getLocalPluginDir(): string {
1430
+ return localPluginDir;
1431
+ },
1432
+
1433
+ // -----------------------------------------------------------------------
1434
+ // hasRuntimeServices
1435
+ // -----------------------------------------------------------------------
1436
+
1437
+ hasRuntimeServices(): boolean {
1438
+ return runtimeServices !== undefined;
1439
+ },
1440
+
1441
+ // -----------------------------------------------------------------------
1442
+ // -----------------------------------------------------------------------
1443
+ // loadAll
1444
+ // -----------------------------------------------------------------------
1445
+
1446
+ /**
1447
+ * loadAll — Loads and activates all plugins that are currently in 'ready' status.
1448
+ *
1449
+ * This method is typically called during server startup. It fetches all ready
1450
+ * plugins from the registry and attempts to activate them in parallel using
1451
+ * Promise.allSettled. Failures in individual plugins do not prevent others from loading.
1452
+ *
1453
+ * @returns A promise that resolves with summary statistics of the load operation.
1454
+ */
1455
+ async loadAll(): Promise<PluginLoadAllResult> {
1456
+ if (!runtimeServices) {
1457
+ throw new Error(
1458
+ "Cannot loadAll: no PluginRuntimeServices provided. " +
1459
+ "Pass runtime services as the third argument to pluginLoader().",
1460
+ );
1461
+ }
1462
+
1463
+ log.info("plugin-loader: loading all ready plugins");
1464
+
1465
+ // Fetch all plugins in ready status, ordered by installOrder
1466
+ const readyPlugins = (await registry.listByStatus("ready")) as PluginRecord[];
1467
+
1468
+ if (readyPlugins.length === 0) {
1469
+ log.info("plugin-loader: no ready plugins to load");
1470
+ return { total: 0, succeeded: 0, failed: 0, results: [] };
1471
+ }
1472
+
1473
+ log.info(
1474
+ { count: readyPlugins.length },
1475
+ "plugin-loader: found ready plugins to load",
1476
+ );
1477
+
1478
+ // Load plugins in parallel
1479
+ const results = await Promise.allSettled(
1480
+ readyPlugins.map((plugin) => activatePlugin(plugin))
1481
+ );
1482
+
1483
+ const loadResults = results.map((r, i) => {
1484
+ if (r.status === "fulfilled") return r.value;
1485
+ return {
1486
+ plugin: readyPlugins[i]!,
1487
+ success: false,
1488
+ error: String(r.reason),
1489
+ registered: { worker: false, eventSubscriptions: 0, jobs: 0, webhooks: 0, tools: 0 },
1490
+ };
1491
+ });
1492
+
1493
+ const succeeded = loadResults.filter((r) => r.success).length;
1494
+ const failed = loadResults.filter((r) => !r.success).length;
1495
+
1496
+ log.info(
1497
+ {
1498
+ total: readyPlugins.length,
1499
+ succeeded,
1500
+ failed,
1501
+ },
1502
+ "plugin-loader: loadAll complete",
1503
+ );
1504
+
1505
+ return {
1506
+ total: readyPlugins.length,
1507
+ succeeded,
1508
+ failed,
1509
+ results: loadResults,
1510
+ };
1511
+ },
1512
+
1513
+ // -----------------------------------------------------------------------
1514
+ // loadSingle
1515
+ // -----------------------------------------------------------------------
1516
+
1517
+ /**
1518
+ * loadSingle — Loads and activates a single plugin by its ID.
1519
+ *
1520
+ * This method retrieves the plugin from the registry, ensures it's in a valid
1521
+ * state, and then calls activatePlugin to start its worker and register its
1522
+ * capabilities (tools, jobs, etc.).
1523
+ *
1524
+ * @param pluginId - The UUID of the plugin to load.
1525
+ * @returns A promise that resolves with the result of the activation.
1526
+ */
1527
+ async loadSingle(pluginId: string): Promise<PluginLoadResult> {
1528
+ if (!runtimeServices) {
1529
+ throw new Error(
1530
+ "Cannot loadSingle: no PluginRuntimeServices provided. " +
1531
+ "Pass runtime services as the third argument to pluginLoader().",
1532
+ );
1533
+ }
1534
+
1535
+ const plugin = (await registry.getById(pluginId)) as PluginRecord | null;
1536
+ if (!plugin) {
1537
+ throw new Error(`Plugin not found: ${pluginId}`);
1538
+ }
1539
+
1540
+ // If the plugin is in 'installed' status, transition it to 'ready' first.
1541
+ // lifecycleManager.load() transitions the status AND activates the plugin
1542
+ // via activateReadyPlugin() → loadSingle() (recursive call with 'ready'
1543
+ // status) → activatePlugin(). We must NOT call activatePlugin() again here,
1544
+ // as that would double-start the worker and duplicate registrations.
1545
+ if (plugin.status === "installed") {
1546
+ await runtimeServices.lifecycleManager.load(pluginId);
1547
+ const updated = (await registry.getById(pluginId)) as PluginRecord | null;
1548
+ if (!updated) throw new Error(`Plugin not found after status update: ${pluginId}`);
1549
+ return {
1550
+ plugin: updated,
1551
+ success: true,
1552
+ registered: { worker: true, eventSubscriptions: 0, jobs: 0, webhooks: 0, tools: 0 },
1553
+ };
1554
+ }
1555
+
1556
+ if (plugin.status !== "ready") {
1557
+ throw new Error(
1558
+ `Cannot load plugin in status '${plugin.status}'. ` +
1559
+ `Plugin must be in 'installed' or 'ready' status.`,
1560
+ );
1561
+ }
1562
+
1563
+ return activatePlugin(plugin);
1564
+ },
1565
+
1566
+ // -----------------------------------------------------------------------
1567
+ // unloadSingle
1568
+ // -----------------------------------------------------------------------
1569
+
1570
+ async unloadSingle(pluginId: string, pluginKey: string): Promise<void> {
1571
+ if (!runtimeServices) {
1572
+ throw new Error(
1573
+ "Cannot unloadSingle: no PluginRuntimeServices provided.",
1574
+ );
1575
+ }
1576
+
1577
+ log.info(
1578
+ { pluginId, pluginKey },
1579
+ "plugin-loader: unloading single plugin",
1580
+ );
1581
+
1582
+ const {
1583
+ workerManager,
1584
+ eventBus,
1585
+ jobScheduler,
1586
+ toolDispatcher,
1587
+ } = runtimeServices;
1588
+
1589
+ // 1. Unregister from job scheduler (cancels in-flight runs)
1590
+ try {
1591
+ await jobScheduler.unregisterPlugin(pluginId);
1592
+ } catch (err) {
1593
+ log.warn(
1594
+ { pluginId, err: err instanceof Error ? err.message : String(err) },
1595
+ "plugin-loader: failed to unregister from job scheduler (best-effort)",
1596
+ );
1597
+ }
1598
+
1599
+ // 2. Clear event subscriptions
1600
+ eventBus.clearPlugin(pluginKey);
1601
+
1602
+ // 3. Unregister agent tools
1603
+ toolDispatcher.unregisterPluginTools(pluginKey);
1604
+
1605
+ // 4. Stop the worker process
1606
+ try {
1607
+ if (workerManager.isRunning(pluginId)) {
1608
+ await workerManager.stopWorker(pluginId);
1609
+ }
1610
+ } catch (err) {
1611
+ log.warn(
1612
+ { pluginId, err: err instanceof Error ? err.message : String(err) },
1613
+ "plugin-loader: failed to stop worker during unload (best-effort)",
1614
+ );
1615
+ }
1616
+
1617
+ log.info(
1618
+ { pluginId, pluginKey },
1619
+ "plugin-loader: plugin unloaded successfully",
1620
+ );
1621
+ },
1622
+
1623
+ // -----------------------------------------------------------------------
1624
+ // shutdownAll
1625
+ // -----------------------------------------------------------------------
1626
+
1627
+ async shutdownAll(): Promise<void> {
1628
+ if (!runtimeServices) {
1629
+ throw new Error(
1630
+ "Cannot shutdownAll: no PluginRuntimeServices provided.",
1631
+ );
1632
+ }
1633
+
1634
+ log.info("plugin-loader: shutting down all plugins");
1635
+
1636
+ const { workerManager, jobScheduler } = runtimeServices;
1637
+
1638
+ // 1. Stop the job scheduler tick loop
1639
+ jobScheduler.stop();
1640
+
1641
+ // 2. Stop all worker processes
1642
+ await workerManager.stopAll();
1643
+
1644
+ log.info("plugin-loader: all plugins shut down");
1645
+ },
1646
+ };
1647
+
1648
+ // -------------------------------------------------------------------------
1649
+ // Internal: activatePlugin — shared logic for loadAll and loadSingle
1650
+ // -------------------------------------------------------------------------
1651
+
1652
+ /**
1653
+ * Activate a single plugin: spawn its worker, register event subscriptions,
1654
+ * sync jobs, register tools.
1655
+ *
1656
+ * This is the core orchestration logic shared by `loadAll()` and `loadSingle()`.
1657
+ * Failures are caught and reported in the result; the plugin is marked as
1658
+ * `error` in the database when activation fails.
1659
+ */
1660
+ async function activatePlugin(plugin: PluginRecord): Promise<PluginLoadResult> {
1661
+ const manifest = plugin.manifestJson;
1662
+ const pluginId = plugin.id;
1663
+ const pluginKey = plugin.pluginKey;
1664
+
1665
+ const registered: PluginLoadResult["registered"] = {
1666
+ worker: false,
1667
+ eventSubscriptions: 0,
1668
+ jobs: 0,
1669
+ webhooks: 0,
1670
+ tools: 0,
1671
+ };
1672
+
1673
+ // Guard: runtime services must exist (callers already checked)
1674
+ if (!runtimeServices) {
1675
+ return {
1676
+ plugin,
1677
+ success: false,
1678
+ error: "No runtime services available",
1679
+ registered,
1680
+ };
1681
+ }
1682
+
1683
+ const {
1684
+ workerManager,
1685
+ eventBus,
1686
+ jobScheduler,
1687
+ jobStore,
1688
+ toolDispatcher,
1689
+ lifecycleManager,
1690
+ buildHostHandlers,
1691
+ instanceInfo,
1692
+ } = runtimeServices;
1693
+
1694
+ try {
1695
+ log.info(
1696
+ { pluginId, pluginKey, version: plugin.version },
1697
+ "plugin-loader: activating plugin",
1698
+ );
1699
+
1700
+ // ------------------------------------------------------------------
1701
+ // 1. Resolve worker entrypoint
1702
+ // ------------------------------------------------------------------
1703
+ const workerEntrypoint = resolveWorkerEntrypoint(plugin, localPluginDir);
1704
+
1705
+ // ------------------------------------------------------------------
1706
+ // 2. Build host handlers for this plugin
1707
+ // ------------------------------------------------------------------
1708
+ const hostHandlers = buildHostHandlers(pluginId, manifest);
1709
+
1710
+ // ------------------------------------------------------------------
1711
+ // 3. Retrieve plugin config (if any)
1712
+ // ------------------------------------------------------------------
1713
+ let config: Record<string, unknown> = {};
1714
+ try {
1715
+ const configRow = await registry.getConfig(pluginId);
1716
+ if (configRow && typeof configRow === "object" && "configJson" in configRow) {
1717
+ config = (configRow as { configJson: Record<string, unknown> }).configJson ?? {};
1718
+ }
1719
+ } catch {
1720
+ // Config may not exist yet — use empty object
1721
+ log.debug({ pluginId }, "plugin-loader: no config found, using empty config");
1722
+ }
1723
+
1724
+ // ------------------------------------------------------------------
1725
+ // 4. Spawn worker process
1726
+ // ------------------------------------------------------------------
1727
+ const workerOptions: WorkerStartOptions = {
1728
+ entrypointPath: workerEntrypoint,
1729
+ manifest,
1730
+ config,
1731
+ instanceInfo,
1732
+ apiVersion: manifest.apiVersion,
1733
+ hostHandlers,
1734
+ autoRestart: true,
1735
+ };
1736
+
1737
+ // Repo-local plugin installs can resolve workspace TS sources at runtime
1738
+ // (for example @corporateai/shared exports). Run those workers through
1739
+ // the tsx loader so first-party example plugins work in development.
1740
+ if (plugin.packagePath && existsSync(DEV_TSX_LOADER_PATH)) {
1741
+ workerOptions.execArgv = ["--import", DEV_TSX_LOADER_PATH];
1742
+ }
1743
+
1744
+ await workerManager.startWorker(pluginId, workerOptions);
1745
+ registered.worker = true;
1746
+
1747
+ log.info(
1748
+ { pluginId, pluginKey },
1749
+ "plugin-loader: worker started",
1750
+ );
1751
+
1752
+ // ------------------------------------------------------------------
1753
+ // 5. Sync job declarations and register with scheduler
1754
+ // ------------------------------------------------------------------
1755
+ const jobDeclarations = manifest.jobs ?? [];
1756
+ if (jobDeclarations.length > 0) {
1757
+ await jobStore.syncJobDeclarations(pluginId, jobDeclarations);
1758
+ await jobScheduler.registerPlugin(pluginId);
1759
+ registered.jobs = jobDeclarations.length;
1760
+
1761
+ log.info(
1762
+ { pluginId, pluginKey, jobs: jobDeclarations.length },
1763
+ "plugin-loader: job declarations synced and plugin registered with scheduler",
1764
+ );
1765
+ }
1766
+
1767
+ // ------------------------------------------------------------------
1768
+ // 6. Register event subscriptions
1769
+ //
1770
+ // Note: Event subscriptions are declared at runtime by the plugin
1771
+ // worker via the SDK's ctx.events.on() calls. The event bus manages
1772
+ // per-plugin subscription scoping. Here we ensure the event bus has
1773
+ // a scoped handle ready for this plugin — the actual subscriptions
1774
+ // are registered by the host handler layer when the worker calls
1775
+ // events.subscribe via RPC.
1776
+ //
1777
+ // The bus.forPlugin() call creates the scoped handle if needed;
1778
+ // any previous subscriptions for this plugin are preserved if the
1779
+ // worker is restarting.
1780
+ // ------------------------------------------------------------------
1781
+ const _scopedBus = eventBus.forPlugin(pluginKey);
1782
+ registered.eventSubscriptions = eventBus.subscriptionCount(pluginKey);
1783
+
1784
+ log.debug(
1785
+ { pluginId, pluginKey },
1786
+ "plugin-loader: event bus scoped handle ready",
1787
+ );
1788
+
1789
+ // ------------------------------------------------------------------
1790
+ // 7. Register webhook endpoints (manifest-declared)
1791
+ //
1792
+ // Webhooks are statically declared in the manifest. The actual
1793
+ // endpoint routing is handled by the plugin routes module which
1794
+ // checks the manifest for declared webhooks. No explicit
1795
+ // registration step is needed here — the manifest is persisted
1796
+ // in the DB and the route handler reads it at request time.
1797
+ //
1798
+ // We track the count for the result reporting.
1799
+ // ------------------------------------------------------------------
1800
+ const webhookDeclarations = manifest.webhooks ?? [];
1801
+ registered.webhooks = webhookDeclarations.length;
1802
+
1803
+ if (webhookDeclarations.length > 0) {
1804
+ log.info(
1805
+ { pluginId, pluginKey, webhooks: webhookDeclarations.length },
1806
+ "plugin-loader: webhook endpoints declared in manifest",
1807
+ );
1808
+ }
1809
+
1810
+ // ------------------------------------------------------------------
1811
+ // 8. Register agent tools
1812
+ // ------------------------------------------------------------------
1813
+ const toolDeclarations = manifest.tools ?? [];
1814
+ if (toolDeclarations.length > 0) {
1815
+ toolDispatcher.registerPluginTools(pluginKey, manifest);
1816
+ registered.tools = toolDeclarations.length;
1817
+
1818
+ log.info(
1819
+ { pluginId, pluginKey, tools: toolDeclarations.length },
1820
+ "plugin-loader: agent tools registered",
1821
+ );
1822
+ }
1823
+
1824
+ // ------------------------------------------------------------------
1825
+ // Done — plugin fully activated
1826
+ // ------------------------------------------------------------------
1827
+ log.info(
1828
+ {
1829
+ pluginId,
1830
+ pluginKey,
1831
+ version: plugin.version,
1832
+ registered,
1833
+ },
1834
+ "plugin-loader: plugin activated successfully",
1835
+ );
1836
+
1837
+ return { plugin, success: true, registered };
1838
+ } catch (err) {
1839
+ const errorMessage = err instanceof Error ? err.message : String(err);
1840
+
1841
+ log.error(
1842
+ { pluginId, pluginKey, err: errorMessage },
1843
+ "plugin-loader: failed to activate plugin",
1844
+ );
1845
+
1846
+ // Mark the plugin as errored in the database so it is not retried
1847
+ // automatically on next startup without operator intervention.
1848
+ try {
1849
+ await lifecycleManager.markError(pluginId, `Activation failed: ${errorMessage}`);
1850
+ } catch (markErr) {
1851
+ log.error(
1852
+ {
1853
+ pluginId,
1854
+ err: markErr instanceof Error ? markErr.message : String(markErr),
1855
+ },
1856
+ "plugin-loader: failed to mark plugin as error after activation failure",
1857
+ );
1858
+ }
1859
+
1860
+ return {
1861
+ plugin,
1862
+ success: false,
1863
+ error: errorMessage,
1864
+ registered,
1865
+ };
1866
+ }
1867
+ }
1868
+ }
1869
+
1870
+ // ---------------------------------------------------------------------------
1871
+ // Worker entrypoint resolution
1872
+ // ---------------------------------------------------------------------------
1873
+
1874
+ /**
1875
+ * Resolve the absolute path to a plugin's worker entrypoint from its manifest
1876
+ * and known install locations.
1877
+ *
1878
+ * The manifest `entrypoints.worker` field is relative to the package root.
1879
+ * We check the local plugin directory (where the package was installed) and
1880
+ * also the package directory if it was a local-path install.
1881
+ *
1882
+ * @see PLUGIN_SPEC.md §10 — Package Contract
1883
+ */
1884
+ function resolveWorkerEntrypoint(
1885
+ plugin: PluginRecord & { packagePath?: string | null },
1886
+ localPluginDir: string,
1887
+ ): string {
1888
+ const manifest = plugin.manifestJson;
1889
+ const workerRelPath = manifest.entrypoints.worker;
1890
+
1891
+ // For local-path installs we persist the resolved package path; use it first
1892
+ if (plugin.packagePath && existsSync(plugin.packagePath)) {
1893
+ const entrypoint = path.resolve(plugin.packagePath, workerRelPath);
1894
+ if (entrypoint.startsWith(path.resolve(plugin.packagePath)) && existsSync(entrypoint)) {
1895
+ return entrypoint;
1896
+ }
1897
+ }
1898
+
1899
+ // Try the local plugin directory (standard npm install location)
1900
+ const packageName = plugin.packageName;
1901
+ let packageDir: string;
1902
+
1903
+ if (packageName.startsWith("@")) {
1904
+ // Scoped package: @scope/plugin-name → localPluginDir/node_modules/@scope/plugin-name
1905
+ const [scope, name] = packageName.split("/");
1906
+ packageDir = path.join(localPluginDir, "node_modules", scope!, name!);
1907
+ } else {
1908
+ packageDir = path.join(localPluginDir, "node_modules", packageName);
1909
+ }
1910
+
1911
+ // Also check if the package exists directly under localPluginDir
1912
+ // (for direct local-path installs or symlinked packages)
1913
+ const directDir = path.join(localPluginDir, packageName);
1914
+
1915
+ // Try in order: node_modules path, direct path
1916
+ for (const dir of [packageDir, directDir]) {
1917
+ const entrypoint = path.resolve(dir, workerRelPath);
1918
+
1919
+ // Security: ensure entrypoint is actually inside the directory (prevent path traversal)
1920
+ if (!entrypoint.startsWith(path.resolve(dir))) {
1921
+ continue;
1922
+ }
1923
+
1924
+ if (existsSync(entrypoint)) {
1925
+ return entrypoint;
1926
+ }
1927
+ }
1928
+
1929
+ // Fallback: try the worker path as-is (absolute or relative to cwd)
1930
+ // ONLY if it's already an absolute path and we trust the manifest (which we've already validated)
1931
+ if (path.isAbsolute(workerRelPath) && existsSync(workerRelPath)) {
1932
+ return workerRelPath;
1933
+ }
1934
+
1935
+ throw new Error(
1936
+ `Worker entrypoint not found for plugin "${plugin.pluginKey}". ` +
1937
+ `Checked: ${path.resolve(packageDir, workerRelPath)}, ` +
1938
+ `${path.resolve(directDir, workerRelPath)}`,
1939
+ );
1940
+ }
1941
+
1942
+ function resolveManagedInstallPackageDir(localPluginDir: string, packageName: string): string {
1943
+ if (packageName.startsWith("@")) {
1944
+ return path.join(localPluginDir, "node_modules", ...packageName.split("/"));
1945
+ }
1946
+ return path.join(localPluginDir, "node_modules", packageName);
1947
+ }
1948
+
1949
+ function isPathInsideDir(candidatePath: string, parentDir: string): boolean {
1950
+ const resolvedCandidate = path.resolve(candidatePath);
1951
+ const resolvedParent = path.resolve(parentDir);
1952
+ const relative = path.relative(resolvedParent, resolvedCandidate);
1953
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
1954
+ }
1955
+