Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Add a generic connector engine with catalog, OAuth, gateway, and mailbox

Fei2411c8f459eca40e
diff --git a/ds-bot/index.js b/ds-bot/index.js
index a524d360..7acdfa59 100644
--- a/ds-bot/index.js
+++ b/ds-bot/index.js
@@ -31,7 +31,7 @@ import * as avatarLibrary from './src/host/avatar-library.js'
import * as browser from './src/host/browser.js'
import * as browserPlugins from './src/host/browser-plugins.js'
import * as secrets from './src/host/secrets.js'
-import * as connectors from './src/host/connectors.js'
+import * as connectors from './src/host/connectors/index.js'
import * as capabilities from './src/host/capabilities.js'
import * as learning from './src/host/learning.js'
import * as schedules from './src/host/schedules.js'
diff --git a/ds-bot/package-lock.json b/ds-bot/package-lock.json
index 1fc49dc1..0273b611 100644
--- a/ds-bot/package-lock.json
+++ b/ds-bot/package-lock.json
@@ -9,7 +9,11 @@
"version": "0.2.7",
"license": "Apache-2.0",
"dependencies": {
- "deep-view": "0.1.0"
+ "@modelcontextprotocol/client": "2.4.0",
+ "deep-view": "0.1.0",
+ "imapflow": "2.9.1",
+ "mailparser": "3.12.4",
+ "nodemailer": "10.2.1"
},
"devDependencies": {
"@xmldom/xmldom": "0.9.12",
@@ -465,6 +469,58 @@
"node": ">=18"
}
},
+ "node_modules/@modelcontextprotocol/client": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz",
+ "integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.4.0",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.8",
+ "jose": "^6.1.3",
+ "pkce-challenge": "^5.0.0",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/core": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz",
+ "integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@pinojs/redact": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
+ "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",
+ "license": "MIT"
+ },
+ "node_modules/@selderee/plugin-htmlparser2": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@selderee/plugin-htmlparser2/-/plugin-htmlparser2-0.12.0.tgz",
+ "integrity": "sha512-oELmoyA6ML9jDRMV3kgcMQFKxUfBU0yFVn6yTctVaLT5ygXnxH52I3TZEgV9EhXJC68/uFvE5Daj1/25c0Xa/A==",
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "~2.3.0",
+ "domhandler": "~5.0.3"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/KillyMXI"
+ },
+ "peerDependencies": {
+ "selderee": "~0.12.0"
+ }
+ },
"node_modules/@xmldom/xmldom": {
"version": "0.9.12",
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz",
@@ -475,6 +531,43 @@
"node": ">=14.6"
}
},
+ "node_modules/@zone-eu/mailsplit": {
+ "version": "5.4.29",
+ "resolved": "https://registry.npmjs.org/@zone-eu/mailsplit/-/mailsplit-5.4.29.tgz",
+ "integrity": "sha512-CCUNycmUjrV5M0wNf23waWAt9eOHczhjLbUQS7k0FNJvR0py9VSqHFt+tSl/D0+XI73VLG0U+PwYtq9R0zsm9Q==",
+ "license": "(MIT OR EUPL-1.1+)",
+ "dependencies": {
+ "libbase64": "1.4.1",
+ "libmime": "5.6.3",
+ "libqp": "3.0.1"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/atomic-sleep": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
+ "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
"node_modules/deep-view": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/deep-view/-/deep-view-0.1.0.tgz",
@@ -487,6 +580,101 @@
"@deepseek-ai/dsh-web": "*"
}
},
+ "node_modules/deepmerge-ts": {
+ "version": "8.0.2",
+ "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-8.0.2.tgz",
+ "integrity": "sha512-uqbvqLUMrc6p0MO+WBRtTxY55hmyh94WRwI5a++PZe54X+bfVh59FSN7uWCBCW1CCVjzjnrwzfI8zidE2obMMw==",
+ "funding": [
+ {
+ "type": "ko-fi",
+ "url": "https://ko-fi.com/rebeccastevens"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/deepmerge-ts"
+ }
+ ],
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=16.9.0"
+ }
+ },
+ "node_modules/dom-serializer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "domelementtype": "^2.3.0"
+ },
+ "engines": {
+ "node": ">= 4"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/domutils": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
+ "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
+ "node_modules/encoding-japanese": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/encoding-japanese/-/encoding-japanese-2.4.0.tgz",
+ "integrity": "sha512-PE0KjlsDy9JSsoU4C2Q8NXb1kC4c+bZRac9ZvHXUE4q1Ht63gScKMdEy9jst9+Fi3M4eDkqzkEhBZvix4blP2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/entities": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/esbuild": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
@@ -528,6 +716,507 @@
"@esbuild/win32-ia32": "0.28.2",
"@esbuild/win32-x64": "0.28.2"
}
+ },
+ "node_modules/eventsource": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
+ "license": "MIT",
+ "dependencies": {
+ "eventsource-parser": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/eventsource-parser": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/he": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz",
+ "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==",
+ "license": "MIT",
+ "bin": {
+ "he": "bin/he"
+ }
+ },
+ "node_modules/html-to-text": {
+ "version": "10.0.1",
+ "resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-10.0.1.tgz",
+ "integrity": "sha512-GiVhRI1BatGARSCmlXWNCjDT0cWrwBWoeduLoV0WSKAgaV/wa+hUWy5LiQLUs4UwiUrE52ZCMfBGiKD87TDPrg==",
+ "license": "MIT",
+ "dependencies": {
+ "@selderee/plugin-htmlparser2": "~0.12.0",
+ "deepmerge-ts": "^8.0.1",
+ "dom-serializer": "^2.0.0",
+ "htmlparser2": "^10.1.0",
+ "selderee": "~0.12.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/KillyMXI"
+ }
+ },
+ "node_modules/htmlparser2": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
+ "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
+ "funding": [
+ "https://github.com/fb55/htmlparser2?sponsor=1",
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.2.2",
+ "entities": "^7.0.1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/entities": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.7.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
+ "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/imapflow": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/imapflow/-/imapflow-2.9.1.tgz",
+ "integrity": "sha512-hOq2/+T+WnQzRy7D40gYlio25nG+c9bhtrxowokOQM57SwZFqRbqAtxFQcIpx82lhYBPQEEVVjmkYpd9Fplj7g==",
+ "license": "MIT",
+ "dependencies": {
+ "@zone-eu/mailsplit": "5.4.29",
+ "encoding-japanese": "2.4.0",
+ "iconv-lite": "0.7.3",
+ "libbase64": "1.4.1",
+ "libmime": "5.6.3",
+ "libqp": "3.0.1",
+ "pino": "10.3.1",
+ "socks": "2.8.10"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/ip-address": {
+ "version": "10.7.6",
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz",
+ "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "license": "ISC"
+ },
+ "node_modules/jose": {
+ "version": "6.2.15",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.15.tgz",
+ "integrity": "sha512-qdF6ewcZARtef63fJ9AKKZPgxw+t7USH6HLXYcD4CrdmSvDp79rpJSPFEKc90QBeGS63u1KQtN2MZQHC0yDIzA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
+ "node_modules/leac": {
+ "version": "0.7.0",
+ "resolved": "https://registry.npmjs.org/leac/-/leac-0.7.0.tgz",
+ "integrity": "sha512-qMrZeyEekgdRQ9o6a4NAB2EQZrv827GJdn1vnapwSJ90hWRB4TzUSunvacPkxQ2TnNqHNI1/zSt0hlo0crG8Jw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/KillyMXI"
+ }
+ },
+ "node_modules/libbase64": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/libbase64/-/libbase64-1.4.1.tgz",
+ "integrity": "sha512-Nyh3H90B3gRtrcxIe56Ayy7635J0jmh6AbxbQgQae8wrSPQMH5wFqJChiMTB13yKG512L3YspbA5DzumhFTITA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/libmime": {
+ "version": "5.6.3",
+ "resolved": "https://registry.npmjs.org/libmime/-/libmime-5.6.3.tgz",
+ "integrity": "sha512-cuTUW/Jybvh5O4/U9p61gyutHOjDtZyGQYuY99+bfnaFwqcDf2Nb+R6hMHY6DDen2H9wLKQSMpofWUgn2TI5JQ==",
+ "license": "MIT",
+ "dependencies": {
+ "encoding-japanese": "2.4.0",
+ "iconv-lite": "0.7.3",
+ "libbase64": "1.4.1",
+ "libqp": "3.0.1"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/libqp": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/libqp/-/libqp-3.0.1.tgz",
+ "integrity": "sha512-7QZxpPX25pga1WiMueduWxmrHMVBFrZPH6ZUaozGYa/H98JH6NVBSET3qVw+4NxzoraIW7rJ81YxSU9IalvCpg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/linkify-it": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.2.tgz",
+ "integrity": "sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/puzrin"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/markdown-it"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "uc.micro": "^2.0.0"
+ }
+ },
+ "node_modules/mailparser": {
+ "version": "3.12.4",
+ "resolved": "https://registry.npmjs.org/mailparser/-/mailparser-3.12.4.tgz",
+ "integrity": "sha512-FdoMF+S89/AQaJHY7StwTfABPHZ8Vey+CDyUno5j+TO0jF0UxM+la4Pe9MeqKqBO4Y9ZMB2eomdyg5i+jzpfZw==",
+ "license": "MIT",
+ "dependencies": {
+ "@zone-eu/mailsplit": "5.4.29",
+ "he": "1.2.0",
+ "html-to-text": "10.0.1",
+ "libmime": "5.6.3",
+ "linkify-it": "5.0.2",
+ "nodemailer": "10.2.1",
+ "punycode.js": "2.3.1",
+ "tlds": "1.261.0"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/nodemailer": {
+ "version": "10.2.1",
+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.2.1.tgz",
+ "integrity": "sha512-ZrDNsPFoDMwefNs7sJwrYiEJ/CG4ClJWDZv05iNJsEBWa8GRDry1QJHTJxsuTAY9eDDKjX4k+q3SxslXJOao7w==",
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/on-exit-leak-free": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
+ "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/parseley": {
+ "version": "0.13.1",
+ "resolved": "https://registry.npmjs.org/parseley/-/parseley-0.13.1.tgz",
+ "integrity": "sha512-uNBJZzmb60l6p6VWLTmevizNAGnE0xoSf1n0B4q3ntegDNzcS68NRCcBDZTcyXHxt2XhBChsCuqj4M+nChvE/A==",
+ "license": "MIT",
+ "dependencies": {
+ "leac": "^0.7.0",
+ "peberminta": "^0.10.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/KillyMXI"
+ }
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/peberminta": {
+ "version": "0.10.0",
+ "resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.10.0.tgz",
+ "integrity": "sha512-80B2AsU+I4Qdb0ZAPSfe9UwvGzwkM37IKIFEvdS3D/3Ndgv2bsuJ0bfG1+iEYO+l7Gfd4EUJmuRyq7efLgRMzQ==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/KillyMXI"
+ }
+ },
+ "node_modules/pino": {
+ "version": "10.3.1",
+ "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz",
+ "integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==",
+ "license": "MIT",
+ "dependencies": {
+ "@pinojs/redact": "^0.4.0",
+ "atomic-sleep": "^1.0.0",
+ "on-exit-leak-free": "^2.1.0",
+ "pino-abstract-transport": "^3.0.0",
+ "pino-std-serializers": "^7.0.0",
+ "process-warning": "^5.0.0",
+ "quick-format-unescaped": "^4.0.3",
+ "real-require": "^0.2.0",
+ "safe-stable-stringify": "^2.3.1",
+ "sonic-boom": "^4.0.1",
+ "thread-stream": "^4.0.0"
+ },
+ "bin": {
+ "pino": "bin.js"
+ }
+ },
+ "node_modules/pino-abstract-transport": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz",
+ "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==",
+ "license": "MIT",
+ "dependencies": {
+ "split2": "^4.0.0"
+ }
+ },
+ "node_modules/pino-std-serializers": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz",
+ "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",
+ "license": "MIT"
+ },
+ "node_modules/pkce-challenge": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/process-warning": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz",
+ "integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/punycode.js": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz",
+ "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/quick-format-unescaped": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
+ "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",
+ "license": "MIT"
+ },
+ "node_modules/real-require": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
+ "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12.13.0"
+ }
+ },
+ "node_modules/safe-stable-stringify": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
+ "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "license": "MIT"
+ },
+ "node_modules/selderee": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/selderee/-/selderee-0.12.0.tgz",
+ "integrity": "sha512-b1YMh3+DHZp59DLna3qVwQ5iOla/nrI6mLBNW02XxU77M3046Df6VLkoaJyFz20VsGIG5kkp+FK0kg4K4HnUFw==",
+ "license": "MIT",
+ "dependencies": {
+ "parseley": "~0.13.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/KillyMXI"
+ }
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/smart-buffer": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
+ "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6.0.0",
+ "npm": ">= 3.0.0"
+ }
+ },
+ "node_modules/socks": {
+ "version": "2.8.10",
+ "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz",
+ "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ip-address": "^10.1.1",
+ "smart-buffer": "^4.2.0"
+ },
+ "engines": {
+ "node": ">= 10.0.0",
+ "npm": ">= 3.0.0"
+ }
+ },
+ "node_modules/sonic-boom": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",
+ "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==",
+ "license": "MIT",
+ "dependencies": {
+ "atomic-sleep": "^1.0.0"
+ }
+ },
+ "node_modules/split2": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
+ "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">= 10.x"
+ }
+ },
+ "node_modules/thread-stream": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.1.tgz",
+ "integrity": "sha512-Stg6edJXC/6/xqGwSXwFokrUhChJ18amEjpKH89WrQQ0oVFDF+pUUcTpiwWhFUrE89Vf16FBOlwhaw+lescxMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "real-require": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/thread-stream/node_modules/real-require": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz",
+ "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",
+ "license": "MIT"
+ },
+ "node_modules/tlds": {
+ "version": "1.261.0",
+ "resolved": "https://registry.npmjs.org/tlds/-/tlds-1.261.0.tgz",
+ "integrity": "sha512-QXqwfEl9ddlGBaRFXIvNKK6OhipSiLXuRuLJX5DErz0o0Q0rYxulWLdFryTkV5PkdZct5iMInwYEGe/eR++1AA==",
+ "license": "MIT",
+ "bin": {
+ "tlds": "bin.js"
+ }
+ },
+ "node_modules/uc.micro": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz",
+ "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==",
+ "license": "MIT"
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/zod": {
+ "version": "4.6.7",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
}
}
}
diff --git a/ds-bot/package.json b/ds-bot/package.json
index 6365ccb0..ce016735 100644
--- a/ds-bot/package.json
+++ b/ds-bot/package.json
@@ -68,6 +68,10 @@
"esbuild": "0.28.2"
},
"dependencies": {
- "deep-view": "0.1.0"
+ "@modelcontextprotocol/client": "2.4.0",
+ "deep-view": "0.1.0",
+ "imapflow": "2.9.1",
+ "mailparser": "3.12.4",
+ "nodemailer": "10.2.1"
}
}
diff --git a/ds-bot/src/host/capabilities.js b/ds-bot/src/host/capabilities.js
index 29b13666..7b22edf4 100644
--- a/ds-bot/src/host/capabilities.js
+++ b/ds-bot/src/host/capabilities.js
@@ -7,10 +7,13 @@ const NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/
const SECRET_REFERENCE = /\$DSH_SECRET_([A-Z][A-Z0-9_]*)/g
const ENSURE_TIMEOUT_MS = 15_000
-export function validateCapabilityName(value) {
+// Connector ids are reserved: a capability named like one would collide with
+// its mcp__<id>__* tool prefix. The connectors module registers its ids here.
+export const CONNECTOR_IDS = new Set(['github', 'mail'])
+export function validateCapabilityName(value, reserved = CONNECTOR_IDS) {
const name = String(value ?? '').trim()
- if (name.length > 32 || !NAME.test(name) || name === 'github') {
- throw new Error('Use a capability name with lowercase letters, digits, and single hyphens; "github" is reserved.')
+ if (name.length > 32 || !NAME.test(name) || name === 'github' || reserved.has(name)) {
+ throw new Error('Use a capability name with lowercase letters, digits, and single hyphens; connector names are reserved.')
}
return name
}
diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.js
index 5ce6b836..055088db 100644
--- a/ds-bot/src/host/channel.js
+++ b/ds-bot/src/host/channel.js
@@ -71,6 +71,8 @@ export function install(rt) {
secrets: rt.secretsView(),
capabilities: rt.capabilityLibraryView(),
secretRequests: state.secretRequests ?? {},
+ connectorRequests: state.connectorRequests ?? {},
+ mailRequests: state.mailRequests ?? {},
colors: [...COLORS, ...EXTRA_COLORS],
models: rt.cachedCatalog(),
defaultModel: rt.cachedDefault() ?? null,
@@ -407,6 +409,19 @@ export function install(rt) {
case 'connector-connect':
case 'connector-disconnect':
case 'connector-retry':
+ case 'connector-sign-in-code':
+ case 'connector-cancel':
+ case 'connector-client':
+ case 'connector-set':
+ case 'connector-add':
+ case 'connector-remove':
+ case 'connector-import-scan':
+ case 'connector-import':
+ case 'connector-request-cancel':
+ case 'mail-account-add':
+ case 'mail-account-remove':
+ case 'mail-send-answer':
+ case 'mail-sign-in-code':
await rt.load()
return ok(await rt.connectorEndpoint(endpoint, body))
case 'capability-save':
diff --git a/ds-bot/src/host/connectors.js b/ds-bot/src/host/connectors.js
deleted file mode 100644
index 65c431bd..00000000
--- a/ds-bot/src/host/connectors.js
+++ /dev/null
@@ -1,169 +0,0 @@
-// Connectors: outside services every Bot can use. GitHub is the first one. Its tools come
-// from GitHub's MCP server through DSH's own MCP client, mounted on the plugin context,
-// so every Bot and Session gets them as mcp__github__<tool>.
-//
-// The token is the GITHUB_TOKEN secret (secrets.js keeps it, redacts it, and offers it to
-// the shell). It reaches GitHub only in the MCP request headers, built here in memory,
-// never written to the DSH profile. A new token is shared with no Bot's shell: the tools
-// do not need it there, and a Bot that reads a planted instruction in an issue could
-// send it anywhere. The Secrets page can still share it. Signing in is `signIn` alone, so a browser login can
-// take its place later without touching the mount.
-
-export const GITHUB = 'github'
-export const GITHUB_SECRET = 'GITHUB_TOKEN'
-const MCP_CLIENT = '@deepseek-ai/dsh-mcp-client'
-const DEFAULTS = {
- url: 'https://api.githubcopilot.com/mcp/',
- api: 'https://api.github.com',
- toolsets: 'context,repos,issues,pull_requests',
-}
-const CHECK_TIMEOUT_MS = 15_000
-const INSECURE = 'GitHub addresses must start with https://'
-
-// Asks GitHub who the token belongs to. Any token GitHub accepts passes.
-export async function signIn(token, { api = DEFAULTS.api, fetch: request = fetch } = {}) {
- let response
- try {
- response = await request(`${api.replace(/\/$/, '')}/user`, {
- headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'User-Agent': 'ds-bot', 'X-GitHub-Api-Version': '2022-11-28' },
- signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
- })
- } catch {
- throw new Error('Could not reach GitHub')
- }
- if (response.status === 401) throw new Error('GitHub did not accept this token')
- if (!response.ok) throw new Error(`GitHub answered ${response.status}`)
- const user = await response.json().catch(() => ({}))
- if (typeof user?.login !== 'string') throw new Error('GitHub did not say who this token belongs to')
- return { login: user.login }
-}
-
-export function install(rt) {
- const { ctx, state } = rt
- const options = rt.config.github === false ? null : { ...DEFAULTS, ...rt.config.github }
- const insecure = options !== null && [options.url, options.api].some(address => !/^https:\/\//i.test(String(address)))
- // `token` is what the current mount was made with, so a changed secret mounts again.
- let mount = null
- let status = { state: 'off' }
- let queue = Promise.resolve()
- let stopped = false
-
- const unmount = async () => {
- const fiber = mount?.fiber
- mount = null
- if (fiber !== undefined) await Promise.resolve().then(() => fiber.dispose()).catch(() => {})
- }
-
- // The MCP client wraps the server's answer (a 401, say) as the cause.
- const reason = (error) => {
- const text = [error, error?.cause].filter(Boolean).map(part => String(part?.message ?? part)).join(': ')
- return rt.redactSecrets(text || 'error').slice(0, 300)
- }
-
- async function reconcile(force) {
- const token = options !== null && !stopped ? rt.secretValue(GITHUB_SECRET) : undefined
- if (!force && mount !== null && mount.token === token) return
- await unmount()
- if (token === undefined) {
- status = { state: 'off' }
- return
- }
- if (insecure) {
- mount = { token }
- status = { state: 'error', error: INSECURE }
- return
- }
- status = { state: 'connecting' }
- const loader = ctx.get?.('loader')
- if (typeof loader?.import !== 'function' || typeof ctx.plugin !== 'function') {
- mount = { token }
- status = { state: 'error', error: 'This DSH cannot load connectors' }
- return
- }
- try {
- const exports = await loader.import(MCP_CLIENT)
- const plugin = loader.unwrapExports?.(exports) ?? exports?.default ?? exports
- const fiber = ctx.plugin(plugin, {
- transport: 'streamable-http',
- serverName: GITHUB,
- url: options.url,
- headers: { Authorization: `Bearer ${token}`, 'X-MCP-Toolsets': options.toolsets },
- failOnStartupError: true,
- })
- mount = { token, fiber }
- await fiber.await()
- if (mount?.fiber !== fiber) return
- status = { state: 'ready' }
- } catch (error) {
- await unmount()
- mount = { token }
- status = { state: 'error', error: reason(error) }
- rt.warn('ds-bot: GitHub connector failed: %s', status.error)
- }
- }
-
- // One change at a time; `force` connects again even when the token is the same.
- const sync = (force = false) => {
- queue = queue.then(() => reconcile(force)).catch(error => { rt.warn('ds-bot: connectors: %s', reason(error)) })
- return queue
- }
-
- const connectorsView = () => options === null ? [] : [{
- id: GITHUB,
- name: 'GitHub',
- state: status.state,
- ...(status.error !== undefined ? { error: status.error } : {}),
- account: rt.secretValue(GITHUB_SECRET) !== undefined ? state.connectors?.[GITHUB]?.login ?? null : null,
- }]
-
- const known = id => {
- if (options === null || id !== GITHUB) throw new Error('No such connector')
- }
-
- const endpoints = {
- async 'connector-connect'(body) {
- known(body.id)
- const token = typeof body.token === 'string' ? body.token.trim() : ''
- if (token === '') throw new Error('Paste a token first')
- if (insecure) throw new Error(INSECURE)
- await rt.loadSecrets()
- const kept = rt.secretValue(GITHUB_SECRET) !== undefined
- const { login } = await signIn(token, { api: options.api })
- await rt.secretEndpoint('secret-set', { name: GITHUB_SECRET, value: token, purpose: 'GitHub connector', ...(kept ? {} : { scope: [] }) })
- state.connectors = { ...state.connectors, [GITHUB]: { login, connectedAt: Date.now() } }
- await rt.save()
- await sync()
- return connectorsView()
- },
- async 'connector-disconnect'(body) {
- known(body.id)
- await rt.loadSecrets()
- if (rt.secretValue(GITHUB_SECRET) !== undefined) await rt.secretEndpoint('secret-delete', { name: GITHUB_SECRET })
- if (state.connectors?.[GITHUB] !== undefined) {
- delete state.connectors[GITHUB]
- await rt.save()
- }
- await sync()
- return connectorsView()
- },
- async 'connector-retry'(body) {
- known(body.id)
- await rt.loadSecrets()
- await sync(true)
- return connectorsView()
- },
- }
-
- const connectorEndpoint = (endpoint, body) => endpoints[endpoint](body ?? {})
-
- ctx.effect(() => {
- stopped = false
- void rt.loadSecrets().then(() => sync())
- return () => {
- stopped = true
- void unmount()
- }
- }, 'ds-bot: connectors')
-
- Object.assign(rt, { connectorsView, connectorEndpoint, secretsChanged: () => { void sync() } })
-}
diff --git a/ds-bot/src/host/connectors/catalog.js b/ds-bot/src/host/connectors/catalog.js
new file mode 100644
index 00000000..81860fe6
--- /dev/null
+++ b/ds-bot/src/host/connectors/catalog.js
@@ -0,0 +1,96 @@
+// The connector catalog: services that publish a remote MCP server (or need no
+// server, like the mailbox). Each entry is plain data: name, category, address,
+// and how it signs in. `about` is our own one-line text.
+//
+// auth kinds:
+// none — the server needs no sign-in.
+// oauth — MCP OAuth sign-in (browser PKCE); `client` names a known public
+// client (GitHub device flow), `token: true` also offers pasting a token.
+// key — an API key in a header (`header`, optional `prefix`) or a query
+// parameter (`query`); `keyUrl` is where the user gets one.
+// `headers` are extra static headers; `whoami` reads the account name after
+// sign-in for the row.
+
+// The OAuth client id DS Bot is registered as on GitHub. Filled in at release;
+// overridable for development. Empty keeps the pasted-token form only.
+export const GITHUB_CLIENT_ID = process.env.DS_BOT_GITHUB_OAUTH_CLIENT_ID ?? ''
+
+const oauth = url => ({ remote: { url }, auth: { kind: 'oauth' } })
+
+export const CATALOG = [
+ {
+ id: 'github', name: 'GitHub', category: 'dev',
+ about: 'Repositories, issues, and pull requests',
+ remote: { url: 'https://api.githubcopilot.com/mcp/' },
+ headers: { 'X-MCP-Toolsets': 'context,repos,issues,pull_requests' },
+ auth: { kind: 'oauth', scopes: ['repo', 'read:org'], client: { id: GITHUB_CLIENT_ID, deviceFlow: true }, token: true },
+ whoami: { url: 'https://api.github.com/user', field: 'login' },
+ },
+ { id: 'notion', name: 'Notion', category: 'docs', about: 'Pages, databases, and wiki content', ...oauth('https://mcp.notion.com/mcp') },
+ { id: 'linear', name: 'Linear', category: 'work', about: 'Issues, projects, and cycles', ...oauth('https://mcp.linear.app/mcp') },
+ { id: 'atlassian', name: 'Atlassian', category: 'work', about: 'Jira issues and Confluence pages', ...oauth('https://mcp.atlassian.com/v1/mcp') },
+ { id: 'sentry', name: 'Sentry', category: 'dev', about: 'Errors, traces, and releases', ...oauth('https://mcp.sentry.dev/mcp') },
+ { id: 'stripe', name: 'Stripe', category: 'commerce', about: 'Payments, invoices, and customers', ...oauth('https://mcp.stripe.com') },
+ { id: 'paypal', name: 'PayPal', category: 'commerce', about: 'Orders, payments, and invoices', ...oauth('https://mcp.paypal.com/mcp') },
+ { id: 'square', name: 'Square', category: 'commerce', about: 'Payments, orders, and catalog', ...oauth('https://mcp.squareup.com/mcp') },
+ { id: 'cloudflare', name: 'Cloudflare', category: 'dev', about: 'Workers, DNS, and account resources', ...oauth('https://bindings.mcp.cloudflare.com/mcp') },
+ { id: 'vercel', name: 'Vercel', category: 'dev', about: 'Projects, deployments, and logs', ...oauth('https://mcp.vercel.com') },
+ { id: 'supabase', name: 'Supabase', category: 'data', about: 'Databases, tables, and project settings', ...oauth('https://mcp.supabase.com/mcp') },
+ { id: 'neon', name: 'Neon', category: 'data', about: 'Postgres databases and branches', ...oauth('https://mcp.neon.tech/mcp') },
+ { id: 'figma', name: 'Figma', category: 'design', about: 'Design files, components, and comments', ...oauth('https://mcp.figma.com/mcp') },
+ { id: 'canva', name: 'Canva', category: 'design', about: 'Designs, folders, and exports', ...oauth('https://mcp.canva.com/mcp') },
+ { id: 'intercom', name: 'Intercom', category: 'work', about: 'Conversations, contacts, and articles', ...oauth('https://mcp.intercom.com/mcp') },
+ { id: 'monday', name: 'monday.com', category: 'work', about: 'Boards, items, and workflows', ...oauth('https://mcp.monday.com/mcp') },
+ { id: 'webflow', name: 'Webflow', category: 'design', about: 'Sites, pages, and CMS content', ...oauth('https://mcp.webflow.com/mcp') },
+ { id: 'wix', name: 'Wix', category: 'design', about: 'Sites, pages, and site content', ...oauth('https://mcp.wix.com/mcp') },
+ { id: 'netlify', name: 'Netlify', category: 'dev', about: 'Sites, deploys, and forms', ...oauth('https://netlify-mcp.netlify.app/mcp') },
+ { id: 'airtable', name: 'Airtable', category: 'data', about: 'Bases, tables, and records', ...oauth('https://mcp.airtable.com/mcp') },
+ { id: 'dropbox', name: 'Dropbox', category: 'docs', about: 'Files and folders', ...oauth('https://mcp.dropbox.com/mcp') },
+ { id: 'zapier', name: 'Zapier', category: 'work', about: 'Zaps and app actions', ...oauth('https://mcp.zapier.com/api/mcp/mcp') },
+ { id: 'clickup', name: 'ClickUp', category: 'work', about: 'Tasks, lists, and docs', ...oauth('https://mcp.clickup.com/mcp') },
+ { id: 'todoist', name: 'Todoist', category: 'work', about: 'Tasks and projects', ...oauth('https://ai.todoist.net/mcp') },
+ { id: 'miro', name: 'Miro', category: 'design', about: 'Boards and whiteboard items', ...oauth('https://mcp.miro.com/') },
+ { id: 'attio', name: 'Attio', category: 'work', about: 'CRM records, lists, and notes', ...oauth('https://mcp.attio.com/mcp') },
+ { id: 'postman', name: 'Postman', category: 'dev', about: 'Collections, requests, and workspaces', ...oauth('https://mcp.postman.com/mcp') },
+ { id: 'asana', name: 'Asana', category: 'work', about: 'Tasks, projects, and workspaces', ...oauth('https://mcp.asana.com/v2/mcp') },
+ { id: 'box', name: 'Box', category: 'docs', about: 'Files, folders, and metadata', ...oauth('https://mcp.box.com') },
+ { id: 'hubspot', name: 'HubSpot', category: 'work', about: 'Contacts, deals, and tickets', ...oauth('https://mcp.hubspot.com/') },
+ { id: 'slack', name: 'Slack', category: 'work', about: 'Channels and messages', ...oauth('https://mcp.slack.com/mcp') },
+ { id: 'huggingface', name: 'Hugging Face', category: 'data', about: 'Models, datasets, and Spaces', remote: { url: 'https://huggingface.co/mcp' }, auth: { kind: 'none' } },
+ { id: 'exa', name: 'Exa', category: 'search', about: 'Web search for agents', remote: { url: 'https://mcp.exa.ai/mcp' }, auth: { kind: 'none' } },
+ { id: 'deepwiki', name: 'DeepWiki', category: 'docs', about: 'Documentation for public code repositories', remote: { url: 'https://mcp.deepwiki.com/mcp' }, auth: { kind: 'none' } },
+ { id: 'context7', name: 'Context7', category: 'docs', about: 'Library documentation and code examples', remote: { url: 'https://mcp.context7.com/mcp' }, auth: { kind: 'none' } },
+ { id: 'mslearn', name: 'Microsoft Learn', category: 'docs', about: 'Microsoft product documentation', remote: { url: 'https://learn.microsoft.com/api/mcp' }, auth: { kind: 'none' } },
+ { id: 'cloudflare-docs', name: 'Cloudflare Docs', category: 'docs', about: 'Cloudflare product documentation', remote: { url: 'https://docs.mcp.cloudflare.com/mcp' }, auth: { kind: 'none' } },
+ {
+ id: 'amap', name: 'Amap', category: 'search', about: 'Maps, places, and routes in China',
+ remote: { url: 'https://mcp.amap.com/mcp' },
+ auth: { kind: 'key', query: 'key', keyUrl: 'https://lbs.amap.com/api/mcp-server/create' },
+ },
+ { id: 'mail', name: 'Mailbox', category: 'mail', about: 'Read and send email over IMAP and SMTP', auth: { kind: 'none' } },
+]
+
+export const CATEGORIES = ['dev', 'docs', 'work', 'design', 'data', 'commerce', 'search', 'mail']
+
+export const entryOf = id => CATALOG.find(entry => entry.id === id)
+
+// The secret names a connector's credentials live under. GitHub keeps its
+// original GITHUB_TOKEN name; other ids become CONNECTOR_<ID>_*.
+export const secretPrefix = (id) => {
+ const safe = id.toUpperCase().replace(/[^A-Z0-9]/g, '_')
+ return `CONNECTOR_${safe}`
+}
+export const tokenSecretOf = id => id === 'github' ? 'GITHUB_TOKEN' : `${secretPrefix(id)}_TOKEN`
+export const refreshSecretOf = id => `${secretPrefix(id)}_REFRESH`
+export const clientSecretOf = id => `${secretPrefix(id)}_CLIENT_SECRET`
+export const keySecretOf = id => `${secretPrefix(id)}_KEY`
+export const envSecretOf = (id, name) => `${secretPrefix(id)}_${name.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`.slice(0, 64)
+
+// Custom connector ids come from the name the user typed; never a catalog id.
+export function customId(name, taken) {
+ const base = String(name ?? '').toLowerCase().trim()
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').replace(/^(\d)/, 'c-$1').slice(0, 28) || 'custom'
+ let id = entryOf(base) === undefined && base !== 'github' && base !== 'mail' ? base : `${base}-x`
+ while (taken.has(id) || entryOf(id) !== undefined || id.length > 32) id = `${id.slice(0, 28)}-${Math.random().toString(36).slice(2, 6)}`
+ return id
+}
diff --git a/ds-bot/src/host/connectors/gateway.js b/ds-bot/src/host/connectors/gateway.js
new file mode 100644
index 00000000..91cf9241
--- /dev/null
+++ b/ds-bot/src/host/connectors/gateway.js
@@ -0,0 +1,210 @@
+// The connector gateway: one local HTTP server inside the plugin process. Every
+// remote connector's mcp-client mounts `http://127.0.0.1:<port>/c/<id>` with a
+// random per-process nonce, so no real credential ever reaches the mcp-client
+// config. The gateway adds the credential here and streams the answer back.
+// When a connector's read-only switch is on, tools/list answers are filtered to
+// readOnlyHint tools and write tools/call is refused locally.
+import { createServer } from 'node:http'
+import { randomBytes, timingSafeEqual } from 'node:crypto'
+import { request as httpsRequest } from 'node:https'
+
+const FORWARD_HEADERS = ['mcp-session-id', 'mcp-protocol-version', 'last-event-id', 'accept', 'content-type']
+const RETURN_HEADERS = ['content-type', 'mcp-session-id', 'mcp-protocol-version']
+const RETRYABLE = new Set(['GET', 'POST', 'DELETE'])
+
+const nonceMatches = (header, nonce) => {
+ const given = /^Bearer\s+(.+)$/i.exec(String(header ?? ''))?.[1] ?? ''
+ const a = Buffer.from(given)
+ const b = Buffer.from(nonce)
+ return a.length === b.length && timingSafeEqual(a, b)
+}
+
+const sseMessage = (body) => {
+ // Pull the JSON-RPC payload out of an SSE body (one or more event frames).
+ const frames = []
+ for (const block of String(body).split(/\r?\n\r?\n/)) {
+ const data = block.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n')
+ if (data !== '') frames.push(data)
+ }
+ return frames.length === 1 ? frames[0] : null
+}
+
+const readAll = stream => new Promise((resolve, reject) => {
+ const chunks = []
+ stream.on('data', chunk => chunks.push(chunk))
+ stream.on('end', () => resolve(Buffer.concat(chunks)))
+ stream.on('error', reject)
+})
+
+export function createGateway({ credential, readOnly, onUnauthorized, log = () => {} }) {
+ const nonce = randomBytes(24).toString('base64url')
+ let server = null
+ let port = 0
+ // Tool annotations seen in tools/list answers, per connector, for read-only checks.
+ const annotations = new Map()
+
+ const toolReadOnly = (id, name) => {
+ const flags = annotations.get(id)
+ return flags?.get(name) === true
+ }
+
+ // Marks annotations from a tools/list result, and filters it when read-only.
+ const processList = (id, result, filtered) => {
+ const tools = Array.isArray(result?.result?.tools) ? result.result.tools : null
+ if (tools === null) return result
+ let flags = annotations.get(id)
+ if (flags === undefined) annotations.set(id, flags = new Map())
+ for (const tool of tools) flags.set(tool.name, tool.annotations?.readOnlyHint === true)
+ if (!filtered) return result
+ return { ...result, result: { ...result.result, tools: tools.filter(tool => tool.annotations?.readOnlyHint === true) } }
+ }
+
+ const refuseCall = (id, rpc) => ({
+ jsonrpc: '2.0',
+ id: rpc?.id ?? null,
+ error: { code: -32600, message: `The ${id} connector is read-only: this tool can change things, so it is off. Turn off the read-only switch in Settings → Connectors to use it.` },
+ })
+
+ async function sendUpstream(entry, method, path, headers, body) {
+ return new Promise((resolve, reject) => {
+ const target = new URL(path, entry.url)
+ const outgoing = { ...entry.headers }
+ for (const name of FORWARD_HEADERS) if (headers[name] !== undefined) outgoing[name] = headers[name]
+ if (body !== undefined) outgoing['content-length'] = body.length
+ const req = httpsRequest(target, { method, headers: outgoing }, resolve)
+ req.on('error', reject)
+ if (body !== undefined) req.write(body)
+ req.end()
+ })
+ }
+
+ async function handle(id, req, res) {
+ const entry = credential(id)
+ if (entry === undefined) {
+ res.writeHead(404, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ error: 'connector not connected' }))
+ return
+ }
+ if (!/^https:\/\//i.test(entry.url)) {
+ res.writeHead(502, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ error: 'connector address must be https' }))
+ return
+ }
+ const path = req.url.slice(`/c/${id}`.length) || '/'
+ const limited = readOnly(id) === true
+ const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : await readAll(req)
+ // Read-only: a write tools/call never reaches the server.
+ if (limited && req.method === 'POST' && body !== undefined) {
+ let rpc
+ try { rpc = JSON.parse(body.toString('utf8')) } catch { rpc = null }
+ if (rpc?.method === 'tools/call' && !toolReadOnly(id, rpc.params?.name)) {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify(refuseCall(id, rpc)))
+ return
+ }
+ if (rpc?.method === 'tools/list') {
+ let upstream = await sendUpstream(entry, req.method, path, req.headers, body)
+ if (upstream.statusCode === 401) {
+ const retried = await onUnauthorized(id)
+ if (retried === true) {
+ upstream.resume()
+ upstream = await sendUpstream(credential(id) ?? entry, req.method, path, req.headers, body)
+ }
+ }
+ const raw = await readAll(upstream)
+ const isSse = String(upstream.headers['content-type'] ?? '').includes('text/event-stream')
+ const payload = isSse ? sseMessage(raw.toString('utf8')) : raw.toString('utf8')
+ let out = raw
+ try {
+ const parsed = payload === null ? null : JSON.parse(payload)
+ if (parsed !== null) {
+ const filtered = JSON.stringify(processList(id, parsed, true))
+ out = isSse ? Buffer.from(`event: message\ndata: ${filtered}\n\n`) : Buffer.from(filtered)
+ }
+ } catch { /* pass the answer through unchanged */ }
+ const heads = {}
+ for (const name of RETURN_HEADERS) if (upstream.headers[name] !== undefined) heads[name] = upstream.headers[name]
+ if (!isSse) heads['content-length'] = out.length
+ else delete heads['content-length']
+ res.writeHead(upstream.statusCode ?? 502, heads)
+ res.end(out)
+ return
+ }
+ }
+ if (!RETRYABLE.has(req.method)) {
+ res.writeHead(405, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ error: 'method not allowed' }))
+ return
+ }
+ let upstream
+ try {
+ upstream = await sendUpstream(entry, req.method, path, req.headers, body)
+ // One refresh + retry when the answer is still unsent.
+ if (upstream.statusCode === 401) {
+ const retried = await onUnauthorized(id)
+ if (retried === true) {
+ upstream.resume()
+ upstream = await sendUpstream(credential(id) ?? entry, req.method, path, req.headers, body)
+ }
+ }
+ } catch (error) {
+ log('ds-bot: connector gateway %s: %s', id, error?.message ?? error)
+ res.writeHead(502, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ error: 'connector upstream failed' }))
+ return
+ }
+ // tools/list without the read-only filter still feeds the annotation cache.
+ const isList = req.method === 'POST' && body !== undefined && (() => { try { return JSON.parse(body.toString('utf8'))?.method === 'tools/list' } catch { return false } })()
+ const heads = {}
+ for (const name of RETURN_HEADERS) if (upstream.headers[name] !== undefined) heads[name] = upstream.headers[name]
+ if (!isList || limited) {
+ res.writeHead(upstream.statusCode ?? 502, heads)
+ upstream.pipe(res)
+ return
+ }
+ // Unfiltered tools/list: buffer to learn annotations, then send as-is.
+ const raw = await readAll(upstream)
+ try {
+ const isSse = String(upstream.headers['content-type'] ?? '').includes('text/event-stream')
+ const payload = isSse ? sseMessage(raw.toString('utf8')) : raw.toString('utf8')
+ if (payload !== null) processList(id, JSON.parse(payload), false)
+ } catch { /* annotations stay as they were */ }
+ res.writeHead(upstream.statusCode ?? 502, heads)
+ res.end(raw)
+ }
+
+ return {
+ get port() { return port },
+ get nonce() { return nonce },
+ urlFor(id) { return `http://127.0.0.1:${port}/c/${id}` },
+ headers() { return { Authorization: `Bearer ${nonce}` } },
+ forget(id) { annotations.delete(id) },
+ async listen() {
+ if (server !== null) return
+ server = createServer((req, res) => {
+ const found = /^\/c\/([A-Za-z0-9_-]{1,32})/.exec(req.url ?? '')
+ if (found === null || !nonceMatches(req.headers.authorization, nonce)) {
+ res.writeHead(404)
+ res.end()
+ return
+ }
+ handle(found[1], req, res).catch((error) => {
+ log('ds-bot: connector gateway: %s', error?.message ?? error)
+ if (!res.headersSent) res.writeHead(500)
+ res.end()
+ })
+ })
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ port = server.address().port
+ },
+ async close() {
+ const closing = server
+ server = null
+ if (closing !== null) await new Promise(resolve => closing.close(resolve))
+ annotations.clear()
+ },
+ }
+}
diff --git a/ds-bot/src/host/connectors/index.js b/ds-bot/src/host/connectors/index.js
new file mode 100644
index 00000000..f3d17b8b
--- /dev/null
+++ b/ds-bot/src/host/connectors/index.js
@@ -0,0 +1,829 @@
+// Connectors: outside services every Bot can use. One engine mounts each
+// connected service's MCP server on the plugin context through the local
+// gateway (gateway.js), so every Bot gets mcp__<id>__* tools while credentials
+// stay DS Bot secrets that never reach the mcp-client config. OAuth sign-in is
+// in oauth.js, the service list in catalog.js, mail in mail/.
+import { randomBytes, randomUUID } from 'node:crypto'
+import { createServer } from 'node:http'
+import { readFile } from 'node:fs/promises'
+import { homedir, platform } from 'node:os'
+import { join } from 'node:path'
+import { defineTool } from '@deepseek-ai/dsh-tools'
+import { CATALOG, entryOf, customId, tokenSecretOf, refreshSecretOf, clientSecretOf, keySecretOf, envSecretOf } from './catalog.js'
+import * as oauth from './oauth.js'
+import { createGateway } from './gateway.js'
+import { install as installMail } from './mail/index.js'
+import { CONNECTOR_IDS } from '../capabilities.js'
+import { output } from '../tools.js'
+
+export const GITHUB = 'github'
+export const GITHUB_SECRET = 'GITHUB_TOKEN'
+const MCP_CLIENT = '@deepseek-ai/dsh-mcp-client'
+const CHECK_TIMEOUT_MS = 15_000
+const SIGN_IN_TIMEOUT_MS = 10 * 60_000
+const SECRET_REF = /\$DSH_SECRET_([A-Z][A-Z0-9_]*)/g
+const MAX_REQUESTS = 20
+
+// Asks GitHub who the token belongs to. Any token GitHub accepts passes.
+export async function signIn(token, { api = 'https://api.github.com', fetch: request = fetch } = {}) {
+ let response
+ try {
+ response = await request(`${api.replace(/\/$/, '')}/user`, {
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'User-Agent': 'ds-bot', 'X-GitHub-Api-Version': '2022-11-28' },
+ signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
+ })
+ } catch {
+ throw new Error('Could not reach GitHub')
+ }
+ if (response.status === 401) throw new Error('GitHub did not accept this token')
+ if (!response.ok) throw new Error(`GitHub answered ${response.status}`)
+ const user = await response.json().catch(() => ({}))
+ if (typeof user?.login !== 'string') throw new Error('GitHub did not say who this token belongs to')
+ return { login: user.login }
+}
+
+export function install(rt) {
+ const { ctx, state } = rt
+ for (const entry of CATALOG) CONNECTOR_IDS.add(entry.id)
+ const options = rt.config.github === false ? null : { api: 'https://api.github.com', ...rt.config.github }
+ const insecure = (url) => !/^https:\/\//i.test(String(url))
+ let stopped = false
+ let queue = Promise.resolve()
+ const mounts = new Map()
+ const statuses = new Map()
+ const pendings = new Map()
+ const refreshes = new Map()
+ const gateways = { gw: null }
+ const pluginP = { p: null }
+
+ const entries = () => {
+ const list = [...CATALOG.filter(entry => entry.id !== 'github' || options !== null)]
+ for (const [id, saved] of Object.entries(state.connectors ?? {})) {
+ if (saved?.custom) list.push({ id, name: saved.custom.name, category: 'custom', about: saved.custom.url ?? saved.custom.command ?? '', auth: { kind: 'custom' }, custom: saved.custom })
+ }
+ return list
+ }
+ const entryFor = (id) => {
+ const catalog = entryOf(id)
+ // rt.config.github keeps its url/api overrides from the old single connector.
+ if (catalog !== undefined && id === 'github' && options?.url !== undefined) {
+ return { ...catalog, remote: { url: options.url } }
+ }
+ if (catalog !== undefined) return catalog
+ const custom = state.connectors?.[id]?.custom
+ if (custom !== undefined) return { id, name: custom.name, category: 'custom', about: custom.url ?? custom.command ?? '', auth: { kind: 'custom' }, custom }
+ return undefined
+ }
+ const known = (id) => {
+ const entry = entryFor(String(id ?? ''))
+ if (entry === undefined || entry.id === 'github' && options === null) throw new Error('No such connector')
+ return entry
+ }
+ const reason = (error) => rt.redactSecrets([error, error?.cause].filter(Boolean).map(part => String(part?.message ?? part)).join(': ') || 'error').slice(0, 300)
+
+ // --- credentials ------------------------------------------------------
+
+ const credentialOf = (id) => {
+ const entry = entryFor(id)
+ if (entry === undefined || entry.auth.kind === 'none') return entry?.auth.kind === 'none' && entry.custom === undefined ? {} : {}
+ if (entry.auth.kind === 'oauth') {
+ const token = rt.secretValue(tokenSecretOf(id))
+ return token === undefined ? undefined : { Authorization: `Bearer ${token}` }
+ }
+ if (entry.auth.kind === 'key') {
+ const key = rt.secretValue(keySecretOf(id))
+ return key === undefined ? undefined : { key }
+ }
+ return {}
+ }
+ const hasCredential = (id) => {
+ const entry = entryFor(id)
+ if (entry === undefined) return false
+ if (entry.custom !== undefined) return true
+ if (entry.auth.kind === 'none') return state.connectors?.[id] !== undefined
+ return credentialOf(id) !== undefined
+ }
+
+ // What the gateway sends upstream for a connector.
+ const upstreamOf = (id) => {
+ const entry = entryFor(id)
+ if (entry === undefined || !hasCredential(id)) return undefined
+ let url = entry.custom?.url ?? entry.remote?.url
+ if (url === undefined) return undefined
+ const headers = { ...(entry.headers ?? {}) }
+ const cred = credentialOf(id)
+ if (entry.auth.kind === 'oauth' && cred !== undefined) Object.assign(headers, cred)
+ if (entry.auth.kind === 'key' && cred !== undefined) {
+ if (entry.auth.header) headers[entry.auth.header] = `${entry.auth.prefix ?? ''}${cred.key}`
+ else if (entry.auth.query) {
+ const parsed = new URL(url)
+ parsed.searchParams.set(entry.auth.query, cred.key)
+ url = String(parsed)
+ }
+ }
+ if (entry.custom !== undefined) {
+ for (const [name, raw] of Object.entries(entry.custom.headers ?? {})) {
+ headers[name] = String(raw).replace(SECRET_REF, (_m, n) => rt.secretValue(n) ?? '')
+ }
+ }
+ return { url, headers }
+ }
+
+ const gateway = async () => {
+ gateways.gw ??= createGateway({
+ credential: upstreamOf,
+ readOnly: id => state.connectors?.[id]?.readOnly === true,
+ onUnauthorized: id => refreshConnector(id),
+ log: (...args) => rt.warn(...args),
+ })
+ await gateways.gw.listen()
+ return gateways.gw
+ }
+
+ const loadMcpPlugin = async () => {
+ pluginP.p ??= (async () => {
+ const loader = ctx.get?.('loader')
+ if (typeof loader?.import !== 'function') throw new Error('This DSH cannot load connectors')
+ const mod = await loader.import(MCP_CLIENT)
+ return loader.unwrapExports?.(mod) ?? mod?.default ?? mod
+ })()
+ return pluginP.p
+ }
+
+ const resolveRefs = (value) => String(value).replace(SECRET_REF, (_m, name) => rt.secretValue(name) ?? '')
+
+ async function configFor(id) {
+ const entry = entryFor(id)
+ if (entry?.custom !== undefined && entry.custom.command !== undefined) {
+ const env = {}
+ for (const [key, raw] of Object.entries(entry.custom.env ?? {})) env[key] = resolveRefs(raw)
+ return { transport: 'stdio', serverName: id, command: entry.custom.command, args: entry.custom.args ?? [], env }
+ }
+ const gw = await gateway()
+ return { transport: 'streamable-http', serverName: id, url: gw.urlFor(id), headers: gw.headers() }
+ }
+
+ // A mount fingerprint covers the config a change must re-mount for; access and
+ // refresh tokens live in the gateway, so changing one never re-mounts.
+ async function fingerprint(id) {
+ const config = await configFor(id)
+ return JSON.stringify(config)
+ }
+
+ const unmount = async (id) => {
+ const mount = mounts.get(id)
+ mounts.delete(id)
+ if (mount?.fiber !== undefined) await Promise.resolve().then(() => mount.fiber.dispose()).catch(() => {})
+ }
+
+ async function mountOne(id) {
+ const fp = await fingerprint(id)
+ if (mounts.get(id)?.fp === fp) return
+ await unmount(id)
+ statuses.set(id, { state: 'connecting' })
+ try {
+ const plugin = await loadMcpPlugin()
+ if (stopped) return
+ const config = { ...(await configFor(id)), failOnStartupError: true }
+ const fiber = ctx.plugin(plugin, config)
+ const mount = { fp, fiber }
+ mounts.set(id, mount)
+ await fiber.await()
+ if (stopped || mounts.get(id) !== mount) return
+ statuses.delete(id)
+ settleRequests(id)
+ } catch (error) {
+ await unmount(id)
+ mounts.set(id, { fp })
+ statuses.set(id, { state: 'error', error: reason(error) })
+ rt.warn('ds-bot: connector %s failed: %s', id, statuses.get(id).error)
+ }
+ }
+
+ async function reconcile() {
+ for (const id of mounts.keys()) {
+ if (!hasCredential(id)) await unmount(id)
+ }
+ for (const entry of entries()) {
+ if (entry.id === 'mail' || !hasCredential(entry.id)) continue
+ await mountOne(entry.id)
+ }
+ }
+ const sync = (force = false) => {
+ queue = queue.then(async () => {
+ if (force) { for (const id of mounts.keys()) await unmount(id) }
+ await reconcile()
+ }).catch(error => rt.warn('ds-bot: connectors: %s', reason(error)))
+ return queue
+ }
+
+ // --- secrets ----------------------------------------------------------
+
+ const keptSecret = async (name) => { await rt.loadSecrets(); return rt.secretValue(name) !== undefined }
+ const writeSecret = async (name, value, purpose) => {
+ const kept = await keptSecret(name)
+ await rt.secretEndpoint('secret-set', { name, value, purpose, ...(kept ? {} : { scope: [] }) })
+ }
+ const dropSecrets = async (id) => {
+ await rt.loadSecrets()
+ for (const name of [tokenSecretOf(id), refreshSecretOf(id), clientSecretOf(id), keySecretOf(id)]) {
+ if (id !== 'github' || name === GITHUB_SECRET || name !== tokenSecretOf(id)) {
+ if (rt.secretValue(name) !== undefined) await rt.secretEndpoint('secret-delete', { name }).catch(() => {})
+ }
+ }
+ }
+ const saveState = async (id, patch) => {
+ state.connectors = { ...(state.connectors ?? {}), [id]: { ...state.connectors?.[id], ...patch } }
+ await rt.save()
+ }
+
+ // --- OAuth sign-in ----------------------------------------------------
+
+ const finishTokens = async (id, entry, tokens) => {
+ await writeSecret(tokenSecretOf(id), tokens.access_token, `${entry.name} connector`)
+ if (typeof tokens.refresh_token === 'string' && tokens.refresh_token !== '') {
+ await writeSecret(refreshSecretOf(id), tokens.refresh_token, `${entry.name} connector`).catch(() => {})
+ }
+ const account = await readAccount(id, entry, tokens.access_token).catch(() => undefined)
+ await saveState(id, { account, connectedAt: Date.now(), tokenExpiresAt: Number.isFinite(tokens.expires_in) ? Date.now() + tokens.expires_in * 1000 : undefined })
+ }
+
+ async function readAccount(id, entry, token) {
+ if (entry.whoami === undefined) return undefined
+ if (id === 'github') return (await signIn(token, { api: options.api })).login
+ const response = await fetch(entry.whoami.url, { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(CHECK_TIMEOUT_MS) })
+ if (!response.ok) return undefined
+ const body = await response.json().catch(() => ({}))
+ return typeof body?.[entry.whoami.field] === 'string' ? body[entry.whoami.field] : undefined
+ }
+
+ async function endPending(id, status) {
+ const pending = pendings.get(id)
+ pendings.delete(id)
+ if (pending?.timer !== undefined) clearTimeout(pending.timer)
+ if (pending?.listener !== undefined) await new Promise(resolve => pending.listener.close(resolve)).catch(() => {})
+ if (status !== undefined) statuses.set(id, status)
+ else statuses.delete(id)
+ }
+
+ // The loopback server for the browser flow: fixed port first, else a random one.
+ async function loopback(ready) {
+ const listener = createServer((req, res) => {
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
+ if (url.pathname !== '/callback') { res.writeHead(404); res.end(); return }
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
+ res.end('<!doctype html><title>Signed in</title><p style="font-family:sans-serif;margin:3em;text-align:center">Signed in — you can close this tab and go back to DS Bot.</p>')
+ void ready({ code: url.searchParams.get('code'), state: url.searchParams.get('state'), iss: url.searchParams.get('iss'), error: url.searchParams.get('error'), errorDescription: url.searchParams.get('error_description') })
+ })
+ const listen = port => new Promise((resolve, reject) => {
+ const onError = error => { listener.off('listening', onOk); reject(error) }
+ const onOk = () => { listener.off('error', onError); resolve() }
+ listener.once('error', onError)
+ listener.once('listening', onOk)
+ listener.listen(port, '127.0.0.1')
+ })
+ try {
+ await listen(oauth.FIXED_CALLBACK_PORT)
+ return { listener, fixed: true, redirectUri: `http://127.0.0.1:${oauth.FIXED_CALLBACK_PORT}/callback` }
+ } catch {
+ await listen(0)
+ const port = listener.address().port
+ return { listener, fixed: false, redirectUri: `http://127.0.0.1:${port}/callback` }
+ }
+ }
+
+ async function startBrowserFlow(id, entry, pending) {
+ const { listener, fixed, redirectUri } = await loopback(({ code, state, iss, error, errorDescription }) => completeBrowser(id, { code, state, iss, error, errorDescription }))
+ const saved = state.connectors?.[id]
+ const persist = async (client) => {
+ const { clientSecret, ...rest } = client
+ if (clientSecret !== undefined) await writeSecret(clientSecretOf(id), clientSecret, `${entry.name} connector`)
+ await saveState(id, { client: rest })
+ }
+ const resolved = await oauth.resolveClient(entry, pending.discovery, redirectUri, fixed, saved?.client ? { ...saved.client, clientSecret: rt.secretValue(clientSecretOf(id)) } : undefined, { persist })
+ if (resolved === null) {
+ pendings.set(id, { ...pending, listener, redirectUri })
+ statuses.set(id, { state: 'needs-client' })
+ return
+ }
+ const stateParam = randomBytes(16).toString('base64url')
+ const { url, codeVerifier } = await oauth.beginBrowser(pending.discovery, resolved.clientInformation, redirectUri, { state: stateParam })
+ pendings.set(id, {
+ ...pending, kind: 'browser', listener, redirectUri, codeVerifier, expectedState: stateParam,
+ clientInformation: resolved.clientInformation,
+ row: { kind: 'browser', url },
+ timer: setTimeout(() => void expire(id), SIGN_IN_TIMEOUT_MS),
+ })
+ statuses.set(id, { state: 'connecting' })
+ }
+
+ async function expire(id) {
+ await endPending(id, { state: 'off', error: 'Sign-in timed out' })
+ }
+
+ async function completeBrowser(id, result) {
+ const pending = pendings.get(id)
+ if (pending === undefined || pending.kind !== 'browser') return
+ try {
+ if (result.error !== null && result.error !== undefined) throw new Error(result.errorDescription ?? result.error)
+ if (result.state !== pending.expectedState) throw new Error('The sign-in answer did not match this attempt (state mismatch). Try again.')
+ const entry = entryFor(id)
+ const tokens = await oauth.exchange(pending.discovery, pending.clientInformation, { code: result.code, codeVerifier: pending.codeVerifier, redirectUri: pending.redirectUri, iss: result.iss ?? undefined })
+ await endPending(id)
+ await finishTokens(id, entry, tokens)
+ await sync(true)
+ } catch (error) {
+ await endPending(id, { state: 'error', error: reason(error) })
+ }
+ }
+
+ async function startDeviceFlow(id, entry, pending) {
+ const clientId = entry.auth.client.id
+ const device = await oauth.deviceBegin(clientId, (entry.auth.scopes ?? []).join(' '), { endpoints: rt.config.github?.endpoints })
+ const poll = async () => {
+ const current = pendings.get(id)
+ if (current === undefined || current.kind !== 'device' || stopped) return
+ if (Date.now() >= current.device.expiresAt) { await expire(id); return }
+ try {
+ const step = await oauth.devicePoll(clientId, current.device, { endpoints: rt.config.github?.endpoints })
+ if (step.state === 'done') {
+ await endPending(id)
+ await writeSecret(GITHUB_SECRET, step.token, 'GitHub connector')
+ const account = await readAccount(id, entry, step.token).catch(() => undefined)
+ await saveState(id, { account, connectedAt: Date.now() })
+ await sync(true)
+ return
+ }
+ if (step.state === 'error') { await endPending(id, { state: 'error', error: reason(step.error) }); return }
+ if (step.state === 'slow_down') current.interval += 5
+ } catch (error) {
+ await endPending(id, { state: 'error', error: reason(error) })
+ return
+ }
+ current.timer = setTimeout(() => void poll(), current.interval * 1000)
+ }
+ pendings.set(id, {
+ ...pending, kind: 'device', device, interval: device.interval,
+ row: { kind: 'device', userCode: device.userCode, verificationUri: device.verificationUri, expiresAt: device.expiresAt },
+ timer: setTimeout(() => void poll(), device.interval * 1000),
+ })
+ }
+
+ async function beginSignIn(id) {
+ const entry = known(id)
+ if (entry.auth.kind !== 'oauth') throw new Error('This connector does not sign in')
+ if (rt.readOnly() !== undefined) throw new Error(rt.readOnly())
+ await rt.loadSecrets()
+ if (pendings.has(id)) await endPending(id)
+ statuses.set(id, { state: 'connecting' })
+ try {
+ // GitHub's own flow: device code through github.com, no discovery.
+ if (entry.auth.client?.deviceFlow === true) {
+ await startDeviceFlow(id, entry, {})
+ return
+ }
+ const remote = entry.remote?.url
+ if (remote === undefined) throw new Error('This connector has no server address')
+ if (insecure(remote)) throw new Error('Connector addresses must start with https://')
+ const discovery = await oauth.discover(remote)
+ if (discovery.metadata === undefined) throw new Error('This service does not publish OAuth sign-in metadata')
+ state.connectors = { ...(state.connectors ?? {}), [id]: { ...state.connectors?.[id], oauth: { authorizationServerUrl: discovery.authorizationServerUrl, resource: discovery.resource, scope: discovery.scope } } }
+ await rt.save()
+ await startBrowserFlow(id, entry, { discovery })
+ } catch (error) {
+ await endPending(id)
+ statuses.set(id, { state: 'error', error: reason(error) })
+ }
+ }
+
+ // One refresh per connector at a time; read-only windows never write.
+ function refreshConnector(id) {
+ if (refreshes.has(id)) return refreshes.get(id)
+ const job = (async () => {
+ const saved = state.connectors?.[id]
+ const readOnly = rt.readOnly()
+ if (readOnly !== undefined) {
+ await rt.loadSecrets()
+ return false
+ }
+ const refresh = rt.secretValue(refreshSecretOf(id))
+ if (refresh === undefined || saved?.oauth === undefined) { statuses.set(id, { state: 'needs-sign-in' }); return false }
+ try {
+ const discovery = await oauth.rediscover(saved.oauth)
+ const client = saved.client?.clientId !== undefined
+ ? { client_id: saved.client.clientId, ...(rt.secretValue(clientSecretOf(id)) !== undefined ? { client_secret: rt.secretValue(clientSecretOf(id)) } : {}) }
+ : undefined
+ if (client === undefined) { statuses.set(id, { state: 'needs-client' }); return false }
+ const tokens = await oauth.refreshTokens(discovery, client, refresh, { scope: saved.oauth.scope })
+ const entry = entryFor(id)
+ await writeSecret(tokenSecretOf(id), tokens.access_token, `${entry.name} connector`)
+ if (typeof tokens.refresh_token === 'string' && tokens.refresh_token !== '' && tokens.refresh_token !== refresh) {
+ // Rotation: the old refresh token stays if this write fails.
+ await writeSecret(refreshSecretOf(id), tokens.refresh_token, `${entry.name} connector`).catch(() => {})
+ }
+ await saveState(id, { tokenExpiresAt: Number.isFinite(tokens.expires_in) ? Date.now() + tokens.expires_in * 1000 : undefined })
+ statuses.delete(id)
+ return true
+ } catch (error) {
+ if (oauth.invalidGrant(error)) statuses.set(id, { state: 'needs-sign-in', error: 'Sign in again' })
+ else statuses.set(id, { state: 'error', error: reason(error) })
+ return false
+ }
+ })().finally(() => refreshes.delete(id))
+ refreshes.set(id, job)
+ return job
+ }
+
+ // --- request cards (request_connector) ---------------------------------
+
+ const requestsOf = (botId) => {
+ const requests = (state.connectorRequests ??= {})
+ if (!Object.hasOwn(requests, botId) && rt.botOf(botId) === undefined) return []
+ return (requests[botId] ??= [])
+ }
+ const settleRequests = async (id) => {
+ const notes = []
+ for (const [botId, list] of Object.entries(state.connectorRequests ?? {})) {
+ for (const request of list) {
+ if (request.status !== 'pending' || request.connectorId !== id) continue
+ request.status = 'connected'
+ request.settledAt = Date.now()
+ const entry = entryFor(id)
+ notes.push([botId, `The user connected ${entry?.name ?? id}. Its tools are available as mcp__${id}__* now. Carry on with what you needed it for.`])
+ }
+ }
+ if (notes.length === 0) return
+ await rt.save()
+ for (const [botId, text] of notes) {
+ await rt.deliver({ toId: botId, role: 'connector', text }).catch(error => rt.warn('ds-bot: connector note to %s failed: %s', botId, error))
+ }
+ }
+
+ rt.teamTools.push(defineTool({
+ name: 'list_connectors',
+ description: 'List the connectors the team can use: name, what it offers, whether it is connected, and whether you may use it. Connect one for yourself with request_connector.',
+ parameters: {},
+ output,
+ async execute(_args, exec) {
+ await rt.load()
+ const self = rt.selfOf(exec.agent?.id)
+ const bot = rt.botOf(self)
+ if (!bot) return 'Only Bots on the team can use list_connectors.'
+ const rows = entries().filter(entry => entry.id !== 'mail' || mailHasAccounts())
+ if (rows.length === 0) return 'No connectors are set up.'
+ const lines = rows.map((entry) => {
+ const connected = entry.id === 'mail' ? mailHasAccounts() : (statuses.get(entry.id)?.state === undefined && mounts.has(entry.id)) || hasCredential(entry.id)
+ const usable = !offFor(entry.id).includes(bot.id)
+ return `- ${entry.name} (${entry.id}) — ${entry.about} — ${connected ? 'connected' : 'not connected'}${usable ? '' : '; turned off for you'}`
+ })
+ return ['Connectors:', ...lines].join('\n')
+ },
+ }))
+
+ rt.teamTools.push(defineTool({
+ name: 'request_connector',
+ description: 'Ask the user to connect an outside service through a card in your own chat, when you need a service that is not connected. The card shows a Connect button; your turn ends and a note arrives when the user connects or dismisses it. If the connector is already connected, this just tells you its tool prefix.',
+ parameters: {
+ id: { type: 'string', required: true, description: 'Connector id from list_connectors' },
+ purpose: { type: 'string', required: true, description: 'One short line for the user: what you need it for' },
+ },
+ output,
+ async execute(args, exec) {
+ await rt.load()
+ const id = String(args.id ?? '').trim()
+ const entry = id === 'mail' ? entryOf('mail') : entryFor(id)
+ if (entry === undefined) return `No connector named ${id}.`
+ const agentId = exec.agent?.id
+ const bot = rt.botOf(rt.selfOf(agentId))
+ if (bot === undefined) return 'Only Bots on the team can use request_connector.'
+ const connected = id === 'mail' ? mailHasAccounts() : hasCredential(id)
+ if (connected && !offFor(id).includes(bot.id)) return `${entry.name} is already connected; use its tools (mcp__${id}__*).`
+ if (offFor(id).includes(bot.id)) return `${entry.name} is turned off for you. The user can turn it on in your details.`
+ if (rt.groupOwners.has(agentId)) return 'Connector cards only work in your own chat. Tell the group you will ask the user in your own chat, and call request_connector there.'
+ if (!rt.chatOwners.has(agentId)) return 'Connector cards only work in your current own chat.'
+ const readOnly = rt.readOnly()
+ if (readOnly !== undefined) return `No card can be shown now. ${readOnly}`
+ const list = requestsOf(bot.id)
+ const now = Date.now()
+ for (const request of list) if (request.status === 'pending' && request.connectorId === id) { request.status = 'canceled'; request.settledAt = now }
+ list.push({
+ id: randomUUID(),
+ ...(exec.callId ? { callId: exec.callId } : {}),
+ sessionId: agentId,
+ connectorId: id,
+ purpose: String(args.purpose ?? '').trim().slice(0, 300),
+ status: 'pending',
+ askedAt: now,
+ })
+ while (list.length > MAX_REQUESTS) { const at = list.findIndex(entry => entry.status !== 'pending'); list.splice(at === -1 ? 0 : at, 1) }
+ await rt.save()
+ exec.concludeTurn?.()
+ return `The card asking the user to connect ${entry.name} is on screen. A note arrives when the user connects or dismisses it.`
+ },
+ }))
+
+ const offFor = id => state.connectors?.[id]?.offFor ?? []
+
+ // --- import -------------------------------------------------------------
+
+ const importFiles = () => {
+ const home = homedir()
+ const appData = platform() === 'win32' ? (process.env.APPDATA ?? join(home, 'AppData', 'Roaming')) : null
+ const files = [
+ { source: 'claude', key: 'mcpServers', path: platform() === 'darwin' ? join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json') : platform() === 'win32' ? join(appData, 'Claude', 'claude_desktop_config.json') : join(home, '.config', 'Claude', 'claude_desktop_config.json') },
+ { source: 'cursor', key: 'mcpServers', path: join(home, '.cursor', 'mcp.json') },
+ { source: 'vscode', key: 'servers', path: platform() === 'darwin' ? join(home, 'Library', 'Application Support', 'Code', 'User', 'mcp.json') : platform() === 'win32' ? join(appData, 'Code', 'User', 'mcp.json') : join(home, '.config', 'Code', 'User', 'mcp.json') },
+ ]
+ return files
+ }
+ const importScan = async () => {
+ const found = []
+ for (const file of importFiles()) {
+ let parsed
+ try { parsed = JSON.parse(await readFile(file.path, 'utf8')) } catch { continue }
+ const servers = parsed?.[file.key]
+ if (servers === null || typeof servers !== 'object' || Array.isArray(servers)) continue
+ for (const [name, spec] of Object.entries(servers)) {
+ if (spec === null || typeof spec !== 'object') continue
+ const url = typeof spec.url === 'string' ? spec.url : typeof spec.serverUrl === 'string' ? spec.serverUrl : undefined
+ const command = typeof spec.command === 'string' ? spec.command : undefined
+ if (url === undefined && command === undefined) continue
+ found.push({
+ source: file.source,
+ name,
+ ...(url !== undefined ? { url } : { command, args: Array.isArray(spec.args) ? spec.args.filter(arg => typeof arg === 'string') : [] }),
+ envNames: Object.keys(spec.env ?? {}),
+ headersNames: Object.keys(spec.headers ?? {}),
+ })
+ }
+ }
+ return found
+ }
+ const importPick = async (items) => {
+ const scanned = await importScan()
+ const wanted = new Set((Array.isArray(items) ? items : []).map(item => `${item?.source ?? ''}:${item?.name ?? ''}`))
+ const picked = []
+ for (const file of importFiles()) {
+ let parsed
+ try { parsed = JSON.parse(await readFile(file.path, 'utf8')) } catch { continue }
+ const servers = parsed?.[file.key] ?? {}
+ for (const [name, spec] of Object.entries(servers)) {
+ if (!wanted.has(`${file.source}:${name}`) || spec === null || typeof spec !== 'object') continue
+ if (scanned.some(entry => entry.source === file.source && entry.name === name)) picked.push({ name, spec })
+ }
+ }
+ return picked
+ }
+
+ // --- view & endpoints ---------------------------------------------------
+
+ const rowFor = (entry) => {
+ const saved = state.connectors?.[entry.id]
+ const status = statuses.get(entry.id)
+ const connected = hasCredential(entry.id)
+ const remote = entry.custom === undefined || entry.custom.url !== undefined
+ const state_ = status?.state ?? (connected && mounts.has(entry.id) ? 'ready' : connected ? 'connecting' : 'off')
+ return {
+ id: entry.id,
+ name: entry.name,
+ category: entry.category,
+ about: entry.about,
+ auth: entry.auth,
+ state: state_,
+ ...(status?.error !== undefined ? { error: status.error } : {}),
+ account: saved?.account ?? (id => id === 'github' ? saved?.login : undefined)(entry.id) ?? null,
+ ...(remote && connected && entry.auth.kind !== 'none' ? { readOnly: saved?.readOnly === true } : {}),
+ ...(remote && connected && (entry.auth.kind === 'oauth' || entry.auth.kind === 'key') ? { readOnly: saved?.readOnly === true } : {}),
+ offFor: saved?.offFor ?? [],
+ tools: gateways.gw?.toolCount?.(entry.id) ?? 0,
+ ...(entry.custom !== undefined ? { custom: true } : {}),
+ ...(pendings.has(entry.id) ? { pending: pendings.get(entry.id).row } : {}),
+ }
+ }
+
+ const connectorsView = () => ({
+ connectors: entries().filter(entry => entry.id !== 'mail').map(rowFor),
+ mail: rt.mailView?.() ?? { accounts: [], google: false },
+ })
+
+ const endpoints = {
+ async 'connector-connect'(body) {
+ const entry = known(body.id)
+ if (entry.id === 'github' && options === null) throw new Error('No such connector')
+ if (entry.auth.kind === 'none') {
+ await saveState(entry.id, { connectedAt: Date.now() })
+ await sync()
+ return connectorsView()
+ }
+ if (entry.auth.kind === 'key') {
+ const key = typeof body.key === 'string' ? body.key.trim() : ''
+ if (key === '') throw new Error('Paste a key first')
+ const remote = entry.remote?.url
+ if (remote !== undefined && insecure(remote)) throw new Error('Connector addresses must start with https://')
+ await writeSecret(keySecretOf(entry.id), key, `${entry.name} connector`)
+ await saveState(entry.id, { connectedAt: Date.now() })
+ await sync()
+ return connectorsView()
+ }
+ const token = typeof body.token === 'string' ? body.token.trim() : ''
+ if (token !== '') {
+ const remote = entry.remote?.url
+ if (remote !== undefined && insecure(remote)) throw new Error('Connector addresses must start with https://')
+ if (entry.id === 'github' && options?.api !== undefined && insecure(options.api)) throw new Error('GitHub addresses must start with https://')
+ await rt.loadSecrets()
+ let account
+ if (entry.id === 'github') account = (await signIn(token, { api: options.api })).login
+ else if (entry.whoami !== undefined) account = await readAccount(entry.id, entry, token)
+ await writeSecret(tokenSecretOf(entry.id), token, `${entry.name} connector`)
+ await saveState(entry.id, { account, ...(entry.id === 'github' ? { login: account } : {}), connectedAt: Date.now() })
+ await sync()
+ return connectorsView()
+ }
+ if (entry.id === 'github' && (entry.auth.client?.id ?? '') === '') throw new Error('Paste a token first')
+ await beginSignIn(entry.id)
+ return connectorsView()
+ },
+ async 'connector-disconnect'(body) {
+ const entry = known(body.id)
+ await endPending(entry.id)
+ await dropSecrets(entry.id)
+ if (state.connectors?.[entry.id] !== undefined) {
+ delete state.connectors[entry.id]
+ await rt.save()
+ }
+ gateways.gw?.forget(entry.id)
+ await sync()
+ return connectorsView()
+ },
+ async 'connector-retry'(body) {
+ const entry = known(body.id)
+ statuses.delete(entry.id)
+ await rt.loadSecrets()
+ await sync(true)
+ return connectorsView()
+ },
+ async 'connector-cancel'(body) {
+ const entry = known(body.id)
+ await endPending(entry.id, { state: hasCredential(entry.id) ? 'ready' : 'off' })
+ return connectorsView()
+ },
+ async 'connector-sign-in-code'(body) {
+ const entry = known(body.id)
+ const pending = pendings.get(entry.id)
+ if (pending === undefined || pending.kind !== 'browser') throw new Error('No sign-in is waiting')
+ const input = String(body.input ?? body.code ?? '').trim()
+ if (input === '') throw new Error('Paste the address or the code')
+ let code = input, stateParam, iss
+ if (/^https?:\/\//i.test(input)) {
+ const url = new URL(input)
+ code = url.searchParams.get('code') ?? ''
+ stateParam = url.searchParams.get('state')
+ iss = url.searchParams.get('iss') ?? undefined
+ if (stateParam !== pending.expectedState) throw new Error('This address is not from this sign-in attempt (state mismatch). Copy the whole address again.')
+ }
+ if (code === '') throw new Error('The address has no code')
+ await completeBrowser(entry.id, { code, state: pending.expectedState, iss })
+ return connectorsView()
+ },
+ async 'connector-client'(body) {
+ const entry = known(body.id)
+ const clientId = String(body.clientId ?? '').trim()
+ if (clientId === '') throw new Error('Enter the client ID')
+ const clientSecret = typeof body.clientSecret === 'string' && body.clientSecret.trim() !== '' ? body.clientSecret.trim() : undefined
+ if (clientSecret !== undefined) await writeSecret(clientSecretOf(entry.id), clientSecret, `${entry.name} connector`)
+ await saveState(entry.id, { client: { via: 'manual', clientId } })
+ const pending = pendings.get(entry.id)
+ if (pending !== undefined && pending.discovery !== undefined) {
+ await startBrowserFlow(entry.id, entry, pending)
+ }
+ return connectorsView()
+ },
+ async 'connector-set'(body) {
+ const entry = known(body.id)
+ const patch = {}
+ if (body.readOnly !== undefined) patch.readOnly = body.readOnly === true
+ if (Array.isArray(body.offFor)) patch.offFor = [...new Set(body.offFor.filter(id => rt.botOf(id) !== undefined))]
+ await saveState(entry.id, patch)
+ rt.reapplyToolMasks?.()
+ return connectorsView()
+ },
+ async 'connector-add'(body) {
+ const name = String(body.name ?? '').trim()
+ if (name === '') throw new Error('Name the connector')
+ const url = typeof body.url === 'string' ? body.url.trim() : undefined
+ const command = typeof body.command === 'string' ? body.command.trim() : undefined
+ if (url !== undefined && insecure(url) && !/^http:\/\/(localhost|127\.)/i.test(url)) throw new Error('Connector addresses must start with https://')
+ if (url === undefined && command === undefined) throw new Error('Enter an address or a command')
+ const taken = new Set(Object.keys(state.connectors ?? {}))
+ const id = customId(name, taken)
+ CONNECTOR_IDS.add(id)
+ const custom = url !== undefined
+ ? { name, url, headers: body.headers && typeof body.headers === 'object' ? body.headers : {} }
+ : { name, command, args: Array.isArray(body.args) ? body.args.map(String) : [], env: body.env && typeof body.env === 'object' ? body.env : {} }
+ await saveState(id, { custom, connectedAt: Date.now() })
+ await sync(true)
+ return connectorsView()
+ },
+ async 'connector-remove'(body) {
+ const entry = known(body.id)
+ if (entry.custom === undefined) throw new Error('Only added connectors can be removed')
+ await endpoints['connector-disconnect']({ id: entry.id })
+ return connectorsView()
+ },
+ async 'connector-import-scan'() {
+ return importScan()
+ },
+ async 'connector-import'(body) {
+ const picked = await importPick(body.items)
+ const created = []
+ for (const { name, spec } of picked) {
+ const taken = new Set(Object.keys(state.connectors ?? {}))
+ const id = customId(name, taken)
+ const custom = { name }
+ if (typeof spec.url === 'string' || typeof spec.serverUrl === 'string') {
+ custom.url = spec.url ?? spec.serverUrl
+ custom.headers = {}
+ for (const [header, raw] of Object.entries(spec.headers ?? {})) {
+ const secretName = envSecretOf(id, `HEAD_${header}`)
+ await writeSecret(secretName, String(raw), `${name} connector`)
+ custom.headers[header] = `$DSH_SECRET_${secretName}`
+ }
+ } else if (typeof spec.command === 'string') {
+ custom.command = spec.command
+ custom.args = Array.isArray(spec.args) ? spec.args.map(String) : []
+ custom.env = {}
+ for (const [envName, raw] of Object.entries(spec.env ?? {})) {
+ const secretName = envSecretOf(id, envName)
+ await writeSecret(secretName, String(raw), `${name} connector`)
+ custom.env[envName] = `$DSH_SECRET_${secretName}`
+ }
+ } else continue
+ await saveState(id, { custom, connectedAt: Date.now() })
+ created.push(id)
+ }
+ await sync(true)
+ return { view: connectorsView(), created }
+ },
+ async 'connector-request-cancel'(body) {
+ const found = (() => {
+ for (const [botId, list] of Object.entries(state.connectorRequests ?? {})) {
+ const request = list.find(entry => entry.id === String(body.requestId ?? ''))
+ if (request !== undefined) return { botId, request }
+ }
+ return undefined
+ })()
+ if (found === undefined) throw new Error('This request is gone')
+ if (found.request.status !== 'pending') throw new Error('This request was already answered')
+ found.request.status = 'canceled'
+ found.request.settledAt = Date.now()
+ await rt.save()
+ await rt.deliver({ toId: found.botId, role: 'connector', text: `The user dismissed your request to connect ${entryFor(found.request.connectorId)?.name ?? found.request.connectorId}. Carry on without it, or tell the user what you cannot do without it.` }).catch(() => {})
+ return true
+ },
+ }
+
+ const mailApi = installMail(rt, { entries: () => entries().find(e => e.id === 'mail'), offFor, secrets: { writeSecret, value: name => rt.secretValue(name) }, reason })
+ const mailHasAccounts = () => mailApi.hasAccounts()
+ rt.mailView = mailApi.mailView
+
+ const connectorEndpoint = async (endpoint, body) => {
+ await rt.loadSecrets()
+ if (endpoint.startsWith('mail-')) return mailApi.endpoint(endpoint, body)
+ return endpoints[endpoint](body ?? {})
+ }
+
+ ctx.on('tools/change', () => { rt.reapplyToolMasks?.() })
+
+ ctx.effect(() => {
+ stopped = false
+ void rt.load().then(() => rt.loadSecrets()).then(() => sync())
+ return () => {
+ stopped = true
+ for (const pending of pendings.values()) if (pending.timer !== undefined) clearTimeout(pending.timer)
+ for (const pending of pendings.values()) pending.listener?.close()
+ pendings.clear()
+ const closing = [...mounts.values()].map(mount => Promise.resolve().then(() => mount.fiber?.dispose()).catch(() => {}))
+ mounts.clear()
+ const gw = gateways.gw
+ gateways.gw = null
+ return Promise.all([...closing, gw?.close(), mailApi.dispose()])
+ }
+ }, 'ds-bot: connectors')
+
+ Object.assign(rt, {
+ connectorsView,
+ connectorEndpoint,
+ connectorOffFor: (botId) => {
+ const prefixes = []
+ for (const entry of entries()) {
+ if (!offFor(entry.id).includes(botId)) continue
+ if (entry.id === 'mail') prefixes.push('mail_')
+ else prefixes.push(`mcp__${entry.id}__`)
+ }
+ return prefixes
+ },
+ connectorSettleRequests: settleRequests,
+ secretsChanged: () => { void sync() },
+ connectorsInternals: { mounts, statuses, pendings, gateways, refreshConnector, upstreamOf },
+ })
+}
diff --git a/ds-bot/src/host/connectors/mail/index.js b/ds-bot/src/host/connectors/mail/index.js
new file mode 100644
index 00000000..2fbc15fe
--- /dev/null
+++ b/ds-bot/src/host/connectors/mail/index.js
@@ -0,0 +1,437 @@
+// The mailbox connector: mail accounts (IMAP+SMTP app password, or Gmail with
+// Google sign-in) in state.connectors.mail.accounts, the mail_* Bot tools, the
+// send card, and the mail-* endpoints. Transports come from transport.js;
+// rt.config.mail.connect injects fakes in tests.
+import { randomUUID } from 'node:crypto'
+import { join } from 'node:path'
+import { defineTool } from '@deepseek-ai/dsh-tools'
+import { PRESETS, presetOf, mailSecretName } from './presets.js'
+import { connectImap, connectGmail } from './transport.js'
+import { output } from '../../tools.js'
+import { refreshTokens, invalidGrant, discover, beginBrowser, exchange } from '../oauth.js'
+
+const GOOGLE_SCOPES = 'openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/gmail.modify'
+const MAX_REQUESTS = 20
+
+export function install(rt, host) {
+ const { state } = rt
+ const sessions = new Map()
+
+ const accounts = () => state.connectors?.mail?.accounts ?? {}
+ const accountList = () => Object.values(accounts())
+ const hasAccounts = () => accountList().length > 0
+ const accountOf = (ref) => {
+ const list = accountList()
+ if (ref === undefined || ref === '') return list.length === 1 ? list[0] : undefined
+ return list.find(account => account.address === String(ref).toLowerCase() || account.id === ref)
+ }
+
+ const googleClient = () => ({
+ id: process.env.DS_BOT_GOOGLE_OAUTH_CLIENT_ID,
+ secret: process.env.DS_BOT_GOOGLE_OAUTH_CLIENT_SECRET,
+ })
+ const googleReady = () => Boolean(googleClient().id && googleClient().secret)
+
+ async function connect(account) {
+ const key = account.id
+ const live = sessions.get(key)
+ if (live !== undefined) return live
+ const make = async () => {
+ if (account.auth === 'google') {
+ const token = () => rt.secretValue(mailSecretName(account.address, 'TOKEN'))
+ const session = connectGmail(account, { token, fetch: rt.config.mail?.fetch, refresh: () => refreshGoogle(account) })
+ sessions.set(key, session)
+ return session
+ }
+ const password = rt.secretValue(mailSecretName(account.address, 'PASSWORD'))
+ if (password === undefined) throw new Error(`The password for ${account.address} is not saved`)
+ const factory = rt.config.mail?.connect ?? connectImap
+ const session = await factory(account, { password })
+ sessions.set(key, session)
+ return session
+ }
+ try {
+ return await make()
+ } catch (error) {
+ sessions.delete(key)
+ throw error
+ }
+ }
+
+ // Gmail tokens refresh through the same OAuth rules as connectors.
+ async function refreshGoogle(account) {
+ if (rt.readOnly() !== undefined) { await rt.loadSecrets(); return false }
+ const refresh = rt.secretValue(mailSecretName(account.address, 'REFRESH'))
+ if (refresh === undefined) return false
+ try {
+ const client = googleClient()
+ const tokens = await refreshTokens(
+ { authorizationServerUrl: 'https://accounts.google.com', metadata: undefined, resource: undefined },
+ { client_id: client.id, client_secret: client.secret },
+ refresh,
+ { scope: GOOGLE_SCOPES, fetch: rt.config.mail?.fetch },
+ )
+ await host.secrets.writeSecret(mailSecretName(account.address, 'TOKEN'), tokens.access_token, `Mailbox ${account.address}`)
+ if (typeof tokens.refresh_token === 'string' && tokens.refresh_token !== '') {
+ await host.secrets.writeSecret(mailSecretName(account.address, 'REFRESH'), tokens.refresh_token, `Mailbox ${account.address}`).catch(() => {})
+ }
+ return true
+ } catch (error) {
+ if (invalidGrant(error)) account.error = 'Sign in again'
+ return false
+ }
+ }
+
+ const workDir = (exec) => rt.sessionFolder?.(exec.agent?.session ?? exec.agent)
+
+ const toolExec = async (exec, args, run) => {
+ await rt.load()
+ const self = rt.selfOf(exec.agent?.id)
+ const bot = rt.botOf(self)
+ if (!bot) return 'Only Bots on the team can use the mail tools.'
+ if ((state.connectors?.mail?.offFor ?? []).includes(bot.id)) return 'The mailbox is turned off for you.'
+ const account = accountOf(args.account)
+ if (account === undefined) return accountList().length === 0 ? 'No mail account is added yet.' : `Name the account: ${accountList().map(a => a.address).join(', ')}`
+ try {
+ const session = await connect(account)
+ return await run(session, account, bot)
+ } catch (error) {
+ sessions.delete(account.id)
+ throw error
+ }
+ }
+
+ const tools = [
+ defineTool({
+ name: 'mail_search',
+ description: 'Search mail in a connected mailbox. Returns matching messages with uid, from, to, subject, and date.',
+ parameters: {
+ account: { type: 'string', description: 'Account address; needed only when more than one is added' },
+ from: { type: 'string' }, to: { type: 'string' }, subject: { type: 'string' }, text: { type: 'string' },
+ since: { type: 'string', description: 'ISO date' }, before: { type: 'string', description: 'ISO date' },
+ unread: { type: 'boolean' }, folder: { type: 'string', description: 'Folder name, default INBOX' },
+ limit: { type: 'number', description: 'Max results, default 20' },
+ },
+ output,
+ async execute(args, exec) {
+ return toolExec(exec, args, async (session) => {
+ const rows = await session.search({ folder: args.folder, from: args.from, to: args.to, subject: args.subject, text: args.text, since: args.since, before: args.before, unread: args.unread === true, limit: args.limit ?? 20 })
+ if (rows.length === 0) return 'No matching mail.'
+ return rows.map(row => `- [${row.uid}] ${row.date} ${row.from} → ${row.to} — ${row.subject}${row.seen ? '' : ' (unread)'}${row.flagged ? ' ★' : ''}`).join('\n')
+ })
+ },
+ }),
+ defineTool({
+ name: 'mail_read',
+ description: 'Read one message or its whole thread: headers, text body, and attachment names. save_attachments writes the files into your working folder.',
+ parameters: {
+ account: { type: 'string', description: 'Account address; needed only when more than one is added' },
+ uid: { type: 'string', required: true, description: 'Message uid from mail_search' },
+ folder: { type: 'string' }, thread: { type: 'boolean' },
+ save_attachments: { type: 'boolean', description: 'Save every attachment into your working folder' },
+ },
+ output,
+ async execute(args, exec) {
+ return toolExec(exec, args, async (session) => {
+ const { messages } = await session.read({ uid: String(args.uid), folder: args.folder, thread: args.thread === true })
+ const saved = []
+ if (args.save_attachments === true) {
+ const dir = workDir(exec)
+ for (const message of messages) {
+ for (const attachment of message.attachments ?? []) {
+ if (dir === undefined) break
+ const target = join(dir, attachment.filename)
+ await session.saveAttachment({ uid: message.uid, folder: message.folder, filename: attachment.filename, to: target })
+ saved.push(attachment.filename)
+ }
+ }
+ }
+ const body = messages.map(message => [
+ `From: ${message.from}\nTo: ${message.to}${message.cc ? `\nCc: ${message.cc}` : ''}\nDate: ${message.date}\nSubject: ${message.subject}`,
+ message.attachments?.length ? `Attachments: ${message.attachments.map(a => `${a.filename} (${a.size} bytes)`).join(', ')}` : '',
+ message.text,
+ ].filter(Boolean).join('\n')).join('\n\n---\n\n')
+ return saved.length > 0 ? `${body}\n\nSaved attachments: ${saved.join(', ')}` : body
+ })
+ },
+ }),
+ defineTool({
+ name: 'mail_draft',
+ description: 'Save a draft in the mailbox Drafts folder. It is not sent.',
+ parameters: {
+ account: { type: 'string' },
+ to: { type: 'string', required: true }, cc: { type: 'string' }, bcc: { type: 'string' },
+ subject: { type: 'string', required: true }, body: { type: 'string', required: true },
+ },
+ output,
+ async execute(args, exec) {
+ return toolExec(exec, args, async (session, account) => {
+ await session.draft({ to: args.to, cc: args.cc, bcc: args.bcc, subject: args.subject, text: args.body })
+ return `Draft saved in ${account.address}'s Drafts folder. It was not sent.`
+ })
+ },
+ }),
+ defineTool({
+ name: 'mail_send',
+ description: 'Send an email. The user sees a card in your own chat with the full message and must press Send; nothing goes out before that. Showing the card ends your turn; a note arrives with the answer.',
+ parameters: {
+ account: { type: 'string' },
+ to: { type: 'string', required: true }, cc: { type: 'string' }, bcc: { type: 'string' },
+ subject: { type: 'string', required: true }, body: { type: 'string', required: true },
+ attachments: { type: 'array', items: { type: 'string' }, description: 'File names in your working folder' },
+ reply_to: { type: 'string', description: 'Message uid this answers' },
+ },
+ output,
+ async execute(args, exec) {
+ await rt.load()
+ const self = rt.selfOf(exec.agent?.id)
+ const bot = rt.botOf(self)
+ if (!bot) return 'Only Bots on the team can use mail_send.'
+ if ((state.connectors?.mail?.offFor ?? []).includes(bot.id)) return 'The mailbox is turned off for you.'
+ const account = accountOf(args.account)
+ if (account === undefined) return accountList().length === 0 ? 'No mail account is added yet.' : `Name the account: ${accountList().map(a => a.address).join(', ')}`
+ if (rt.groupOwners.has(exec.agent?.id)) return 'Send cards only work in your own chat. Draft it here with mail_draft, or call mail_send in your own chat.'
+ if (!rt.chatOwners.has(exec.agent?.id)) return 'Send cards only work in your current own chat.'
+ const readOnly = rt.readOnly()
+ if (readOnly !== undefined) return `No card can be shown now. ${readOnly}`
+ const list = (state.mailRequests ??= {})[bot.id] ??= []
+ const request = {
+ id: randomUUID(),
+ ...(exec.callId ? { callId: exec.callId } : {}),
+ sessionId: exec.agent?.id,
+ account: account.id,
+ to: String(args.to ?? ''), cc: String(args.cc ?? ''), bcc: String(args.bcc ?? ''),
+ subject: String(args.subject ?? ''), body: String(args.body ?? ''),
+ attachments: (Array.isArray(args.attachments) ? args.attachments : []).map(String),
+ dir: workDir(exec),
+ replyTo: args.reply_to ? String(args.reply_to) : undefined,
+ status: 'pending', askedAt: Date.now(),
+ }
+ for (const old of list) if (old.status === 'pending') { old.status = 'canceled'; old.settledAt = Date.now() }
+ list.push(request)
+ while (list.length > MAX_REQUESTS) { const at = list.findIndex(entry => entry.status !== 'pending'); list.splice(at === -1 ? 0 : at, 1) }
+ await rt.save()
+ exec.concludeTurn?.()
+ return `The send card for "${request.subject}" is on screen. Nothing is sent until the user presses Send; a note arrives with the answer.`
+ },
+ }),
+ defineTool({
+ name: 'mail_update',
+ description: 'Mark a message read or unread, flag or unflag it, or move it to another folder or the Trash. Mail is never deleted permanently.',
+ parameters: {
+ account: { type: 'string' },
+ uid: { type: 'string', required: true }, folder: { type: 'string' },
+ seen: { type: 'boolean' }, flagged: { type: 'boolean' },
+ move: { type: 'string', description: 'Folder name, or "trash"' },
+ },
+ output,
+ async execute(args, exec) {
+ return toolExec(exec, args, async (session) => {
+ await session.update({ uid: String(args.uid), folder: args.folder, seen: args.seen, flagged: args.flagged, move: args.move })
+ return 'Done.'
+ })
+ },
+ }),
+ ]
+
+ // Mail tools are registered only while at least one account exists.
+ let toolsOn = false
+ const syncTools = () => {
+ const want = hasAccounts()
+ if (want === toolsOn) return
+ toolsOn = want
+ for (const tool of tools) {
+ if (want) rt.addTeamTool?.(tool)
+ else rt.removeTeamTool?.(tool.name)
+ }
+ }
+
+ const tell = async (botId, text) => {
+ if (rt.botOf(botId) === undefined) return
+ await rt.deliver({ toId: botId, role: 'mail', text }).catch(error => rt.warn('ds-bot: mail note to %s failed: %s', botId, error))
+ }
+
+ const endpoints = {
+ async 'mail-account-add'(body) {
+ const address = String(body.address ?? '').trim().toLowerCase()
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address)) throw new Error('Enter an email address')
+ if (body.google === true) {
+ if (!googleReady()) throw new Error('Google sign-in is not available in this build')
+ return beginGoogle(address)
+ }
+ const password = String(body.password ?? '').trim()
+ if (password === '') throw new Error('Enter the app password')
+ const preset = presetOf(address)
+ const provider = typeof body.provider === 'string' ? body.provider : preset?.id ?? 'other'
+ const chosen = PRESETS.find(p => p.id === provider)
+ const imap = chosen && provider !== 'other' ? chosen.imap : { host: String(body.imapHost ?? '').trim(), port: Number(body.imapPort) || 993, secure: body.imapTls !== false }
+ const smtp = chosen && provider !== 'other' ? chosen.smtp : { host: String(body.smtpHost ?? '').trim(), port: Number(body.smtpPort) || 465, secure: body.smtpTls !== false }
+ if (imap.host === '' || smtp.host === '') throw new Error('Enter the IMAP and SMTP hosts')
+ const id = `m${randomUUID().slice(0, 8)}`
+ const account = { id, address, provider, auth: 'password', imap, smtp, createdAt: Date.now() }
+ // Log in once before saving, so a bad password never lands in state.
+ const factory = rt.config.mail?.connect ?? connectImap
+ let session
+ try {
+ session = await factory(account, { password })
+ } catch (error) {
+ throw new Error(mailError(error))
+ }
+ state.connectors = { ...(state.connectors ?? {}), mail: { ...state.connectors?.mail, accounts: { ...accounts(), [id]: account } } }
+ await host.secrets.writeSecret(mailSecretName(address, 'PASSWORD'), password, `Mailbox ${address}`)
+ await rt.save()
+ sessions.set(id, session)
+ syncTools()
+ return mailView()
+ },
+ async 'mail-account-remove'(body) {
+ const account = accountOf(body.id ?? body.address)
+ if (account === undefined) throw new Error('No such account')
+ await rt.loadSecrets()
+ for (const suffix of ['PASSWORD', 'TOKEN', 'REFRESH']) {
+ const name = mailSecretName(account.address, suffix)
+ if (rt.secretValue(name) !== undefined) await rt.secretEndpoint('secret-delete', { name }).catch(() => {})
+ }
+ const rest = { ...accounts() }
+ delete rest[account.id]
+ state.connectors = { ...state.connectors, mail: { ...state.connectors.mail, accounts: rest } }
+ await rt.save()
+ const session = sessions.get(account.id)
+ sessions.delete(account.id)
+ await session?.close?.().catch(() => {})
+ syncTools()
+ return mailView()
+ },
+ async 'mail-send-answer'(body) {
+ const found = (() => {
+ for (const [botId, list] of Object.entries(state.mailRequests ?? {})) {
+ const request = list.find(entry => entry.id === String(body.requestId ?? ''))
+ if (request !== undefined) return { botId, request }
+ }
+ return undefined
+ })()
+ if (found === undefined || found.request.status !== 'pending') throw new Error('This card was already answered')
+ const { botId, request } = found
+ if (body.choice !== 'send') {
+ request.status = 'canceled'; request.settledAt = Date.now()
+ await rt.save()
+ await tell(botId, `The user canceled sending "${request.subject}". Nothing was sent.`)
+ return true
+ }
+ const account = accounts()[request.account]
+ if (account === undefined) {
+ request.status = 'failed'; request.settledAt = Date.now()
+ await rt.save()
+ await tell(botId, `The account for "${request.subject}" is gone, so nothing was sent.`)
+ return true
+ }
+ try {
+ const session = await connect(account)
+ const attachments = (request.attachments ?? []).map(name => ({ filename: name, path: join(request.dir ?? '', name) }))
+ await session.send({ to: request.to, cc: request.cc || undefined, bcc: request.bcc || undefined, subject: request.subject, text: request.body, attachments, ...(request.replyTo ? { inReplyTo: request.replyTo } : {}) })
+ request.status = 'sent'; request.settledAt = Date.now()
+ await rt.save()
+ await tell(botId, `The user sent "${request.subject}" to ${request.to} from ${account.address}.`)
+ } catch (error) {
+ request.status = 'failed'; request.settledAt = Date.now()
+ request.error = host.reason(error)
+ await rt.save()
+ await tell(botId, `Sending "${request.subject}" failed: ${request.error}. You can try mail_send again.`)
+ }
+ return true
+ },
+ async 'mail-sign-in-code'(body) {
+ return googleCode(body)
+ },
+ }
+
+ // --- Google sign-in ------------------------------------------------------
+
+ const googlePendings = new Map()
+ async function beginGoogle(address) {
+ const client = googleClient()
+ const discovery = await discover('https://accounts.google.com', { originFallback: true, fetch: rt.config.mail?.fetch ?? fetch })
+ const pending = { discovery, address }
+ googlePendings.set(address, pending)
+ const { createServer } = await import('node:http')
+ const listener = createServer((req, res) => {
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
+ res.writeHead(200, { 'content-type': 'text/html' })
+ res.end('<p style="font-family:sans-serif">Signed in — you can close this tab.</p>')
+ void googleCode({ address, input: url.toString() })
+ })
+ await new Promise((resolve, reject) => { listener.once('error', reject); listener.listen(0, '127.0.0.1', resolve) })
+ pending.listener = listener
+ pending.redirectUri = `http://127.0.0.1:${listener.address().port}/callback`
+ const { url, codeVerifier } = await beginBrowser(discovery, { client_id: client.id, client_secret: client.secret }, pending.redirectUri, { state: randomUUID(), scope: GOOGLE_SCOPES })
+ pending.codeVerifier = codeVerifier
+ pending.url = url
+ return mailView()
+ }
+ async function googleCode(body) {
+ const address = String(body.address ?? '').toLowerCase()
+ const pending = googlePendings.get(address) ?? [...googlePendings.values()][0]
+ if (pending === undefined) throw new Error('No Google sign-in is waiting')
+ const input = String(body.input ?? '').trim()
+ const url = /^https?:/i.test(input) ? new URL(input) : undefined
+ const code = url ? url.searchParams.get('code') : input
+ if (!code) throw new Error('The address has no code')
+ const client = googleClient()
+ const tokens = await exchange(pending.discovery, { client_id: client.id, client_secret: client.secret }, { code, codeVerifier: pending.codeVerifier, redirectUri: pending.redirectUri, iss: url?.searchParams.get('iss') ?? undefined }, { fetch: rt.config.mail?.fetch })
+ const email = pending.address || await googleEmail(tokens.access_token)
+ const id = `g${randomUUID().slice(0, 8)}`
+ const account = { id, address: email, provider: 'gmail', auth: 'google', createdAt: Date.now() }
+ state.connectors = { ...(state.connectors ?? {}), mail: { ...state.connectors?.mail, accounts: { ...accounts(), [id]: account } } }
+ await host.secrets.writeSecret(mailSecretName(email, 'TOKEN'), tokens.access_token, `Mailbox ${email}`)
+ if (typeof tokens.refresh_token === 'string') await host.secrets.writeSecret(mailSecretName(email, 'REFRESH'), tokens.refresh_token, `Mailbox ${email}`)
+ await rt.save()
+ pending.listener?.close()
+ googlePendings.delete(pending.address)
+ syncTools()
+ return mailView()
+ }
+ async function googleEmail(token) {
+ const response = await (rt.config.mail?.fetch ?? fetch)('https://openidconnect.googleapis.com/v1/userinfo', { headers: { Authorization: `Bearer ${token}` } })
+ const body = await response.json().catch(() => ({}))
+ if (typeof body.email !== 'string') throw new Error('Google did not say which account this is')
+ return body.email.toLowerCase()
+ }
+
+ const mailView = () => ({
+ accounts: accountList().map(account => ({
+ id: account.id, address: account.address, provider: account.provider, auth: account.auth,
+ state: account.error ? 'error' : 'ready',
+ ...(account.error ? { error: account.error } : {}),
+ })),
+ google: googleReady(),
+ ...(googlePendings.size > 0 ? { pending: [...googlePendings.values()].map(p => ({ kind: 'browser', url: p.url, address: p.address })) } : {}),
+ })
+
+ syncTools()
+
+ return {
+ hasAccounts,
+ mailView,
+ connect,
+ async endpoint(name, body) {
+ await rt.loadSecrets()
+ if (!endpoints[name]) throw new Error(`Unknown endpoint ${name}`)
+ return endpoints[name](body ?? {})
+ },
+ async dispose() {
+ const live = [...sessions.values()]
+ sessions.clear()
+ for (const pending of googlePendings.values()) pending.listener?.close()
+ googlePendings.clear()
+ await Promise.all(live.map(session => session.close?.().catch(() => {})))
+ },
+ _internals: { sessions, refreshGoogle, mailSecretName },
+ }
+}
+
+function mailError(error) {
+ const text = String(error?.responseText ?? error?.message ?? error)
+ if (/Unsafe Login/i.test(text)) return 'The mail service refused the login (Unsafe Login). Enable IMAP/SMTP in the mailbox settings and use its authorization code, not the account password.'
+ if (/authentication|invalid credentials|535|534/i.test(text)) return 'The password was refused. Use the mailbox app password or authorization code, not the account password.'
+ return text.slice(0, 300)
+}
diff --git a/ds-bot/src/host/connectors/mail/presets.js b/ds-bot/src/host/connectors/mail/presets.js
new file mode 100644
index 00000000..0fe62e6c
--- /dev/null
+++ b/ds-bot/src/host/connectors/mail/presets.js
@@ -0,0 +1,23 @@
+// Mailbox presets by address domain. "Other" takes hosts and ports from the user.
+export const PRESETS = [
+ { id: 'qq', name: 'QQ Mail', domains: ['qq.com', 'foxmail.com'], imap: { host: 'imap.qq.com', port: 993, secure: true }, smtp: { host: 'smtp.qq.com', port: 465, secure: true } },
+ { id: '163', name: '163 Mail', domains: ['163.com'], imap: { host: 'imap.163.com', port: 993, secure: true }, smtp: { host: 'smtp.163.com', port: 465, secure: true } },
+ { id: '126', name: '126 Mail', domains: ['126.com'], imap: { host: 'imap.126.com', port: 993, secure: true }, smtp: { host: 'smtp.126.com', port: 465, secure: true } },
+ { id: 'gmail', name: 'Gmail', domains: ['gmail.com', 'googlemail.com'], imap: { host: 'imap.gmail.com', port: 993, secure: true }, smtp: { host: 'smtp.gmail.com', port: 465, secure: true } },
+ { id: 'icloud', name: 'iCloud Mail', domains: ['icloud.com', 'me.com', 'mac.com'], imap: { host: 'imap.mail.me.com', port: 993, secure: true }, smtp: { host: 'smtp.mail.me.com', port: 587, secure: false, starttls: true } },
+]
+
+export const presetOf = (address) => {
+ const domain = String(address ?? '').split('@')[1]?.toLowerCase() ?? ''
+ return PRESETS.find(preset => preset.domains.includes(domain))
+}
+
+// 163 and 126 answer "Unsafe Login" without the IMAP ID command (RFC 2971);
+// sending it for every server that supports ID is harmless elsewhere.
+export const IMAP_ID = { name: 'ds-bot', version: '0.1', vendor: 'DS Bot' }
+
+export const mailSecretName = (address, suffix) => {
+ const safe = String(address ?? '').toUpperCase().replace(/[^A-Z0-9]/g, '_')
+ const name = `MAIL_${safe}_${suffix}`
+ return name.length <= 64 ? name : `MAIL_${safe.slice(0, 40)}_${suffix}`
+}
diff --git a/ds-bot/src/host/connectors/mail/transport.js b/ds-bot/src/host/connectors/mail/transport.js
new file mode 100644
index 00000000..607bd300
--- /dev/null
+++ b/ds-bot/src/host/connectors/mail/transport.js
@@ -0,0 +1,256 @@
+// Mail transports. `connectAccount(account, deps)` returns one account session
+// behind a small interface the tools and tests share; tests inject fakes
+// through rt.config.mail.connect.
+import { simpleParser } from 'mailparser'
+import { IMAP_ID } from './presets.js'
+
+// IMAP + SMTP (imapflow + nodemailer). One live IMAP connection per account is
+// kept by the caller (QQ throttles frequent logins); on a dropped connection the
+// caller reconnects once.
+export async function connectImap(account, deps = {}) {
+ const { ImapFlow } = await import('imapflow')
+ const nodemailer = await import('nodemailer')
+ const imap = new ImapFlow({
+ host: account.imap.host, port: account.imap.port, secure: account.imap.secure !== false,
+ auth: { user: account.address, pass: deps.password },
+ id: IMAP_ID,
+ logger: false,
+ socketTimeout: 60_000,
+ })
+ const smtp = nodemailer.createTransport({
+ host: account.smtp.host, port: account.smtp.port, secure: account.smtp.secure === true,
+ requireTLS: account.smtp.starttls === true,
+ auth: { user: account.address, pass: deps.password },
+ })
+ await imap.connect()
+ await smtp.verify()
+
+ const folders = async () => {
+ const list = await imap.list()
+ const pick = (use, names) => list.find(box => box.specialUse === use)?.path
+ ?? list.find(box => names.some(name => box.path.toLowerCase() === name))?.path
+ return {
+ inbox: 'INBOX',
+ drafts: pick('\\Drafts', ['drafts', 'draft']),
+ trash: pick('\\Trash', ['trash', 'deleted messages', 'deleted', '已删除']),
+ }
+ }
+ let folderCache
+ const special = async () => (folderCache ??= await folders())
+
+ const toRow = (msg, folder) => ({
+ uid: msg.uid, folder,
+ from: msg.envelope?.from?.map(a => a.address ?? a.name).join(', ') ?? '',
+ to: msg.envelope?.to?.map(a => a.address ?? a.name).join(', ') ?? '',
+ subject: msg.envelope?.subject ?? '',
+ date: msg.envelope?.date?.toISOString?.() ?? '',
+ seen: msg.flags?.has('\\Seen') === true,
+ flagged: msg.flags?.has('\\Flagged') === true,
+ })
+
+ const parseMessage = async (uid, folder) => {
+ const lock = await imap.getMailboxLock(folder)
+ try {
+ const message = await imap.fetchOne(uid, { source: true, envelope: true, bodyStructure: true }, { uid: true })
+ if (message === false) throw new Error('No such message')
+ const parsed = await simpleParser(message.source)
+ return {
+ uid, folder,
+ messageId: parsed.messageId ?? message.envelope?.messageId ?? '',
+ subject: parsed.subject ?? '',
+ from: parsed.from?.text ?? '',
+ to: parsed.to?.text ?? '',
+ cc: parsed.cc?.text ?? '',
+ date: parsed.date?.toISOString?.() ?? '',
+ text: parsed.text ?? '',
+ references: parsed.references ?? [],
+ attachments: (parsed.attachments ?? []).map((a, i) => ({ filename: a.filename ?? `attachment-${i + 1}`, size: a.size ?? 0, partId: a.partId })),
+ _parsed: parsed,
+ }
+ } finally { lock.release() }
+ }
+
+ return {
+ kind: 'imap',
+ async close() { try { await imap.logout() } catch { /* dropped */ } },
+ async search({ folder = 'INBOX', from, to, subject, text, since, before, unread, limit = 20 }) {
+ const query = {}
+ if (from) query.from = from
+ if (to) query.to = to
+ if (subject) query.subject = subject
+ if (text) query.text = text
+ if (since) query.since = new Date(since)
+ if (before) query.before = new Date(before)
+ if (unread) query.seen = false
+ const lock = await imap.getMailboxLock(folder)
+ try {
+ const uids = await imap.search(query, { uid: true })
+ const wanted = (Array.isArray(uids) ? uids : []).slice(-limit)
+ if (wanted.length === 0) return []
+ const rows = []
+ for await (const msg of imap.fetch(wanted, { envelope: true, flags: true }, { uid: true })) rows.push(toRow(msg, folder))
+ return rows
+ } finally { lock.release() }
+ },
+ async read({ uid, folder = 'INBOX', thread = false }) {
+ const main = await parseMessage(uid, folder)
+ if (!thread) return { messages: [strip(main)] }
+ const lock = await imap.getMailboxLock(folder)
+ try {
+ const related = []
+ const ids = new Set([main.messageId, ...(main.references ?? [])])
+ for await (const msg of imap.fetch('1:*', { envelope: true }, { uid: true })) {
+ const mid = msg.envelope?.messageId
+ const inReply = msg.envelope?.inReplyTo
+ if (msg.uid === uid || ids.has(inReply)) related.push(await parseMessage(msg.uid, folder))
+ if (mid !== undefined && ids.has(mid)) ids.add(mid)
+ }
+ related.sort((a, b) => String(a.date).localeCompare(String(b.date)))
+ return { messages: [strip(main), ...related.filter(m => m.uid !== uid).map(strip)] }
+ } finally { lock.release() }
+ },
+ async saveAttachment({ uid, folder = 'INBOX', filename, to }) {
+ const message = await parseMessage(uid, folder)
+ const part = message._parsed.attachments.find(a => (a.filename ?? '') === filename) ?? message._parsed.attachments[0]
+ if (part === undefined) throw new Error('No such attachment')
+ const { writeFile } = await import('node:fs/promises')
+ await writeFile(to, part.content)
+ return { path: to, filename: part.filename ?? filename, bytes: part.size ?? part.content.length }
+ },
+ async draft({ to, cc, bcc, subject, text }) {
+ const { drafts } = await special()
+ if (drafts === undefined) throw new Error('This account has no Drafts folder')
+ const raw = await compose(account.address, { to, cc, bcc, subject, text })
+ await imap.append(drafts, raw, ['\\Seen'])
+ return { folder: drafts }
+ },
+ async send({ to, cc, bcc, subject, text, attachments = [], inReplyTo, references }) {
+ const info = await smtp.sendMail({
+ from: account.address, to, cc, bcc, subject, text,
+ ...(inReplyTo ? { inReplyTo, references: references ?? [inReplyTo] } : {}),
+ attachments,
+ })
+ return { messageId: info.messageId }
+ },
+ async update({ uid, folder = 'INBOX', seen, flagged, move }) {
+ const lock = await imap.getMailboxLock(folder)
+ try {
+ if (seen !== undefined) await (seen ? imap.messageFlagsAdd(uid, ['\\Seen'], { uid: true }) : imap.messageFlagsRemove(uid, ['\\Seen'], { uid: true }))
+ if (flagged !== undefined) await (flagged ? imap.messageFlagsAdd(uid, ['\\Flagged'], { uid: true }) : imap.messageFlagsRemove(uid, ['\\Flagged'], { uid: true }))
+ if (move !== undefined) {
+ const { trash } = await special()
+ const target = move === 'trash' ? trash : move
+ if (target === undefined) throw new Error('This account has no Trash folder')
+ await imap.messageMove(uid, target, { uid: true })
+ }
+ } finally { lock.release() }
+ },
+ }
+}
+
+const strip = ({ _parsed, ...message }) => message
+
+const compose = async (from, { to, cc, bcc, subject, text }) => {
+ const MailComposer = (await import('nodemailer/lib/mail-composer.js')).default
+ return await new MailComposer({ from, to, cc, bcc, subject, text }).compile().build()
+}
+
+// Gmail REST API backend for accounts signed in with Google. Same interface.
+export function connectGmail(account, deps = {}) {
+ const send = async (path, init = {}) => {
+ const response = await (deps.fetch ?? fetch)(`https://gmail.googleapis.com/gmail/v1/users/me${path}`, {
+ ...init,
+ headers: { Authorization: `Bearer ${deps.token()}`, 'Content-Type': 'application/json', ...(init.headers ?? {}) },
+ })
+ if (response.status === 401 && deps.refresh) {
+ if (await deps.refresh() === true) return send(path, init)
+ }
+ if (!response.ok) throw new Error(`Gmail answered ${response.status}`)
+ return response.json().catch(() => ({}))
+ }
+ const header = (list, name) => list?.find(h => h.name.toLowerCase() === name)?.value ?? ''
+ const decode = data => data === undefined ? '' : Buffer.from(data.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')
+ const walk = (part, out = { text: '', attachments: [] }) => {
+ if (part === undefined) return out
+ if (part.mimeType === 'text/plain' && part.body?.data) out.text += decode(part.body.data)
+ if (part.filename) out.attachments.push({ filename: part.filename, size: part.body?.size ?? 0, attachmentId: part.body?.attachmentId })
+ for (const child of part.parts ?? []) walk(child, out)
+ return out
+ }
+ const toMessage = (full) => {
+ const headers = full.payload?.headers ?? []
+ const body = walk(full.payload)
+ return {
+ uid: full.id, folder: 'gmail', messageId: header(headers, 'Message-ID'),
+ subject: header(headers, 'Subject'), from: header(headers, 'From'), to: header(headers, 'To'), cc: header(headers, 'Cc'),
+ date: header(headers, 'Date'), text: body.text, attachments: body.attachments, threadId: full.threadId,
+ references: [header(headers, 'References'), header(headers, 'In-Reply-To')].filter(Boolean),
+ }
+ }
+ return {
+ kind: 'gmail',
+ async close() {},
+ async search({ folder, from, to, subject, text, since, before, unread, limit = 20 }) {
+ const q = [
+ from ? `from:${from}` : '', to ? `to:${to}` : '', subject ? `subject:${subject}` : '',
+ text ?? '', since ? `after:${Math.floor(new Date(since).getTime() / 1000)}` : '', before ? `before:${Math.floor(new Date(before).getTime() / 1000)}` : '',
+ unread ? 'is:unread' : '', folder && folder !== 'INBOX' ? `in:${folder}` : '',
+ ].filter(Boolean).join(' ')
+ const list = await send(`/messages?${new URLSearchParams({ q, maxResults: String(limit) })}`)
+ const rows = []
+ for (const ref of list.messages ?? []) {
+ const full = await send(`/messages/${ref.id}?format=metadata&metadataHeaders=Subject&metadataHeaders=From&metadataHeaders=To&metadataHeaders=Date`)
+ const headers = full.payload?.headers ?? []
+ rows.push({ uid: full.id, folder: 'gmail', from: header(headers, 'From'), to: header(headers, 'To'), subject: header(headers, 'Subject'), date: header(headers, 'Date'), seen: !(full.labelIds ?? []).includes('UNREAD'), flagged: (full.labelIds ?? []).includes('STARRED') })
+ }
+ return rows
+ },
+ async read({ uid, thread = false }) {
+ const full = await send(`/messages/${uid}?format=full`)
+ const main = toMessage(full)
+ if (!thread) return { messages: [main] }
+ const all = await send(`/threads/${full.threadId}?format=full`)
+ const messages = (all.messages ?? []).map(toMessage)
+ messages.sort((a, b) => String(a.date).localeCompare(String(b.date)))
+ return { messages: messages.length > 0 ? messages : [main] }
+ },
+ async saveAttachment({ uid, filename, to }) {
+ const full = await send(`/messages/${uid}?format=full`)
+ const { attachments } = walk(full.payload)
+ const part = attachments.find(a => a.filename === filename) ?? attachments[0]
+ if (part === undefined) throw new Error('No such attachment')
+ const data = await send(`/messages/${uid}/attachments/${part.attachmentId}`)
+ const { writeFile } = await import('node:fs/promises')
+ await writeFile(to, Buffer.from(String(data.data ?? '').replace(/-/g, '+').replace(/_/g, '/'), 'base64'))
+ return { path: to, filename: part.filename, bytes: part.size }
+ },
+ async draft(args) { return gmailDraft(send, account.address, args) },
+ async send(args) { return gmailSend(send, account.address, args) },
+ async update({ uid, seen, flagged, move }) {
+ if (move === 'trash' || move === 'TRASH') { await send(`/messages/${uid}/trash`, { method: 'POST' }); return }
+ const add = [], remove = []
+ if (seen === true) remove.push('UNREAD')
+ if (seen === false) add.push('UNREAD')
+ if (flagged === true) add.push('STARRED')
+ if (flagged === false) remove.push('STARRED')
+ if (move !== undefined) { remove.push('INBOX'); add.push(String(move).toUpperCase()) }
+ await send(`/messages/${uid}/modify`, { method: 'POST', body: JSON.stringify({ addLabelIds: add, removeLabelIds: remove }) })
+ },
+ }
+}
+
+const gmailRaw = async (from, { to, cc, bcc, subject, text, inReplyTo, references }) => {
+ const MailComposer = (await import('nodemailer/lib/mail-composer.js')).default
+ const raw = await new MailComposer({ from, to, cc, bcc, subject, text, ...(inReplyTo ? { inReplyTo, references: references ?? [inReplyTo] } : {}) }).compile().build()
+ return raw.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+}
+const gmailDraft = async (send, from, args) => {
+ const raw = await gmailRaw(from, args)
+ const draft = await send('/drafts', { method: 'POST', body: JSON.stringify({ message: { raw } }) })
+ return { folder: 'DRAFT', id: draft.id }
+}
+const gmailSend = async (send, from, args) => {
+ const raw = await gmailRaw(from, args)
+ const sent = await send('/messages/send', { method: 'POST', body: JSON.stringify({ raw }) })
+ return { messageId: sent.id }
+}
diff --git a/ds-bot/src/host/connectors/oauth.js b/ds-bot/src/host/connectors/oauth.js
new file mode 100644
index 00000000..7ea161b5
--- /dev/null
+++ b/ds-bot/src/host/connectors/oauth.js
@@ -0,0 +1,189 @@
+// OAuth sign-in for connectors, on the official MCP SDK auth helpers. Discovery:
+// an unauthenticated request → 401 WWW-Authenticate → protected-resource
+// metadata (well-known fallback; AS metadata on the MCP origin for older
+// servers) → AS metadata. Client: catalog → CIMD → DCR → needs-client.
+import {
+ discoverOAuthProtectedResourceMetadata,
+ discoverAuthorizationServerMetadata,
+ extractWWWAuthenticateParams,
+ startAuthorization,
+ exchangeAuthorization,
+ refreshAuthorization,
+ registerClient,
+ IssuerMismatchError,
+} from '@modelcontextprotocol/client'
+
+const TIMEOUT_MS = 20_000
+// The loopback port the client-metadata document at this address may name.
+export const FIXED_CALLBACK_PORT = 38517
+export const CIMD_CLIENT_ID = 'https://dsbot.app/oauth/client.json'
+
+const timed = (request = fetch) => (url, init) => request(url, { ...init, signal: init?.signal ?? AbortSignal.timeout(TIMEOUT_MS) })
+
+const https = (url, what) => {
+ if (!/^https:\/\//i.test(String(url))) throw new Error(`${what} addresses must start with https://`)
+}
+
+// Probes the MCP server and resolves the authorization server and its metadata.
+export async function discover(serverUrl, { fetch: request = fetch, originFallback = true } = {}) {
+ const send = timed(request)
+ https(serverUrl, 'Connector')
+ let challenge = {}
+ try {
+ const probe = await send(serverUrl, { method: 'POST', headers: { Accept: 'application/json, text/event-stream', 'Content-Type': 'application/json' }, body: '{}' })
+ if (probe.status === 401 || probe.status === 403) challenge = extractWWWAuthenticateParams(probe)
+ } catch { /* discovery below still tries the well-known paths */ }
+ let resourceMetadata
+ try {
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: challenge.resourceMetadataUrl }, send)
+ } catch { resourceMetadata = undefined }
+ // Older servers publish AS metadata on the MCP origin with no protected-resource doc.
+ const asUrl = resourceMetadata?.authorization_servers?.[0] ?? (originFallback ? new URL(serverUrl).origin : serverUrl)
+ let metadata
+ try {
+ metadata = await discoverAuthorizationServerMetadata(asUrl, { fetchFn: send })
+ } catch (error) {
+ if (error instanceof IssuerMismatchError) metadata = await discoverAuthorizationServerMetadata(asUrl, { fetchFn: send, skipIssuerValidation: true }).catch(() => undefined)
+ }
+ const scope = challenge.scope ?? resourceMetadata?.scopes_supported?.join(' ')
+ return {
+ authorizationServerUrl: String(asUrl),
+ metadata,
+ resourceMetadata,
+ scope,
+ // RFC 8707: the resource parameter always goes out; the PRM's own id wins.
+ resource: resourceMetadata?.resource ?? String(serverUrl),
+ }
+}
+
+// Picks how this attempt identifies itself to the AS. Returns {clientInformation,
+// via, store} or null when nothing works — the row then shows the client form.
+// `stored` is the client state saved last time; `persist` writes DCR results.
+export async function resolveClient(entry, discovery, redirectUri, fixedPort, stored, { fetch: request = fetch, persist } = {}) {
+ const catalogClient = entry.auth?.client?.id
+ if (catalogClient) return { via: 'catalog', clientInformation: { client_id: catalogClient } }
+ if (stored?.clientId) {
+ const expired = Number.isFinite(stored.secretExpiresAt) && stored.secretExpiresAt * 1000 <= Date.now()
+ const uriMissing = Array.isArray(stored.redirectUris) && !stored.redirectUris.includes(redirectUri)
+ if (!expired && !uriMissing && stored.via !== 'dcr') return { via: stored.via, clientInformation: { client_id: stored.clientId } }
+ if (!expired && !uriMissing && stored.via === 'dcr') return { via: 'dcr', clientInformation: { client_id: stored.clientId, ...(stored.clientSecret ? { client_secret: stored.clientSecret } : {}) } }
+ }
+ const metadata = discovery.metadata
+ if (metadata?.client_id_metadata_document_supported === true && fixedPort) {
+ return { via: 'cimd', clientInformation: { client_id: CIMD_CLIENT_ID } }
+ }
+ if (typeof metadata?.registration_endpoint === 'string') {
+ const clientMetadata = {
+ client_name: 'DS Bot',
+ redirect_uris: [redirectUri],
+ grant_types: ['authorization_code', 'refresh_token'],
+ response_types: ['code'],
+ token_endpoint_auth_method: 'none',
+ }
+ const full = await registerClient(discovery.authorizationServerUrl, { metadata, clientMetadata, scope: discovery.scope, fetchFn: timed(request) })
+ const info = {
+ via: 'dcr',
+ clientId: full.client_id,
+ clientSecret: full.client_secret,
+ redirectUris: full.redirect_uris ?? [redirectUri],
+ secretExpiresAt: full.client_secret_expires_at,
+ }
+ await persist?.(info)
+ return { via: 'dcr', clientInformation: { client_id: full.client_id, ...(full.client_secret ? { client_secret: full.client_secret } : {}) } }
+ }
+ return null
+}
+
+// Browser PKCE: the SDK makes the S256 verifier and the URL.
+export async function beginBrowser(discovery, clientInformation, redirectUri, { state, scope } = {}) {
+ const { authorizationUrl, codeVerifier } = await startAuthorization(discovery.authorizationServerUrl, {
+ metadata: discovery.metadata,
+ clientInformation,
+ redirectUrl: redirectUri,
+ scope: scope ?? discovery.scope,
+ state,
+ resource: discovery.resource,
+ })
+ return { url: String(authorizationUrl), codeVerifier }
+}
+
+export async function exchange(discovery, clientInformation, { code, codeVerifier, redirectUri, iss }, { fetch: request = fetch } = {}) {
+ return exchangeAuthorization(discovery.authorizationServerUrl, {
+ metadata: discovery.metadata,
+ clientInformation,
+ authorizationCode: code,
+ iss,
+ codeVerifier,
+ redirectUri,
+ resource: discovery.resource,
+ fetchFn: timed(request),
+ })
+}
+
+const invalidGrant = (error) => {
+ const code = error?.error ?? error?.code
+ if (code === 'invalid_grant') return true
+ const text = String(error?.message ?? error)
+ return /invalid_grant/.test(text)
+}
+export { invalidGrant }
+
+export async function refreshTokens(discovery, clientInformation, refreshToken, { scope, fetch: request = fetch } = {}) {
+ return refreshAuthorization(discovery.authorizationServerUrl, {
+ metadata: discovery.metadata,
+ clientInformation,
+ refreshToken,
+ scope: scope ?? discovery.scope,
+ resource: discovery.resource,
+ fetchFn: timed(request),
+ })
+}
+
+// Re-discovers AS metadata for a stored authorization server (after a restart).
+export async function rediscover(stored, { fetch: request = fetch } = {}) {
+ const send = timed(request)
+ const metadata = await discoverAuthorizationServerMetadata(stored.authorizationServerUrl, { fetchFn: send }).catch(() => undefined)
+ return { authorizationServerUrl: stored.authorizationServerUrl, metadata, resource: stored.resource, scope: stored.scope }
+}
+
+// --- GitHub device flow -------------------------------------------------
+
+const post = async (send, url, params) => {
+ const response = await send(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
+ body: new URLSearchParams(params).toString(),
+ })
+ const body = await response.json().catch(() => ({}))
+ return { status: response.status, body }
+}
+
+export async function deviceBegin(clientId, scope, { fetch: request = fetch, endpoints } = {}) {
+ const send = timed(request)
+ const codeUrl = endpoints?.deviceCode ?? 'https://github.com/login/device/code'
+ const { status, body } = await post(send, codeUrl, { client_id: clientId, ...(scope ? { scope } : {}) })
+ if (status !== 200 || typeof body.device_code !== 'string') throw new Error(body.error_description ?? `Device sign-in was refused (${status})`)
+ return {
+ deviceCode: body.device_code,
+ userCode: body.user_code,
+ verificationUri: body.verification_uri ?? 'https://github.com/login/device',
+ interval: Number(body.interval) || 5,
+ expiresAt: Date.now() + (Number(body.expires_in) || 900) * 1000,
+ }
+}
+
+// One poll step. Returns {state:'pending'|'slow_down'|'done'|'error', ...}.
+export async function devicePoll(clientId, device, { fetch: request = fetch, endpoints } = {}) {
+ const send = timed(request)
+ const tokenUrl = endpoints?.accessToken ?? 'https://github.com/login/oauth/access_token'
+ const { status, body } = await post(send, tokenUrl, {
+ client_id: clientId,
+ device_code: device.deviceCode,
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
+ })
+ if (status === 200 && typeof body.access_token === 'string') return { state: 'done', token: body.access_token, refreshToken: body.refresh_token, expiresIn: body.expires_in }
+ const error = body.error
+ if (error === 'authorization_pending') return { state: 'pending' }
+ if (error === 'slow_down') return { state: 'slow_down' }
+ return { state: 'error', error: body.error_description ?? error ?? `Sign-in failed (${status})` }
+}
diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.js
index d07ba3ea..795c7073 100644
--- a/ds-bot/src/host/constants.js
+++ b/ds-bot/src/host/constants.js
@@ -68,7 +68,7 @@ export const TEAM_TOOLS = [
'request_secret', 'list_secrets', 'group_relay', 'read_own_chat',
'read_group_chat', 'remember', 'forget', 'recall', 'read_browser',
'list_capabilities', 'save_capability', 'delete_capability',
- 'attach_capability', 'detach_capability', 'group_goal',
+ 'attach_capability', 'detach_capability', 'group_goal', 'list_connectors', 'request_connector',
]
// Consecutive automatic admin wakes with no goal progress before the goal waits
// for the user instead of waking the admin again.
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index da70e1e3..51950b1a 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -811,7 +811,11 @@ export function install(rt) {
if (relayOnly && def.name !== 'group_relay') continue
try {
const dispose = agent.ctx.tools.register(def)
- if (typeof dispose === 'function') disposers.push(dispose)
+ if (typeof dispose === 'function') {
+ disposers.push(dispose)
+ ;(held ??= { relay: relayOnly, tools: false, restricted: false, filtered: false, disposers: [], unlisted: new Set() }).toolLifts ??= new Map()
+ held.toolLifts.set(def.name, dispose)
+ }
registered.push(def.name)
} catch (error) {
// A tool another plugin already scoped onto this agent stays missing
@@ -852,6 +856,58 @@ export function install(rt) {
if (typeof dispose === 'function') held.disposers.push(dispose)
}
+ // Tools joined after the first scoping (mail tools appear when the first
+ // account is added) register into every held Agent and are offered once.
+ const addTeamTool = (def) => {
+ if (rt.teamTools.some(tool => tool.name === def.name)) return
+ rt.teamTools.push(def)
+ for (const held of scoped.values()) {
+ if (held.relay || typeof held.agent?.ctx?.tools?.register !== 'function') continue
+ try {
+ const dispose = held.agent.ctx.tools.register(def)
+ if (typeof dispose === 'function') held.disposers.push(dispose)
+ held.unlisted.add(def.name)
+ } catch { /* an agent that refuses it simply lacks the tool */ }
+ }
+ }
+ const removeTeamTool = (name) => {
+ const at = rt.teamTools.findIndex(tool => tool.name === name)
+ if (at !== -1) rt.teamTools.splice(at, 1)
+ // Scoped registrations already handed out are disposed by name.
+ for (const held of scoped.values()) {
+ held.toolLifts?.get(name)?.()
+ held.toolLifts?.delete(name)
+ held.unlisted.delete(name)
+ }
+ }
+
+ // Per-Bot connector switches (state.connectors[id].offFor): deny the served
+ // tools matching each off connector's prefix. Re-applied on tools/change.
+ const maskConnectorTools = (agent, held) => {
+ if (typeof agent.ctx?.tools?.restrict !== 'function' || typeof ctx.tools?.schemas !== 'function') return
+ const botId = rt.selfOf(agent.session?.id)
+ const prefixes = rt.connectorOffFor?.(botId) ?? []
+ const served = new Set(ctx.tools.schemas(agent).map(schema => schema.name))
+ const deny = [...served].filter(name => prefixes.some(prefix => name.startsWith(prefix)))
+ const before = held.connectorDenied ?? new Set()
+ if (deny.length === before.size && deny.every(name => before.has(name))) return
+ for (const lift of held.connectorLifts ?? []) { try { lift() } catch { /* already lifted */ } }
+ held.connectorLifts = []
+ held.connectorDenied = new Set(deny)
+ for (const name of deny) {
+ try {
+ const lift = agent.ctx.tools.restrict({ deny: [name] })
+ if (typeof lift === 'function') held.connectorLifts.push(lift)
+ } catch { /* a scoped name cannot be restricted; connectors are global */ }
+ }
+ }
+ const reapplyToolMasks = () => {
+ for (const held of scoped.values()) {
+ if (held.agent === undefined) continue
+ try { maskConnectorTools(held.agent, held) } catch (error) { rt.warn('ds-bot: connector mask failed: %s', error) }
+ }
+ }
+
// restrict() throws on a name this profile does not serve.
const maskHiddenTools = (agent, held, served) => {
const groups = HIDDEN_TOOL_GROUPS.map(group => group.filter(name => served.has(name))).filter(group => group.length > 0)
@@ -901,9 +957,12 @@ export function install(rt) {
held.agent = agent
scoped.set(id, held)
filterBotAssembly(agent, held)
- if (held.restricted === true || typeof agent.ctx?.tools?.restrict !== 'function') return
- maskHiddenTools(agent, held, new Set(ctx.tools.schemas(agent).map(schema => schema.name)))
+ if (held.restricted !== true && typeof agent.ctx?.tools?.restrict === 'function') {
+ maskHiddenTools(agent, held, new Set(ctx.tools.schemas(agent).map(schema => schema.name)))
+ }
+ maskConnectorTools(agent, held)
}
+ ctx.on('tools/change', () => reapplyToolMasks())
// A new Bot, part, or group Session gets its Agent before ds-bot records it, so the
// recording path resolves it again once the session is known as a Bot's; meanwhile
// the guard refuses the question and delegation tools in any Bot Session, and a
@@ -1101,5 +1160,5 @@ export function install(rt) {
}))
}
- Object.assign(rt, { pickRoom, hideBotUnusedTools, syncScopedTools })
+ Object.assign(rt, { pickRoom, hideBotUnusedTools, syncScopedTools, addTeamTool, removeTeamTool, reapplyToolMasks })
}