@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,652 @@
1
+ /**
2
+ * Chat SDK bridge — wraps a Chat SDK adapter + Chat instance
3
+ * to conform to the Paraclaw ChannelAdapter interface.
4
+ *
5
+ * Used by Discord, Slack, and other Chat SDK-supported platforms.
6
+ */
7
+ import http from 'http';
8
+
9
+ import {
10
+ Chat,
11
+ Card,
12
+ CardText,
13
+ Actions,
14
+ Button,
15
+ type Adapter,
16
+ type ConcurrencyStrategy,
17
+ type Message as ChatMessage,
18
+ } from 'chat';
19
+ import { log } from '../log.js';
20
+ import { SqliteStateAdapter } from '../state-sqlite.js';
21
+ import { registerWebhookAdapter } from '../webhook-server.js';
22
+ import { getAskQuestionRender } from '../db/sessions.js';
23
+ import { encodePlatformId } from '../platform-id.js';
24
+ import { normalizeOptions, type NormalizedOption } from './ask-question.js';
25
+ import type { ChannelAdapter, ChannelSetup, InboundMessage } from './adapter.js';
26
+
27
+ /** Adapter with optional gateway support (e.g., Discord). */
28
+ interface GatewayAdapter extends Adapter {
29
+ startGatewayListener?(
30
+ options: { waitUntil?: (task: Promise<unknown>) => void },
31
+ durationMs?: number,
32
+ abortSignal?: AbortSignal,
33
+ webhookUrl?: string,
34
+ ): Promise<Response>;
35
+ }
36
+
37
+ /** Reply context extracted from a platform's raw message. */
38
+ export interface ReplyContext {
39
+ text: string;
40
+ sender: string;
41
+ }
42
+
43
+ /** Extract reply context from a platform-specific raw message. Return null if no reply. */
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ export type ReplyContextExtractor = (raw: Record<string, any>) => ReplyContext | null;
46
+
47
+ export interface ChatSdkBridgeConfig {
48
+ adapter: Adapter;
49
+ concurrency?: ConcurrencyStrategy;
50
+ /**
51
+ * Bot identity for v2 platform_id encoding. The bridge prefixes inbound
52
+ * platform_ids with `<botId>` so multiple bots on the same channel
53
+ * (e.g. two Telegram bots in the same install) route to distinct
54
+ * messaging_groups rows. Outbound deliveries strip the bot dim back out
55
+ * before handing to the SDK adapter, which only knows the v1 form.
56
+ *
57
+ * Rationale: see src/platform-id.ts module comment.
58
+ */
59
+ botId: string;
60
+ /** Bot token for authenticating forwarded Gateway events (required for interaction handling). */
61
+ botToken?: string;
62
+ /** Platform-specific reply context extraction. */
63
+ extractReplyContext?: ReplyContextExtractor;
64
+ /**
65
+ * Whether this platform uses threads as the primary conversation unit.
66
+ * See `ChannelAdapter.supportsThreads`. Declared by the calling channel
67
+ * skill, not inferred, because some platforms (Discord) can be used either
68
+ * way and the default depends on installation style.
69
+ */
70
+ supportsThreads: boolean;
71
+ /**
72
+ * Optional transform applied to outbound text/markdown before it reaches the
73
+ * adapter. Used by channels that need to sanitize for a platform-specific
74
+ * quirk (e.g. Telegram's legacy Markdown parse mode).
75
+ */
76
+ transformOutboundText?: (text: string) => string;
77
+ /**
78
+ * Maximum text length the underlying adapter accepts in a single message.
79
+ * When set, the bridge splits outbound text longer than this on paragraph
80
+ * → line → hard-char boundaries and posts multiple messages. Without this,
81
+ * adapters like Discord (2000) and Telegram (4096) silently truncate
82
+ * mid-response. The returned id is the first chunk's id so subsequent edits
83
+ * and reactions still target the head of the reply.
84
+ */
85
+ maxTextLength?: number;
86
+ }
87
+
88
+ /**
89
+ * Split `text` into chunks no larger than `limit`, preferring paragraph
90
+ * breaks, then line breaks, then a hard character cut as a last resort.
91
+ * Preserves code fences only structurally — a fenced block that straddles a
92
+ * chunk boundary will render as two independent blocks on the receiving
93
+ * platform, which is the same behavior as manually re-opening a fence.
94
+ */
95
+ /**
96
+ * Decode the actual option value from a button callback. Buttons are encoded
97
+ * with an integer index (to keep under Telegram's 64-byte callback_data cap),
98
+ * and the real value is looked up via `getAskQuestionRender(questionId)`.
99
+ * Falls back to treating the tail as a literal value so old in-flight cards
100
+ * (encoded before this shortening landed) still resolve.
101
+ */
102
+ function resolveSelectedOption(
103
+ render: { options: NormalizedOption[] } | undefined,
104
+ eventValue: string | undefined,
105
+ tail: string | undefined,
106
+ ): string {
107
+ const candidate = eventValue ?? tail ?? '';
108
+ if (render && /^\d+$/.test(candidate)) {
109
+ const idx = Number(candidate);
110
+ if (render.options[idx]) return render.options[idx].value;
111
+ }
112
+ return candidate;
113
+ }
114
+
115
+ export function splitForLimit(text: string, limit: number): string[] {
116
+ if (text.length <= limit) return [text];
117
+ const chunks: string[] = [];
118
+ let remaining = text;
119
+ while (remaining.length > limit) {
120
+ let cut = remaining.lastIndexOf('\n\n', limit);
121
+ if (cut <= 0) cut = remaining.lastIndexOf('\n', limit);
122
+ if (cut <= 0) cut = remaining.lastIndexOf(' ', limit);
123
+ if (cut <= 0) cut = limit;
124
+ chunks.push(remaining.slice(0, cut).trimEnd());
125
+ remaining = remaining.slice(cut).trimStart();
126
+ }
127
+ if (remaining.length > 0) chunks.push(remaining);
128
+ return chunks;
129
+ }
130
+
131
+ export function createChatSdkBridge(config: ChatSdkBridgeConfig): ChannelAdapter {
132
+ const { adapter, botId } = config;
133
+ const transformText = (t: string): string => (config.transformOutboundText ? config.transformOutboundText(t) : t);
134
+
135
+ /**
136
+ * Insert the bot id into a v1 platform_id from the SDK.
137
+ * `<channel>:<native>` → `<channel>:<botId>:<native>`.
138
+ * If the input does not start with `<channel>:` (defensive — shouldn't
139
+ * happen for Chat-SDK-namespaced ids), it is returned unchanged.
140
+ */
141
+ function withBot(sdkPlatformId: string): string {
142
+ const colon = sdkPlatformId.indexOf(':');
143
+ if (colon === -1) return sdkPlatformId;
144
+ const channel = sdkPlatformId.slice(0, colon);
145
+ const native = sdkPlatformId.slice(colon + 1);
146
+ return encodePlatformId(channel, botId, native);
147
+ }
148
+
149
+ /**
150
+ * Inverse of {@link withBot}: strip the bot id from a v2 platform_id so
151
+ * the SDK adapter sees the form it produced. Tolerates already-v1 input
152
+ * (legacy queue rows that haven't been backfilled) — passes through.
153
+ */
154
+ function withoutBot(v2PlatformId: string): string {
155
+ const colon = v2PlatformId.indexOf(':');
156
+ if (colon === -1) return v2PlatformId;
157
+ const rest = v2PlatformId.slice(colon + 1);
158
+ if (rest.startsWith(`${botId}:`)) {
159
+ return `${v2PlatformId.slice(0, colon + 1)}${rest.slice(botId.length + 1)}`;
160
+ }
161
+ return v2PlatformId;
162
+ }
163
+ let chat: Chat;
164
+ let state: SqliteStateAdapter;
165
+ let setupConfig: ChannelSetup;
166
+ let gatewayAbort: AbortController | null = null;
167
+
168
+ async function messageToInbound(
169
+ message: ChatMessage,
170
+ isMention: boolean,
171
+ isGroup?: boolean,
172
+ ): Promise<InboundMessage> {
173
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
174
+ const serialized = message.toJSON() as Record<string, any>;
175
+
176
+ // Download attachment data before serialization loses fetchData()
177
+ if (message.attachments && message.attachments.length > 0) {
178
+ const enriched = [];
179
+ for (const att of message.attachments) {
180
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
181
+ const entry: Record<string, any> = {
182
+ type: att.type,
183
+ name: att.name,
184
+ mimeType: att.mimeType,
185
+ size: att.size,
186
+ width: (att as unknown as Record<string, unknown>).width,
187
+ height: (att as unknown as Record<string, unknown>).height,
188
+ };
189
+ if (att.fetchData) {
190
+ try {
191
+ const buffer = await att.fetchData();
192
+ entry.data = buffer.toString('base64');
193
+ } catch (err) {
194
+ log.warn('Failed to download attachment', { type: att.type, err });
195
+ }
196
+ }
197
+ enriched.push(entry);
198
+ }
199
+ serialized.attachments = enriched;
200
+ }
201
+
202
+ // Extract reply context via platform-specific hook
203
+ if (config.extractReplyContext && message.raw) {
204
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
205
+ const replyTo = config.extractReplyContext(message.raw as Record<string, any>);
206
+ if (replyTo) serialized.replyTo = replyTo;
207
+ }
208
+
209
+ // Project chat-sdk's nested author into the flat sender fields the router
210
+ // expects (see src/router.ts extractAndUpsertUser). Native adapters already
211
+ // populate these directly; this brings chat-sdk adapters in line.
212
+ const author = serialized.author as { userId?: string; fullName?: string; userName?: string } | undefined;
213
+ if (author) {
214
+ const name = author.fullName ?? author.userName;
215
+ serialized.senderId = author.userId;
216
+ serialized.sender = name;
217
+ serialized.senderName = name;
218
+ }
219
+
220
+ // Drop raw to save DB space (can be very large)
221
+ serialized.raw = undefined;
222
+
223
+ return {
224
+ id: message.id,
225
+ kind: 'chat-sdk',
226
+ content: serialized,
227
+ timestamp: message.metadata.dateSent.toISOString(),
228
+ isMention,
229
+ isGroup,
230
+ };
231
+ }
232
+
233
+ const bridge: ChannelAdapter = {
234
+ name: adapter.name,
235
+ channelType: adapter.name,
236
+ supportsThreads: config.supportsThreads,
237
+
238
+ async setup(hostConfig: ChannelSetup) {
239
+ setupConfig = hostConfig;
240
+
241
+ state = new SqliteStateAdapter();
242
+
243
+ chat = new Chat({
244
+ adapters: { [adapter.name]: adapter },
245
+ userName: adapter.userName || 'Parachute Agent',
246
+ concurrency: config.concurrency ?? 'concurrent',
247
+ state,
248
+ logger: 'silent',
249
+ });
250
+
251
+ // Four SDK dispatch paths — bridge just forwards. All per-wiring
252
+ // engage / accumulate / drop / subscribe decisions live in the host
253
+ // router (src/router.ts routeInbound / evaluateEngage). The bridge
254
+ // only resolves channel ids and sets the platform-confirmed isMention
255
+ // flag that routeInbound evaluates; the router calls back into
256
+ // bridge.subscribe(...) when a mention-sticky wiring engages.
257
+
258
+ // Subscribed threads — every message in a thread we've previously
259
+ // engaged. Carry the SDK's `message.isMention` through so mention-mode
260
+ // wirings still fire on in-thread mentions.
261
+ chat.onSubscribedMessage(async (thread, message) => {
262
+ const channelId = withBot(adapter.channelIdFromThreadId(thread.id));
263
+ await setupConfig.onInbound(
264
+ channelId,
265
+ thread.id,
266
+ await messageToInbound(message, message.isMention === true, true),
267
+ );
268
+ });
269
+
270
+ // @mention in an unsubscribed thread — SDK-confirmed bot mention.
271
+ chat.onNewMention(async (thread, message) => {
272
+ const channelId = withBot(adapter.channelIdFromThreadId(thread.id));
273
+ await setupConfig.onInbound(channelId, thread.id, await messageToInbound(message, true, true));
274
+ });
275
+
276
+ // DMs — by definition addressed to the bot. Thread id flows through
277
+ // so sub-thread context reaches delivery (Slack users can open threads
278
+ // inside a DM). Router collapses DM sub-threads to one session via
279
+ // is_group=0 short-circuit.
280
+ chat.onDirectMessage(async (thread, message) => {
281
+ const channelId = withBot(adapter.channelIdFromThreadId(thread.id));
282
+ log.info('Inbound DM received', {
283
+ adapter: adapter.name,
284
+ channelId,
285
+ sender: (message.author as any)?.fullName ?? (message.author as any)?.userId ?? 'unknown',
286
+ threadId: thread.id,
287
+ });
288
+ await setupConfig.onInbound(channelId, thread.id, await messageToInbound(message, true, false));
289
+ });
290
+
291
+ // Plain messages in unsubscribed threads.
292
+ //
293
+ // Chat SDK dispatch (handling-events.mdx §"Handler dispatch order") is
294
+ // exclusive: subscribed → onSubscribedMessage; unsubscribed+mention →
295
+ // onNewMention; unsubscribed+pattern-match → onNewMessage. Registering
296
+ // with `/./` lets the router see every plain message on every
297
+ // unsubscribed thread the bot can see. The router short-circuits via
298
+ // getMessagingGroupWithAgentCount (~1 DB read) for unwired channels,
299
+ // so forwarding every one is cheap enough to not need a bridge-side
300
+ // flood gate.
301
+ chat.onNewMessage(/./, async (thread, message) => {
302
+ const channelId = withBot(adapter.channelIdFromThreadId(thread.id));
303
+ await setupConfig.onInbound(channelId, thread.id, await messageToInbound(message, false, true));
304
+ });
305
+
306
+ // Handle button clicks (ask_user_question)
307
+ chat.onAction(async (event) => {
308
+ if (!event.actionId.startsWith('ncq:')) return;
309
+ const parts = event.actionId.split(':');
310
+ if (parts.length < 3) return;
311
+ const questionId = parts[1];
312
+ const tail = parts.slice(2).join(':');
313
+ const userId = event.user?.userId || '';
314
+
315
+ // Resolve render metadata BEFORE dispatching onAction (which deletes the row).
316
+ const render = getAskQuestionRender(questionId);
317
+ // New format: button id/value is an integer index into options (kept
318
+ // short to fit Telegram's 64-byte callback_data cap). Old format:
319
+ // the full value is embedded in actionId/value directly.
320
+ const selectedOption = resolveSelectedOption(render, event.value, tail);
321
+ const title = render?.title ?? '❓ Question';
322
+ const matched = render?.options.find((o) => o.value === selectedOption);
323
+ const selectedLabel = matched?.selectedLabel ?? selectedOption ?? '(clicked)';
324
+
325
+ // Update the card to show the selected answer and remove buttons
326
+ try {
327
+ const tid = event.threadId;
328
+ await adapter.editMessage(tid, event.messageId, {
329
+ markdown: `${title}\n\n${selectedLabel}`,
330
+ });
331
+ } catch (err) {
332
+ log.warn('Failed to update card after action', { err });
333
+ }
334
+
335
+ setupConfig.onAction(questionId, selectedOption, userId);
336
+ });
337
+
338
+ await chat.initialize();
339
+
340
+ // Start Gateway listener for adapters that support it (e.g., Discord)
341
+ const gatewayAdapter = adapter as GatewayAdapter;
342
+ if (gatewayAdapter.startGatewayListener) {
343
+ gatewayAbort = new AbortController();
344
+
345
+ // Start local HTTP server to receive forwarded Gateway events (including interactions)
346
+ const webhookUrl = await startLocalWebhookServer(gatewayAdapter, setupConfig, config.botToken);
347
+
348
+ const startGateway = () => {
349
+ if (gatewayAbort?.signal.aborted) return;
350
+ // Capture the long-running listener promise via waitUntil
351
+ let listenerPromise: Promise<unknown> | undefined;
352
+ gatewayAdapter.startGatewayListener!(
353
+ {
354
+ waitUntil: (p: Promise<unknown>) => {
355
+ listenerPromise = p;
356
+ },
357
+ },
358
+ 24 * 60 * 60 * 1000,
359
+ gatewayAbort!.signal,
360
+ webhookUrl,
361
+ ).then(() => {
362
+ // startGatewayListener resolves immediately with a Response;
363
+ // the actual work is in the listenerPromise passed to waitUntil
364
+ if (listenerPromise) {
365
+ listenerPromise
366
+ .then(() => {
367
+ if (!gatewayAbort?.signal.aborted) {
368
+ log.info('Gateway listener expired, restarting', { adapter: adapter.name });
369
+ startGateway();
370
+ }
371
+ })
372
+ .catch((err) => {
373
+ if (!gatewayAbort?.signal.aborted) {
374
+ log.error('Gateway listener error, restarting in 5s', { adapter: adapter.name, err });
375
+ setTimeout(startGateway, 5000);
376
+ }
377
+ });
378
+ }
379
+ });
380
+ };
381
+ startGateway();
382
+ log.info('Gateway listener started', { adapter: adapter.name });
383
+ } else {
384
+ // Non-gateway adapters (Slack, Teams, GitHub, etc.) — register on the shared webhook server
385
+ registerWebhookAdapter(chat, adapter.name);
386
+ }
387
+
388
+ log.info('Chat SDK bridge initialized', { adapter: adapter.name });
389
+ },
390
+
391
+ async deliver(platformId: string, threadId: string | null, message): Promise<string | undefined> {
392
+ // platformId arrives in v2 form (`<channel>:<botId>:<native>`); the SDK
393
+ // adapter only understands v1 (`<channel>:<native>`), so strip the bot
394
+ // dim before using it as the thread id. threadId, when present, is
395
+ // already an SDK-native thread id and goes through unchanged.
396
+ const tid = threadId ?? withoutBot(platformId);
397
+ const content = message.content as Record<string, unknown>;
398
+
399
+ if (content.operation === 'edit' && content.messageId) {
400
+ await adapter.editMessage(tid, content.messageId as string, {
401
+ markdown: transformText((content.text as string) || (content.markdown as string) || ''),
402
+ });
403
+ return;
404
+ }
405
+
406
+ if (content.operation === 'reaction' && content.messageId && content.emoji) {
407
+ await adapter.addReaction(tid, content.messageId as string, content.emoji as string);
408
+ return;
409
+ }
410
+
411
+ // Ask question card — render as Card with buttons
412
+ if (content.type === 'ask_question' && content.questionId && content.options) {
413
+ const questionId = content.questionId as string;
414
+ const title = content.title as string;
415
+ const question = content.question as string;
416
+ if (!title) {
417
+ log.error('ask_question missing required title — skipping delivery', { questionId });
418
+ return;
419
+ }
420
+ const options: NormalizedOption[] = normalizeOptions(content.options as never);
421
+ const card = Card({
422
+ title,
423
+ children: [
424
+ CardText(question),
425
+ Actions(
426
+ // Encode button id/value with the option index rather than the
427
+ // full value. Telegram caps callback_data at 64 bytes, and
428
+ // long values (e.g. ISO datetimes, URLs) push the JSON payload
429
+ // well past that. The onAction handlers resolve the index back
430
+ // to the real value via getAskQuestionRender(questionId).
431
+ options.map((opt, idx) =>
432
+ Button({ id: `ncq:${questionId}:${idx}`, label: opt.label, value: String(idx) }),
433
+ ),
434
+ ),
435
+ ],
436
+ });
437
+ const result = await adapter.postMessage(tid, {
438
+ card,
439
+ fallbackText: `${title}\n\n${question}\nOptions: ${options.map((o) => o.label).join(', ')}`,
440
+ });
441
+ return result?.id;
442
+ }
443
+
444
+ // Normal message
445
+ const rawText = (content.markdown as string) || (content.text as string);
446
+ const text = rawText ? transformText(rawText) : rawText;
447
+ if (text) {
448
+ // Attach files if present (FileUpload format: { data, filename })
449
+ const fileUploads = message.files?.map((f: { data: Buffer; filename: string }) => ({
450
+ data: f.data,
451
+ filename: f.filename,
452
+ }));
453
+ // Split if over the adapter's max length. Files ride on the first
454
+ // chunk so the head of the reply still carries them.
455
+ const chunks =
456
+ config.maxTextLength && text.length > config.maxTextLength
457
+ ? splitForLimit(text, config.maxTextLength)
458
+ : [text];
459
+ let firstId: string | undefined;
460
+ for (let i = 0; i < chunks.length; i++) {
461
+ const chunk = chunks[i];
462
+ const attachFiles = i === 0 && fileUploads && fileUploads.length > 0;
463
+ const result = await adapter.postMessage(
464
+ tid,
465
+ attachFiles ? { markdown: chunk, files: fileUploads } : { markdown: chunk },
466
+ );
467
+ if (i === 0) firstId = result?.id;
468
+ }
469
+ return firstId;
470
+ } else if (message.files && message.files.length > 0) {
471
+ // Files only, no text
472
+ const fileUploads = message.files.map((f: { data: Buffer; filename: string }) => ({
473
+ data: f.data,
474
+ filename: f.filename,
475
+ }));
476
+ const result = await adapter.postMessage(tid, { markdown: '', files: fileUploads });
477
+ return result?.id;
478
+ }
479
+ },
480
+
481
+ async setTyping(platformId: string, threadId: string | null) {
482
+ const tid = threadId ?? withoutBot(platformId);
483
+ await adapter.startTyping(tid);
484
+ },
485
+
486
+ async teardown() {
487
+ gatewayAbort?.abort();
488
+ await chat.shutdown();
489
+ log.info('Chat SDK bridge shut down', { adapter: adapter.name });
490
+ },
491
+
492
+ isConnected() {
493
+ return true;
494
+ },
495
+
496
+ async subscribe(_platformId: string, threadId: string) {
497
+ // Chat SDK's subscription state lives on the StateAdapter (not on the
498
+ // Chat instance itself). SqliteStateAdapter.subscribe is idempotent —
499
+ // a second call on an already-subscribed thread is a no-op. threadId
500
+ // is the SDK's thread id, which is what the router already has from
501
+ // the original inbound event.
502
+ await state.subscribe(threadId);
503
+ },
504
+ };
505
+
506
+ // Only expose openDM when the underlying Chat SDK adapter implements it.
507
+ // Delegate straight to adapter.openDM rather than going through chat.openDM:
508
+ // the latter dispatches via inferAdapterFromUserId, which only recognizes
509
+ // Discord snowflakes, Slack U-ids, Teams 29:-ids, and gChat users/-ids, and
510
+ // throws for everything else (Telegram numeric ids, iMessage, Matrix, …).
511
+ // Calling adapter.openDM directly also preserves the adapter's native
512
+ // platform_id encoding via channelIdFromThreadId (e.g. "telegram:<chatId>"),
513
+ // which matches what onInbound stores in messaging_groups — avoiding a
514
+ // duplicate-row / decode-error cascade at delivery time. See user-dm.ts for
515
+ // the direct-addressable fallback when the adapter has no openDM at all.
516
+ if (adapter.openDM) {
517
+ bridge.openDM = async (userHandle: string): Promise<string> => {
518
+ const threadId = await adapter.openDM!(userHandle);
519
+ return withBot(adapter.channelIdFromThreadId(threadId));
520
+ };
521
+ }
522
+
523
+ return bridge;
524
+ }
525
+
526
+ /**
527
+ * Start a local HTTP server to receive forwarded Gateway events.
528
+ * This is needed because the Gateway listener in webhook-forwarding mode
529
+ * sends ALL raw events (including INTERACTION_CREATE for button clicks)
530
+ * to the webhookUrl, which we handle here.
531
+ */
532
+ function startLocalWebhookServer(
533
+ adapter: GatewayAdapter,
534
+ setupConfig: ChannelSetup,
535
+ botToken?: string,
536
+ ): Promise<string> {
537
+ return new Promise((resolve) => {
538
+ const server = http.createServer((req, res) => {
539
+ const chunks: Buffer[] = [];
540
+ req.on('data', (chunk: Buffer) => chunks.push(chunk));
541
+ req.on('end', () => {
542
+ const body = Buffer.concat(chunks).toString();
543
+ handleForwardedEvent(body, adapter, setupConfig, botToken)
544
+ .then(() => {
545
+ res.writeHead(200, { 'Content-Type': 'application/json' });
546
+ res.end('{"ok":true}');
547
+ })
548
+ .catch((err) => {
549
+ log.error('Webhook server error', { err });
550
+ res.writeHead(500);
551
+ res.end('{"error":"internal"}');
552
+ });
553
+ });
554
+ });
555
+
556
+ server.listen(0, '127.0.0.1', () => {
557
+ const addr = server.address() as { port: number };
558
+ const url = `http://127.0.0.1:${addr.port}/webhook`;
559
+ log.info('Local webhook server started', { port: addr.port });
560
+ resolve(url);
561
+ });
562
+ });
563
+ }
564
+
565
+ async function handleForwardedEvent(
566
+ body: string,
567
+ adapter: GatewayAdapter,
568
+ setupConfig: ChannelSetup,
569
+ botToken?: string,
570
+ ): Promise<void> {
571
+ let event: { type: string; data: Record<string, unknown> };
572
+ try {
573
+ event = JSON.parse(body);
574
+ } catch {
575
+ return;
576
+ }
577
+
578
+ // Handle interaction events (button clicks) — not handled by adapter's handleForwardedGatewayEvent
579
+ if (event.type === 'GATEWAY_INTERACTION_CREATE' && event.data) {
580
+ const interaction = event.data;
581
+ // type 3 = MessageComponent (button/select)
582
+ if (interaction.type === 3) {
583
+ const customId = (interaction.data as Record<string, unknown>)?.custom_id as string;
584
+ // In guilds the clicker is at interaction.member.user; in DMs it's interaction.user directly.
585
+ const user =
586
+ ((interaction.member as Record<string, unknown>)?.user as Record<string, string> | undefined) ??
587
+ (interaction.user as Record<string, string> | undefined);
588
+ const interactionId = interaction.id as string;
589
+ const interactionToken = interaction.token as string;
590
+
591
+ // Parse the selected option from custom_id
592
+ let questionId: string | undefined;
593
+ let tail: string | undefined;
594
+ if (customId?.startsWith('ncq:')) {
595
+ const colonIdx = customId.indexOf(':', 4); // after "ncq:"
596
+ if (colonIdx !== -1) {
597
+ questionId = customId.slice(4, colonIdx);
598
+ tail = customId.slice(colonIdx + 1);
599
+ }
600
+ }
601
+
602
+ // Update the card to show the selected answer and remove buttons
603
+ const originalEmbeds =
604
+ ((interaction.message as Record<string, unknown>)?.embeds as Array<Record<string, unknown>>) || [];
605
+ const originalDescription = (originalEmbeds[0]?.description as string) || '';
606
+ const render = questionId ? getAskQuestionRender(questionId) : undefined;
607
+ // Discord custom_id mirrors the new index-based encoding (see Button
608
+ // construction). Decode back to the real option value for downstream.
609
+ const selectedOption = resolveSelectedOption(render, tail, tail);
610
+ const cardTitle = render?.title ?? ((originalEmbeds[0]?.title as string) || '❓ Question');
611
+ const matchedOpt = render?.options.find((o) => o.value === selectedOption);
612
+ const selectedLabel = matchedOpt?.selectedLabel ?? selectedOption ?? customId;
613
+ try {
614
+ await fetch(`https://discord.com/api/v10/interactions/${interactionId}/${interactionToken}/callback`, {
615
+ method: 'POST',
616
+ headers: { 'Content-Type': 'application/json' },
617
+ body: JSON.stringify({
618
+ type: 7, // UPDATE_MESSAGE — acknowledge + update in one call
619
+ data: {
620
+ embeds: [
621
+ {
622
+ title: cardTitle,
623
+ description: `${originalDescription}\n\n${selectedLabel}`,
624
+ },
625
+ ],
626
+ components: [], // remove buttons
627
+ },
628
+ }),
629
+ });
630
+ } catch (err) {
631
+ log.error('Failed to update interaction', { err });
632
+ }
633
+
634
+ // Dispatch to host
635
+ if (questionId && selectedOption) {
636
+ setupConfig.onAction(questionId, selectedOption, user?.id || '');
637
+ }
638
+ return;
639
+ }
640
+ }
641
+
642
+ // Forward other events to the adapter's webhook handler for normal processing
643
+ const fakeRequest = new Request('http://localhost/webhook', {
644
+ method: 'POST',
645
+ headers: {
646
+ 'Content-Type': 'application/json',
647
+ 'x-discord-gateway-token': botToken || '',
648
+ },
649
+ body,
650
+ });
651
+ await adapter.handleWebhook(fakeRequest, {});
652
+ }