@openparachute/agent 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (501) hide show
  1. package/.claude/scheduled_tasks.lock +1 -0
  2. package/.claude/settings.json +5 -0
  3. package/.claude/skills/add-atomic-chat-tool/SKILL.md +243 -0
  4. package/.claude/skills/add-atomic-chat-tool/atomic-chat-mcp-stdio.ts +229 -0
  5. package/.claude/skills/add-codex/SKILL.md +161 -0
  6. package/.claude/skills/add-dashboard/SKILL.md +138 -0
  7. package/.claude/skills/add-dashboard/resources/dashboard-pusher.ts +495 -0
  8. package/.claude/skills/add-emacs/SKILL.md +296 -0
  9. package/.claude/skills/add-gcal-tool/SKILL.md +210 -0
  10. package/.claude/skills/add-gchat/REMOVE.md +6 -0
  11. package/.claude/skills/add-gchat/SKILL.md +92 -0
  12. package/.claude/skills/add-gchat/VERIFY.md +3 -0
  13. package/.claude/skills/add-github/REMOVE.md +6 -0
  14. package/.claude/skills/add-github/SKILL.md +148 -0
  15. package/.claude/skills/add-github/VERIFY.md +3 -0
  16. package/.claude/skills/add-gmail-tool/SKILL.md +229 -0
  17. package/.claude/skills/add-imessage/REMOVE.md +6 -0
  18. package/.claude/skills/add-imessage/SKILL.md +113 -0
  19. package/.claude/skills/add-imessage/VERIFY.md +3 -0
  20. package/.claude/skills/add-karpathy-llm-wiki/SKILL.md +110 -0
  21. package/.claude/skills/add-karpathy-llm-wiki/llm-wiki.md +75 -0
  22. package/.claude/skills/add-linear/REMOVE.md +6 -0
  23. package/.claude/skills/add-linear/SKILL.md +168 -0
  24. package/.claude/skills/add-linear/VERIFY.md +3 -0
  25. package/.claude/skills/add-macos-statusbar/SKILL.md +133 -0
  26. package/.claude/skills/add-macos-statusbar/add/src/statusbar.swift +147 -0
  27. package/.claude/skills/add-matrix/REMOVE.md +6 -0
  28. package/.claude/skills/add-matrix/SKILL.md +148 -0
  29. package/.claude/skills/add-matrix/VERIFY.md +3 -0
  30. package/.claude/skills/add-ollama-provider/SKILL.md +179 -0
  31. package/.claude/skills/add-ollama-tool/SKILL.md +193 -0
  32. package/.claude/skills/add-opencode/SKILL.md +229 -0
  33. package/.claude/skills/add-parallel/SKILL.md +290 -0
  34. package/.claude/skills/add-resend/REMOVE.md +6 -0
  35. package/.claude/skills/add-resend/SKILL.md +93 -0
  36. package/.claude/skills/add-resend/VERIFY.md +3 -0
  37. package/.claude/skills/add-signal/REMOVE.md +13 -0
  38. package/.claude/skills/add-signal/SKILL.md +318 -0
  39. package/.claude/skills/add-signal/VERIFY.md +5 -0
  40. package/.claude/skills/add-slack/REMOVE.md +6 -0
  41. package/.claude/skills/add-slack/SKILL.md +112 -0
  42. package/.claude/skills/add-slack/VERIFY.md +3 -0
  43. package/.claude/skills/add-teams/REMOVE.md +6 -0
  44. package/.claude/skills/add-teams/SKILL.md +207 -0
  45. package/.claude/skills/add-teams/VERIFY.md +3 -0
  46. package/.claude/skills/add-vercel/SKILL.md +147 -0
  47. package/.claude/skills/add-vercel/container-skills/vercel-cli/SKILL.md +103 -0
  48. package/.claude/skills/add-webex/REMOVE.md +6 -0
  49. package/.claude/skills/add-webex/SKILL.md +88 -0
  50. package/.claude/skills/add-webex/VERIFY.md +3 -0
  51. package/.claude/skills/add-wechat/REMOVE.md +49 -0
  52. package/.claude/skills/add-wechat/SKILL.md +170 -0
  53. package/.claude/skills/add-wechat/scripts/wire-dm.ts +172 -0
  54. package/.claude/skills/add-whatsapp/SKILL.md +264 -0
  55. package/.claude/skills/add-whatsapp-cloud/REMOVE.md +6 -0
  56. package/.claude/skills/add-whatsapp-cloud/SKILL.md +95 -0
  57. package/.claude/skills/add-whatsapp-cloud/VERIFY.md +3 -0
  58. package/.claude/skills/claw/SKILL.md +131 -0
  59. package/.claude/skills/claw/scripts/claw +374 -0
  60. package/.claude/skills/convert-to-apple-container/SKILL.md +212 -0
  61. package/.claude/skills/customize/SKILL.md +110 -0
  62. package/.claude/skills/debug/SKILL.md +349 -0
  63. package/.claude/skills/get-qodo-rules/SKILL.md +122 -0
  64. package/.claude/skills/get-qodo-rules/references/output-format.md +41 -0
  65. package/.claude/skills/get-qodo-rules/references/pagination.md +33 -0
  66. package/.claude/skills/get-qodo-rules/references/repository-scope.md +26 -0
  67. package/.claude/skills/init-first-agent/SKILL.md +120 -0
  68. package/.claude/skills/init-onecli/SKILL.md +270 -0
  69. package/.claude/skills/manage-channels/SKILL.md +87 -0
  70. package/.claude/skills/manage-mounts/SKILL.md +47 -0
  71. package/.claude/skills/migrate-from-openclaw/MIGRATE_CRONS.md +100 -0
  72. package/.claude/skills/migrate-from-openclaw/SKILL.md +447 -0
  73. package/.claude/skills/migrate-from-openclaw/scripts/discover-openclaw.ts +734 -0
  74. package/.claude/skills/migrate-from-openclaw/scripts/extract-channel-credentials.ts +476 -0
  75. package/.claude/skills/migrate-nanoclaw/SKILL.md +484 -0
  76. package/.claude/skills/migrate-nanoclaw/diagnostics.md +51 -0
  77. package/.claude/skills/qodo-pr-resolver/SKILL.md +326 -0
  78. package/.claude/skills/qodo-pr-resolver/resources/providers.md +329 -0
  79. package/.claude/skills/update-nanoclaw/SKILL.md +243 -0
  80. package/.claude/skills/update-nanoclaw/diagnostics.md +48 -0
  81. package/.claude/skills/update-skills/SKILL.md +130 -0
  82. package/.claude/skills/use-native-credential-proxy/SKILL.md +167 -0
  83. package/.claude/skills/x-integration/SKILL.md +417 -0
  84. package/.claude/skills/x-integration/agent.ts +243 -0
  85. package/.claude/skills/x-integration/host.ts +155 -0
  86. package/.claude/skills/x-integration/lib/browser.ts +148 -0
  87. package/.claude/skills/x-integration/lib/config.ts +62 -0
  88. package/.claude/skills/x-integration/scripts/like.ts +56 -0
  89. package/.claude/skills/x-integration/scripts/post.ts +66 -0
  90. package/.claude/skills/x-integration/scripts/quote.ts +80 -0
  91. package/.claude/skills/x-integration/scripts/reply.ts +74 -0
  92. package/.claude/skills/x-integration/scripts/retweet.ts +62 -0
  93. package/.claude/skills/x-integration/scripts/setup.ts +87 -0
  94. package/.github/CODEOWNERS +10 -0
  95. package/.github/PULL_REQUEST_TEMPLATE.md +18 -0
  96. package/.github/workflows/bump-version.yml +35 -0
  97. package/.github/workflows/ci.yml +39 -0
  98. package/.github/workflows/label-pr.yml +40 -0
  99. package/.github/workflows/update-tokens.yml +43 -0
  100. package/.husky/pre-commit +1 -0
  101. package/.mcp.json +3 -0
  102. package/.nvmrc +1 -0
  103. package/.parachute/module.json +14 -0
  104. package/.prettierrc +4 -0
  105. package/CHANGELOG.md +215 -0
  106. package/CLAUDE.md +307 -0
  107. package/CODE_OF_CONDUCT.md +128 -0
  108. package/CONTRIBUTING.md +159 -0
  109. package/CONTRIBUTORS.md +26 -0
  110. package/LICENSE +21 -0
  111. package/README.md +190 -0
  112. package/README_ja.md +194 -0
  113. package/README_zh.md +194 -0
  114. package/assets/nanoclaw-favicon.png +0 -0
  115. package/assets/nanoclaw-icon.png +0 -0
  116. package/assets/nanoclaw-logo-dark.png +0 -0
  117. package/assets/nanoclaw-logo.png +0 -0
  118. package/assets/nanoclaw-profile.jpeg +0 -0
  119. package/assets/nanoclaw-sales.png +0 -0
  120. package/assets/social-preview.jpg +0 -0
  121. package/config-examples/mount-allowlist.json +25 -0
  122. package/container/.dockerignore +2 -0
  123. package/container/CLAUDE.md +21 -0
  124. package/container/Dockerfile +121 -0
  125. package/container/agent-runner/bun.lock +243 -0
  126. package/container/agent-runner/package.json +22 -0
  127. package/container/agent-runner/scripts/sdk-signal-probe.ts +169 -0
  128. package/container/agent-runner/src/config.ts +55 -0
  129. package/container/agent-runner/src/db/connection.ts +267 -0
  130. package/container/agent-runner/src/db/index.ts +20 -0
  131. package/container/agent-runner/src/db/messages-in.ts +138 -0
  132. package/container/agent-runner/src/db/messages-out.ts +143 -0
  133. package/container/agent-runner/src/db/session-routing.ts +30 -0
  134. package/container/agent-runner/src/db/session-state.test.ts +100 -0
  135. package/container/agent-runner/src/db/session-state.ts +79 -0
  136. package/container/agent-runner/src/destinations.ts +135 -0
  137. package/container/agent-runner/src/formatter.test.ts +167 -0
  138. package/container/agent-runner/src/formatter.ts +260 -0
  139. package/container/agent-runner/src/index.ts +110 -0
  140. package/container/agent-runner/src/integration.test.ts +121 -0
  141. package/container/agent-runner/src/mcp-tools/agents.instructions.md +26 -0
  142. package/container/agent-runner/src/mcp-tools/agents.ts +66 -0
  143. package/container/agent-runner/src/mcp-tools/core.instructions.md +27 -0
  144. package/container/agent-runner/src/mcp-tools/core.ts +262 -0
  145. package/container/agent-runner/src/mcp-tools/index.ts +22 -0
  146. package/container/agent-runner/src/mcp-tools/interactive.instructions.md +22 -0
  147. package/container/agent-runner/src/mcp-tools/interactive.ts +169 -0
  148. package/container/agent-runner/src/mcp-tools/scheduling.instructions.md +40 -0
  149. package/container/agent-runner/src/mcp-tools/scheduling.ts +299 -0
  150. package/container/agent-runner/src/mcp-tools/self-mod.instructions.md +25 -0
  151. package/container/agent-runner/src/mcp-tools/self-mod.ts +120 -0
  152. package/container/agent-runner/src/mcp-tools/server.ts +54 -0
  153. package/container/agent-runner/src/mcp-tools/types.ts +6 -0
  154. package/container/agent-runner/src/poll-loop.test.ts +248 -0
  155. package/container/agent-runner/src/poll-loop.ts +437 -0
  156. package/container/agent-runner/src/providers/claude.ts +379 -0
  157. package/container/agent-runner/src/providers/factory.test.ts +19 -0
  158. package/container/agent-runner/src/providers/factory.ts +13 -0
  159. package/container/agent-runner/src/providers/index.ts +6 -0
  160. package/container/agent-runner/src/providers/mock.ts +77 -0
  161. package/container/agent-runner/src/providers/provider-registry.ts +33 -0
  162. package/container/agent-runner/src/providers/types.ts +82 -0
  163. package/container/agent-runner/src/scheduling/task-script.ts +121 -0
  164. package/container/agent-runner/src/timezone.test.ts +93 -0
  165. package/container/agent-runner/src/timezone.ts +107 -0
  166. package/container/agent-runner/tsconfig.json +14 -0
  167. package/container/build.sh +48 -0
  168. package/container/entrypoint.sh +16 -0
  169. package/container/skills/agent-browser/SKILL.md +159 -0
  170. package/container/skills/frontend-engineer/SKILL.md +157 -0
  171. package/container/skills/self-customize/SKILL.md +87 -0
  172. package/container/skills/slack-formatting/SKILL.md +94 -0
  173. package/container/skills/vercel-cli/SKILL.md +111 -0
  174. package/container/skills/welcome/SKILL.md +85 -0
  175. package/docs/APPLE-CONTAINER-NETWORKING.md +90 -0
  176. package/docs/BRANCH-FORK-MAINTENANCE.md +81 -0
  177. package/docs/README.md +25 -0
  178. package/docs/SDK_DEEP_DIVE.md +643 -0
  179. package/docs/SECURITY.md +162 -0
  180. package/docs/agent-runner-details.md +749 -0
  181. package/docs/api-details.md +365 -0
  182. package/docs/architecture-diagram.html +422 -0
  183. package/docs/architecture-diagram.md +215 -0
  184. package/docs/architecture.md +751 -0
  185. package/docs/audit/2026-04-30-channel-endpoint-audit.md +36 -0
  186. package/docs/build-and-runtime.md +80 -0
  187. package/docs/cross-mount-stress/README.md +112 -0
  188. package/docs/cross-mount-stress/container-writer-retry.mjs +55 -0
  189. package/docs/cross-mount-stress/container-writer-slow.mjs +42 -0
  190. package/docs/cross-mount-stress/container-writer.mjs +47 -0
  191. package/docs/cross-mount-stress/host-writer-retry.mjs +55 -0
  192. package/docs/cross-mount-stress/host-writer-slow.mjs +43 -0
  193. package/docs/cross-mount-stress/host-writer.mjs +47 -0
  194. package/docs/db-central.md +316 -0
  195. package/docs/db-session.md +183 -0
  196. package/docs/db.md +119 -0
  197. package/docs/design/2026-04-29-vault-management-ui.md +231 -0
  198. package/docs/design/2026-04-30-channel-wiring-rework.md +234 -0
  199. package/docs/design/2026-05-01-channel-wiring-approvals-deep-dive.md +272 -0
  200. package/docs/design/2026-05-02-channel-policy-and-approval-routing.md +250 -0
  201. package/docs/docker-sandboxes.md +359 -0
  202. package/docs/isolation-model.md +88 -0
  203. package/docs/ollama.md +79 -0
  204. package/docs/parachute-integration.md +109 -0
  205. package/docs/post-night-rebirth-reflections.md +151 -0
  206. package/eslint.config.js +32 -0
  207. package/package.json +54 -0
  208. package/pnpm-workspace.yaml +8 -0
  209. package/repo-tokens/README.md +113 -0
  210. package/repo-tokens/action.yml +186 -0
  211. package/repo-tokens/badge.svg +23 -0
  212. package/repo-tokens/examples/green.svg +14 -0
  213. package/repo-tokens/examples/red.svg +14 -0
  214. package/repo-tokens/examples/yellow-green.svg +14 -0
  215. package/repo-tokens/examples/yellow.svg +14 -0
  216. package/scripts/chat.ts +101 -0
  217. package/scripts/cleanup-sessions.sh +150 -0
  218. package/scripts/init-cli-agent.ts +171 -0
  219. package/scripts/init-first-agent.ts +377 -0
  220. package/scripts/parachute.ts +158 -0
  221. package/scripts/run-migrations.ts +105 -0
  222. package/scripts/sanity-live-poll.ts +95 -0
  223. package/scripts/seed-discord.ts +79 -0
  224. package/scripts/test-v2-agent.ts +106 -0
  225. package/scripts/test-v2-channel-e2e.ts +265 -0
  226. package/scripts/test-v2-host.ts +184 -0
  227. package/src/channels/adapter.ts +214 -0
  228. package/src/channels/ask-question.ts +46 -0
  229. package/src/channels/channel-registry.test.ts +421 -0
  230. package/src/channels/channel-registry.ts +313 -0
  231. package/src/channels/chat-sdk-bridge.test.ts +84 -0
  232. package/src/channels/chat-sdk-bridge.ts +652 -0
  233. package/src/channels/cli.ts +276 -0
  234. package/src/channels/discord.ts +90 -0
  235. package/src/channels/index.ts +17 -0
  236. package/src/channels/telegram-markdown-sanitize.test.ts +78 -0
  237. package/src/channels/telegram-markdown-sanitize.ts +55 -0
  238. package/src/channels/telegram-pairing.test.ts +254 -0
  239. package/src/channels/telegram-pairing.ts +339 -0
  240. package/src/channels/telegram.ts +279 -0
  241. package/src/channels/trust-hint.test.ts +48 -0
  242. package/src/channels/trust-hint.ts +75 -0
  243. package/src/claude-md-compose.migrate.test.ts +64 -0
  244. package/src/claude-md-compose.ts +205 -0
  245. package/src/command-gate.ts +63 -0
  246. package/src/config.test.ts +93 -0
  247. package/src/config.ts +108 -0
  248. package/src/container-config.ts +167 -0
  249. package/src/container-runner.test.ts +32 -0
  250. package/src/container-runner.ts +576 -0
  251. package/src/container-runtime.test.ts +169 -0
  252. package/src/container-runtime.ts +92 -0
  253. package/src/db/_bun-sqlite-shim.ts +88 -0
  254. package/src/db/agent-activity.test.ts +155 -0
  255. package/src/db/agent-activity.ts +121 -0
  256. package/src/db/agent-groups.ts +77 -0
  257. package/src/db/connection.migrate.test.ts +143 -0
  258. package/src/db/connection.ts +224 -0
  259. package/src/db/db-v2.test.ts +440 -0
  260. package/src/db/dropped-messages.ts +44 -0
  261. package/src/db/index.ts +40 -0
  262. package/src/db/messaging-groups.ts +252 -0
  263. package/src/db/migrations/001-initial.ts +112 -0
  264. package/src/db/migrations/002-chat-sdk-state.ts +36 -0
  265. package/src/db/migrations/008-dropped-messages.ts +27 -0
  266. package/src/db/migrations/009-drop-pending-credentials.ts +13 -0
  267. package/src/db/migrations/010-engage-modes.ts +103 -0
  268. package/src/db/migrations/011-pending-sender-approvals.ts +40 -0
  269. package/src/db/migrations/012-channel-registration.ts +48 -0
  270. package/src/db/migrations/013-approval-render-metadata.ts +27 -0
  271. package/src/db/migrations/014-secrets.ts +44 -0
  272. package/src/db/migrations/015-secrets-drop-host-pattern.ts +18 -0
  273. package/src/db/migrations/016-secret-assignments.ts +30 -0
  274. package/src/db/migrations/017-agent-activity.ts +40 -0
  275. package/src/db/migrations/018-oauth-app-configs.ts +34 -0
  276. package/src/db/migrations/019-oauth-app-connections.ts +48 -0
  277. package/src/db/migrations/020-agent-app-connections.ts +28 -0
  278. package/src/db/migrations/021-pending-oauth-states.ts +35 -0
  279. package/src/db/migrations/022-app-connections-provider.ts +25 -0
  280. package/src/db/migrations/023-agent-group-secret-mode.test.ts +124 -0
  281. package/src/db/migrations/023-agent-group-secret-mode.ts +65 -0
  282. package/src/db/migrations/024-collapse-approvals.test.ts +249 -0
  283. package/src/db/migrations/024-collapse-approvals.ts +182 -0
  284. package/src/db/migrations/025-secret-mode-check.test.ts +155 -0
  285. package/src/db/migrations/025-secret-mode-check.ts +49 -0
  286. package/src/db/migrations/026-user-dms-bot-id.test.ts +116 -0
  287. package/src/db/migrations/026-user-dms-bot-id.ts +54 -0
  288. package/src/db/migrations/027-provider-credentials.ts +41 -0
  289. package/src/db/migrations/_test-helpers.ts +41 -0
  290. package/src/db/migrations/index.ts +127 -0
  291. package/src/db/migrations/module-agent-to-agent-destinations.ts +84 -0
  292. package/src/db/migrations/module-approvals-pending-approvals.ts +42 -0
  293. package/src/db/migrations/module-approvals-title-options.ts +40 -0
  294. package/src/db/schema.ts +258 -0
  295. package/src/db/session-db.test.ts +93 -0
  296. package/src/db/session-db.ts +325 -0
  297. package/src/db/sessions.ts +241 -0
  298. package/src/delivery.test.ts +148 -0
  299. package/src/delivery.ts +445 -0
  300. package/src/env.ts +74 -0
  301. package/src/group-folder.test.ts +35 -0
  302. package/src/group-folder.ts +44 -0
  303. package/src/group-init.ts +92 -0
  304. package/src/host-core.test.ts +456 -0
  305. package/src/host-sweep.test.ts +146 -0
  306. package/src/host-sweep.ts +287 -0
  307. package/src/index.ts +227 -0
  308. package/src/install-slug.ts +33 -0
  309. package/src/log.test.ts +81 -0
  310. package/src/log.ts +117 -0
  311. package/src/mcp/http.ts +72 -0
  312. package/src/mcp/server.ts +92 -0
  313. package/src/mcp/stdio.ts +51 -0
  314. package/src/mcp/tools/activity.ts +88 -0
  315. package/src/mcp/tools/agent-groups.ts +183 -0
  316. package/src/mcp/tools/approvals.ts +122 -0
  317. package/src/mcp/tools/channels.ts +199 -0
  318. package/src/mcp/tools/index.ts +27 -0
  319. package/src/mcp/tools/oauth.ts +48 -0
  320. package/src/mcp/tools/secrets.ts +169 -0
  321. package/src/mcp/tools/sessions.ts +135 -0
  322. package/src/mcp/types.ts +51 -0
  323. package/src/modules/agent-to-agent/agent-route.test.ts +46 -0
  324. package/src/modules/agent-to-agent/agent-route.ts +223 -0
  325. package/src/modules/agent-to-agent/create-agent.ts +127 -0
  326. package/src/modules/agent-to-agent/db/agent-destinations.ts +135 -0
  327. package/src/modules/agent-to-agent/index.ts +22 -0
  328. package/src/modules/agent-to-agent/write-destinations.ts +59 -0
  329. package/src/modules/approvals/agent.md +45 -0
  330. package/src/modules/approvals/index.ts +21 -0
  331. package/src/modules/approvals/picks.test.ts +291 -0
  332. package/src/modules/approvals/primitive.ts +279 -0
  333. package/src/modules/approvals/project.md +27 -0
  334. package/src/modules/approvals/response-handler.ts +87 -0
  335. package/src/modules/index.ts +24 -0
  336. package/src/modules/interactive/agent.md +21 -0
  337. package/src/modules/interactive/index.ts +69 -0
  338. package/src/modules/interactive/project.md +12 -0
  339. package/src/modules/mount-security/index.ts +448 -0
  340. package/src/modules/mount-security/migrate.test.ts +91 -0
  341. package/src/modules/permissions/access.ts +28 -0
  342. package/src/modules/permissions/channel-approval.test.ts +389 -0
  343. package/src/modules/permissions/channel-approval.ts +188 -0
  344. package/src/modules/permissions/db/agent-group-members.ts +44 -0
  345. package/src/modules/permissions/db/pending-channel-approvals.test.ts +86 -0
  346. package/src/modules/permissions/db/pending-channel-approvals.ts +66 -0
  347. package/src/modules/permissions/db/pending-sender-approvals.ts +60 -0
  348. package/src/modules/permissions/db/user-dms.ts +58 -0
  349. package/src/modules/permissions/db/user-roles.ts +85 -0
  350. package/src/modules/permissions/db/users.ts +38 -0
  351. package/src/modules/permissions/index.ts +421 -0
  352. package/src/modules/permissions/permissions.test.ts +358 -0
  353. package/src/modules/permissions/sender-approval.test.ts +470 -0
  354. package/src/modules/permissions/sender-approval.ts +165 -0
  355. package/src/modules/permissions/user-dm.ts +200 -0
  356. package/src/modules/provider-credentials/db.ts +121 -0
  357. package/src/modules/provider-credentials/index.ts +12 -0
  358. package/src/modules/provider-credentials/spawn.test.ts +206 -0
  359. package/src/modules/provider-credentials/spawn.ts +114 -0
  360. package/src/modules/scheduling/actions.ts +113 -0
  361. package/src/modules/scheduling/db.test.ts +282 -0
  362. package/src/modules/scheduling/db.ts +148 -0
  363. package/src/modules/scheduling/index.ts +34 -0
  364. package/src/modules/scheduling/recurrence.test.ts +98 -0
  365. package/src/modules/scheduling/recurrence.ts +54 -0
  366. package/src/modules/self-mod/agent.md +30 -0
  367. package/src/modules/self-mod/apply.ts +85 -0
  368. package/src/modules/self-mod/index.ts +30 -0
  369. package/src/modules/self-mod/project.md +39 -0
  370. package/src/modules/self-mod/request.ts +91 -0
  371. package/src/modules/typing/index.ts +165 -0
  372. package/src/oauth/agent-app-connections.ts +103 -0
  373. package/src/oauth/app-configs.test.ts +64 -0
  374. package/src/oauth/app-configs.ts +114 -0
  375. package/src/oauth/app-connections.test.ts +109 -0
  376. package/src/oauth/app-connections.ts +178 -0
  377. package/src/oauth/crypto.ts +56 -0
  378. package/src/oauth/flow.ts +104 -0
  379. package/src/oauth/providers/google.test.ts +38 -0
  380. package/src/oauth/providers/google.ts +46 -0
  381. package/src/oauth/providers/index.ts +48 -0
  382. package/src/oauth/state-store.test.ts +54 -0
  383. package/src/oauth/state-store.ts +93 -0
  384. package/src/parachute/README.md +27 -0
  385. package/src/parachute/create-agent.test.ts +83 -0
  386. package/src/parachute/create-agent.ts +122 -0
  387. package/src/parachute/group-status.test.ts +165 -0
  388. package/src/parachute/group-status.ts +136 -0
  389. package/src/parachute/types.ts +41 -0
  390. package/src/parachute/vault-mcp.test.ts +251 -0
  391. package/src/parachute/vault-mcp.ts +232 -0
  392. package/src/platform-id.test.ts +104 -0
  393. package/src/platform-id.ts +109 -0
  394. package/src/providers/index.ts +6 -0
  395. package/src/providers/provider-container-registry.ts +58 -0
  396. package/src/response-registry.ts +45 -0
  397. package/src/router.ts +530 -0
  398. package/src/secrets/crypto.test.ts +45 -0
  399. package/src/secrets/crypto.ts +55 -0
  400. package/src/secrets/index.ts +355 -0
  401. package/src/secrets/master-key.ts +70 -0
  402. package/src/secrets/secrets.test.ts +354 -0
  403. package/src/session-manager.migrate.test.ts +59 -0
  404. package/src/session-manager.ts +433 -0
  405. package/src/startup-bootstrap.test.ts +226 -0
  406. package/src/startup-bootstrap.ts +207 -0
  407. package/src/state-sqlite.ts +182 -0
  408. package/src/timezone.test.ts +64 -0
  409. package/src/timezone.ts +37 -0
  410. package/src/types.ts +230 -0
  411. package/src/web/auth.test.ts +335 -0
  412. package/src/web/auth.ts +214 -0
  413. package/src/web/discord-validate.test.ts +77 -0
  414. package/src/web/discord-validate.ts +88 -0
  415. package/src/web/hub-discovery.test.ts +98 -0
  416. package/src/web/hub-discovery.ts +69 -0
  417. package/src/web/routes/activity.ts +106 -0
  418. package/src/web/routes/agent-provider.test.ts +282 -0
  419. package/src/web/routes/agent-provider.ts +309 -0
  420. package/src/web/routes/approvals.ts +185 -0
  421. package/src/web/routes/apps.ts +434 -0
  422. package/src/web/routes/channels-mg-detail.test.ts +324 -0
  423. package/src/web/routes/channels-mga-detail.test.ts +425 -0
  424. package/src/web/routes/channels.ts +489 -0
  425. package/src/web/routes/oauth-providers.ts +42 -0
  426. package/src/web/routes/secrets.test.ts +175 -0
  427. package/src/web/routes/secrets.ts +282 -0
  428. package/src/web/routes/sessions.ts +123 -0
  429. package/src/web/routes/settings.test.ts +106 -0
  430. package/src/web/routes/settings.ts +247 -0
  431. package/src/web/routes/setup-status.ts +205 -0
  432. package/src/web/routes/vaults.test.ts +389 -0
  433. package/src/web/routes/vaults.ts +225 -0
  434. package/src/web/server-version.test.ts +16 -0
  435. package/src/web/server.ts +1003 -0
  436. package/src/web/services-manifest.test.ts +120 -0
  437. package/src/web/services-manifest.ts +61 -0
  438. package/src/web/static-serve.test.ts +255 -0
  439. package/src/web/static-serve.ts +104 -0
  440. package/src/web/telegram-validate.test.ts +116 -0
  441. package/src/web/telegram-validate.ts +107 -0
  442. package/src/web/vault-proxy.test.ts +214 -0
  443. package/src/web/vault-proxy.ts +120 -0
  444. package/src/web/wire-channel.ts +181 -0
  445. package/src/webhook-server.ts +134 -0
  446. package/tsconfig.json +21 -0
  447. package/vitest.config.ts +18 -0
  448. package/web/README.md +63 -0
  449. package/web/ui/index.html +13 -0
  450. package/web/ui/package.json +35 -0
  451. package/web/ui/pnpm-lock.yaml +2164 -0
  452. package/web/ui/scripts/verify-base.mjs +31 -0
  453. package/web/ui/src/App.tsx +88 -0
  454. package/web/ui/src/components/ActivityFeed.tsx +444 -0
  455. package/web/ui/src/components/AgentGroupPicker.tsx +263 -0
  456. package/web/ui/src/components/AgentProviderCards.tsx +220 -0
  457. package/web/ui/src/components/CredentialForm.tsx +214 -0
  458. package/web/ui/src/components/ScopeGrants.tsx +74 -0
  459. package/web/ui/src/components/StatusDot.tsx +43 -0
  460. package/web/ui/src/components/VaultPicker.tsx +127 -0
  461. package/web/ui/src/components/setup/AdapterInstallStep.tsx +178 -0
  462. package/web/ui/src/components/setup/AgentGroupStep.tsx +43 -0
  463. package/web/ui/src/components/setup/ChannelPickStep.tsx +74 -0
  464. package/web/ui/src/components/setup/DoneStep.tsx +49 -0
  465. package/web/ui/src/components/setup/PrereqStep.tsx +129 -0
  466. package/web/ui/src/components/setup/TestConnectionStep.tsx +108 -0
  467. package/web/ui/src/components/setup/TestMessageStep.tsx +104 -0
  468. package/web/ui/src/components/setup/WireChannelStep.tsx +166 -0
  469. package/web/ui/src/components/setup/types.ts +105 -0
  470. package/web/ui/src/lib/api.test.ts +410 -0
  471. package/web/ui/src/lib/api.ts +1210 -0
  472. package/web/ui/src/lib/auth.test.ts +139 -0
  473. package/web/ui/src/lib/auth.ts +348 -0
  474. package/web/ui/src/lib/channel-adapters.ts +136 -0
  475. package/web/ui/src/main.tsx +19 -0
  476. package/web/ui/src/routes/ApprovalsList.tsx +294 -0
  477. package/web/ui/src/routes/Apps.tsx +613 -0
  478. package/web/ui/src/routes/ChannelWireDetail.test.tsx +233 -0
  479. package/web/ui/src/routes/ChannelWireDetail.tsx +403 -0
  480. package/web/ui/src/routes/ChannelsList.tsx +158 -0
  481. package/web/ui/src/routes/GroupDetail.tsx +755 -0
  482. package/web/ui/src/routes/GroupList.tsx +187 -0
  483. package/web/ui/src/routes/MessagingGroupDetail.test.tsx +233 -0
  484. package/web/ui/src/routes/MessagingGroupDetail.tsx +306 -0
  485. package/web/ui/src/routes/NewGroupWizard.tsx +390 -0
  486. package/web/ui/src/routes/OAuthCallback.tsx +56 -0
  487. package/web/ui/src/routes/SecretsList.tsx +921 -0
  488. package/web/ui/src/routes/SessionsList.tsx +220 -0
  489. package/web/ui/src/routes/SettingsAgentProvider.tsx +109 -0
  490. package/web/ui/src/routes/SettingsApprovals.tsx +234 -0
  491. package/web/ui/src/routes/SetupWizard.tsx +219 -0
  492. package/web/ui/src/routes/VaultDetail.test.tsx +361 -0
  493. package/web/ui/src/routes/VaultDetail.tsx +960 -0
  494. package/web/ui/src/routes/VaultsList.tsx +295 -0
  495. package/web/ui/src/routes/WireChannelPage.tsx +413 -0
  496. package/web/ui/src/styles.css +608 -0
  497. package/web/ui/src/test/setup.ts +23 -0
  498. package/web/ui/src/vite-env.d.ts +10 -0
  499. package/web/ui/tsconfig.json +20 -0
  500. package/web/ui/vite.config.ts +34 -0
  501. package/web/ui/vitest.config.ts +25 -0
@@ -0,0 +1,433 @@
1
+ /**
2
+ * Session lifecycle: folders, DBs, messages, container status.
3
+ *
4
+ * Two-DB split — inbound.db (host writes) + outbound.db (container writes).
5
+ * Three cross-mount invariants are load-bearing:
6
+ * 1. journal_mode=DELETE — WAL's mmapped -shm doesn't refresh host→guest;
7
+ * the container would silently miss every new message.
8
+ * 2. Host opens-writes-CLOSES per op — close invalidates the container's
9
+ * page cache; a long-lived connection freezes its view at first read.
10
+ * 3. One writer per file — DELETE-mode journal-unlink isn't atomic across
11
+ * the mount; concurrent writers corrupt the DB.
12
+ */
13
+ import type { Database } from './db/connection.js';
14
+ import fs from 'fs';
15
+ import path from 'path';
16
+
17
+ import type { OutboundFile } from './channels/adapter.js';
18
+ import { DATA_DIR } from './config.js';
19
+ import { getMessagingGroup } from './db/messaging-groups.js';
20
+ import {
21
+ createSession,
22
+ findSession,
23
+ findSessionByAgentGroup,
24
+ findSessionForAgent,
25
+ getSession,
26
+ updateSession,
27
+ } from './db/sessions.js';
28
+ import {
29
+ ensureSchema,
30
+ openInboundDb as openInboundDbRaw,
31
+ openOutboundDb as openOutboundDbRaw,
32
+ upsertSessionRouting,
33
+ insertMessage,
34
+ migrateMessagesInTable,
35
+ } from './db/session-db.js';
36
+ import { log } from './log.js';
37
+ import type { Session } from './types.js';
38
+
39
+ /** Root directory for all session data. */
40
+ export function sessionsBaseDir(): string {
41
+ return path.join(DATA_DIR, 'sessions');
42
+ }
43
+
44
+ /** Legacy location, pre-rename. Kept only so `migrateSessionsDir` can find it. */
45
+ export function legacySessionsBaseDir(): string {
46
+ return path.join(DATA_DIR, 'v2-sessions');
47
+ }
48
+
49
+ /**
50
+ * One-shot rename: `data/v2-sessions/` → `data/sessions/`. Idempotent — noop
51
+ * if the legacy directory doesn't exist or the new directory already does.
52
+ *
53
+ * Called from `src/index.ts` at startup, before any session DB is opened.
54
+ * Same-filesystem rename is atomic, so partial-migration recovery is not a
55
+ * concern (unlike the central-DB copy in `migrateCentralDbLocation`).
56
+ *
57
+ * Path overrides exist for tests; production callers pass no args.
58
+ */
59
+ export function migrateSessionsDir(
60
+ legacy: string = legacySessionsBaseDir(),
61
+ current: string = sessionsBaseDir(),
62
+ ): void {
63
+ if (fs.existsSync(current)) return;
64
+ if (!fs.existsSync(legacy)) return;
65
+ fs.renameSync(legacy, current);
66
+ log.info('Sessions directory renamed', { from: legacy, to: current });
67
+ }
68
+
69
+ /** Directory for a specific session: sessions/{agent_group_id}/{session_id}/ */
70
+ export function sessionDir(agentGroupId: string, sessionId: string): string {
71
+ return path.join(sessionsBaseDir(), agentGroupId, sessionId);
72
+ }
73
+
74
+ /** Path to the host-owned inbound DB (messages_in + delivered). */
75
+ export function inboundDbPath(agentGroupId: string, sessionId: string): string {
76
+ return path.join(sessionDir(agentGroupId, sessionId), 'inbound.db');
77
+ }
78
+
79
+ /** Path to the container-owned outbound DB (messages_out + processing_ack). */
80
+ export function outboundDbPath(agentGroupId: string, sessionId: string): string {
81
+ return path.join(sessionDir(agentGroupId, sessionId), 'outbound.db');
82
+ }
83
+
84
+ /** Path to the container heartbeat file (touched instead of DB writes). */
85
+ export function heartbeatPath(agentGroupId: string, sessionId: string): string {
86
+ return path.join(sessionDir(agentGroupId, sessionId), '.heartbeat');
87
+ }
88
+
89
+ /**
90
+ * @deprecated Use inboundDbPath / outboundDbPath instead.
91
+ * Kept temporarily for test compatibility during migration.
92
+ */
93
+ export function sessionDbPath(agentGroupId: string, sessionId: string): string {
94
+ return inboundDbPath(agentGroupId, sessionId);
95
+ }
96
+
97
+ function generateId(): string {
98
+ return `sess-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
99
+ }
100
+
101
+ /**
102
+ * Find or create a session for a messaging group + thread.
103
+ *
104
+ * Session modes:
105
+ * - 'shared': one session per messaging group (ignores threadId)
106
+ * - 'per-thread': one session per (messaging group, thread)
107
+ * - 'agent-shared': one session per agent group — all messaging groups
108
+ * wired with this mode share a single session (e.g. GitHub + Slack)
109
+ */
110
+ export function resolveSession(
111
+ agentGroupId: string,
112
+ messagingGroupId: string | null,
113
+ threadId: string | null,
114
+ sessionMode: 'shared' | 'per-thread' | 'agent-shared',
115
+ ): { session: Session; created: boolean } {
116
+ // agent-shared: single session per agent group, regardless of messaging group
117
+ if (sessionMode === 'agent-shared') {
118
+ const existing = findSessionByAgentGroup(agentGroupId);
119
+ if (existing) {
120
+ return { session: existing, created: false };
121
+ }
122
+ } else if (messagingGroupId) {
123
+ const lookupThreadId = sessionMode === 'shared' ? null : threadId;
124
+ // Scope lookup by agent_group_id so fan-out to multiple agents in the
125
+ // same chat doesn't accidentally deliver to the wrong agent's session.
126
+ const existing = findSessionForAgent(agentGroupId, messagingGroupId, lookupThreadId);
127
+ if (existing) {
128
+ return { session: existing, created: false };
129
+ }
130
+ }
131
+
132
+ const id = generateId();
133
+ const lookupThreadId = sessionMode === 'per-thread' ? threadId : null;
134
+ const session: Session = {
135
+ id,
136
+ agent_group_id: agentGroupId,
137
+ messaging_group_id: messagingGroupId,
138
+ thread_id: lookupThreadId,
139
+ agent_provider: null,
140
+ status: 'active',
141
+ container_status: 'stopped',
142
+ last_active: null,
143
+ created_at: new Date().toISOString(),
144
+ };
145
+
146
+ createSession(session);
147
+ initSessionFolder(agentGroupId, id);
148
+ log.info('Session created', { id, agentGroupId, messagingGroupId, threadId: lookupThreadId, sessionMode });
149
+
150
+ return { session, created: true };
151
+ }
152
+
153
+ /** Create the session folder and initialize both DBs. */
154
+ export function initSessionFolder(agentGroupId: string, sessionId: string): void {
155
+ const dir = sessionDir(agentGroupId, sessionId);
156
+ fs.mkdirSync(dir, { recursive: true });
157
+ fs.mkdirSync(path.join(dir, 'outbox'), { recursive: true });
158
+
159
+ ensureSchema(inboundDbPath(agentGroupId, sessionId), 'inbound');
160
+ ensureSchema(outboundDbPath(agentGroupId, sessionId), 'outbound');
161
+ }
162
+
163
+ /**
164
+ * Write the default reply routing for a session into its inbound.db.
165
+ *
166
+ * The container reads this as the default (channel_type, platform_id, thread_id)
167
+ * for outbound messages when the agent doesn't specify an explicit destination.
168
+ * Derived from session.messaging_group_id → messaging_groups row + session.thread_id.
169
+ *
170
+ * Called on every container wake alongside the agent-to-agent module's
171
+ * writeDestinations() (when installed) so the latest routing is always in
172
+ * place, including after admin rewiring.
173
+ */
174
+ export function writeSessionRouting(agentGroupId: string, sessionId: string): void {
175
+ const dbPath = inboundDbPath(agentGroupId, sessionId);
176
+ if (!fs.existsSync(dbPath)) return;
177
+
178
+ const session = getSession(sessionId);
179
+ if (!session) return;
180
+
181
+ let channelType: string | null = null;
182
+ let platformId: string | null = null;
183
+ if (session.messaging_group_id) {
184
+ const mg = getMessagingGroup(session.messaging_group_id);
185
+ if (mg) {
186
+ channelType = mg.channel_type;
187
+ platformId = mg.platform_id;
188
+ }
189
+ }
190
+
191
+ const db = openInboundDb(agentGroupId, sessionId);
192
+ try {
193
+ upsertSessionRouting(db, {
194
+ channel_type: channelType,
195
+ platform_id: platformId,
196
+ thread_id: session.thread_id,
197
+ });
198
+ } finally {
199
+ db.close();
200
+ }
201
+ log.debug('Session routing written', { sessionId, channelType, platformId, threadId: session.thread_id });
202
+ }
203
+
204
+ /**
205
+ * Write a message to a session's inbound DB (messages_in). Host-only.
206
+ *
207
+ * ⚠ Opens and closes the DB on every call. Do not refactor to reuse a
208
+ * long-lived connection — see the "Cross-mount visibility invariants" note
209
+ * at the top of this file.
210
+ */
211
+ export function writeSessionMessage(
212
+ agentGroupId: string,
213
+ sessionId: string,
214
+ message: {
215
+ id: string;
216
+ kind: string;
217
+ timestamp: string;
218
+ platformId?: string | null;
219
+ channelType?: string | null;
220
+ threadId?: string | null;
221
+ content: string;
222
+ processAfter?: string | null;
223
+ recurrence?: string | null;
224
+ /**
225
+ * 1 = this message should wake the agent (the default); 0 = accumulate
226
+ * as context only, don't wake. Host's countDueMessages gates on this
227
+ * column; the container still reads all prior messages as context when
228
+ * a trigger-1 message does arrive.
229
+ */
230
+ trigger?: 0 | 1;
231
+ },
232
+ ): void {
233
+ // Extract base64 attachment data, save to inbox, replace with file paths
234
+ const content = extractAttachmentFiles(agentGroupId, sessionId, message.id, message.content);
235
+
236
+ const db = openInboundDb(agentGroupId, sessionId);
237
+ let inserted: boolean;
238
+ try {
239
+ ({ inserted } = insertMessage(db, {
240
+ id: message.id,
241
+ kind: message.kind,
242
+ timestamp: message.timestamp,
243
+ platformId: message.platformId ?? null,
244
+ channelType: message.channelType ?? null,
245
+ threadId: message.threadId ?? null,
246
+ content,
247
+ processAfter: message.processAfter ?? null,
248
+ recurrence: message.recurrence ?? null,
249
+ trigger: message.trigger ?? 1,
250
+ }));
251
+ } finally {
252
+ db.close();
253
+ }
254
+
255
+ if (!inserted) {
256
+ log.debug('messages_in id already present — duplicate dispatch, skipping', {
257
+ agentGroupId,
258
+ sessionId,
259
+ messageId: message.id,
260
+ });
261
+ return;
262
+ }
263
+
264
+ updateSession(sessionId, { last_active: new Date().toISOString() });
265
+ }
266
+
267
+ /**
268
+ * If message content has attachments with base64 `data`, save them to
269
+ * the session's inbox directory and replace with `localPath`.
270
+ */
271
+ function extractAttachmentFiles(
272
+ agentGroupId: string,
273
+ sessionId: string,
274
+ messageId: string,
275
+ contentStr: string,
276
+ ): string {
277
+ let parsed: Record<string, unknown>;
278
+ try {
279
+ parsed = JSON.parse(contentStr);
280
+ } catch {
281
+ return contentStr;
282
+ }
283
+
284
+ const attachments = parsed.attachments as Array<Record<string, unknown>> | undefined;
285
+ if (!Array.isArray(attachments)) return contentStr;
286
+
287
+ let changed = false;
288
+ for (const att of attachments) {
289
+ if (typeof att.data === 'string') {
290
+ const inboxDir = path.join(sessionDir(agentGroupId, sessionId), 'inbox', messageId);
291
+ fs.mkdirSync(inboxDir, { recursive: true });
292
+ const filename = (att.name as string) || `attachment-${Date.now()}`;
293
+ const filePath = path.join(inboxDir, filename);
294
+ fs.writeFileSync(filePath, Buffer.from(att.data as string, 'base64'));
295
+ att.localPath = `inbox/${messageId}/${filename}`;
296
+ delete att.data;
297
+ changed = true;
298
+ log.debug('Saved attachment to inbox', { messageId, filename, size: att.size });
299
+ }
300
+ }
301
+
302
+ return changed ? JSON.stringify(parsed) : contentStr;
303
+ }
304
+
305
+ /** Open the inbound DB for a session (host reads/writes). */
306
+ export function openInboundDb(agentGroupId: string, sessionId: string): Database {
307
+ const db = openInboundDbRaw(inboundDbPath(agentGroupId, sessionId));
308
+ migrateMessagesInTable(db);
309
+ return db;
310
+ }
311
+
312
+ /** Open the outbound DB for a session (host reads only). */
313
+ export function openOutboundDb(agentGroupId: string, sessionId: string): Database {
314
+ return openOutboundDbRaw(outboundDbPath(agentGroupId, sessionId));
315
+ }
316
+
317
+ /**
318
+ * Write a message directly to a session's outbound DB so the host delivery
319
+ * loop picks it up. Used by the command gate to send denial responses
320
+ * without waking a container.
321
+ */
322
+ export function writeOutboundDirect(
323
+ agentGroupId: string,
324
+ sessionId: string,
325
+ message: {
326
+ id: string;
327
+ kind: string;
328
+ platformId: string | null;
329
+ channelType: string | null;
330
+ threadId: string | null;
331
+ content: string;
332
+ },
333
+ ): void {
334
+ const db = openOutboundDb(agentGroupId, sessionId);
335
+ try {
336
+ db.prepare(
337
+ `INSERT OR IGNORE INTO messages_out (id, seq, timestamp, kind, platform_id, channel_type, thread_id, content)
338
+ VALUES (?, (SELECT COALESCE(MAX(seq), 0) + 2 FROM messages_out), datetime('now'), ?, ?, ?, ?, ?)`,
339
+ ).run(message.id, message.kind, message.platformId, message.channelType, message.threadId, message.content);
340
+ } finally {
341
+ db.close();
342
+ }
343
+ }
344
+
345
+ /**
346
+ * @deprecated Use openInboundDb / openOutboundDb instead.
347
+ */
348
+ export function openSessionDb(agentGroupId: string, sessionId: string): Database {
349
+ return openInboundDb(agentGroupId, sessionId);
350
+ }
351
+
352
+ /** Write a system response to a session's inbound.db so the container's findQuestionResponse() picks it up. */
353
+ export function writeSystemResponse(
354
+ agentGroupId: string,
355
+ sessionId: string,
356
+ requestId: string,
357
+ status: string,
358
+ result: Record<string, unknown>,
359
+ ): void {
360
+ writeSessionMessage(agentGroupId, sessionId, {
361
+ id: `sys-resp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
362
+ kind: 'system',
363
+ timestamp: new Date().toISOString(),
364
+ content: JSON.stringify({
365
+ type: 'question_response',
366
+ questionId: requestId,
367
+ status,
368
+ result,
369
+ }),
370
+ });
371
+ }
372
+
373
+ /**
374
+ * Load outbox attachments for a delivered message.
375
+ *
376
+ * Symmetric with `extractAttachmentFiles` on the inbound side: the container
377
+ * writes files into the session's `outbox/<messageId>/` directory alongside
378
+ * its `messages_out` row, and the host reads them back at delivery time.
379
+ *
380
+ * Returns undefined when the outbox dir is missing or no declared file was
381
+ * actually on disk — delivery continues without attachments rather than
382
+ * failing the whole message.
383
+ */
384
+ export function readOutboxFiles(
385
+ agentGroupId: string,
386
+ sessionId: string,
387
+ messageId: string,
388
+ filenames: string[],
389
+ ): OutboundFile[] | undefined {
390
+ const outboxDir = path.join(sessionDir(agentGroupId, sessionId), 'outbox', messageId);
391
+ if (!fs.existsSync(outboxDir)) return undefined;
392
+ const files: OutboundFile[] = [];
393
+ for (const filename of filenames) {
394
+ const filePath = path.join(outboxDir, filename);
395
+ if (fs.existsSync(filePath)) {
396
+ files.push({ filename, data: fs.readFileSync(filePath) });
397
+ } else {
398
+ log.warn('Outbox file not found', { messageId, filename });
399
+ }
400
+ }
401
+ return files.length > 0 ? files : undefined;
402
+ }
403
+
404
+ /**
405
+ * Remove a message's outbox directory after successful delivery. Best-effort:
406
+ * failures log and swallow. A cleanup failure must NOT propagate to the
407
+ * delivery caller — the message is already on the user's screen, and a
408
+ * thrown error would trigger the delivery retry path and deliver twice.
409
+ */
410
+ export function clearOutbox(agentGroupId: string, sessionId: string, messageId: string): void {
411
+ const outboxDir = path.join(sessionDir(agentGroupId, sessionId), 'outbox', messageId);
412
+ if (!fs.existsSync(outboxDir)) return;
413
+ try {
414
+ fs.rmSync(outboxDir, { recursive: true, force: true });
415
+ } catch (err) {
416
+ log.warn('Outbox cleanup failed (message already delivered)', { messageId, err });
417
+ }
418
+ }
419
+
420
+ /** Mark a container as running for a session. */
421
+ export function markContainerRunning(sessionId: string): void {
422
+ updateSession(sessionId, { container_status: 'running', last_active: new Date().toISOString() });
423
+ }
424
+
425
+ /** Mark a container as idle for a session. */
426
+ export function markContainerIdle(sessionId: string): void {
427
+ updateSession(sessionId, { container_status: 'idle' });
428
+ }
429
+
430
+ /** Mark a container as stopped for a session. */
431
+ export function markContainerStopped(sessionId: string): void {
432
+ updateSession(sessionId, { container_status: 'stopped' });
433
+ }
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Tests for the startup bootstrap (`.env` token copy + messaging_groups
3
+ * v1→v2 backfill). The bootstrap reads from the registry's getActiveAdapters
4
+ * + readEnvFile, so each test stands up a real central DB plus a fake
5
+ * adapter and a stubbed env source.
6
+ */
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+
11
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
12
+
13
+ import { _resetActiveAdaptersForTest, _setActiveAdapterForTest } from './channels/channel-registry.js';
14
+ import type { ChannelAdapter } from './channels/adapter.js';
15
+ import { createMessagingGroup, getMessagingGroup } from './db/messaging-groups.js';
16
+ import { closeDb, initTestDb } from './db/connection.js';
17
+ import { runMigrations } from './db/migrations/index.js';
18
+ import { getSecret, putSecret } from './secrets/index.js';
19
+ import {
20
+ backfillMessagingGroupsToV2,
21
+ bootstrapChannelTokensToSecrets,
22
+ channelTokenSecretName,
23
+ } from './startup-bootstrap.js';
24
+
25
+ let envDir: string | null = null;
26
+ let envCwd: string | null = null;
27
+
28
+ function fakeAdapter(channelType: string, botId: string | null): ChannelAdapter {
29
+ return {
30
+ name: channelType,
31
+ channelType,
32
+ botId,
33
+ supportsThreads: false,
34
+ setup: async () => {},
35
+ teardown: async () => {},
36
+ isConnected: () => true,
37
+ deliver: async () => undefined,
38
+ };
39
+ }
40
+
41
+ function writeEnvFile(contents: string): void {
42
+ envDir = fs.mkdtempSync(path.join(os.tmpdir(), 'paraclaw-bootstrap-test-'));
43
+ fs.writeFileSync(path.join(envDir, '.env'), contents);
44
+ envCwd = process.cwd();
45
+ process.chdir(envDir);
46
+ }
47
+
48
+ beforeEach(() => {
49
+ // master.key for AES-GCM lives next to the central DB; use HOME override
50
+ // (master-key.ts reads ~/.parachute/...) by routing HOME at the top of
51
+ // each test.
52
+ process.env.HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'paraclaw-bootstrap-home-'));
53
+ const db = initTestDb();
54
+ runMigrations(db);
55
+ });
56
+
57
+ afterEach(() => {
58
+ _resetActiveAdaptersForTest();
59
+ closeDb();
60
+ if (envCwd) {
61
+ process.chdir(envCwd);
62
+ envCwd = null;
63
+ }
64
+ if (envDir) {
65
+ fs.rmSync(envDir, { recursive: true, force: true });
66
+ envDir = null;
67
+ }
68
+ vi.unstubAllEnvs();
69
+ });
70
+
71
+ describe('backfillMessagingGroupsToV2', () => {
72
+ it('rewrites legacy telegram:<chatId> → telegram:<botId>:<chatId>', () => {
73
+ _setActiveAdapterForTest(fakeAdapter('telegram', '8792496425'));
74
+ createMessagingGroup({
75
+ id: 'mg-1',
76
+ channel_type: 'telegram',
77
+ platform_id: 'telegram:1190596288',
78
+ name: 'Aaron DM',
79
+ is_group: 0,
80
+ unknown_sender_policy: 'strict',
81
+ created_at: new Date().toISOString(),
82
+ });
83
+ const upgraded = backfillMessagingGroupsToV2();
84
+ expect(upgraded).toBe(1);
85
+ expect(getMessagingGroup('mg-1')!.platform_id).toBe('telegram:8792496425:1190596288');
86
+ });
87
+
88
+ it('rewrites legacy discord:<guildId>:<channelId> → discord:<botId>:<guildId>:<channelId>', () => {
89
+ _setActiveAdapterForTest(fakeAdapter('discord', 'app-1'));
90
+ createMessagingGroup({
91
+ id: 'mg-2',
92
+ channel_type: 'discord',
93
+ platform_id: 'discord:guild999:chan111',
94
+ name: 'guild',
95
+ is_group: 1,
96
+ unknown_sender_policy: 'strict',
97
+ created_at: new Date().toISOString(),
98
+ });
99
+ backfillMessagingGroupsToV2();
100
+ expect(getMessagingGroup('mg-2')!.platform_id).toBe('discord:app-1:guild999:chan111');
101
+ });
102
+
103
+ it('preserves an @me DM segment intact under the new bot dim', () => {
104
+ _setActiveAdapterForTest(fakeAdapter('discord', 'app-1'));
105
+ createMessagingGroup({
106
+ id: 'mg-3',
107
+ channel_type: 'discord',
108
+ platform_id: 'discord:@me:user456',
109
+ name: 'DM',
110
+ is_group: 0,
111
+ unknown_sender_policy: 'strict',
112
+ created_at: new Date().toISOString(),
113
+ });
114
+ backfillMessagingGroupsToV2();
115
+ expect(getMessagingGroup('mg-3')!.platform_id).toBe('discord:app-1:@me:user456');
116
+ });
117
+
118
+ it('is idempotent — already-v2 rows are not double-prefixed', () => {
119
+ _setActiveAdapterForTest(fakeAdapter('telegram', 'bot1'));
120
+ createMessagingGroup({
121
+ id: 'mg-4',
122
+ channel_type: 'telegram',
123
+ platform_id: 'telegram:bot1:1190596288',
124
+ name: null,
125
+ is_group: 0,
126
+ unknown_sender_policy: 'strict',
127
+ created_at: new Date().toISOString(),
128
+ });
129
+ expect(backfillMessagingGroupsToV2()).toBe(0);
130
+ expect(getMessagingGroup('mg-4')!.platform_id).toBe('telegram:bot1:1190596288');
131
+ // Second run must also be a no-op.
132
+ expect(backfillMessagingGroupsToV2()).toBe(0);
133
+ expect(getMessagingGroup('mg-4')!.platform_id).toBe('telegram:bot1:1190596288');
134
+ });
135
+
136
+ it('does not re-prefix already-v2 rows that belong to a registered-but-not-yet-active secondary bot', () => {
137
+ // Reproduces the live regression that corrupted TechneRobot's rows on
138
+ // reboot: only the .env primary adapter is active at boot, but the
139
+ // secondary bot's CHANNEL_BOT_TOKEN secret is already in the table
140
+ // (Proposal A: register-bot persists the token before adapter spawn).
141
+ // The backfill iterates over the primary; if it forgets the secondary's
142
+ // botId, it sees the secondary's already-v2 row, treats it as v1, and
143
+ // re-prefixes it under the primary → 4-segment garbage id.
144
+ _setActiveAdapterForTest(fakeAdapter('telegram', 'primary-bot'));
145
+ putSecret(channelTokenSecretName('telegram', 'secondary-bot'), 'tg-token-2', {
146
+ kind: 'channel-token',
147
+ agent_group_id: null,
148
+ });
149
+ createMessagingGroup({
150
+ id: 'mg-primary',
151
+ channel_type: 'telegram',
152
+ platform_id: 'telegram:primary-bot:1190596288',
153
+ name: null,
154
+ is_group: 0,
155
+ unknown_sender_policy: 'strict',
156
+ created_at: new Date().toISOString(),
157
+ });
158
+ createMessagingGroup({
159
+ id: 'mg-secondary',
160
+ channel_type: 'telegram',
161
+ platform_id: 'telegram:secondary-bot:-1002245300962',
162
+ name: null,
163
+ is_group: 1,
164
+ unknown_sender_policy: 'strict',
165
+ created_at: new Date().toISOString(),
166
+ });
167
+
168
+ expect(backfillMessagingGroupsToV2()).toBe(0);
169
+ expect(getMessagingGroup('mg-primary')!.platform_id).toBe('telegram:primary-bot:1190596288');
170
+ expect(getMessagingGroup('mg-secondary')!.platform_id).toBe('telegram:secondary-bot:-1002245300962');
171
+
172
+ // Second pass must remain a no-op even with mixed-bot rows present.
173
+ expect(backfillMessagingGroupsToV2()).toBe(0);
174
+ expect(getMessagingGroup('mg-primary')!.platform_id).toBe('telegram:primary-bot:1190596288');
175
+ expect(getMessagingGroup('mg-secondary')!.platform_id).toBe('telegram:secondary-bot:-1002245300962');
176
+ });
177
+
178
+ it('skips channels with no active adapter (e.g. install with only Telegram running)', () => {
179
+ _setActiveAdapterForTest(fakeAdapter('telegram', 'bot1'));
180
+ // Discord row with no Discord adapter — must be left untouched until
181
+ // its adapter comes up on a future restart.
182
+ createMessagingGroup({
183
+ id: 'mg-5',
184
+ channel_type: 'discord',
185
+ platform_id: 'discord:guild:chan',
186
+ name: null,
187
+ is_group: 1,
188
+ unknown_sender_policy: 'strict',
189
+ created_at: new Date().toISOString(),
190
+ });
191
+ backfillMessagingGroupsToV2();
192
+ expect(getMessagingGroup('mg-5')!.platform_id).toBe('discord:guild:chan');
193
+ });
194
+ });
195
+
196
+ describe('bootstrapChannelTokensToSecrets', () => {
197
+ it('copies TELEGRAM_BOT_TOKEN into a per-bot secret row keyed by botId', () => {
198
+ writeEnvFile('TELEGRAM_BOT_TOKEN=tg-secret-token\n');
199
+ _setActiveAdapterForTest(fakeAdapter('telegram', '8792496425'));
200
+ bootstrapChannelTokensToSecrets();
201
+ const name = channelTokenSecretName('telegram', '8792496425');
202
+ expect(getSecret(name)).toBe('tg-secret-token');
203
+ });
204
+
205
+ it('is idempotent — re-running with the same value does not duplicate', () => {
206
+ writeEnvFile('TELEGRAM_BOT_TOKEN=tg-secret-token\n');
207
+ _setActiveAdapterForTest(fakeAdapter('telegram', 'bot1'));
208
+ bootstrapChannelTokensToSecrets();
209
+ bootstrapChannelTokensToSecrets();
210
+ expect(getSecret(channelTokenSecretName('telegram', 'bot1'))).toBe('tg-secret-token');
211
+ });
212
+
213
+ it('skips adapters without a botId (e.g. CLI admin transport)', () => {
214
+ writeEnvFile('TELEGRAM_BOT_TOKEN=tg-secret-token\n');
215
+ _setActiveAdapterForTest(fakeAdapter('cli', null));
216
+ bootstrapChannelTokensToSecrets();
217
+ expect(getSecret('CHANNEL_BOT_TOKEN:cli:')).toBeUndefined();
218
+ });
219
+
220
+ it('skips channels with no env var mapping (no-op for unknown channels)', () => {
221
+ writeEnvFile('SOMETHING_ELSE=x\n');
222
+ _setActiveAdapterForTest(fakeAdapter('whatsapp', 'wa-bot'));
223
+ bootstrapChannelTokensToSecrets();
224
+ expect(getSecret(channelTokenSecretName('whatsapp', 'wa-bot'))).toBeUndefined();
225
+ });
226
+ });