Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
Release/1.11.13 (#79)
Salman Qureshi0de89558cb52
diff --git a/.env.example b/.env.exampleindex 3e46da38..b89e497f 100644--- a/.env.example+++ b/.env.example@@ -62,6 +62,54 @@ DEFAULT_PROVIDER=deepseek# Get a bot token from @BotFather on TelegramTELEGRAM_BOT_TOKEN=+# ── Discord ──+# Get a bot token from https://discord.com/developers/applications+# 1. Go to Discord Developer Portal → Applications → New Application+# 2. Navigate to Bot → Copy Token+# 3. Enable Privileged Gateway Intents: Message Content, Server Members+# 4. Generate OAuth2 URL with scopes: bot, applications.commands+# Bot permissions: Send Messages, Read Message History, Use Slash Commands, Attach Files, Embed Links+# 5. Invite the bot to your server using the generated URL+# 6. Optionally create a "Mercury Admin" role in your server for admin control+DISCORD_ENABLED=false+DISCORD_BOT_TOKEN=+# Restrict to a specific guild (server). Leave empty to work across all servers.+DISCORD_GUILD_ID=+# Restrict to a specific channel. Leave empty to respond in all channels.+DISCORD_CHANNEL_ID=+# Discord role name that grants admin access (default: "Mercury Admin")+DISCORD_ADMIN_ROLE_NAME=Mercury Admin+# Enable streaming responses (edit-in-place)+DISCORD_STREAMING=true++# ── Slack ──+# Create a Slack app at https://api.slack.com/apps+# 1. Click "Create New App" → "From scratch"+# 2. Under "Socket Mode", enable it and generate an App-Level Token+# with connections:write scope → copy the xapp- token+# 3. Under "OAuth & Permissions", add Bot Token Scopes:+# chat:write, chat:write.public, chat:write.customize,+# channels:history, groups:history, im:history, im:write,+# files:write, commands, app_mentions:read+# 4. Install app to workspace → copy Bot User OAuth Token (xoxb-)+# 5. Under "Event Subscriptions", enable and subscribe to:+# message.channels, message.groups, message.im, app_mention+# 6. Under "Interactivity & Shortcuts", enable interactivity+# 7. Under "Slash Commands", create /mercury command+# 8. Under "App Home", check "Allow users to send Slash commands+# and messages from the messages tab"+# 9. Invite the bot to your channel: /invite @Mercury+# 10. DM the bot /mercury start to become the first admin+SLACK_ENABLED=false+SLACK_BOT_TOKEN=+SLACK_APP_TOKEN=+# Restrict to a specific channel. Leave empty to respond in all channels.+SLACK_CHANNEL_ID=+# Workspace/Team ID (optional)+SLACK_TEAM_ID=+# Enable streaming responses (edit-in-place)+SLACK_STREAMING=true+# ── Memory ──MEMORY_DIR=./memorydiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 955027da..ca996cb3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -92,24 +92,49 @@ jobs:- name: Run CI in Termux containershell: bashrun: |+ cat > /tmp/termux-ci.sh <<'CI_SCRIPT'+ #!/bin/sh+ set -ex+ export PATH=/data/data/com.termux/files/usr/bin:$PATH+ export HOME=/home/builder+ export npm_config_cache=/home/builder/project/.npm-cache+ export TERMUX_VERSION=u0+ # pkg update can hit bad mirrors; retry with a known-good mirror if needed+ pkg update -y || {+ echo 'pkg update failed, trying specific mirror...'+ termux-change-repo || true+ pkg update -y+ }+ pkg install -y git nodejs-lts python build-essential+ cd /home/builder/project+ npm install --no-audit --no-fund+ npm install --no-save --no-audit --no-fund @rollup/wasm-node@4+ rm -rf node_modules/rollup+ ln -s @rollup/wasm-node node_modules/rollup+ # .bin symlinks aren't in PATH in Termux's ash — add them explicitly+ export PATH="$PWD/node_modules/.bin:$PATH"+ node node_modules/tsup/dist/cli-default.js+ node scripts/post-build.cjs+ node node_modules/vitest/vitest.mjs run+ CI_SCRIPT+ chmod +x /tmp/termux-ci.sh+docker run --rm \--privileged \--entrypoint /entrypoint_root.sh \-v "${{ github.workspace }}:/home/builder/project" \+ -v /tmp/termux-ci.sh:/tmp/termux-ci.sh:ro \-e "HOME=/home/builder" \termux/termux-docker:x86_64 \bash -c "set -e- chown -R system:system /home/builder/project- su - system -c '- set -e- pkg update -y- pkg install -y git nodejs-lts- cd /home/builder/project- npm ci- npm run build- npm test- '+ chown -R system:system /home/builder+ mkdir -p /home/builder/.npm+ chown -R system:system /home/builder/.npm+ cp /tmp/termux-ci.sh /home/builder/termux-ci.sh+ chown system:system /home/builder/termux-ci.sh+ chmod +x /home/builder/termux-ci.sh+ su system /home/builder/termux-ci.sh"publish:diff --git a/package-lock.json b/package-lock.jsonindex e0391edb..2948a6ab 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@cosmicstack/mercury-agent",- "version": "1.1.9",+ "version": "1.1.12","lockfileVersion": 2,"requires": true,"packages": {"": {"name": "@cosmicstack/mercury-agent",- "version": "1.1.9",+ "version": "1.1.12","license": "MIT","dependencies": {"@ai-sdk/anthropic": "^3.0.71",@@ -14,10 +14,12 @@"@ai-sdk/openai": "^3.0.53","@grammyjs/auto-retry": "^2.0.2","@hono/node-server": "^2.0.0",+ "@slack/bolt": "^4.7.3","ai": "^6.0.168","bcryptjs": "^3.0.3","chalk": "^5.4.0","commander": "^12.1.0",+ "discord.js": "^14.26.4","dotenv": "^16.4.7","grammy": "^1.42.0","hono": "^4.12.15",@@ -26,6 +28,7 @@"node-cron": "^3.0.3","ollama-ai-provider": "^1.2.0","pino": "^10.3.1",+ "qrcode-terminal": "^0.12.0","react": "^18.3.1","sql.js": "^1.14.1","yaml": "^2.7.0",@@ -39,6 +42,7 @@"@types/better-sqlite3": "^7.6.13","@types/node": "^22.13.0","@types/node-cron": "^3.0.11",+ "@types/qrcode-terminal": "^0.12.2","@types/react": "^18.3.28","react-devtools-core": "^4.28.5","tsup": "^8.4.0",@@ -152,6 +156,146 @@"node": ">=14.13.1"}},+ "node_modules/@discordjs/builders": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",+ "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@discordjs/formatters": "^0.6.2",+ "@discordjs/util": "^1.2.0",+ "@sapphire/shapeshift": "^4.0.0",+ "discord-api-types": "^0.38.40",+ "fast-deep-equal": "^3.1.3",+ "ts-mixer": "^6.0.4",+ "tslib": "^2.6.3"+ },+ "engines": {+ "node": ">=16.11.0"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/collection": {+ "version": "1.5.3",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",+ "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=16.11.0"+ }+ },+ "node_modules/@discordjs/formatters": {+ "version": "0.6.2",+ "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz",+ "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "discord-api-types": "^0.38.33"+ },+ "engines": {+ "node": ">=16.11.0"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/rest": {+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.1.tgz",+ "integrity": "sha512-wwQdgjeaoYFiaG+atbqx6aJDpqW7JHAo0HrQkBTbYzM3/PJ3GweQIpgElNcGZ26DCUOXMyawYd0YF7vtr+fZXg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@discordjs/collection": "^2.1.1",+ "@discordjs/util": "^1.2.0",+ "@sapphire/async-queue": "^1.5.3",+ "@sapphire/snowflake": "^3.5.5",+ "@vladfrangu/async_event_emitter": "^2.4.6",+ "discord-api-types": "^0.38.40",+ "magic-bytes.js": "^1.13.0",+ "tslib": "^2.6.3",+ "undici": "6.24.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/rest/node_modules/@discordjs/collection": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",+ "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/rest/node_modules/@sapphire/snowflake": {+ "version": "3.5.5",+ "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz",+ "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==",+ "license": "MIT",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },+ "node_modules/@discordjs/util": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz",+ "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",+ "license": "Apache-2.0",+ "dependencies": {+ "discord-api-types": "^0.38.33"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/ws": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz",+ "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@discordjs/collection": "^2.1.0",+ "@discordjs/rest": "^2.5.1",+ "@discordjs/util": "^1.1.0",+ "@sapphire/async-queue": "^1.5.2",+ "@types/ws": "^8.5.10",+ "@vladfrangu/async_event_emitter": "^2.2.4",+ "discord-api-types": "^0.38.1",+ "tslib": "^2.6.2",+ "ws": "^8.17.0"+ },+ "engines": {+ "node": ">=16.11.0"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/ws/node_modules/@discordjs/collection": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",+ "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },"node_modules/@esbuild/aix-ppc64": {"version": "0.27.7","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",@@ -971,6 +1115,146 @@"win32"]},+ "node_modules/@sapphire/async-queue": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz",+ "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==",+ "license": "MIT",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },+ "node_modules/@sapphire/shapeshift": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz",+ "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "lodash": "^4.17.21"+ },+ "engines": {+ "node": ">=v16"+ }+ },+ "node_modules/@sapphire/snowflake": {+ "version": "3.5.3",+ "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.3.tgz",+ "integrity": "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ==",+ "license": "MIT",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },+ "node_modules/@slack/bolt": {+ "version": "4.7.3",+ "resolved": "https://registry.npmjs.org/@slack/bolt/-/bolt-4.7.3.tgz",+ "integrity": "sha512-bODs8q/yNDWUPoxmQhFrRqLMA5vhB/PDizYWqb6CkQhLWEUo5JFtfJcmeU4ElGl6qSt++OKjSYNa4MPc77CleQ==",+ "license": "MIT",+ "dependencies": {+ "@slack/logger": "^4.0.1",+ "@slack/oauth": "^3.0.5",+ "@slack/socket-mode": "^2.0.7",+ "@slack/types": "^2.21.1",+ "@slack/web-api": "^7.16.0",+ "axios": "^1.12.0",+ "express": "^5.0.0",+ "path-to-regexp": "^8.1.0",+ "raw-body": "^3",+ "tsscmp": "^1.0.6"+ },+ "engines": {+ "node": ">=18",+ "npm": ">=8.6.0"+ },+ "peerDependencies": {+ "@types/express": "^5.0.0"+ }+ },+ "node_modules/@slack/logger": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/@slack/logger/-/logger-4.0.1.tgz",+ "integrity": "sha512-6cmdPrV/RYfd2U0mDGiMK8S7OJqpCTm7enMLRR3edccsPX8j7zXTLnaEF4fhxxJJTAIOil6+qZrnUPTuaLvwrQ==",+ "license": "MIT",+ "dependencies": {+ "@types/node": ">=18"+ },+ "engines": {+ "node": ">= 18",+ "npm": ">= 8.6.0"+ }+ },+ "node_modules/@slack/oauth": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/@slack/oauth/-/oauth-3.0.5.tgz",+ "integrity": "sha512-exqFQySKhNDptWYSWhvRUJ4/+ndu2gayIy7vg/JfmJq3wGtGdHk531P96fAZyBm5c1Le3yaPYqv92rL4COlU3A==",+ "license": "MIT",+ "dependencies": {+ "@slack/logger": "^4.0.1",+ "@slack/web-api": "^7.15.0",+ "@types/jsonwebtoken": "^9",+ "@types/node": ">=18",+ "jsonwebtoken": "^9"+ },+ "engines": {+ "node": ">=18",+ "npm": ">=8.6.0"+ }+ },+ "node_modules/@slack/socket-mode": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@slack/socket-mode/-/socket-mode-2.0.7.tgz",+ "integrity": "sha512-qYy07je71WnEHgRwmw12DlAnZLi5HXmdlI2WUzUK2LH/rYXQpP6uEg462S5CwfE8FoCKUdIigHtYnOOfzZH1lQ==",+ "license": "MIT",+ "dependencies": {+ "@slack/logger": "^4.0.1",+ "@slack/web-api": "^7.15.0",+ "@types/node": ">=18",+ "@types/ws": "^8",+ "eventemitter3": "^5",+ "ws": "^8"+ },+ "engines": {+ "node": ">= 18",+ "npm": ">= 8.6.0"+ }+ },+ "node_modules/@slack/types": {+ "version": "2.21.1",+ "resolved": "https://registry.npmjs.org/@slack/types/-/types-2.21.1.tgz",+ "integrity": "sha512-I8vmSjNYWsaxuWPx6dz4yeh0h7vRBWbgAMK14LEmblbZ404BtrPbXs6jDPx4cYgGf8msDGF4A9opLZBu21FViQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 12.13.0",+ "npm": ">= 6.12.0"+ }+ },+ "node_modules/@slack/web-api": {+ "version": "7.17.0",+ "resolved": "https://registry.npmjs.org/@slack/web-api/-/web-api-7.17.0.tgz",+ "integrity": "sha512-jejr34a8B4L5AS713wOAx1LAqNkW16HVMDEa6sYBvFDc/llUBl8hXaiI4BwF+Al+Sug19Vn2O7iokTVIhVvZ1Q==",+ "license": "MIT",+ "dependencies": {+ "@slack/logger": "^4.0.1",+ "@slack/types": "^2.21.0",+ "@types/node": ">=18",+ "@types/retry": "0.12.0",+ "axios": "^1.16.0",+ "eventemitter3": "^5.0.1",+ "form-data": "^4.0.4",+ "is-electron": "2.2.2",+ "is-stream": "^2",+ "p-queue": "^6",+ "p-retry": "^4",+ "retry": "^0.13.1"+ },+ "engines": {+ "node": ">= 18",+ "npm": ">= 8.6.0"+ }+ },"node_modules/@standard-schema/spec": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",@@ -995,6 +1279,17 @@"@types/node": "*"}},+ "node_modules/@types/body-parser": {+ "version": "1.19.6",+ "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",+ "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/connect": "*",+ "@types/node": "*"+ }+ },"node_modules/@types/chai": {"version": "5.2.3","resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",@@ -1005,6 +1300,16 @@"assertion-error": "^2.0.1"}},+ "node_modules/@types/connect": {+ "version": "3.4.38",+ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",+ "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/deep-eql": {"version": "4.0.2","resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",@@ -1017,11 +1322,58 @@"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==","dev": true},+ "node_modules/@types/express": {+ "version": "5.0.6",+ "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",+ "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/body-parser": "*",+ "@types/express-serve-static-core": "^5.0.0",+ "@types/serve-static": "^2"+ }+ },+ "node_modules/@types/express-serve-static-core": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz",+ "integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/node": "*",+ "@types/qs": "*",+ "@types/range-parser": "*",+ "@types/send": "*"+ }+ },+ "node_modules/@types/http-errors": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",+ "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/@types/jsonwebtoken": {+ "version": "9.0.10",+ "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",+ "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",+ "license": "MIT",+ "dependencies": {+ "@types/ms": "*",+ "@types/node": "*"+ }+ },+ "node_modules/@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",+ "license": "MIT"+ },"node_modules/@types/node": {"version": "22.19.19","resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.19.tgz","integrity": "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==",- "dev": true,"dependencies": {"undici-types": "~6.21.0"}@@ -1038,6 +1390,27 @@"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==","devOptional": true},+ "node_modules/@types/qrcode-terminal": {+ "version": "0.12.2",+ "resolved": "https://registry.npmjs.org/@types/qrcode-terminal/-/qrcode-terminal-0.12.2.tgz",+ "integrity": "sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/qs": {+ "version": "6.15.1",+ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",+ "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/@types/range-parser": {+ "version": "1.2.7",+ "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",+ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",+ "license": "MIT",+ "peer": true+ },"node_modules/@types/react": {"version": "18.3.28","resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",@@ -1048,6 +1421,42 @@"csstype": "^3.2.2"}},+ "node_modules/@types/retry": {+ "version": "0.12.0",+ "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",+ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",+ "license": "MIT"+ },+ "node_modules/@types/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",+ "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/serve-static": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",+ "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/http-errors": "*",+ "@types/node": "*"+ }+ },+ "node_modules/@types/ws": {+ "version": "8.18.1",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@vercel/oidc": {"version": "3.2.0","resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.2.0.tgz",@@ -1164,6 +1573,16 @@"url": "https://opencollective.com/vitest"}},+ "node_modules/@vladfrangu/async_event_emitter": {+ "version": "2.4.7",+ "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz",+ "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==",+ "license": "MIT",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },"node_modules/abort-controller": {"version": "3.0.0","resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",@@ -1175,6 +1594,19 @@"node": ">=6.5"}},+ "node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/acorn": {"version": "8.16.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",@@ -1187,6 +1619,18 @@"node": ">=0.4.0"}},+ "node_modules/agent-base": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",+ "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "4"+ },+ "engines": {+ "node": ">= 6.0.0"+ }+ },"node_modules/ai": {"version": "6.0.185","resolved": "https://registry.npmjs.org/ai/-/ai-6.0.185.tgz",@@ -1255,6 +1699,12 @@"node": ">=12"}},+ "node_modules/asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",+ "license": "MIT"+ },"node_modules/atomic-sleep": {"version": "1.0.0","resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",@@ -1274,6 +1724,18 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/axios": {+ "version": "1.18.0",+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.0.tgz",+ "integrity": "sha512-E32NzpYKp++W7XRe52rHiXV2ehxmh3wbdgO7MHeFM+vqxLBYHzt0ElkiImtOBxtOmyp0yoC8C6uESVV84Y2/hw==",+ "license": "MIT",+ "dependencies": {+ "follow-redirects": "^1.16.0",+ "form-data": "^4.0.5",+ "https-proxy-agent": "^5.0.1",+ "proxy-from-env": "^2.1.0"+ }+ },"node_modules/base64-js": {"version": "1.5.1","resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",@@ -1336,6 +1798,43 @@"readable-stream": "^3.4.0"}},+ "node_modules/body-parser": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",+ "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^2.0.0",+ "debug": "^4.4.3",+ "http-errors": "^2.0.1",+ "iconv-lite": "^0.7.2",+ "on-finished": "^2.4.1",+ "qs": "^6.15.2",+ "raw-body": "^3.0.2",+ "type-is": "^2.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/body-parser/node_modules/content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/buffer": {"version": "5.7.1","resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",@@ -1360,6 +1859,12 @@"ieee754": "^1.1.13"}},+ "node_modules/buffer-equal-constant-time": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",+ "license": "BSD-3-Clause"+ },"node_modules/bundle-require": {"version": "5.1.0","resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz",@@ -1375,6 +1880,15 @@"esbuild": ">=0.18"}},+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/cac": {"version": "6.7.14","resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",@@ -1384,6 +1898,35 @@"node": ">=8"}},+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/chai": {"version": "5.3.3","resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",@@ -1507,6 +2050,18 @@"node": "^12.20.0 || ^14.13.1 || >=16.0.0"}},+ "node_modules/combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "license": "MIT",+ "dependencies": {+ "delayed-stream": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/commander": {"version": "12.1.0","resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",@@ -1530,6 +2085,28 @@"node": "^14.18.0 || >=16.10.0"}},+ "node_modules/content-disposition": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/convert-to-spaces": {"version": "2.0.1","resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-2.0.1.tgz",@@ -1538,9 +2115,27 @@"node": "^12.20.0 || ^14.13.1 || >=16.0.0"}},- "node_modules/csstype": {- "version": "3.2.3",- "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz","integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==","devOptional": true},@@ -1593,6 +2188,24 @@"node": ">=4.0.0"}},+ "node_modules/delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/detect-libc": {"version": "2.1.2","resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",@@ -1602,6 +2215,42 @@"node": ">=8"}},+ "node_modules/discord-api-types": {+ "version": "0.38.48",+ "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.48.tgz",+ "integrity": "sha512-WFUE/2o0lBlLeCQonQ+Pu2RqHAqbytBJ2RlXR91gzk05InSS6k9ShzzLYoymrA4c2oRgRKGE7/VqQJNNdGWSxQ==",+ "license": "MIT",+ "workspaces": [+ "scripts/actions/documentation"+ ]+ },+ "node_modules/discord.js": {+ "version": "14.26.4",+ "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.26.4.tgz",+ "integrity": "sha512-4oBp8tc6Kf8IDBwAHhbsMaAqx1b5fob9SNasZT7V6yyyUydoO5i5fGuX7TmvRtR+q/WgKRnRViRoAWnG7fNyvA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@discordjs/builders": "^1.14.1",+ "@discordjs/collection": "1.5.3",+ "@discordjs/formatters": "^0.6.2",+ "@discordjs/rest": "^2.6.1",+ "@discordjs/util": "^1.2.0",+ "@discordjs/ws": "^1.2.3",+ "@sapphire/snowflake": "3.5.3",+ "discord-api-types": "^0.38.40",+ "fast-deep-equal": "3.1.3",+ "lodash.snakecase": "4.1.1",+ "magic-bytes.js": "^1.13.0",+ "tslib": "^2.6.3",+ "undici": "6.24.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },"node_modules/dotenv": {"version": "16.6.1","resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",@@ -1613,11 +2262,49 @@"url": "https://dotenvx.com"}},+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/ecdsa-sig-formatter": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },"node_modules/emoji-regex": {"version": "10.6.0","resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz","integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="},+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/end-of-stream": {"version": "1.4.5","resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",@@ -1638,12 +2325,57 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/es-module-lexer": {"version": "1.7.0","resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz","integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==","dev": true},+ "node_modules/es-object-atoms": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/es-toolkit": {"version": "1.46.1","resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.46.1.tgz",@@ -1690,6 +2422,12 @@"@esbuild/win32-x64": "0.27.7"}},+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },"node_modules/escape-string-regexp": {"version": "2.0.0","resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz",@@ -1707,6 +2445,15 @@"@types/estree": "^1.0.0"}},+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/event-target-shim": {"version": "5.0.1","resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",@@ -1715,6 +2462,12 @@"node": ">=6"}},+ "node_modules/eventemitter3": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",+ "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",+ "license": "MIT"+ },"node_modules/eventsource-parser": {"version": "3.0.8","resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.8.tgz",@@ -1741,6 +2494,55 @@"node": ">=12.0.0"}},+ "node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },"node_modules/fdir": {"version": "6.5.0","resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",@@ -1764,6 +2566,27 @@"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==","optional": true},+ "node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/fix-dts-default-cjs-exports": {"version": "1.0.1","resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz",@@ -1775,6 +2598,81 @@"rollup": "^4.34.8"}},+ "node_modules/follow-redirects": {+ "version": "1.16.0",+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",+ "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/RubenVerborgh"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=4.0"+ },+ "peerDependenciesMeta": {+ "debug": {+ "optional": true+ }+ }+ },+ "node_modules/form-data": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",+ "license": "MIT",+ "dependencies": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "es-set-tostringtag": "^2.1.0",+ "hasown": "^2.0.4",+ "mime-types": "^2.1.35"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/form-data/node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/form-data/node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/fs-constants": {"version": "1.0.0","resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",@@ -1795,6 +2693,15 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/get-east-asian-width": {"version": "1.6.0","resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz",@@ -1806,12 +2713,61 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/github-from-package": {"version": "0.0.0","resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz","integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==","optional": true},+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/grammy": {"version": "1.43.0","resolved": "https://registry.npmjs.org/grammy/-/grammy-1.43.0.tgz",@@ -1826,6 +2782,45 @@"node": "^12.20.0 || >=14.13.1"}},+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "license": "MIT",+ "dependencies": {+ "has-symbols": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/hono": {"version": "4.12.21","resolved": "https://registry.npmjs.org/hono/-/hono-4.12.21.tgz",@@ -1834,6 +2829,55 @@"node": ">=16.9.0"}},+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/https-proxy-agent": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",+ "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",+ "license": "MIT",+ "dependencies": {+ "agent-base": "6",+ "debug": "4"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/iconv-lite": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",+ "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/ieee754": {"version": "1.2.1","resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",@@ -1868,8 +2912,7 @@"node_modules/inherits": {"version": "2.0.4","resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",- "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",- "optional": true+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="},"node_modules/ini": {"version": "1.3.8",@@ -1924,6 +2967,21 @@}}},+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/is-electron": {+ "version": "2.2.2",+ "resolved": "https://registry.npmjs.org/is-electron/-/is-electron-2.2.2.tgz",+ "integrity": "sha512-FO/Rhvz5tuw4MCWkpMzHFKWD2LsfHzIb7i6MdPYZ/KW7AlxawyLkqdy+jPZP1WubqEADE3O4FUENlJHDfQASRg==",+ "license": "MIT"+ },"node_modules/is-fullwidth-code-point": {"version": "4.0.0","resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz",@@ -1949,6 +3007,24 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },+ "node_modules/is-stream": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/joycon": {"version": "3.1.1","resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",@@ -1968,6 +3044,49 @@"resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz","integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="},+ "node_modules/jsonwebtoken": {+ "version": "9.0.3",+ "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",+ "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",+ "license": "MIT",+ "dependencies": {+ "jws": "^4.0.1",+ "lodash.includes": "^4.3.0",+ "lodash.isboolean": "^3.0.3",+ "lodash.isinteger": "^4.0.4",+ "lodash.isnumber": "^3.0.3",+ "lodash.isplainobject": "^4.0.6",+ "lodash.isstring": "^4.0.1",+ "lodash.once": "^4.0.0",+ "ms": "^2.1.1",+ "semver": "^7.5.4"+ },+ "engines": {+ "node": ">=12",+ "npm": ">=6"+ }+ },+ "node_modules/jwa": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",+ "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",+ "license": "MIT",+ "dependencies": {+ "buffer-equal-constant-time": "^1.0.1",+ "ecdsa-sig-formatter": "1.0.11",+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/jws": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",+ "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",+ "license": "MIT",+ "dependencies": {+ "jwa": "^2.0.1",+ "safe-buffer": "^5.0.1"+ }+ },"node_modules/lilconfig": {"version": "3.1.3","resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",@@ -1995,6 +3114,60 @@"node": "^12.20.0 || ^14.13.1 || >=16.0.0"}},+ "node_modules/lodash": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",+ "license": "MIT"+ },+ "node_modules/lodash.includes": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",+ "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",+ "license": "MIT"+ },+ "node_modules/lodash.isboolean": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",+ "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",+ "license": "MIT"+ },+ "node_modules/lodash.isinteger": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",+ "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",+ "license": "MIT"+ },+ "node_modules/lodash.isnumber": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",+ "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",+ "license": "MIT"+ },+ "node_modules/lodash.isplainobject": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",+ "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",+ "license": "MIT"+ },+ "node_modules/lodash.isstring": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",+ "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",+ "license": "MIT"+ },+ "node_modules/lodash.once": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",+ "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",+ "license": "MIT"+ },+ "node_modules/lodash.snakecase": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",+ "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",+ "license": "MIT"+ },"node_modules/loose-envify": {"version": "1.4.0","resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",@@ -2012,6 +3185,12 @@"integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==","dev": true},+ "node_modules/magic-bytes.js": {+ "version": "1.13.0",+ "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.0.tgz",+ "integrity": "sha512-afO2mnxW7GDTXMm5/AoN1WuOcdoKhtgXjIvHmobqTD1grNplhGdv3PFOyjCVmrnOZBIT/gD/koDKpYG+0mvHcg==",+ "license": "MIT"+ },"node_modules/magic-string": {"version": "0.30.21","resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",@@ -2032,6 +3211,61 @@"node": ">= 18"}},+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/mimic-fn": {"version": "2.1.0","resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",@@ -2118,6 +3352,15 @@"integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==","optional": true},+ "node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/node-abi": {"version": "3.92.0","resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.92.0.tgz",@@ -2169,6 +3412,18 @@"node": ">=0.10.0"}},+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/ollama-ai-provider": {"version": "1.2.0","resolved": "https://registry.npmjs.org/ollama-ai-provider/-/ollama-ai-provider-1.2.0.tgz",@@ -2225,11 +3480,22 @@"node": ">=14.0.0"}},+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/once": {"version": "1.4.0","resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz","integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",- "optional": true,"dependencies": {"wrappy": "1"}@@ -2248,6 +3514,71 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/p-finally": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",+ "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/p-queue": {+ "version": "6.6.2",+ "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz",+ "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==",+ "license": "MIT",+ "dependencies": {+ "eventemitter3": "^4.0.4",+ "p-timeout": "^3.2.0"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/p-queue/node_modules/eventemitter3": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",+ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",+ "license": "MIT"+ },+ "node_modules/p-retry": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",+ "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",+ "license": "MIT",+ "dependencies": {+ "@types/retry": "0.12.0",+ "retry": "^0.13.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/p-timeout": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz",+ "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==",+ "license": "MIT",+ "dependencies": {+ "p-finally": "^1.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/partial-json": {"version": "0.1.7","resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",@@ -2261,6 +3592,16 @@"node": "^12.20.0 || ^14.13.1 || >=16.0.0"}},+ "node_modules/path-to-regexp": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/pathe": {"version": "2.0.3","resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",@@ -2462,6 +3803,28 @@}]},+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/proxy-from-env": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",+ "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },"node_modules/pump": {"version": "3.0.4","resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",@@ -2472,11 +3835,58 @@"once": "^1.3.1"}},+ "node_modules/qrcode-terminal": {+ "version": "0.12.0",+ "resolved": "https://registry.npmjs.org/qrcode-terminal/-/qrcode-terminal-0.12.0.tgz",+ "integrity": "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ==",+ "bin": {+ "qrcode-terminal": "bin/qrcode-terminal.js"+ }+ },+ "node_modules/qs": {+ "version": "6.15.2",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",+ "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"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=="},+ "node_modules/range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },"node_modules/rc": {"version": "1.2.8","resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",@@ -2609,6 +4019,15 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/retry": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",+ "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },"node_modules/rollup": {"version": "4.60.4","resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.4.tgz",@@ -2653,6 +4072,22 @@"fsevents": "~2.3.2"}},+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },"node_modules/safe-buffer": {"version": "5.2.1","resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",@@ -2670,8 +4105,7 @@"type": "consulting","url": "https://feross.org/support"}- ],- "optional": true+ ]},"node_modules/safe-stable-stringify": {"version": "2.5.0",@@ -2681,6 +4115,12 @@"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/scheduler": {"version": "0.23.2","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",@@ -2698,7 +4138,6 @@"version": "7.8.0","resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz","integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==",- "optional": true,"bin": {"semver": "bin/semver.js"},@@ -2706,6 +4145,57 @@"node": ">=10"}},+ "node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },"node_modules/shell-quote": {"version": "1.8.4","resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.4.tgz",@@ -2718,6 +4208,78 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/side-channel": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",+ "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4",+ "side-channel-list": "^1.0.1",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/siginfo": {"version": "2.0.0","resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",@@ -2860,6 +4422,15 @@"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==","dev": true},+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/std-env": {"version": "3.10.0","resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",@@ -3085,6 +4656,15 @@"node": ">=14.0.0"}},+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },"node_modules/tr46": {"version": "0.0.3","resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",@@ -3105,6 +4685,27 @@"integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==","dev": true},+ "node_modules/ts-mixer": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",+ "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==",+ "license": "MIT"+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/tsscmp": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz",+ "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6.x"+ }+ },"node_modules/tsup": {"version": "8.5.1","resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz",@@ -3180,6 +4781,37 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/type-is": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",+ "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^2.0.0",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/type-is/node_modules/content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/typescript": {"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",@@ -3199,11 +4831,28 @@"integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==","dev": true},+ "node_modules/undici": {+ "version": "6.24.1",+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.24.1.tgz",+ "integrity": "sha512-sC+b0tB1whOCzbtlx20fx3WgCXwkW627p4EA9uM+/tNNPkSS+eSEld6pAs9nDv7WbY1UUljBMYPtu9BCOrCWKA==",+ "license": "MIT",+ "engines": {+ "node": ">=18.17"+ }+ },"node_modules/undici-types": {"version": "6.21.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",- "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",- "dev": true+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="+ },+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }},"node_modules/util-deprecate": {"version": "1.0.2",@@ -3220,6 +4869,15 @@"uuid": "dist/bin/uuid"}},+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/vite": {"version": "6.4.2","resolved": "https://registry.npmjs.org/vite/-/vite-6.4.2.tgz",@@ -3908,8 +5566,7 @@"node_modules/wrappy": {"version": "1.0.2","resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",- "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",- "optional": true+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="},"node_modules/ws": {"version": "8.20.1",@@ -4024,6 +5681,92 @@"is-fullwidth-code-point": "^4.0.0"}},+ "@discordjs/builders": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",+ "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",+ "requires": {+ "@discordjs/formatters": "^0.6.2",+ "@discordjs/util": "^1.2.0",+ "@sapphire/shapeshift": "^4.0.0",+ "discord-api-types": "^0.38.40",+ "fast-deep-equal": "^3.1.3",+ "ts-mixer": "^6.0.4",+ "tslib": "^2.6.3"+ }+ },+ "@discordjs/collection": {+ "version": "1.5.3",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",+ "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ=="+ },+ "@discordjs/formatters": {+ "version": "0.6.2",+ "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz",+ "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",+ "requires": {+ "discord-api-types": "^0.38.33"+ }+ },+ "@discordjs/rest": {+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.1.tgz",+ "integrity": "sha512-wwQdgjeaoYFiaG+atbqx6aJDpqW7JHAo0HrQkBTbYzM3/PJ3GweQIpgElNcGZ26DCUOXMyawYd0YF7vtr+fZXg==",+ "requires": {+ "@discordjs/collection": "^2.1.1",+ "@discordjs/util": "^1.2.0",+ "@sapphire/async-queue": "^1.5.3",+ "@sapphire/snowflake": "^3.5.5",+ "@vladfrangu/async_event_emitter": "^2.4.6",+ "discord-api-types": "^0.38.40",+ "magic-bytes.js": "^1.13.0",+ "tslib": "^2.6.3",+ "undici": "6.24.1"+ },+ "dependencies": {+ "@discordjs/collection": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",+ "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg=="+ },+ "@sapphire/snowflake": {+ "version": "3.5.5",+ "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz",+ "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ=="+ }+ }+ },+ "@discordjs/util": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz",+ "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",+ "requires": {+ "discord-api-types": "^0.38.33"+ }+ },+ "@discordjs/ws": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz",+ "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",+ "requires": {+ "@discordjs/collection": "^2.1.0",+ "@discordjs/rest": "^2.5.1",+ "@discordjs/util": "^1.1.0",+ "@sapphire/async-queue": "^1.5.2",+ "@types/ws": "^8.5.10",+ "@vladfrangu/async_event_emitter": "^2.2.4",+ "discord-api-types": "^0.38.1",+ "tslib": "^2.6.2",+ "ws": "^8.17.0"+ },+ "dependencies": {+ "@discordjs/collection": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",+ "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg=="+ }+ }+ },"@esbuild/aix-ppc64": {"version": "0.27.7","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",@@ -4442,6 +6185,99 @@"dev": true,"optional": true},+ "@sapphire/async-queue": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz",+ "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg=="+ },+ "@sapphire/shapeshift": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz",+ "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",+ "requires": {+ "fast-deep-equal": "^3.1.3",+ "lodash": "^4.17.21"+ }+ },+ "@sapphire/snowflake": {+ "version": "3.5.3",+ "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.3.tgz",+ "integrity": "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ=="+ },+ "@slack/bolt": {+ "version": "4.7.3",+ "resolved": "https://registry.npmjs.org/@slack/bolt/-/bolt-4.7.3.tgz",+ "integrity": "sha512-bODs8q/yNDWUPoxmQhFrRqLMA5vhB/PDizYWqb6CkQhLWEUo5JFtfJcmeU4ElGl6qSt++OKjSYNa4MPc77CleQ==",+ "requires": {+ "@slack/logger": "^4.0.1",+ "@slack/oauth": "^3.0.5",+ "@slack/socket-mode": "^2.0.7",+ "@slack/types": "^2.21.1",+ "@slack/web-api": "^7.16.0",+ "axios": "^1.12.0",+ "express": "^5.0.0",+ "path-to-regexp": "^8.1.0",+ "raw-body": "^3",+ "tsscmp": "^1.0.6"+ }+ },+ "@slack/logger": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/@slack/logger/-/logger-4.0.1.tgz",+ "integrity": "sha512-6cmdPrV/RYfd2U0mDGiMK8S7OJqpCTm7enMLRR3edccsPX8j7zXTLnaEF4fhxxJJTAIOil6+qZrnUPTuaLvwrQ==",+ "requires": {+ "@types/node": ">=18"+ }+ },+ "@slack/oauth": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/@slack/oauth/-/oauth-3.0.5.tgz",+ "integrity": "sha512-exqFQySKhNDptWYSWhvRUJ4/+ndu2gayIy7vg/JfmJq3wGtGdHk531P96fAZyBm5c1Le3yaPYqv92rL4COlU3A==",+ "requires": {+ "@slack/logger": "^4.0.1",+ "@slack/web-api": "^7.15.0",+ "@types/jsonwebtoken": "^9",+ "@types/node": ">=18",+ "jsonwebtoken": "^9"+ }+ },+ "@slack/socket-mode": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@slack/socket-mode/-/socket-mode-2.0.7.tgz",+ "integrity": "sha512-qYy07je71WnEHgRwmw12DlAnZLi5HXmdlI2WUzUK2LH/rYXQpP6uEg462S5CwfE8FoCKUdIigHtYnOOfzZH1lQ==",+ "requires": {+ "@slack/logger": "^4.0.1",+ "@slack/web-api": "^7.15.0",+ "@types/node": ">=18",+ "@types/ws": "^8",+ "eventemitter3": "^5",+ "ws": "^8"+ }+ },+ "@slack/types": {+ "version": "2.21.1",+ "resolved": "https://registry.npmjs.org/@slack/types/-/types-2.21.1.tgz",+ "integrity": "sha512-I8vmSjNYWsaxuWPx6dz4yeh0h7vRBWbgAMK14LEmblbZ404BtrPbXs6jDPx4cYgGf8msDGF4A9opLZBu21FViQ=="+ },+ "@slack/web-api": {+ "version": "7.17.0",+ "resolved": "https://registry.npmjs.org/@slack/web-api/-/web-api-7.17.0.tgz",+ "integrity": "sha512-jejr34a8B4L5AS713wOAx1LAqNkW16HVMDEa6sYBvFDc/llUBl8hXaiI4BwF+Al+Sug19Vn2O7iokTVIhVvZ1Q==",+ "requires": {+ "@slack/logger": "^4.0.1",+ "@slack/types": "^2.21.0",+ "@types/node": ">=18",+ "@types/retry": "0.12.0",+ "axios": "^1.16.0",+ "eventemitter3": "^5.0.1",+ "form-data": "^4.0.4",+ "is-electron": "2.2.2",+ "is-stream": "^2",+ "p-queue": "^6",+ "p-retry": "^4",+ "retry": "^0.13.1"+ }+ },"@standard-schema/spec": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",@@ -4465,6 +6301,16 @@"@types/node": "*"}},+ "@types/body-parser": {+ "version": "1.19.6",+ "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",+ "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",+ "peer": true,+ "requires": {+ "@types/connect": "*",+ "@types/node": "*"+ }+ },"@types/chai": {"version": "5.2.3","resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",@@ -4475,6 +6321,15 @@"assertion-error": "^2.0.1"}},+ "@types/connect": {+ "version": "3.4.38",+ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",+ "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",+ "peer": true,+ "requires": {+ "@types/node": "*"+ }+ },"@types/deep-eql": {"version": "4.0.2","resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",@@ -4487,11 +6342,53 @@"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==","dev": true},+ "@types/express": {+ "version": "5.0.6",+ "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",+ "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",+ "peer": true,+ "requires": {+ "@types/body-parser": "*",+ "@types/express-serve-static-core": "^5.0.0",+ "@types/serve-static": "^2"+ }+ },+ "@types/express-serve-static-core": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz",+ "integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==",+ "peer": true,+ "requires": {+ "@types/node": "*",+ "@types/qs": "*",+ "@types/range-parser": "*",+ "@types/send": "*"+ }+ },+ "@types/http-errors": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",+ "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",+ "peer": true+ },+ "@types/jsonwebtoken": {+ "version": "9.0.10",+ "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",+ "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",+ "requires": {+ "@types/ms": "*",+ "@types/node": "*"+ }+ },+ "@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="+ },"@types/node": {"version": "22.19.19","resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.19.tgz","integrity": "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==",- "dev": true,"requires": {"undici-types": "~6.21.0"}@@ -4508,6 +6405,24 @@"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==","devOptional": true},+ "@types/qrcode-terminal": {+ "version": "0.12.2",+ "resolved": "https://registry.npmjs.org/@types/qrcode-terminal/-/qrcode-terminal-0.12.2.tgz",+ "integrity": "sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q==",+ "dev": true+ },+ "@types/qs": {+ "version": "6.15.1",+ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",+ "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==",+ "peer": true+ },+ "@types/range-parser": {+ "version": "1.2.7",+ "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",+ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",+ "peer": true+ },"@types/react": {"version": "18.3.28","resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",@@ -4518,6 +6433,38 @@"csstype": "^3.2.2"}},+ "@types/retry": {+ "version": "0.12.0",+ "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",+ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="+ },+ "@types/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",+ "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",+ "peer": true,+ "requires": {+ "@types/node": "*"+ }+ },+ "@types/serve-static": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",+ "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",+ "peer": true,+ "requires": {+ "@types/http-errors": "*",+ "@types/node": "*"+ }+ },+ "@types/ws": {+ "version": "8.18.1",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",+ "requires": {+ "@types/node": "*"+ }+ },"@vercel/oidc": {"version": "3.2.0","resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.2.0.tgz",@@ -4598,6 +6545,11 @@"tinyrainbow": "^2.0.0"}},+ "@vladfrangu/async_event_emitter": {+ "version": "2.4.7",+ "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz",+ "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g=="+ },"abort-controller": {"version": "3.0.0","resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",@@ -4606,12 +6558,29 @@"event-target-shim": "^5.0.0"}},+ "accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "requires": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ }+ },"acorn": {"version": "8.16.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz","integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==","dev": true},+ "agent-base": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",+ "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",+ "requires": {+ "debug": "4"+ }+ },"ai": {"version": "6.0.185","resolved": "https://registry.npmjs.org/ai/-/ai-6.0.185.tgz",@@ -4653,6 +6622,11 @@"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==","dev": true},+ "asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="+ },"atomic-sleep": {"version": "1.0.0","resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",@@ -4663,6 +6637,17 @@"resolved": "https://registry.npmjs.org/auto-bind/-/auto-bind-5.0.1.tgz","integrity": "sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg=="},+ "axios": {+ "version": "1.18.0",+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.0.tgz",+ "integrity": "sha512-E32NzpYKp++W7XRe52rHiXV2ehxmh3wbdgO7MHeFM+vqxLBYHzt0ElkiImtOBxtOmyp0yoC8C6uESVV84Y2/hw==",+ "requires": {+ "follow-redirects": "^1.16.0",+ "form-data": "^4.0.5",+ "https-proxy-agent": "^5.0.1",+ "proxy-from-env": "^2.1.0"+ }+ },"base64-js": {"version": "1.5.1","resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",@@ -4704,6 +6689,29 @@"readable-stream": "^3.4.0"}},+ "body-parser": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",+ "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",+ "requires": {+ "bytes": "^3.1.2",+ "content-type": "^2.0.0",+ "debug": "^4.4.3",+ "http-errors": "^2.0.1",+ "iconv-lite": "^0.7.2",+ "on-finished": "^2.4.1",+ "qs": "^6.15.2",+ "raw-body": "^3.0.2",+ "type-is": "^2.1.0"+ },+ "dependencies": {+ "content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="+ }+ }+ },"buffer": {"version": "5.7.1","resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",@@ -4714,6 +6722,11 @@"ieee754": "^1.1.13"}},+ "buffer-equal-constant-time": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="+ },"bundle-require": {"version": "5.1.0","resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz",@@ -4723,12 +6736,35 @@"load-tsconfig": "^0.2.3"}},+ "bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="+ },"cac": {"version": "6.7.14","resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz","integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==","dev": true},+ "call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "requires": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ }+ },+ "call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "requires": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ }+ },"chai": {"version": "5.3.3","resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",@@ -4809,6 +6845,14 @@"convert-to-spaces": "^2.0.1"}},+ "combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "requires": {+ "delayed-stream": "~1.0.0"+ }+ },"commander": {"version": "12.1.0","resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",@@ -4826,11 +6870,31 @@"integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==","dev": true},+ "content-disposition": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="+ },+ "content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="+ },"convert-to-spaces": {"version": "2.0.1","resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-2.0.1.tgz","integrity": "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ=="},+ "cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="+ },+ "cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="+ },"csstype": {"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",@@ -4866,22 +6930,85 @@"integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==","optional": true},+ "delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="+ },+ "depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="+ },"detect-libc": {"version": "2.1.2","resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz","integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==","optional": true},+ "discord-api-types": {+ "version": "0.38.48",+ "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.48.tgz",+ "integrity": "sha512-WFUE/2o0lBlLeCQonQ+Pu2RqHAqbytBJ2RlXR91gzk05InSS6k9ShzzLYoymrA4c2oRgRKGE7/VqQJNNdGWSxQ=="+ },+ "discord.js": {+ "version": "14.26.4",+ "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.26.4.tgz",+ "integrity": "sha512-4oBp8tc6Kf8IDBwAHhbsMaAqx1b5fob9SNasZT7V6yyyUydoO5i5fGuX7TmvRtR+q/WgKRnRViRoAWnG7fNyvA==",+ "requires": {+ "@discordjs/builders": "^1.14.1",+ "@discordjs/collection": "1.5.3",+ "@discordjs/formatters": "^0.6.2",+ "@discordjs/rest": "^2.6.1",+ "@discordjs/util": "^1.2.0",+ "@discordjs/ws": "^1.2.3",+ "@sapphire/snowflake": "3.5.3",+ "discord-api-types": "^0.38.40",+ "fast-deep-equal": "3.1.3",+ "lodash.snakecase": "4.1.1",+ "magic-bytes.js": "^1.13.0",+ "tslib": "^2.6.3",+ "undici": "6.24.1"+ }+ },"dotenv": {"version": "16.6.1","resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz","integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="},+ "dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "requires": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ }+ },+ "ecdsa-sig-formatter": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",+ "requires": {+ "safe-buffer": "^5.0.1"+ }+ },+ "ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="+ },"emoji-regex": {"version": "10.6.0","resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz","integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="},+ "encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="+ },"end-of-stream": {"version": "1.4.5","resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",@@ -4896,12 +7023,41 @@"resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz","integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q=="},+ "es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="+ },+ "es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="+ },"es-module-lexer": {"version": "1.7.0","resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz","integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==","dev": true},+ "es-object-atoms": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",+ "requires": {+ "es-errors": "^1.3.0"+ }+ },+ "es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "requires": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ }+ },"es-toolkit": {"version": "1.46.1","resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.46.1.tgz",@@ -4941,6 +7097,11 @@"@esbuild/win32-x64": "0.27.7"}},+ "escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="+ },"escape-string-regexp": {"version": "2.0.0","resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz",@@ -4955,11 +7116,21 @@"@types/estree": "^1.0.0"}},+ "etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="+ },"event-target-shim": {"version": "5.0.1","resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz","integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="},+ "eventemitter3": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",+ "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="+ },"eventsource-parser": {"version": "3.0.8","resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.8.tgz",@@ -4977,6 +7148,46 @@"integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==","dev": true},+ "express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "requires": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ }+ },+ "fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="+ },"fdir": {"version": "6.5.0","resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",@@ -4990,6 +7201,19 @@"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==","optional": true},+ "finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "requires": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ }+ },"fix-dts-default-cjs-exports": {"version": "1.0.1","resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz",@@ -5001,6 +7225,48 @@"rollup": "^4.34.8"}},+ "follow-redirects": {+ "version": "1.16.0",+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",+ "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw=="+ },+ "form-data": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",+ "requires": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "es-set-tostringtag": "^2.1.0",+ "hasown": "^2.0.4",+ "mime-types": "^2.1.35"+ },+ "dependencies": {+ "mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="+ },+ "mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "requires": {+ "mime-db": "1.52.0"+ }+ }+ }+ },+ "forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="+ },+ "fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="+ },"fs-constants": {"version": "1.0.0","resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",@@ -5014,17 +7280,53 @@"dev": true,"optional": true},+ "function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="+ },"get-east-asian-width": {"version": "1.6.0","resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz","integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA=="},+ "get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "requires": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ }+ },+ "get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "requires": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ }+ },"github-from-package": {"version": "0.0.0","resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz","integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==","optional": true},+ "gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="+ },"grammy": {"version": "1.43.0","resolved": "https://registry.npmjs.org/grammy/-/grammy-1.43.0.tgz",@@ -5036,11 +7338,61 @@"node-fetch": "^2.7.0"}},+ "has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="+ },+ "has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "requires": {+ "has-symbols": "^1.0.3"+ }+ },+ "hasown": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",+ "requires": {+ "function-bind": "^1.1.2"+ }+ },"hono": {"version": "4.12.21","resolved": "https://registry.npmjs.org/hono/-/hono-4.12.21.tgz","integrity": "sha512-uV63apnb0kyPtAUwoWgaGh9HyIFcv8lgmzPZSiTBQAFOFGIzka5EZ1dZocmGnn0XdX0+XTqJ6Tqv7selMuGLRQ=="},+ "http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "requires": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ }+ },+ "https-proxy-agent": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",+ "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",+ "requires": {+ "agent-base": "6",+ "debug": "4"+ }+ },+ "iconv-lite": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",+ "requires": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ }+ },"ieee754": {"version": "1.2.1","resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",@@ -5055,8 +7407,7 @@"inherits": {"version": "2.0.4","resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",- "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",- "optional": true+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="},"ini": {"version": "1.3.8",@@ -5095,6 +7446,16 @@"yoga-layout": "~3.2.1"}},+ "ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="+ },+ "is-electron": {+ "version": "2.2.2",+ "resolved": "https://registry.npmjs.org/is-electron/-/is-electron-2.2.2.tgz",+ "integrity": "sha512-FO/Rhvz5tuw4MCWkpMzHFKWD2LsfHzIb7i6MdPYZ/KW7AlxawyLkqdy+jPZP1WubqEADE3O4FUENlJHDfQASRg=="+ },"is-fullwidth-code-point": {"version": "4.0.0","resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz",@@ -5105,6 +7466,16 @@"resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-1.0.0.tgz","integrity": "sha512-eUuAjybVTHMYWm/U+vBO1sY/JOCgoPCXRxzdju0K+K0BiGW0SChEL1MLC0PoCIR1OlPo5YAp8HuQoUlsWEICwg=="},+ "is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="+ },+ "is-stream": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="+ },"joycon": {"version": "3.1.1","resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",@@ -5121,6 +7492,42 @@"resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz","integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="},+ "jsonwebtoken": {+ "version": "9.0.3",+ "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",+ "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",+ "requires": {+ "jws": "^4.0.1",+ "lodash.includes": "^4.3.0",+ "lodash.isboolean": "^3.0.3",+ "lodash.isinteger": "^4.0.4",+ "lodash.isnumber": "^3.0.3",+ "lodash.isplainobject": "^4.0.6",+ "lodash.isstring": "^4.0.1",+ "lodash.once": "^4.0.0",+ "ms": "^2.1.1",+ "semver": "^7.5.4"+ }+ },+ "jwa": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",+ "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",+ "requires": {+ "buffer-equal-constant-time": "^1.0.1",+ "ecdsa-sig-formatter": "1.0.11",+ "safe-buffer": "^5.0.1"+ }+ },+ "jws": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",+ "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",+ "requires": {+ "jwa": "^2.0.1",+ "safe-buffer": "^5.0.1"+ }+ },"lilconfig": {"version": "3.1.3","resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",@@ -5139,6 +7546,51 @@"integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==","dev": true},+ "lodash": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="+ },+ "lodash.includes": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",+ "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="+ },+ "lodash.isboolean": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",+ "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="+ },+ "lodash.isinteger": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",+ "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA=="+ },+ "lodash.isnumber": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",+ "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw=="+ },+ "lodash.isplainobject": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",+ "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="+ },+ "lodash.isstring": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",+ "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="+ },+ "lodash.once": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",+ "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="+ },+ "lodash.snakecase": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",+ "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw=="+ },"loose-envify": {"version": "1.4.0","resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",@@ -5153,6 +7605,11 @@"integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==","dev": true},+ "magic-bytes.js": {+ "version": "1.13.0",+ "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.0.tgz",+ "integrity": "sha512-afO2mnxW7GDTXMm5/AoN1WuOcdoKhtgXjIvHmobqTD1grNplhGdv3PFOyjCVmrnOZBIT/gD/koDKpYG+0mvHcg=="+ },"magic-string": {"version": "0.30.21","resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",@@ -5167,6 +7624,34 @@"resolved": "https://registry.npmjs.org/marked/-/marked-14.1.4.tgz","integrity": "sha512-vkVZ8ONmUdPnjCKc5uTRvmkRbx4EAi2OkTOXmfTDhZz3OFqMNBM1oTTWwTr4HY4uAEojhzPf+Fy8F1DWa3Sndg=="},+ "math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="+ },+ "media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="+ },+ "merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="+ },+ "mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="+ },+ "mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "requires": {+ "mime-db": "^1.54.0"+ }+ },"mimic-fn": {"version": "2.1.0","resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",@@ -5229,6 +7714,11 @@"integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==","optional": true},+ "negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="+ },"node-abi": {"version": "3.92.0","resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.92.0.tgz",@@ -5260,6 +7750,11 @@"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==","dev": true},+ "object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="+ },"ollama-ai-provider": {"version": "1.2.0","resolved": "https://registry.npmjs.org/ollama-ai-provider/-/ollama-ai-provider-1.2.0.tgz",@@ -5295,11 +7790,18 @@"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz","integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="},+ "on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "requires": {+ "ee-first": "1.1.1"+ }+ },"once": {"version": "1.4.0","resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz","integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",- "optional": true,"requires": {"wrappy": "1"}@@ -5312,6 +7814,49 @@"mimic-fn": "^2.1.0"}},+ "p-finally": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",+ "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow=="+ },+ "p-queue": {+ "version": "6.6.2",+ "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz",+ "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==",+ "requires": {+ "eventemitter3": "^4.0.4",+ "p-timeout": "^3.2.0"+ },+ "dependencies": {+ "eventemitter3": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",+ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw=="+ }+ }+ },+ "p-retry": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",+ "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",+ "requires": {+ "@types/retry": "0.12.0",+ "retry": "^0.13.1"+ }+ },+ "p-timeout": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz",+ "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==",+ "requires": {+ "p-finally": "^1.0.0"+ }+ },+ "parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="+ },"partial-json": {"version": "0.1.7","resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",@@ -5322,6 +7867,11 @@"resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz","integrity": "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA=="},+ "path-to-regexp": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="+ },"pathe": {"version": "2.0.3","resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",@@ -5439,6 +7989,20 @@"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz","integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA=="},+ "proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "requires": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ }+ },+ "proxy-from-env": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",+ "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA=="+ },"pump": {"version": "3.0.4","resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",@@ -5449,11 +8013,40 @@"once": "^1.3.1"}},+ "qrcode-terminal": {+ "version": "0.12.0",+ "resolved": "https://registry.npmjs.org/qrcode-terminal/-/qrcode-terminal-0.12.0.tgz",+ "integrity": "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ=="+ },+ "qs": {+ "version": "6.15.2",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",+ "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==",+ "requires": {+ "side-channel": "^1.1.0"+ }+ },"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=="},+ "range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="+ },+ "raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "requires": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ }+ },"rc": {"version": "1.2.8","resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",@@ -5539,6 +8132,11 @@"signal-exit": "^3.0.2"}},+ "retry": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",+ "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="+ },"rollup": {"version": "4.60.4","resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.4.tgz",@@ -5574,17 +8172,33 @@"fsevents": "~2.3.2"}},+ "router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "requires": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ }+ },"safe-buffer": {"version": "5.2.1","resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",- "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",- "optional": true+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="},"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=="},+ "safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="+ },"scheduler": {"version": "0.23.2","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",@@ -5601,8 +8215,41 @@"semver": {"version": "7.8.0","resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz",- "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==",- "optional": true+ "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA=="+ },+ "send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "requires": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ }+ },+ "serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "requires": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ }+ },+ "setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="},"shell-quote": {"version": "1.8.4",@@ -5610,6 +8257,50 @@"integrity": "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==","devOptional": true},+ "side-channel": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",+ "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",+ "requires": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4",+ "side-channel-list": "^1.0.1",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ }+ },+ "side-channel-list": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",+ "requires": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4"+ }+ },+ "side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "requires": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ }+ },+ "side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "requires": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ }+ },"siginfo": {"version": "2.0.0","resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",@@ -5701,6 +8392,11 @@"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==","dev": true},+ "statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="+ },"std-env": {"version": "3.10.0","resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",@@ -5878,6 +8574,11 @@"integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==","dev": true},+ "toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="+ },"tr46": {"version": "0.0.3","resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",@@ -5895,6 +8596,21 @@"integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==","dev": true},+ "ts-mixer": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",+ "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA=="+ },+ "tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="+ },+ "tsscmp": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz",+ "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA=="+ },"tsup": {"version": "8.5.1","resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz",@@ -5934,6 +8650,23 @@"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz","integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="},+ "type-is": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",+ "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",+ "requires": {+ "content-type": "^2.0.0",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "dependencies": {+ "content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="+ }+ }+ },"typescript": {"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",@@ -5946,11 +8679,20 @@"integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==","dev": true},+ "undici": {+ "version": "6.24.1",+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.24.1.tgz",+ "integrity": "sha512-sC+b0tB1whOCzbtlx20fx3WgCXwkW627p4EA9uM+/tNNPkSS+eSEld6pAs9nDv7WbY1UUljBMYPtu9BCOrCWKA=="+ },"undici-types": {"version": "6.21.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",- "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",- "dev": true+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="+ },+ "unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="},"util-deprecate": {"version": "1.0.2",@@ -5963,6 +8705,11 @@"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz","integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="},+ "vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="+ },"vite": {"version": "6.4.2","resolved": "https://registry.npmjs.org/vite/-/vite-6.4.2.tgz",@@ -6285,8 +9032,7 @@"wrappy": {"version": "1.0.2","resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",- "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",- "optional": true+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="},"ws": {"version": "8.20.1",diff --git a/package.json b/package.jsonindex a23de4c4..fd36ed3f 100644--- a/package.json+++ b/package.json@@ -65,10 +65,12 @@"@ai-sdk/openai": "^3.0.53","@grammyjs/auto-retry": "^2.0.2","@hono/node-server": "^2.0.0",+ "@slack/bolt": "^4.7.3","ai": "^6.0.168","bcryptjs": "^3.0.3","chalk": "^5.4.0","commander": "^12.1.0",+ "discord.js": "^14.26.4","dotenv": "^16.4.7","grammy": "^1.42.0","hono": "^4.12.15",@@ -77,6 +79,7 @@"node-cron": "^3.0.3","ollama-ai-provider": "^1.2.0","pino": "^10.3.1",+ "qrcode-terminal": "^0.12.0","react": "^18.3.1","sql.js": "^1.14.1","yaml": "^2.7.0",@@ -90,6 +93,7 @@"@types/better-sqlite3": "^7.6.13","@types/node": "^22.13.0","@types/node-cron": "^3.0.11",+ "@types/qrcode-terminal": "^0.12.2","@types/react": "^18.3.28","react-devtools-core": "^4.28.5","tsup": "^8.4.0",@@ -98,5 +102,8 @@},"engines": {"node": ">=20.0.0"+ },+ "allowScripts": {+ "esbuild": true}}diff --git a/random_message.txt b/random_message.txtnew file mode 100644index 00000000..de7ab117--- /dev/null+++ b/random_message.txt@@ -0,0 +1,3 @@+This is a random text file sent just for fun. 🎲++— From Mercurydiff --git a/scripts/build-bin.cjs b/scripts/build-bin.cjsindex 6936afd3..923a952d 100644--- a/scripts/build-bin.cjs+++ b/scripts/build-bin.cjs@@ -15,6 +15,9 @@* mercury-linux-x64* mercury-linux-arm64* mercury-win-x64.exe+ * web/ ← static assets for the web dashboard+ * static/...+ * ui/...* checksums.txt* v1.2.0/ ...* latest -> v1.2.0 (symlink to most-recent build)@@ -45,6 +48,19 @@ const root = path.join(__dirname, '..');const releaseRoot = path.join(root, 'release');const entry = path.join(root, 'dist', 'index.js');+function copyDirSync(src, dest) {+ fs.mkdirSync(dest, { recursive: true });+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {+ const srcPath = path.join(src, entry.name);+ const destPath = path.join(dest, entry.name);+ if (entry.isDirectory()) {+ copyDirSync(srcPath, destPath);+ } else {+ fs.copyFileSync(srcPath, destPath);+ }+ }+}+// Read version straight from package.json — single source of truth.const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));const version = pkg.version;@@ -126,6 +142,19 @@ function compile(bun, target, { force }) {if (fs.existsSync(alt) && target.out.endsWith('.exe')) fs.renameSync(alt, outPath);}+ // Copy web assets (UI + static) alongside the binary so the web dashboard+ // works in standalone mode. server.ts resolves these relative to execPath+ // when running as a Bun-compiled binary.+ const webSrc = path.join(root, 'dist', 'web');+ const webDest = path.join(versionDir, 'web');+ if (fs.existsSync(webSrc)) {+ copyDirSync(webSrc, webDest);+ console.log(` ✓ web assets copied to ${path.relative(root, webDest)}`);+ } else {+ console.warn(` ⚠ dist/web/ not found — web dashboard will not work in the binary`);+ console.warn(` Run \`npm run build\` first to generate web assets.`);+ }+const stat = fs.statSync(outPath);const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);console.log(` ✓ ${path.relative(root, outPath)} (${sizeMB} MB)\n`);@@ -134,15 +163,24 @@ function compile(bun, target, { force }) {function writeChecksums(builtPaths) {const checksumsPath = path.join(versionDir, 'checksums.txt');- // Re-hash everything that exists in versionDir so re-runs keep the file- // accurate even when only a subset was rebuilt.- const entries = fs.readdirSync(versionDir)- .filter((f) => f !== 'checksums.txt')- .filter((f) => fs.statSync(path.join(versionDir, f)).isFile())- .sort();- const lines = entries.map((name) => `${sha256(path.join(versionDir, name))} ${name}`);+ // Collect all files in versionDir (including web/ subdirectory)+ const files = [];+ function walk(dir, base) {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const fullPath = path.join(dir, entry.name);+ const relPath = base ? `${base}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ walk(fullPath, relPath);+ } else if (entry.name !== 'checksums.txt') {+ files.push({ fullPath, relPath });+ }+ }+ }+ walk(versionDir, '');+ files.sort((a, b) => a.relPath.localeCompare(b.relPath));+ const lines = files.map(({ fullPath, relPath }) => `${sha256(fullPath)} ${relPath}`);fs.writeFileSync(checksumsPath, lines.join('\n') + '\n');- console.log(` ✓ checksums.txt (${entries.length} file${entries.length === 1 ? '' : 's'})`);+ console.log(` ✓ checksums.txt (${files.length} file${files.length === 1 ? '' : 's'})`);}function updateLatestSymlink() {@@ -183,6 +221,23 @@ for (const target of targets) {}writeChecksums(results.map((r) => r.outPath));++// Create a web.tar.gz for GitHub release uploads so installers can fetch+// dashboard assets separately (the binary doesn't embed them).+const webDir = path.join(root, 'dist', 'web');+if (fs.existsSync(webDir)) {+ const webTarPath = path.join(versionDir, 'web.tar.gz');+ try {+ execSync(`tar -czf "${webTarPath}" -C "${path.dirname(webDir)}" web`, { cwd: root, stdio: 'pipe' });+ const sizeKB = (fs.statSync(webTarPath).size / 1024).toFixed(0);+ console.log(` ✓ web.tar.gz (${sizeKB} KB)`);+ } catch (e) {+ console.warn(` ⚠ Failed to create web.tar.gz: ${e.message}`);+ }+} else {+ console.warn(' ⚠ dist/web/ not found — skipping web.tar.gz');+}+updateLatestSymlink();const built = results.filter((r) => !r.skipped).length;diff --git a/scripts/install.ps1 b/scripts/install.ps1index 0ec8f9c2..c3063684 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -136,6 +136,23 @@ catch {if (Test-Path $binPath) { Remove-Item $binPath -Force }Move-Item -Path $tmp -Destination $binPath -Force+# Download web dashboard assets (required for the web UI).+$webTarUrl = "$GhDl/v$version/web.tar.gz"+$webTmp = Join-Path $env:TEMP ("mercury-web-" + [guid]::NewGuid().ToString('N') + '.tar.gz')+try {+ Invoke-WebRequest -Uri $webTarUrl -OutFile $webTmp -UseBasicParsing+ $webDir = Join-Path $binDir 'web'+ New-Item -ItemType Directory -Force -Path $webDir | Out-Null+ tar -xzf $webTmp -C $binDir 2>$null+ Write-Info 'Web dashboard assets installed'+}+catch {+ Write-Warn2 'Web dashboard assets not found for v'"$version — web UI will not work"+}+finally {+ Remove-Item $webTmp -Force -ErrorAction SilentlyContinue+}+Write-Info "Installed to $binPath"$pathUpdated = Update-UserPath -BinDir $binDirdiff --git a/scripts/install.sh b/scripts/install.shindex f7d6a8e3..58062939 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -206,6 +206,21 @@ main() {trap - EXIT INT TERMchmod +x "$bin_path"+ # Download web dashboard assets (required for the web UI).+ web_tar_url="${GITHUB_DL}/v${version}/web.tar.gz"+ web_tmp=$(mktemp -t mercury-web.XXXXXX.tar.gz)+ if fetch_to "$web_tar_url" "$web_tmp" 2>/dev/null; then+ mkdir -p "$bin_dir/web"+ if tar -xzf "$web_tmp" -C "$bin_dir" 2>/dev/null; then+ info "Web dashboard assets installed"+ else+ warn "Failed to extract web dashboard assets"+ fi+ else+ warn "Web dashboard assets not found for v${version} — web UI will not work"+ fi+ rm -f "$web_tmp"+# macOS: strip the quarantine attribute so Gatekeeper doesn't bark on# unsigned binaries downloaded via curl.if [ "$os" = "macos" ] && have xattr; thendiff --git a/scripts/post-build.cjs b/scripts/post-build.cjsindex 59474c5a..6e2f6224 100644--- a/scripts/post-build.cjs+++ b/scripts/post-build.cjs@@ -30,34 +30,42 @@ const wasmDest = path.join(staticDest, 'vendor', 'sql-wasm.wasm');fs.mkdirSync(path.dirname(wasmDest), { recursive: true });fs.copyFileSync(wasmSrc, wasmDest);-// 3. Build UI (install deps if needed)+// 3. Build UI (install deps if needed). Skip on Termux — esbuild has no+// prebuilt binary for android/x86_64, and the CLI agent does not need+// the web dashboard to run. The web UI is exercised by the linux/macos/+// windows CI jobs; Termux only needs to confirm the CLI builds.const uiDir = path.join(__dirname, '..', 'ui');-if (!fs.existsSync(path.join(uiDir, 'node_modules'))) {- console.log(' Installing UI dependencies...');- execSync('npm install', { cwd: uiDir, stdio: 'pipe' });-}-console.log(' Building UI...');-try {- execSync('npx vite build', { cwd: uiDir, stdio: 'pipe' });-} catch (e) {- // PWA terser plugin fails on Node <20 (crypto not defined) but assets are still built- if (!fs.existsSync(path.join(uiDir, 'dist', 'index.html'))) {- // Real failure — show output for debugging- if (e.stdout) process.stderr.write(e.stdout);- if (e.stderr) process.stderr.write(e.stderr);- console.error('ERROR: Vite build failed and no output was produced');- process.exit(1);+const isTermux = process.env.TERMUX_VERSION || fs.existsSync('/data/data/com.termux');+if (isTermux) {+ console.log(' Skipping UI build on Termux (esbuild has no android/x86_64 prebuilt).');+} else {+ if (!fs.existsSync(path.join(uiDir, 'node_modules'))) {+ console.log(' Installing UI dependencies...');+ execSync('npm install', { cwd: uiDir, stdio: 'pipe' });+ }+ console.log(' Building UI...');+ try {+ execSync('npx vite build', { cwd: uiDir, stdio: 'pipe' });+ } catch (e) {+ // PWA terser plugin fails on Node <20 (crypto not defined) but assets are still built+ if (!fs.existsSync(path.join(uiDir, 'dist', 'index.html'))) {+ // Real failure — show output for debugging+ if (e.stdout) process.stderr.write(e.stdout);+ if (e.stderr) process.stderr.write(e.stderr);+ console.error('ERROR: Vite build failed and no output was produced');+ process.exit(1);+ }}}// 4. Copy ui/dist -> dist/web/uiconst uiDistSrc = path.join(uiDir, 'dist');const uiDistDest = path.join(__dirname, '..', 'dist', 'web', 'ui');-if (!fs.existsSync(uiDistSrc)) {- console.error('ERROR: ui/dist does not exist after vite build');- process.exit(1);+if (fs.existsSync(uiDistSrc)) {+ copyDirSync(uiDistSrc, uiDistDest);+} else {+ console.log(' No ui/dist present (e.g. Termux build) — skipping UI copy.');}-copyDirSync(uiDistSrc, uiDistDest);// 5. Write a self-unregistering service worker.// PWA is currently disabled — any previously-installed SW would keep serving@@ -75,6 +83,8 @@ self.addEventListener('activate', (event) => {})());});`;-fs.writeFileSync(path.join(uiDistDest, 'sw.js'), killSwitchSW);+if (fs.existsSync(uiDistDest)) {+ fs.writeFileSync(path.join(uiDistDest, 'sw.js'), killSwitchSW);+}console.log(' ✓ Build complete');diff --git a/src/capabilities/filesystem/send-file.ts b/src/capabilities/filesystem/send-file.tsindex be3ae289..f863948a 100644--- a/src/capabilities/filesystem/send-file.ts+++ b/src/capabilities/filesystem/send-file.ts@@ -7,15 +7,16 @@ import type { PermissionManager } from '../permissions.js';export function createSendFileTool(permissions: PermissionManager,getCwd: () => string,- sendFile: (filePath: string) => Promise<void>,+ sendFile: (filePath: string, channel?: string) => Promise<void>,) {return tool({description:- 'Send a file to the user. On Telegram the file is uploaded as an attachment to the relevant approved recipients. On CLI the file path and size are displayed. The path must be within an allowed read scope.',+ 'Send a file to the user. Use the channel parameter to send via a specific channel (signal, telegram). If omitted, sends via the current channel or the best available channel.',inputSchema: zodSchema(z.object({path: z.string().describe('Absolute or relative path to the file to send'),+ channel: z.enum(['signal', 'telegram']).optional().describe('The channel to send the file via. Use this when the user explicitly requests a specific channel, e.g. "send via Signal" or "send to Telegram".'),})),- execute: async ({ path }) => {+ execute: async ({ path, channel }) => {const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);const check = await permissions.checkFsAccess(resolved, 'read');if (!check.allowed) {@@ -37,7 +38,7 @@ export function createSendFileTool(}try {- await sendFile(resolved);+ await sendFile(resolved, channel);const filename = basename(resolved);const sizeStr =stat.size > 1024 * 1024diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.tsindex b0d577ef..00a0cdd8 100644--- a/src/capabilities/registry.ts+++ b/src/capabilities/registry.ts@@ -83,7 +83,7 @@ export class CapabilityRegistry {private supervisor?: SubAgentSupervisor;private spotifyClient?: SpotifyClient;private userMemory?: UserMemoryStore;- private sendFileHandler?: (filePath: string) => Promise<void>;+ private sendFileHandler?: (filePath: string, channel?: string) => Promise<void>;private sendMessageHandler?: (content: string) => Promise<void>;private currentChannelId = 'cli';private currentChannelType = 'cli';@@ -124,7 +124,7 @@ export class CapabilityRegistry {this.currentCwd = dir;}- setSendFileHandler(handler: (filePath: string) => Promise<void>): void {+ setSendFileHandler(handler: (filePath: string, channel?: string) => Promise<void>): void {this.sendFileHandler = handler;}diff --git a/src/channels/discord.ts b/src/channels/discord.tsnew file mode 100644index 00000000..827435a4--- /dev/null+++ b/src/channels/discord.ts@@ -0,0 +1,1274 @@+import fs from 'node:fs';+import path from 'node:path';+import {+ Client,+ GatewayIntentBits,+ Options,+ Events,+ ChannelType,+ PermissionFlagsBits,+ EmbedBuilder,+ ActionRowBuilder,+ ButtonBuilder,+ ButtonStyle,+ MessageFlags,+ Partials,+ type Message,+ type TextChannel,+ type DMChannel,+ type Guild,+ type GuildMember,+ type Interaction,+ type Snowflake,+ type ButtonInteraction,+ type ChatInputCommandInteraction,+} from 'discord.js';+import type { ChannelMessage } from '../types/channel.js';+import { BaseChannel, type PermissionMode } from './base.js';+import type { MercuryConfig } from '../utils/config.js';+import type { DiscordAccessUser } from '../types/channel.js';+import {+ addDiscordPendingRequest,+ approveDiscordPendingRequest,+ approveDiscordPendingRequestByPairingCode,+ clearDiscordAccess,+ findDiscordAdmin,+ findDiscordApprovedUser,+ findDiscordPendingRequest,+ getDiscordAccessSummary,+ getDiscordAdmins,+ hasDiscordAdmins,+ rejectDiscordPendingRequest,+ removeDiscordUser,+ saveConfig,+} from '../utils/config.js';+import { logger } from '../utils/logger.js';+import { mdToDiscord } from '../utils/markdown.js';+import { formatToolStep, formatToolResult } from '../utils/tool-label.js';++const MAX_MESSAGE_LENGTH = 2000;+const DISCORD_DM_PREFIX = 'discord:dm';+const DISCORD_GUILD_PREFIX = 'discord';++type ApprovalResolver = () => void;++export class DiscordChannel extends BaseChannel {+ readonly type = 'discord' as const;+ private client: Client | null = null;+ private lastActiveChannelId: string | null = null;+ private chatCommandContext?: import('../capabilities/registry.js').ChatCommandContext;+ private pendingApprovals: Map<string, ApprovalResolver> = new Map();+ private permissionModes = new Map<string, PermissionMode>();+ private onPermissionMode?: (mode: PermissionMode, channelId: string) => void;++ private statusMessageIds = new Map<string, Snowflake>();+ private stepCounters = new Map<string, number>();+ private stepHistory = new Map<string, string[]>();+ private taskActive = new Map<string, boolean>();+ private deferredResponses = new Map<string, string>();+ private statusNotices = new Map<string, string[]>();+ private static readonly MAX_STATUS_NOTICES = 3;++ private typingInterval: NodeJS.Timeout | null = null;+ private userLastMessageTime = new Map<string, number>();+ private static readonly USER_RATE_LIMIT_MS = 30_000;+ private static readonly BUSY_COOLDOWN_MS = 15_000;+ private lastBusyReplyTime = new Map<string, number>();++ private adminChannel: TextChannel | null = null;+ private lastMessageMetadata: { isDM: boolean; isAdmin: boolean } | null = null;++ constructor(private config: MercuryConfig) {+ super();+ }++ setChatCommandContext(ctx: import('../capabilities/registry.js').ChatCommandContext): void {+ this.chatCommandContext = ctx;+ }++ beginTask(targetId?: string): void {+ const key = targetId || 'notification';+ this.taskActive.set(key, true);+ this.deferredResponses.delete(key);+ this.statusNotices.delete(key);+ }++ endTask(targetId?: string): void {+ const key = targetId || 'notification';+ this.taskActive.set(key, false);+ }++ isTaskActive(targetId?: string): boolean {+ const key = targetId || 'notification';+ return this.taskActive.get(key) ?? false;+ }++ popDeferredResponse(targetId?: string): string | undefined {+ const key = targetId || 'notification';+ const text = this.deferredResponses.get(key);+ this.deferredResponses.delete(key);+ return text;+ }++ setOnPermissionMode(handler: (mode: PermissionMode, channelId: string) => void): void {+ this.onPermissionMode = handler;+ }++ getPermissionMode(channelId: string): PermissionMode {+ return this.permissionModes.get(channelId) ?? 'ask-me';+ }++ async start(): Promise<void> {+ if (this.client) return;++ const token = this.config.channels.discord.botToken;+ if (!token) {+ logger.warn('Discord bot token not set — skipping');+ return;+ }++ const client = new Client({+ intents: [+ GatewayIntentBits.Guilds,+ GatewayIntentBits.GuildMessages,+ GatewayIntentBits.MessageContent,+ GatewayIntentBits.DirectMessages,+ ],+ partials: [Partials.Channel],+ makeCache: Options.cacheWithLimits({+ MessageManager: 10,+ UserManager: 50,+ }),+ });++ client.on(Events.ClientReady, async () => {+ logger.info({ bot: client.user?.tag }, 'Discord bot started — gateway connected');+ this.ready = true;++ if (this.config.channels.discord.channelId) {+ const channel = client.channels.cache.get(this.config.channels.discord.channelId!);+ if (channel?.isTextBased()) {+ this.adminChannel = channel as TextChannel;+ }+ }++ await this.registerSlashCommands();+ });++ client.on(Events.MessageCreate, async (message) => {+ if (message.author?.bot) return;+ if (message.partial) {+ try {+ message = await message.fetch();+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Failed to fetch partial Discord message');+ return;+ }+ }+ await this.handleMessage(message);+ });++ client.on(Events.InteractionCreate, async (interaction) => {+ await this.handleInteraction(interaction);+ });++ client.on(Events.GuildCreate, (guild: Guild) => {+ if (this.config.channels.discord.guildId && guild.id !== this.config.channels.discord.guildId) {+ logger.warn({ guildId: guild.id }, 'Discord bot joined an unconfigured guild — leaving');+ guild.leave().catch(() => {});+ return;+ }+ logger.info({ guildId: guild.id, guildName: guild.name }, 'Discord bot joined guild');+ });++ this.client = client;++ try {+ await client.login(token);+ } catch (err: any) {+ logger.error({ err: err.message }, 'Discord bot login failed');+ this.client = null;+ }+ }++ async stop(): Promise<void> {+ if (this.client) {+ this.client.destroy();+ this.client = null;+ }+ this.ready = false;+ this.stopTypingLoop();+ }++ private async handleMessage(message: Message): Promise<void> {+ const isDM = message.channel.isDMBased();++ if (isDM) {+ await this.handleDMMessage(message);+ return;+ }++ if (this.config.channels.discord.guildId && message.guild?.id !== this.config.channels.discord.guildId) {+ return;+ }++ if (this.config.channels.discord.channelId && message.channel.id !== this.config.channels.discord.channelId) {+ return;+ }++ const userId = message.author.id;+ const guild = message.guild;+ if (!guild) return;++ const isAdmin = await this.isGuildAdmin(message.member, guild);++ if (!isAdmin) {+ const now = Date.now();+ const lastTime = this.userLastMessageTime.get(userId) || 0;+ if (now - lastTime < DiscordChannel.USER_RATE_LIMIT_MS) {+ const remaining = Math.ceil((DiscordChannel.USER_RATE_LIMIT_MS - (now - lastTime)) / 1000);+ await message.reply(`Please wait ${remaining}s before sending another message.`).catch(() => {});+ return;+ }+ this.userLastMessageTime.set(userId, now);+ }++ let content = message.content.trim();+ const botId = this.client?.user?.id;+ if (botId) {+ const mentionPattern = new RegExp(`<@!?${botId}>\\s*`, 'g');+ content = content.replace(mentionPattern, '').trim();+ }+ if (!content) return;++ const command = this.getCommandName(content);++ if (command === '/start' || command === '/pair') {+ await message.reply('To pair with Mercury, send me a **direct message** (DM) with /start. Pairing codes should not be shared in public channels.').catch(() => {});+ return;+ }++ this.lastActiveChannelId = message.channel.id;+ logger.info({ channelId: message.channel.id, userId, text: content.slice(0, 50) }, 'Discord message received');++ if (!this.permissionModes.has(message.channel.id) && this.onPermissionMode) {+ this.askPermissionMode(`${DISCORD_GUILD_PREFIX}:${message.channel.id}`).then((mode) => {+ this.permissionModes.set(message.channel.id, mode);+ if (this.onPermissionMode) {+ this.onPermissionMode(mode, message.channel.id);+ }+ }).catch((e: any) => logger.warn({ e }, 'discord permission ask failed'));+ this.permissionModes.set(message.channel.id, 'ask-me');+ }++ const channelId = `${DISCORD_GUILD_PREFIX}:${message.channel.id}`;+ const msg: ChannelMessage = {+ id: message.id,+ channelId,+ channelType: 'discord',+ senderId: userId,+ senderName: message.member?.displayName || message.author.username,+ content,+ timestamp: message.createdTimestamp,+ metadata: {+ channelId: message.channel.id,+ guildId: guild.id,+ isDM: false,+ isAdmin,+ },+ };+ this.lastMessageMetadata = { isDM: false, isAdmin };+ this.emit(msg);+ }++ private async handleDMMessage(message: Message): Promise<void> {+ const userId = message.author.id;+ const content = message.content.trim();+ if (!content) return;++ const command = this.getCommandName(content);++ if (command === '/start' || command === '/pair') {+ await this.handleDMAccessRequest(message);+ return;+ }++ const approvedUser = findDiscordApprovedUser(this.config, userId);+ if (!approvedUser) {+ const pending = findDiscordPendingRequest(this.config, userId);+ if (pending) {+ await message.reply(this.getPendingStatusMessage(pending)).catch(() => {});+ } else {+ await message.reply('This bot is not available to you. Send /start to request access.').catch(() => {});+ }+ return;+ }++ if (command === '/unpair') {+ if (!findDiscordAdmin(this.config, userId)) {+ await message.reply('Only Discord admins can reset access.').catch(() => {});+ return;+ }+ this.resetDMAccess();+ await message.reply('Discord DM access reset. New users can send /start to request access.').catch(() => {});+ return;+ }++ this.lastActiveChannelId = message.channel.id;+ logger.info({ userId, text: content.slice(0, 50) }, 'Discord DM received');++ const channelId = `${DISCORD_DM_PREFIX}:${userId}`;+ if (!this.permissionModes.has(channelId) && this.onPermissionMode) {+ this.askPermissionMode(channelId).then((mode) => {+ this.permissionModes.set(channelId, mode);+ if (this.onPermissionMode) {+ this.onPermissionMode(mode, channelId);+ }+ }).catch((e: any) => logger.warn({ e }, 'discord permission ask failed'));+ this.permissionModes.set(channelId, 'ask-me');+ }++ const msg: ChannelMessage = {+ id: message.id,+ channelId,+ channelType: 'discord',+ senderId: userId,+ senderName: message.author.username,+ content,+ timestamp: message.createdTimestamp,+ metadata: {+ channelId: message.channel.id,+ isDM: true,+ },+ };+ this.lastMessageMetadata = { isDM: true, isAdmin: false };+ this.emit(msg);+ }++ private async handleDMAccessRequest(message: Message): Promise<void> {+ const userId = message.author.id;+ const username = message.author.username;+ const displayName = message.author.displayName || message.author.username;++ const approvedUser = findDiscordApprovedUser(this.config, userId);+ if (approvedUser) {+ const role = approvedUser.role;+ await message.reply(`You are already approved as a ${role}.`).catch(() => {});+ return;+ }++ const existingRequest = findDiscordPendingRequest(this.config, userId);+ if (existingRequest) {+ await message.reply(this.getPendingStatusMessage(existingRequest)).catch(() => {});+ return;+ }++ if (!hasDiscordAdmins(this.config) && this.config.channels.discord.pending.length > 0) {+ await message.reply(+ 'Initial Discord pairing is already in progress for another user. Ask the Mercury operator to finish setup or reset Discord access first.',+ ).catch(() => {});+ return;+ }++ const request = addDiscordPendingRequest(this.config, {+ userId,+ username,+ displayName,+ pairingCode: hasDiscordAdmins(this.config) ? undefined : this.generatePairingCode(),+ });+ saveConfig(this.config);+ logger.info({ userId, username }, 'Discord DM access request recorded');++ await message.reply(this.getPendingStatusMessage(request)).catch(() => {});++ if (hasDiscordAdmins(this.config)) {+ await this.notifyAdminsOfPendingRequest(request);+ }+ }++ private async notifyAdminsOfPendingRequest(request: import('../types/channel.js').DiscordPendingRequest): Promise<void> {+ if (!this.client) return;++ const username = request.username ? ` (@${request.username})` : '';+ const displayName = request.displayName ? ` (${request.displayName})` : '';+ const lines = [+ '**Discord access request pending approval.**',+ '',+ `User ID: \`${request.userId}\`${username}${displayName}`,+ `Requested: ${new Date(request.requestedAt).toLocaleString()}`,+ '',+ 'Use the buttons below to approve or reject this user.',+ ];++ const row = new ActionRowBuilder<ButtonBuilder>()+ .addComponents(+ new ButtonBuilder()+ .setCustomId(`discord_access:approve:${request.userId}`)+ .setLabel('Approve')+ .setStyle(ButtonStyle.Success),+ new ButtonBuilder()+ .setCustomId(`discord_access:reject:${request.userId}`)+ .setLabel('Reject')+ .setStyle(ButtonStyle.Danger),+ );++ for (const admin of getDiscordAdmins(this.config)) {+ try {+ const dmChannel = await this.client.users.createDM(admin.userId);+ await dmChannel.send({ content: lines.join('\n'), components: [row] });+ } catch (err: any) {+ logger.warn({ err: err.message, adminId: admin.userId }, 'Failed to notify Discord admin');+ }+ }+ }++ private async isGuildAdmin(member: GuildMember | null, guild: Guild): Promise<boolean> {+ if (!member) return false;++ if (member.permissions.has(PermissionFlagsBits.Administrator)) return true;+ if (guild.ownerId === member.id) return true;++ const adminRoleName = this.config.channels.discord.adminRoleName;+ if (adminRoleName) {+ return member.roles.cache.some((role) => role.name === adminRoleName);+ }++ return false;+ }++ async send(content: string, targetId?: string, elapsedMs?: number): Promise<void> {+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel || !this.client) {+ logger.warn({ targetId }, 'Discord send: no valid channel');+ return;+ }++ const key = targetId || 'notification';++ if (this.taskActive.get(key)) {+ const timeSuffix = elapsedMs != null ? ` (${(elapsedMs / 1000).toFixed(1)}s)` : '';+ const fullContent = content + timeSuffix;+ if (!fullContent.trim()) return;++ const isSystemNotice = content.startsWith('\u263f ') || content.startsWith('\u26a0') || content.startsWith(' [') || content.length < 200;+ if (isSystemNotice) {+ const notices = this.statusNotices.get(key) || [];+ const truncated = fullContent.length > 80 ? fullContent.slice(0, 77) + '\u2026' : fullContent;+ notices.push(truncated);+ this.statusNotices.set(key, notices);+ await this.refreshStatusCard(targetId);+ } else {+ this.deferredResponses.set(key, fullContent);+ }+ return;+ }++ const timeSuffix = elapsedMs != null ? `\n\u23f1 ${(elapsedMs / 1000).toFixed(1)}s` : '';+ const fullContent = content + timeSuffix;+ if (!fullContent.trim()) {+ logger.info({ targetId }, 'Discord send: skipping empty message');+ return;+ }++ const discordContent = mdToDiscord(fullContent);+ const chunks = this.splitMessage(discordContent, MAX_MESSAGE_LENGTH);++ for (const chunk of chunks) {+ try {+ await channel.send({ content: chunk, allowedMentions: { parse: [] } });+ } catch (err: any) {+ logger.error({ err: err.message, channelId: channel.id }, 'Discord send failed');+ }+ }+ }++ async sendFile(filePath: string, targetId?: string): Promise<void> {+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel || !this.client) {+ logger.warn({ targetId }, 'Discord sendFile: no valid channel');+ return;+ }++ const resolved = path.resolve(filePath);+ if (!fs.existsSync(resolved)) {+ await channel.send(`File not found: ${filePath}`).catch(() => {});+ return;+ }++ const filename = path.basename(resolved);++ try {+ await channel.send({+ files: [{ attachment: resolved, name: filename }],+ allowedMentions: { parse: [] },+ });+ logger.info({ file: resolved, channelId: channel.id }, 'File sent via Discord');+ } catch (err: any) {+ logger.error({ err: err.message, file: resolved }, 'Discord sendFile failed');+ await channel.send(`Failed to send file: ${err.message}`).catch(() => {});+ }+ }++ async stream(content: AsyncIterable<string>, targetId?: string): Promise<string> {+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel || !this.client) return '';++ const key = targetId || 'notification';+ if (this.taskActive.get(key)) {+ let full = '';+ for await (const chunk of content) {+ full += chunk;+ }+ this.deferredResponses.set(key, full);+ return full;+ }++ this.deleteStatusMessage(targetId);++ if (!this.config.channels.discord.streaming) {+ let full = '';+ for await (const chunk of content) {+ full += chunk;+ }+ const discordContent = mdToDiscord(full);+ const chunks = this.splitMessage(discordContent, MAX_MESSAGE_LENGTH);+ for (const chunk of chunks) {+ try {+ await channel.send({ content: chunk, allowedMentions: { parse: [] } });+ } catch (err: any) {+ logger.error({ err: err.message }, 'Discord stream send failed');+ }+ }+ return full;+ }++ const STREAM_EDIT_INTERVAL = 2000;+ const STREAM_MIN_LENGTH = 20;++ this.startTypingLoop(channel);++ try {+ let full = '';+ let streamMsg: Message | null = null;+ let lastEditTime = 0;++ for await (const chunk of content) {+ full += chunk;++ const now = Date.now();+ const timeSinceLastEdit = now - lastEditTime;++ if (!streamMsg && full.length >= STREAM_MIN_LENGTH) {+ try {+ streamMsg = await channel.send({+ content: mdToDiscord(full) + ' \u258c',+ allowedMentions: { parse: [] },+ });+ lastEditTime = now;+ } catch {+ streamMsg = null;+ }+ } else if (streamMsg && timeSinceLastEdit >= STREAM_EDIT_INTERVAL) {+ try {+ await streamMsg.edit(mdToDiscord(full) + ' \u258c');+ lastEditTime = now;+ } catch {+ // edit failed — rate limited, skip+ }+ }+ }++ if (streamMsg) {+ const finalContent = mdToDiscord(full);+ const chunks = this.splitMessage(finalContent, MAX_MESSAGE_LENGTH);+ if (chunks.length <= 1) {+ try {+ await streamMsg.edit({ content: finalContent, allowedMentions: { parse: [] } });+ } catch {+ // final edit failed+ }+ } else {+ try {+ await streamMsg.delete();+ } catch {+ // delete failed+ }+ for (const chunk of chunks) {+ try {+ await channel.send({ content: chunk, allowedMentions: { parse: [] } });+ } catch {+ // send failed+ }+ }+ }+ } else if (full.trim()) {+ const discordContent = mdToDiscord(full);+ const chunks = this.splitMessage(discordContent, MAX_MESSAGE_LENGTH);+ for (const chunk of chunks) {+ try {+ await channel.send({ content: chunk, allowedMentions: { parse: [] } });+ } catch {+ // send failed+ }+ }+ }++ return full;+ } finally {+ this.stopTypingLoop();+ }+ }++ async typing(targetId?: string): Promise<void> {+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel || !this.client) return;+ if ('sendTyping' in channel) {+ await channel.sendTyping().catch(() => {});+ }+ }++ startTypingLoop(channel: TextChannel | DMChannel): void {+ this.stopTypingLoop();+ if ('sendTyping' in channel) {+ channel.sendTyping().catch(() => {});+ }+ this.typingInterval = setInterval(() => {+ if ('sendTyping' in channel) {+ channel.sendTyping().catch(() => {});+ }+ }, 8000);+ }++ stopTypingLoop(): void {+ if (this.typingInterval) {+ clearInterval(this.typingInterval);+ this.typingInterval = null;+ }+ }++ async askPermission(prompt: string, targetId?: string): Promise<string> {+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel || !this.client) return 'no';++ const id = `perm_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;++ const row = new ActionRowBuilder<ButtonBuilder>()+ .addComponents(+ new ButtonBuilder().setCustomId(`${id}:yes`).setLabel('Allow').setStyle(ButtonStyle.Success),+ new ButtonBuilder().setCustomId(`${id}:always`).setLabel('Always').setStyle(ButtonStyle.Primary),+ new ButtonBuilder().setCustomId(`${id}:no`).setLabel('Deny').setStyle(ButtonStyle.Danger),+ );++ const discordContent = mdToDiscord(prompt);+ let sentMsg: Message | undefined;++ try {+ sentMsg = await channel.send({ content: discordContent, components: [row], allowedMentions: { parse: [] } });+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Discord askPermission send failed');+ }++ return new Promise((resolve) => {+ const cleanup = (result: string) => {+ this.pendingApprovals.delete(`${id}:yes`);+ this.pendingApprovals.delete(`${id}:always`);+ this.pendingApprovals.delete(`${id}:no`);+ if (sentMsg) {+ sentMsg.delete().catch(() => {});+ }+ resolve(result);+ };+ this.pendingApprovals.set(`${id}:yes`, () => cleanup('yes'));+ this.pendingApprovals.set(`${id}:always`, () => cleanup('always'));+ this.pendingApprovals.set(`${id}:no`, () => cleanup('no'));++ setTimeout(() => {+ this.pendingApprovals.delete(`${id}:yes`);+ this.pendingApprovals.delete(`${id}:always`);+ this.pendingApprovals.delete(`${id}:no`);+ if (sentMsg) {+ sentMsg.delete().catch(() => {});+ }+ resolve('no');+ }, 120_000);+ });+ }++ async askToContinue(question: string, targetId?: string): Promise<boolean> {+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel || !this.client) return false;++ const id = `loop_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;++ const row = new ActionRowBuilder<ButtonBuilder>()+ .addComponents(+ new ButtonBuilder().setCustomId(`${id}:yes`).setLabel('Continue').setStyle(ButtonStyle.Success),+ new ButtonBuilder().setCustomId(`${id}:no`).setLabel('Stop').setStyle(ButtonStyle.Danger),+ );++ const discordContent = mdToDiscord(question);+ let sentMsg: Message | undefined;++ try {+ sentMsg = await channel.send({ content: discordContent, components: [row], allowedMentions: { parse: [] } });+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Discord askToContinue send failed');+ }++ return new Promise((resolve) => {+ const cleanup = (result: boolean) => {+ this.pendingApprovals.delete(`${id}:yes`);+ this.pendingApprovals.delete(`${id}:no`);+ if (sentMsg) {+ sentMsg.delete().catch(() => {});+ }+ resolve(result);+ };+ this.pendingApprovals.set(`${id}:yes`, () => cleanup(true));+ this.pendingApprovals.set(`${id}:no`, () => cleanup(false));++ setTimeout(() => {+ this.pendingApprovals.delete(`${id}:yes`);+ this.pendingApprovals.delete(`${id}:no`);+ if (sentMsg) {+ sentMsg.delete().catch(() => {});+ }+ resolve(false);+ }, 120_000);+ });+ }++ async askPermissionMode(targetId?: string): Promise<PermissionMode> {+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel || !this.client) return 'ask-me';++ const id = `perm_mode_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;++ const row = new ActionRowBuilder<ButtonBuilder>()+ .addComponents(+ new ButtonBuilder().setCustomId(`${id}:ask-me`).setLabel('\uD83D\uDD12 Ask Me').setStyle(ButtonStyle.Secondary),+ new ButtonBuilder().setCustomId(`${id}:allow-all`).setLabel('\u2705 Allow All').setStyle(ButtonStyle.Success),+ );++ const content = [+ '**Permission Mode**',+ 'How should Mercury handle risky actions this session?',+ '',+ '\uD83D\uDD12 **Ask Me** \u2014 confirm before file writes, commands, and scope changes',+ '\u2705 **Allow All** \u2014 auto-approve everything (scopes, commands, loops)',+ ].join('\n');++ let sentMsg: Message | undefined;+ try {+ sentMsg = await channel.send({ content, components: [row], allowedMentions: { parse: [] } });+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Discord askPermissionMode send failed');+ }++ return new Promise((resolve) => {+ const cleanup = (result: PermissionMode) => {+ this.pendingApprovals.delete(`${id}:ask-me`);+ this.pendingApprovals.delete(`${id}:allow-all`);+ if (sentMsg) {+ sentMsg.delete().catch(() => {});+ }+ resolve(result);+ };+ this.pendingApprovals.set(`${id}:ask-me`, () => cleanup('ask-me'));+ this.pendingApprovals.set(`${id}:allow-all`, () => cleanup('allow-all'));++ setTimeout(() => {+ this.pendingApprovals.delete(`${id}:ask-me`);+ this.pendingApprovals.delete(`${id}:allow-all`);+ if (sentMsg) {+ sentMsg.delete().catch(() => {});+ }+ resolve('ask-me');+ }, 120_000);+ });+ }++ async sendToolFeedback(toolName: string, args: Record<string, any>, targetId?: string): Promise<void> {+ const key = targetId || 'notification';+ const step = (this.stepCounters.get(key) || 0) + 1;+ this.stepCounters.set(key, step);+ const label = formatToolStep(toolName, args);++ const history = this.stepHistory.get(key) || [];+ const recentHistory = history.slice(-5);++ const embed = new EmbedBuilder()+ .setColor(0x5865F2)+ .setTitle(`\u2699\uFE0F Mercury working (step ${step})`)+ .setDescription([+ ...recentHistory.map(h => `\u2705 ${h}`),+ `\u23f3 ${label}\u2026`,+ ].join('\n'))+ .setTimestamp();++ await this.updateStatusEmbed(embed, targetId);+ }++ async sendStepDone(toolName: string, result: unknown, targetId?: string): Promise<void> {+ const key = targetId || 'notification';+ const step = this.stepCounters.get(key) || 0;+ const summary = formatToolResult(toolName, result);+ const label = formatToolStep(toolName, {} as any);+ const doneLine = summary ? `${label} \u00b7 ${summary}` : label;++ const history = this.stepHistory.get(key) || [];+ history.push(doneLine);+ this.stepHistory.set(key, history);++ const recentHistory = history.slice(-5);++ const embed = new EmbedBuilder()+ .setColor(0x57F287)+ .setTitle(`\u2699\uFE0F Mercury working (${step} steps done)`)+ .setDescription(recentHistory.map(h => `\u2705 ${h}`).join('\n'))+ .setTimestamp();++ await this.updateStatusEmbed(embed, targetId);+ }++ private async updateStatusEmbed(embed: EmbedBuilder, targetId?: string): Promise<void> {+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel || !this.client) return;++ const key = targetId || 'notification';+ const existingId = this.statusMessageIds.get(key);++ if (existingId) {+ try {+ const msg = await channel.messages.fetch(existingId);+ await msg.edit({ embeds: [embed] });+ return;+ } catch {+ this.statusMessageIds.delete(key);+ }+ }++ try {+ const msg = await channel.send({ embeds: [embed], allowedMentions: { parse: [] } });+ this.statusMessageIds.set(key, msg.id);+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Discord status embed send failed');+ }+ }++ private async refreshStatusCard(targetId?: string): Promise<void> {+ const key = targetId || 'notification';+ const notices = this.statusNotices.get(key) || [];+ const step = this.stepCounters.get(key) || 0;+ const history = this.stepHistory.get(key) || [];+ const recentHistory = history.slice(-5);++ const lines = [+ ...recentHistory.map(h => `\u2705 ${h}`),+ ];+ if (notices.length > 0) {+ lines.push('', ...notices.slice(-DiscordChannel.MAX_STATUS_NOTICES));+ }++ const embed = new EmbedBuilder()+ .setColor(0x5865F2)+ .setTitle(`\u2699\uFE0F Mercury working (step ${step})`)+ .setDescription(lines.join('\n') || 'Processing\u2026')+ .setTimestamp();++ await this.updateStatusEmbed(embed, targetId);+ }++ private deleteStatusMessage(targetId?: string): void {+ const key = targetId || 'notification';+ this.statusMessageIds.delete(key);+ this.stepCounters.delete(key);+ this.stepHistory.delete(key);+ this.statusNotices.delete(key);+ }++ private async deleteStatusMessageFromDiscord(targetId?: string): Promise<void> {+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel) return;++ const key = targetId || 'notification';+ const existingId = this.statusMessageIds.get(key);+ if (existingId) {+ try {+ const msg = await channel.messages.fetch(existingId);+ await msg.delete();+ } catch {+ // already deleted+ }+ this.statusMessageIds.delete(key);+ }+ }++ private async handleInteraction(interaction: Interaction): Promise<void> {+ if (interaction.isChatInputCommand()) {+ await this.handleSlashCommand(interaction);+ return;+ }++ if (!interaction.isButton()) return;++ const customId = interaction.customId;++ if (customId.startsWith('discord_access:')) {+ await this.handleAccessButton(interaction, customId);+ return;+ }++ const resolver = this.pendingApprovals.get(customId);+ if (resolver) {+ if (customId.startsWith('perm_') || customId.startsWith('perm_mode_') || customId.startsWith('loop_')) {+ const metadata = this.lastMessageMetadata;+ if (metadata && !metadata.isDM && !metadata.isAdmin) {+ await interaction.reply({ content: 'Only admins can approve actions in server channels.', flags: MessageFlags.Ephemeral });+ return;+ }+ }+ this.pendingApprovals.delete(customId);+ resolver();+ const action = customId.split(':')[1];+ try {+ await interaction.reply({ content: action === 'no' ? 'Denied' : 'Approved', flags: MessageFlags.Ephemeral });+ } catch {+ // interaction already replied or expired+ }+ return;+ }++ try {+ await interaction.reply({ content: 'Expired', flags: MessageFlags.Ephemeral });+ } catch {+ // interaction expired+ }+ }++ private async handleAccessButton(interaction: ButtonInteraction, customId: string): Promise<void> {+ if (!findDiscordAdmin(this.config, interaction.user.id)) {+ await interaction.reply({ content: 'Only Discord admins can approve or reject access requests.', flags: MessageFlags.Ephemeral });+ return;+ }++ const parts = customId.split(':');+ if (parts.length < 3) return;+ const action = parts[1];+ const userId = parts[2];++ if (action === 'approve') {+ const role = hasDiscordAdmins(this.config) ? 'member' : 'admin';+ const approved = approveDiscordPendingRequest(this.config, userId, role);+ if (approved) {+ saveConfig(this.config);+ const label = approved.displayName || approved.username || approved.userId;+ await interaction.reply({ content: `Approved ${label} as ${role}.`, flags: MessageFlags.Ephemeral });++ try {+ const dmChannel = await this.client!.users.createDM(userId);+ await dmChannel.send(`You have been approved as a ${role}! You can now chat with Mercury.`);+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Failed to notify approved Discord user');+ }+ } else {+ await interaction.reply({ content: 'No pending request found for this user.', flags: MessageFlags.Ephemeral });+ }+ } else if (action === 'reject') {+ const rejected = rejectDiscordPendingRequest(this.config, userId);+ if (rejected) {+ saveConfig(this.config);+ await interaction.reply({ content: 'Rejected access request.', flags: MessageFlags.Ephemeral });+ } else {+ await interaction.reply({ content: 'No pending request found for this user.', flags: MessageFlags.Ephemeral });+ }+ }+ }++ private async registerSlashCommands(): Promise<void> {+ if (!this.client?.application) return;++ const guildId = this.config.channels.discord.guildId;+ if (!guildId) {+ logger.debug('No Discord guildId configured — skipping slash command registration');+ return;+ }++ try {+ await this.client.application.commands.set(+ [+ { name: 'start', description: 'Request Discord access to this Mercury instance' },+ { name: 'help', description: 'Show available commands' },+ { name: 'status', description: 'Show agent config, budget, and uptime' },+ { name: 'stop', description: 'Stop all agents and clear queue' },+ { name: 'budget', description: 'Token budget status and management' },+ { name: 'saver', description: 'Toggle Token Saver Mode' },+ { name: 'memory', description: 'View and manage second brain memory (admin only)' },+ { name: 'permissions', description: 'Change permission mode' },+ { name: 'models', description: 'List providers or switch AI model' },+ { name: 'unpair', description: 'Reset all Discord DM access (admin only)' },+ ],+ guildId,+ );+ logger.info({ guildId }, 'Discord slash commands registered');+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Failed to register Discord slash commands (non-critical)');+ }+ }++ private async handleSlashCommand(interaction: ChatInputCommandInteraction): Promise<void> {+ const commandName = interaction.commandName;++ if (commandName === 'start' || commandName === 'pair') {+ const userId = interaction.user.id;+ const approvedUser = findDiscordApprovedUser(this.config, userId);+ if (approvedUser) {+ await interaction.reply({ content: `You are already approved as a ${approvedUser.role}.`, flags: MessageFlags.Ephemeral });+ return;+ }++ const existingRequest = findDiscordPendingRequest(this.config, userId);+ if (existingRequest) {+ await interaction.reply({ content: this.getPendingStatusMessage(existingRequest), flags: MessageFlags.Ephemeral });+ return;+ }++ if (!hasDiscordAdmins(this.config) && this.config.channels.discord.pending.length > 0) {+ await interaction.reply({ content: 'Initial Discord pairing is already in progress for another user.', flags: MessageFlags.Ephemeral });+ return;+ }++ const request = addDiscordPendingRequest(this.config, {+ userId,+ username: interaction.user.username,+ displayName: interaction.user.displayName || interaction.user.username,+ pairingCode: hasDiscordAdmins(this.config) ? undefined : this.generatePairingCode(),+ });+ saveConfig(this.config);+ logger.info({ userId, username: interaction.user.username }, 'Discord slash command access request recorded');++ await interaction.reply({ content: this.getPendingStatusMessage(request), flags: MessageFlags.Ephemeral });++ if (hasDiscordAdmins(this.config)) {+ await this.notifyAdminsOfPendingRequest(request);+ }+ return;+ }++ if (commandName === 'unpair') {+ const userId = interaction.user.id;+ if (!findDiscordAdmin(this.config, userId)) {+ await interaction.reply({ content: 'Only Discord admins can reset access.', flags: MessageFlags.Ephemeral });+ return;+ }+ this.resetDMAccess();+ await interaction.reply({ content: 'Discord DM access reset. New users can send /start to request access.', flags: MessageFlags.Ephemeral });+ return;+ }++ const channelId = interaction.channel?.id;+ if (!channelId) {+ await interaction.reply({ content: 'This command can only be used in a server channel.', flags: MessageFlags.Ephemeral });+ return;+ }++ const memberPerms = interaction.member?.permissions;+ const isAdmin = (typeof memberPerms !== 'string' && memberPerms?.has(PermissionFlagsBits.Administrator)) ?? false;++ const msg: ChannelMessage = {+ id: interaction.id,+ channelId: `${DISCORD_GUILD_PREFIX}:${channelId}`,+ channelType: 'discord',+ senderId: interaction.user.id,+ senderName: (interaction.member as GuildMember | null)?.displayName || interaction.user.username,+ content: `/${commandName}`,+ timestamp: Date.now(),+ metadata: {+ channelId,+ guildId: interaction.guild?.id,+ isDM: false,+ isAdmin,+ },+ };++ await interaction.reply({ content: 'Command received.', flags: MessageFlags.Ephemeral });+ this.lastActiveChannelId = channelId;+ this.emit(msg);+ }++ private async resolveTargetChannel(targetId?: string): Promise<TextChannel | DMChannel | null> {+ if (!this.client) return null;++ if (!targetId || targetId === 'notification') {+ if (this.lastActiveChannelId) {+ const channel = this.client.channels.cache.get(this.lastActiveChannelId);+ if (channel?.isTextBased()) return channel as TextChannel | DMChannel;+ }+ if (this.config.channels.discord.channelId) {+ const channel = this.client.channels.cache.get(this.config.channels.discord.channelId!);+ if (channel?.isTextBased()) return channel as TextChannel;+ }+ return null;+ }++ if (targetId.startsWith(`${DISCORD_DM_PREFIX}:`)) {+ const userId = targetId.slice(DISCORD_DM_PREFIX.length + 1);+ const cachedUser = this.client.users.cache.get(userId);+ if (cachedUser?.dmChannel) return cachedUser.dmChannel;+ try {+ const dmChannel = await this.client.users.createDM(userId);+ return dmChannel;+ } catch (err: any) {+ logger.warn({ err: err.message, userId }, 'Failed to create Discord DM channel');+ return null;+ }+ }++ if (targetId.startsWith(`${DISCORD_GUILD_PREFIX}:`)) {+ const channelId = targetId.slice(DISCORD_GUILD_PREFIX.length + 1);+ const channel = this.client.channels.cache.get(channelId);+ if (channel?.isTextBased()) return channel as TextChannel;+ return null;+ }++ const channel = this.client.channels.cache.get(targetId);+ if (channel?.isTextBased()) return channel as TextChannel;+ return null;+ }++ private splitMessage(text: string, maxLength: number): string[] {+ if (text.length <= maxLength) return [text];++ const chunks: string[] = [];+ let remaining = text;++ while (remaining.length > 0) {+ if (remaining.length <= maxLength) {+ chunks.push(remaining);+ break;+ }++ let splitAt = -1;++ const codeBlockMatch = remaining.slice(0, maxLength).match(/```\w*$/);+ if (codeBlockMatch) {+ splitAt = remaining.slice(0, maxLength).lastIndexOf('```');+ }++ if (splitAt === -1) {+ const inCodeBlock = (remaining.slice(0, maxLength).match(/```/g) || []).length % 2 === 1;+ if (inCodeBlock) {+ splitAt = remaining.slice(0, maxLength).lastIndexOf('\n');+ }+ }++ if (splitAt === -1) {+ splitAt = remaining.slice(0, maxLength).lastIndexOf('\n');+ }++ if (splitAt === -1) {+ splitAt = remaining.slice(0, maxLength).lastIndexOf(' ');+ }++ if (splitAt <= 0) {+ splitAt = maxLength;+ }++ chunks.push(remaining.slice(0, splitAt));+ remaining = remaining.slice(splitAt).trimStart();+ }++ return chunks;+ }++ private getCommandName(text: string): string {+ const trimmed = text.trim();+ const match = trimmed.match(/^\/(\w+)/);+ return match ? `/${match[1]}` : '';+ }++ private generatePairingCode(): string {+ return Math.random().toString(36).slice(2, 8).toUpperCase();+ }++ private getPendingStatusMessage(request: import('../types/channel.js').DiscordPendingRequest): string {+ if (request.pairingCode) {+ return [+ 'Almost there! Your pairing code is being generated.',+ '',+ `Your code: \`${request.pairingCode}\``,+ 'Enter this code in the Mercury terminal to complete setup.',+ ].join('\n');+ }+ return 'Your access request has been recorded. An admin will review it shortly.';+ }++ private resetDMAccess(): void {+ clearDiscordAccess(this.config);+ saveConfig(this.config);+ }++ resetStepCounter(targetId?: string): void {+ const key = targetId || 'notification';+ this.stepCounters.delete(key);+ this.stepHistory.delete(key);+ this.statusNotices.delete(key);+ }++ async sendCompletion(elapsedMs: number, stepCount: number, targetId?: string, meta?: {+ provider: string;+ model: string;+ inputTokens: number;+ outputTokens: number;+ totalTokens: number;+ budgetUsed: number;+ budgetTotal: number;+ budgetPercentage: number;+ }): Promise<void> {+ this.endTask(targetId);+ await this.deleteStatusMessageFromDiscord(targetId);++ const deferred = this.popDeferredResponse(targetId);+ if (deferred?.trim()) {+ await this.send(deferred, targetId);+ }++ const channel = await this.resolveTargetChannel(targetId);+ if (!channel || !this.client) return;++ const timeStr = (elapsedMs / 1000).toFixed(1);+ const embed = new EmbedBuilder()+ .setColor(0x57F287)+ .setTitle(`\u2705 Done \u2014 ${stepCount} steps in ${timeStr}s`)+ .addFields(+ { name: 'Provider', value: meta?.provider ?? 'unknown', inline: true },+ { name: 'Model', value: meta?.model ?? 'unknown', inline: true },+ { name: 'Tokens', value: `${meta?.totalTokens ?? 0}`, inline: true },+ )+ .setTimestamp();++ if (meta) {+ embed.addFields({ name: 'Budget', value: `${meta.budgetUsed} / ${meta.budgetTotal} (${meta.budgetPercentage}%)`, inline: false });+ }++ await channel.send({ embeds: [embed], allowedMentions: { parse: [] } }).catch(() => {});+ this.resetStepCounter(targetId);+ }++ async sendBusyNotice(targetId?: string): Promise<void> {+ if (!this.client) return;+ const channel = await this.resolveTargetChannel(targetId);+ if (!channel) return;++ const key = targetId || 'notification';+ const now = Date.now();+ const lastBusy = this.lastBusyReplyTime.get(key) || 0;+ if (now - lastBusy < DiscordChannel.BUSY_COOLDOWN_MS) return;++ this.lastBusyReplyTime.set(key, now);+ await channel.send({+ content: '\u23f3 Mercury is busy processing another request. Your message has been queued.',+ allowedMentions: { parse: [] },+ }).catch(() => {});+ }+}\ No newline at end of filediff --git a/src/channels/index.ts b/src/channels/index.tsindex e1c6e62f..7fff8772 100644--- a/src/channels/index.ts+++ b/src/channels/index.ts@@ -2,5 +2,8 @@ export { BaseChannel } from './base.js';export type { Channel } from './base.js';export { CLIChannel } from './cli.js';export { TelegramChannel } from './telegram.js';+export { SignalChannel } from './signal.js';export { WebChannel } from './web.js';+export { DiscordChannel } from './discord.js';+export { SlackChannel } from './slack.js';export { ChannelRegistry } from './registry.js';\ No newline at end of filediff --git a/src/channels/registry.ts b/src/channels/registry.tsindex 052b4432..674da6b4 100644--- a/src/channels/registry.ts+++ b/src/channels/registry.ts@@ -2,6 +2,9 @@ import type { Channel } from './base.js';import type { ChannelMessage, ChannelType } from '../types/channel.js';import { CLIChannel } from './cli.js';import { TelegramChannel } from './telegram.js';+import { SignalChannel } from './signal.js';+import { DiscordChannel } from './discord.js';+import { SlackChannel } from './slack.js';import type { MercuryConfig } from '../utils/config.js';import { logger } from '../utils/logger.js';@@ -14,12 +17,32 @@ export class ChannelRegistry {if (config.channels.telegram.enabled && config.channels.telegram.botToken) {this.register('telegram', new TelegramChannel(config));}++ if (config.channels.signal.enabled && config.channels.signal.phoneNumber) {+ this.register('signal', new SignalChannel(config));+ }++ if (config.channels.discord.enabled && config.channels.discord.botToken) {+ this.register('discord', new DiscordChannel(config));+ }++ if (config.channels.slack.enabled && config.channels.slack.botToken) {+ this.register('slack', new SlackChannel(config));+ }}getCliChannel(): CLIChannel | undefined {return this.channels.get('cli') as CLIChannel | undefined;}+ getDiscordChannel(): DiscordChannel | undefined {+ return this.channels.get('discord') as DiscordChannel | undefined;+ }++ getSlackChannel(): SlackChannel | undefined {+ return this.channels.get('slack') as SlackChannel | undefined;+ }+register(type: ChannelType, channel: Channel): void {channel.onMessage((msg) => this.handleIncomingMessage(msg));this.channels.set(type, channel);@@ -59,8 +82,14 @@ export class ChannelRegistry {}getNotificationChannel(): Channel | undefined {+ const signal = this.channels.get('signal');+ if (signal?.isReady()) return signal;const telegram = this.channels.get('telegram');if (telegram?.isReady()) return telegram;+ const discord = this.channels.get('discord');+ if (discord?.isReady()) return discord;+ const slack = this.channels.get('slack');+ if (slack?.isReady()) return slack;const cli = this.channels.get('cli');if (cli?.isReady()) return cli;return this.channels.values().next().value;diff --git a/src/channels/signal.ts b/src/channels/signal.tsnew file mode 100644index 00000000..ddcedf66--- /dev/null+++ b/src/channels/signal.ts@@ -0,0 +1,1034 @@+import fs from 'node:fs';+import path from 'node:path';+import type { ChannelMessage } from '../types/channel.js';+import { BaseChannel, type PermissionMode } from './base.js';+import type { MercuryConfig } from '../utils/config.js';+import {+ addSignalPendingRequest,+ approveSignalPendingRequestByPairingCode,+ clearSignalAccess,+ findSignalAdmin,+ findSignalApprovedUser,+ findSignalPendingRequest,+ getSignalAccessSummary,+ hasSignalAdmins,+ loadConfig,+ saveConfig,+} from '../utils/config.js';+import { logger } from '../utils/logger.js';+import { mdToSignal } from '../utils/markdown.js';+import { formatToolStep, formatToolResult } from '../utils/tool-label.js';+import { redactPhone } from '../utils/redact.js';+import { JsonRpcClient } from '../signal/jsonrpc.js';+import type { JsonRpcEnvelope } from '../signal/process.js';+import { ensureSignalCli, getSignalCliCommand } from '../signal/binary.js';++const MAX_MESSAGE_LENGTH = 4000;+const INTER_MESSAGE_DELAY_MS = 350;++const AFFIRMATIVE = new Set(['yes', 'y', 'ok', 'okay', 'sure', 'allow', 'approve', 'yeah', 'yep', 'yup']);+const NEGATIVE = new Set(['no', 'n', 'nope', 'deny', 'stop', 'cancel', 'never']);+const ALWAYS_WORDS = new Set(['always', 'all', 'allow-all', 'allow all', 'forever']);++function normalizeReply(raw: string): string {+ const cleaned = raw.trim().toLowerCase().replace(/[.!]/g, '');+ if (ALWAYS_WORDS.has(cleaned)) return 'always';+ if (AFFIRMATIVE.has(cleaned)) return 'yes';+ if (NEGATIVE.has(cleaned)) return 'no';+ if (/^\d+$/.test(cleaned)) return cleaned;+ if (AFFIRMATIVE.has(cleaned.split(/\s+/)[0])) return 'yes';+ return cleaned || 'no';+}++type PendingReply = {+ resolve: (value: string) => void;+ timeout: NodeJS.Timeout;+};++const UNPAIRED_RESPONSE = 'Pair Mercury by sending /pair and then entering the code in the Mercury terminal.';++export class SignalChannel extends BaseChannel {+ readonly type = 'signal' as const;+ private rpc: JsonRpcClient | null = null;+ private binaryPath: string | null = null;+ private _running = false;+ get running(): boolean { return this._running; }+ private chatCommandContext?: import('../capabilities/registry.js').ChatCommandContext;++ private processedMessages = new Map<string, number>();+ private static readonly DEDUP_TTL = 60_000;+ private static readonly DEDUP_MAX_SIZE = 10000;+ private dedupCleanupInterval: NodeJS.Timeout | null = null;++ private pendingReplies = new Map<string, PendingReply>();+ private permissionModes = new Map<string, PermissionMode>();+ private onPermissionMode?: (mode: PermissionMode, source: string) => void;++ private stepCounters = new Map<string, number>();+ private stepHistory = new Map<string, string[]>();+ private taskActive = new Map<string, boolean>();+ private deferredResponses = new Map<string, string>();+ private statusNotices = new Map<string, string[]>();+ private static readonly MAX_STATUS_NOTICES = 3;++ constructor(private config: MercuryConfig) {+ super();+ }++ async listGroups(): Promise<{ groupId: string; groupName: string } | null> {+ if (!this.rpc) throw new Error('Signal RPC client not running');+ const phoneNumber = this.config.channels.signal.phoneNumber;+ const groups = await this.rpc.listGroups({ account: phoneNumber }) as any[];+ if (!Array.isArray(groups)) return null;+ logger.debug({ groups: groups.map(g => ({ id: g.groupId || g.id, name: g.name || g.groupName })) }, 'Signal: listGroups response');+ for (const group of groups) {+ const name = (group.name || group.groupName || '').toLowerCase().trim();+ if (name === 'mercury') {+ return {+ groupId: group.groupId || group.id,+ groupName: group.name || group.groupName || 'Mercury',+ };+ }+ }+ return null;+ }++ setChatCommandContext(ctx: import('../capabilities/registry.js').ChatCommandContext): void {+ this.chatCommandContext = ctx;+ }++ beginTask(targetId?: string): void {+ const key = targetId || 'notification';+ this.taskActive.set(key, true);+ this.deferredResponses.delete(key);+ this.statusNotices.delete(key);+ }++ endTask(targetId?: string): void {+ const key = targetId || 'notification';+ this.taskActive.set(key, false);+ }++ isTaskActive(targetId?: string): boolean {+ const key = targetId || 'notification';+ return this.taskActive.get(key) ?? false;+ }++ popDeferredResponse(targetId?: string): string | undefined {+ const key = targetId || 'notification';+ const text = this.deferredResponses.get(key);+ this.deferredResponses.delete(key);+ return text;+ }++ setOnPermissionMode(handler: (mode: PermissionMode, source: string) => void): void {+ this.onPermissionMode = handler;+ }++ getPermissionMode(senderPhone: string): PermissionMode {+ return this.permissionModes.get(senderPhone) ?? 'ask-me';+ }++ async start(): Promise<void> {+ if (this._running) return;++ const { phoneNumber, mode } = this.config.channels.signal;+ if (!phoneNumber) {+ throw new Error('Signal phone number not configured');+ }++ try {+ this.binaryPath = await ensureSignalCli();+ const cmd = getSignalCliCommand(this.binaryPath);+ logger.info({ binary: cmd[0], native: cmd.length === 1 }, 'Signal CLI binary located');+ } catch (err: any) {+ throw new Error(`Failed to find or download signal-cli: ${err.message}`);+ }++ this.rpc = new JsonRpcClient({+ binaryPath: this.binaryPath,+ phoneNumber,+ });++ this.rpc.onEnvelope((envelope) => this.handleEnvelope(envelope));+ logger.info('Signal: envelope handler registered on RPC client');++ try {+ await this.rpc.start();+ } catch (err: any) {+ throw new Error(`Failed to start signal-cli daemon: ${err.message}`);+ }++ this._running = true;+ this.ready = true;++ this.dedupCleanupInterval = setInterval(() => this.cleanupDedup(), 30_000);++ if (mode === 'group' && !this.config.channels.signal.groupId) {+ logger.info('Signal group mode: no groupId configured, will auto-detect "Mercury" group');+ }++ logger.info({ mode, phone: redactPhone(phoneNumber) }, 'Signal channel started');+ }++ async stop(): Promise<void> {+ this._running = false;+ this.ready = false;++ if (this.dedupCleanupInterval) {+ clearInterval(this.dedupCleanupInterval);+ this.dedupCleanupInterval = null;+ }++ if (this.rpc) {+ await this.rpc.stop();+ this.rpc = null;+ }++ for (const [, pending] of this.pendingReplies) {+ clearTimeout(pending.timeout);+ }+ this.pendingReplies.clear();++ logger.info('Signal channel stopped');+ }++ private handleEnvelope(envelope: JsonRpcEnvelope): void {+ logger.info({ source: redactPhone(envelope.source), hasData: !!envelope.dataMessage, hasSync: !!envelope.syncMessage, hasTyping: !!envelope.typingMessage, hasReceipt: !!envelope.receiptMessage }, 'Signal: handleEnvelope called');+ try {+ this.handleEnvelopeInner(envelope);+ } catch (err: any) {+ logger.error({ err: err.message, source: redactPhone(envelope.source) }, 'Error handling Signal envelope');+ }+ }++ private handleEnvelopeInner(envelope: JsonRpcEnvelope): void {+ this.reloadConfigFromDisk();++ const source = envelope.source;+ const timestamp = envelope.timestamp;++ const dedupKey = `${source}:${timestamp}`;+ if (this.processedMessages.has(dedupKey)) {+ logger.debug({ source: redactPhone(source), timestamp }, 'Signal: dedup skipping message');+ return;+ }+ this.processedMessages.set(dedupKey, Date.now());+ if (this.processedMessages.size > SignalChannel.DEDUP_MAX_SIZE) {+ this.cleanupDedup();+ }++ if (envelope.typingMessage) return;+ if (envelope.receiptMessage) return;+ if (envelope.callMessage) return;++ // Convert syncMessage.sentMessage into a dataMessage-like structure+ // so we can process commands sent from the same account (e.g., /pair+ // sent from the linked phone to a group the bot is also in).+ let effectiveDataMessage = envelope.dataMessage;+ let effectiveSource = source;+ let effectiveSourceUuid = envelope.sourceUuid;+ let effectiveSourceName = envelope.sourceName;++ if (!effectiveDataMessage && envelope.syncMessage?.sentMessage) {+ const sent = envelope.syncMessage.sentMessage;+ effectiveDataMessage = {+ timestamp: sent.timestamp,+ message: sent.message,+ groupInfo: sent.groupInfo,+ expiresInSeconds: sent.expiresInSeconds,+ attachments: undefined,+ quote: undefined,+ sticker: undefined,+ remoteDelete: undefined,+ };+ // The source of a sync message is the account itself, which is an admin+ effectiveSource = this.config.channels.signal.phoneNumber || source;+ effectiveSourceUuid = envelope.sourceUuid;+ effectiveSourceName = envelope.sourceName || 'You';+ logger.info({ source: redactPhone(effectiveSource), message: sent.message }, 'Signal: processing syncMessage.sentMessage as dataMessage');+ }++ if (!effectiveDataMessage) {+ logger.debug({ source: redactPhone(source) }, 'Signal: no dataMessage, skipping');+ return;+ }+ const data = effectiveDataMessage;++ if (data.remoteDelete) return;++ const groupId = data.groupInfo?.groupId;+ const groupName = data.groupInfo?.groupName;++ // SOURCE FILTER: Mercury only listens to the configured channel.+ // Everything else is silently dropped before any processing.+ if (this.config.channels.signal.mode === 'private') {+ if (groupId || effectiveSource !== this.config.channels.signal.phoneNumber) {+ return;+ }+ } else {+ if (!groupId) {+ return;+ }+ const configuredGroupId = this.config.channels.signal.groupId;+ if (configuredGroupId && groupId !== configuredGroupId) {+ return;+ }+ if (!configuredGroupId) {+ if (groupName && groupName.toLowerCase().trim() === 'mercury') {+ this.config.channels.signal.groupId = groupId;+ this.config.channels.signal.groupName = groupName;+ saveConfig(this.config);+ logger.info({ groupId, groupName }, 'Signal: auto-detected Mercury group');+ } else {+ return;+ }+ }+ }++ // Private mode: auto-pair account owner as admin on first message+ if (this.config.channels.signal.mode === 'private' && !hasSignalAdmins(this.config)) {+ this.config.channels.signal.admins.push({+ phoneNumber: this.config.channels.signal.phoneNumber,+ role: 'admin',+ pairedAt: new Date().toISOString(),+ });+ saveConfig(this.config);+ logger.info('Signal: auto-paired account owner as admin (private mode)');+ }++ const text = data.message?.trim();+ const hasAttachments = data.attachments && data.attachments.length > 0;+ if (!text && !hasAttachments) return;++ const command = text ? this.getCommandName(text) : '';+ const role = this.getRole(effectiveSource);++ logger.info({ source: redactPhone(effectiveSource), text: text?.substring(0, 50), groupId: groupId ? 'present' : 'none', groupName, command, role }, 'Signal: processing message');++ // Group mode: unpaired user handling (after source filter)+ if (this.config.channels.signal.mode === 'group') {+ if (role === 'unpaired' && command === '/pair') {+ this.handlePairCommand(effectiveSource, effectiveSourceUuid, effectiveSourceName);+ return;+ }+ if (role === 'unpaired') {+ this.sendToTarget(UNPAIRED_RESPONSE, source);+ return;+ }+ }++ if (command === '/pair') {+ if (hasSignalAdmins(this.config)) {+ this.sendToTarget('Mercury is already paired. Only the admin can /unpair.', source);+ } else {+ this.handlePairCommand(source, envelope.sourceUuid, envelope.sourceName);+ }+ return;+ }++ if (command === '/unpair') {+ if (this.isAdmin(source)) {+ clearSignalAccess(this.config);+ saveConfig(this.config);+ this.reloadConfigFromDisk();+ this.sendToTarget('Signal has been unpaired. Send /pair to reconnect.', source);+ } else {+ this.sendToTarget('Only admins can unpair Mercury.', source);+ }+ return;+ }++ if (command === '/memory') {+ if (!this.isAdmin(source)) {+ this.sendToTarget('Memory commands are admin-only.', source);+ return;+ }+ this.handleMemoryCommand(source, text || '');+ return;+ }++ if (command === '/permissions') {+ if (!this.isAdmin(source)) {+ this.sendToTarget('Permission settings are admin-only.', source);+ return;+ }+ this.askPermissionMode(`signal:${source}`).then((mode) => {+ this.permissionModes.set(source, mode);+ if (this.onPermissionMode) this.onPermissionMode(mode, `signal:${source}`);+ }).catch(() => {});+ return;+ }++ if (command === '/help') {+ this.sendHelp(source);+ return;+ }++ if (command === '/status') {+ this.sendStatus(source);+ return;+ }++ if (command === '/skills') {+ this.handleSkillsCommand(source, text || '');+ return;+ }++ if (!this.permissionModes.has(source) && this.onPermissionMode) {+ this.permissionModes.set(source, 'ask-me');+ }++ const pending = this.pendingReplies.get(source);+ if (pending && text) {+ const normalized = normalizeReply(text);+ if (AFFIRMATIVE.has(normalized) || ALWAYS_WORDS.has(normalized) || NEGATIVE.has(normalized)) {+ clearTimeout(pending.timeout);+ this.pendingReplies.delete(source);+ pending.resolve(normalized);+ return;+ }+ }++ let content = text || '';+ if (hasAttachments && data.attachments) {+ const attachmentNames = data.attachments+ .map((a) => a.filename || a.contentType || 'attachment')+ .join(', ');+ if (content) {+ content += `\n[Attachments: ${attachmentNames}]`;+ } else {+ content = `[Attachments: ${attachmentNames}]`;+ }+ }++ if (!content) return;++ const rawId = this.config.channels.signal.mode === 'group'+ ? this.config.channels.signal.groupId || 'unknown'+ : source;+ const channelId = `signal:${rawId}`;++ const msg: ChannelMessage = {+ id: `${envelope.timestamp}`,+ channelId,+ channelType: 'signal',+ senderId: source,+ senderName: envelope.sourceName,+ content,+ timestamp: envelope.timestamp,+ metadata: {+ sourcePhone: source,+ sourceUuid: envelope.sourceUuid,+ sourceName: envelope.sourceName,+ senderRole: role,+ groupId,+ groupName,+ },+ };+ this.emit(msg);+ }++ async send(content: string, targetId?: string, elapsedMs?: number): Promise<void> {+ const target = this.resolveTarget(targetId);+ if (!target || !this.rpc) {+ logger.warn({ targetId }, 'Signal send: no valid target');+ return;+ }++ const key = targetId || 'notification';++ if (this.taskActive.get(key)) {+ const timeSuffix = elapsedMs != null ? ` (${(elapsedMs / 1000).toFixed(1)}s)` : '';+ const fullContent = content + timeSuffix;+ if (!fullContent.trim()) return;++ const isSystemNotice = content.startsWith('☿ ') || content.startsWith('⚠') || content.startsWith(' [') || content.length < 200;+ if (isSystemNotice) {+ const notices = this.statusNotices.get(key) || [];+ const truncated = fullContent.length > 80 ? fullContent.slice(0, 77) + '…' : fullContent;+ notices.push(truncated);+ this.statusNotices.set(key, notices);+ } else {+ this.deferredResponses.set(key, fullContent);+ }+ return;+ }++ const timeSuffix = elapsedMs != null ? `\n⏱ ${(elapsedMs / 1000).toFixed(1)}s` : '';+ const fullContent = content + timeSuffix;+ if (!fullContent.trim()) return;++ const formatted = mdToSignal(fullContent);+ const chunks = this.splitMessage(formatted, MAX_MESSAGE_LENGTH);++ for (const chunk of chunks) {+ await this.sendRaw(chunk, target);+ if (chunks.length > 1) {+ await this.delay(INTER_MESSAGE_DELAY_MS);+ }+ }+ }++ async sendFile(filePath: string, targetId?: string): Promise<void> {+ const target = this.resolveTarget(targetId);+ if (!target || !this.rpc) {+ logger.warn({ targetId }, 'Signal sendFile: no valid target');+ return;+ }++ const resolved = path.resolve(filePath);+ if (!fs.existsSync(resolved)) {+ await this.send(`File not found: ${filePath}`, targetId);+ return;+ }++ const { phoneNumber, mode, groupId } = this.config.channels.signal;++ try {+ await this.rpc.sendMessage({+ account: phoneNumber,+ message: path.basename(resolved),+ recipients: mode === 'group' && groupId ? undefined : [target],+ groupId: mode === 'group' && groupId ? groupId : undefined,+ attachments: [resolved],+ });+ logger.info({ file: resolved, target }, 'File sent via Signal');+ } catch (err: any) {+ logger.error({ err: err.message, file: resolved, target }, 'Signal sendFile failed');+ await this.send(`Failed to send file: ${err.message}`, targetId);+ }+ }++ async stream(content: AsyncIterable<string>, targetId?: string): Promise<string> {+ const key = targetId || 'notification';++ let full = '';+ for await (const chunk of content) {+ full += chunk;+ }++ if (this.taskActive.get(key)) {+ this.deferredResponses.set(key, full);+ return full;+ }++ const formatted = mdToSignal(full);+ const target = this.resolveTarget(targetId);+ if (target && this.rpc) {+ const chunks = this.splitMessage(formatted, MAX_MESSAGE_LENGTH);+ for (const chunk of chunks) {+ await this.sendRaw(chunk, target);+ if (chunks.length > 1) {+ await this.delay(INTER_MESSAGE_DELAY_MS);+ }+ }+ }+ return full;+ }++ async typing(targetId?: string): Promise<void> {+ if (!this.rpc) return;+ const { phoneNumber, mode, groupId } = this.config.channels.signal;++ try {+ const params: { account: string; recipient?: string; groupId?: string } = { account: phoneNumber };+ if (mode === 'group' && groupId) {+ params.groupId = groupId;+ }+ await this.rpc.sendTyping(params);+ } catch {+ // typing indicator is best-effort+ }+ }++ async askPermission(prompt: string, targetId?: string): Promise<string> {+ const target = this.resolveTarget(targetId);+ if (!target || !this.rpc) return 'no';++ const formatted = mdToSignal(prompt);+ const question = `${formatted}\n\nReply "yes" to allow, "no" to deny, or "always" to auto-approve.`;++ await this.sendRaw(question, target);++ return new Promise((resolve) => {+ const timeout = setTimeout(() => {+ this.pendingReplies.delete(target);+ resolve('no');+ }, 120_000);++ this.pendingReplies.set(target, { resolve, timeout });+ });+ }++ async askToContinue(question: string, targetId?: string): Promise<boolean> {+ const target = this.resolveTarget(targetId);+ if (!target || !this.rpc) return false;++ const formatted = mdToSignal(question);+ const prompt = `${formatted}\n\nReply "yes" to continue or "no" to stop.`;++ await this.sendRaw(prompt, target);++ return new Promise((resolve) => {+ const timeout = setTimeout(() => {+ this.pendingReplies.delete(target);+ resolve(false);+ }, 120_000);++ this.pendingReplies.set(target, {+ resolve: (val: string) => resolve(AFFIRMATIVE.has(val) || ALWAYS_WORDS.has(val)),+ timeout,+ });+ });+ }++ async askPermissionMode(targetId?: string): Promise<PermissionMode> {+ const target = this.resolveTarget(targetId);+ if (!target || !this.rpc) return 'ask-me';++ const prompt = `Permission Mode\nHow should Mercury handle risky actions?\n\n🔒 "ask-me" — confirm before file writes, commands, and scope changes\n✅ "allow-all" — auto-approve everything\n\nReply "ask-me" or "allow-all".`;++ await this.sendRaw(prompt, target);++ return new Promise((resolve) => {+ const timeout = setTimeout(() => {+ this.pendingReplies.delete(target);+ resolve('ask-me');+ }, 120_000);++ this.pendingReplies.set(target, {+ resolve: (val: string) => {+ const mode = ALWAYS_WORDS.has(val) ? 'allow-all' : 'ask-me';+ resolve(mode as PermissionMode);+ return mode;+ },+ timeout,+ });+ });+ }++ private getRole(senderPhone: string): 'admin' | 'member' | 'unpaired' {+ if (findSignalAdmin(this.config, senderPhone)) return 'admin';+ if (findSignalApprovedUser(this.config, senderPhone)) return 'member';+ return 'unpaired';+ }++ private isAdmin(senderPhone: string): boolean {+ return this.getRole(senderPhone) === 'admin';+ }++ private handlePairCommand(senderPhone: string, senderUuid: string | undefined, senderName: string | undefined): void {+ if (hasSignalAdmins(this.config)) {+ this.sendToTarget('Mercury is already paired. Only the admin can /unpair.', senderPhone);+ return;+ }++ const existing = findSignalPendingRequest(this.config, senderPhone);+ if (existing) {+ this.sendToTarget(`Pairing already in progress. Your code is: ${existing.pairingCode}\nEnter this code in the Mercury terminal.`, senderPhone);+ return;+ }++ const pairingCode = this.generatePairingCode();+ addSignalPendingRequest(this.config, {+ phoneNumber: senderPhone,+ pairingCode,+ uuid: senderUuid,+ name: senderName,+ });+ saveConfig(this.config);++ this.sendToTarget(+ `Pairing initiated. Your code is: *${pairingCode}*\nEnter this code in the Mercury terminal to complete setup.`,+ senderPhone,+ );++ logger.info({ phone: redactPhone(senderPhone) }, 'Signal pairing request received');+ }++ private sendHelp(senderPhone: string): void {+ const isAdmin = this.isAdmin(senderPhone);+ const lines = [+ '*Mercury Commands:*',+ '',+ '/pair — Start pairing (first user becomes admin)',+ '/status — Show Mercury status',+ '/skills — Browse skills',+ '/help — Show this help',+ ];++ if (isAdmin) {+ lines.push('', '*Admin only:*');+ lines.push('/unpair — Reset all Signal access');+ lines.push('/memory — View and manage memory');+ lines.push('/permissions — Change permission mode');+ }++ this.sendToTarget(lines.join('\n'), senderPhone);+ }++ private sendStatus(senderPhone: string): void {+ const isAdmin = this.isAdmin(senderPhone);+ const { mode, groupId, groupName } = this.config.channels.signal;+ const summary = getSignalAccessSummary(this.config);++ const lines = [+ '*Mercury Status*',+ '',+ `Mode: ${mode}`,+ `Paired: ${hasSignalAdmins(this.config) ? 'Yes' : 'No'}`,+ `Access: ${summary}`,+ ];++ if (mode === 'group') {+ lines.push(`Group: ${groupName || groupId || 'Not set'}`);+ }++ if (isAdmin) {+ const permMode = this.permissionModes.get(senderPhone) || 'ask-me';+ lines.push(`Your permissions: ${permMode}`);+ } else {+ lines.push('Your role: member');+ }++ this.sendToTarget(lines.join('\n'), senderPhone);+ }++ private handleMemoryCommand(senderPhone: string, text: string): void {+ if (!this.chatCommandContext) {+ this.sendToTarget('Memory not available.', senderPhone);+ return;+ }++ const parts = text.trim().split(/\s+/).slice(1);+ const sub = (parts[0] || 'overview').toLowerCase();++ switch (sub) {+ case 'overview': {+ const summary = this.chatCommandContext.memorySummary();+ const lines = [+ '*Memory Overview*',+ `Conscious memories: ${summary.total}`,+ `Subconscious memories: ${summary.subconsciousTotal}`,+ `Learning: ${summary.learningPaused ? '⏸ PAUSED' : '✅ ACTIVE'}`,+ ];+ this.sendToTarget(lines.join('\n'), senderPhone);+ return;+ }+ case 'recent': {+ const recent = this.chatCommandContext.memoryRecent(10);+ if (recent.length === 0) {+ this.sendToTarget('No memories yet.', senderPhone);+ return;+ }+ const lines = recent.map((r) => {+ const scope = r.scope === 'active' ? '⏳' : r.scope === 'subconscious' ? '💤' : '📌';+ return `${scope} [${r.type}] ${r.summary} (conf: ${r.confidence.toFixed(2)}, seen: ${r.evidenceCount}x)`;+ });+ this.sendToTarget('*Recent Memories:*\n' + lines.join('\n'), senderPhone);+ return;+ }+ case 'toggle':+ case 'pause':+ case 'resume': {+ const currentSummary = this.chatCommandContext.memorySummary();+ const currentlyPaused = currentSummary.learningPaused;+ this.chatCommandContext.memorySetLearningPaused(!currentlyPaused);+ this.sendToTarget(+ currentlyPaused ? 'Learning resumed.' : 'Learning paused.',+ senderPhone,+ );+ return;+ }+ case 'clear': {+ this.sendToTarget(+ '⚠️ Are you sure you want to clear ALL memories? Reply "yes" to confirm.',+ senderPhone,+ );+ const timeout = setTimeout(() => {+ this.pendingReplies.delete(senderPhone);+ }, 60_000);+ this.pendingReplies.set(senderPhone, {+ resolve: (val: string) => {+ if (val === 'yes') {+ const cleared = this.chatCommandContext!.memoryClear();+ this.sendToTarget(`Cleared ${cleared} memories.`, senderPhone);+ } else {+ this.sendToTarget('Memory clear cancelled.', senderPhone);+ }+ },+ timeout,+ });+ return;+ }+ case 'subconscious': {+ const subconsciousMemories = this.chatCommandContext.memoryGetSubconscious(5);+ const subconsciousTotal = this.chatCommandContext.memorySummary().subconsciousTotal;+ if (subconsciousMemories.length === 0) {+ this.sendToTarget('No subconscious memories yet.', senderPhone);+ return;+ }+ const lines = subconsciousMemories.map((r) => `💤 [${r.type}] ${r.summary}`);+ this.sendToTarget('*Subconscious Memory:*\n' + lines.join('\n'), senderPhone);+ return;+ }+ case 'shared': {+ this.sendToTarget('Shared memory feature is not yet available on Signal.', senderPhone);+ return;+ }+ default:+ this.sendToTarget(+ '/memory overview — view memory summary\n/memory recent — recent memories\n/memory toggle — pause/resume learning\n/memory clear — clear all memories\n/memory subconscious — view subconscious\n/memory shared — shared memories',+ senderPhone,+ );+ }+ }++ private handleSkillsCommand(senderPhone: string, text: string): void {+ const parts = text.trim().split(/\s+/).slice(1);+ const sub = (parts[0] || 'list').toLowerCase();+ const arg = parts.slice(1).join(' ').trim();++ if (sub === 'help' || sub === '-h' || sub === '--help') {+ this.sendToTarget(+ '*Skills Commands:*\n/skills — list installed skills\n/skills search <query> — search registry\n/skills view <id> — show details\n/skills install <id> — admin only\n/skills remove <id> — admin only',+ senderPhone,+ );+ return;+ }++ if (sub === 'list') {+ const loader = new (require('../skills/loader.js').SkillLoader)();+ const installed = loader.getAllSkills();+ if (installed.length === 0) {+ this.sendToTarget('No skills installed.', senderPhone);+ return;+ }+ const lines = installed.slice(0, 25).map((s: any) => `• ${s.name} — ${s.active ? 'active' : 'inactive'}${s.description ? ` — ${s.description}` : ''}`);+ this.sendToTarget(`*Installed skills (${installed.length})*\n\n${lines.join('\n')}`, senderPhone);+ return;+ }++ this.sendToTarget('Full skills browsing via Signal is coming soon. Use the Mercury terminal for now.', senderPhone);+ }++ async sendToolFeedback(toolName: string, args: Record<string, any>, targetId?: string): Promise<void> {+ const key = targetId || 'notification';+ const step = (this.stepCounters.get(key) || 0) + 1;+ this.stepCounters.set(key, step);+ const label = formatToolStep(toolName, args);++ const history = this.stepHistory.get(key) || [];+ const recentHistory = history.slice(-5);+ const lines = [+ `⚙️ *Mercury working* (step ${step})`,+ '',+ ...recentHistory.map(h => `✅ ${h}`),+ `⏳ ${label}…`,+ ];+ await this.send(lines.join('\n'), targetId);+ }++ async sendStepDone(toolName: string, result: unknown, targetId?: string): Promise<void> {+ const key = targetId || 'notification';+ const step = this.stepCounters.get(key) || 0;+ const summary = formatToolResult(toolName, result);+ const label = formatToolStep(toolName, {} as any);+ const doneLine = summary ? `${label} · ${summary}` : label;++ const history = this.stepHistory.get(key) || [];+ history.push(doneLine);+ this.stepHistory.set(key, history);++ const recentHistory = history.slice(-5);+ const lines = [+ `⚙️ *Mercury working* (${step} steps done)`,+ '',+ ...recentHistory.map(h => `✅ ${h}`),+ ];+ await this.send(lines.join('\n'), targetId);+ }++ resetStepCounter(targetId?: string): void {+ const key = targetId || 'notification';+ this.stepCounters.delete(key);+ this.stepHistory.delete(key);+ this.statusNotices.delete(key);+ this.endTask(targetId);+ }++ async sendCompletion(elapsedMs: number, stepCount: number, targetId?: string, meta?: { provider: string; model: string; inputTokens: number; outputTokens: number; totalTokens: number; budgetUsed: number; budgetTotal: number; budgetPercentage: number }): Promise<void> {+ const secs = Math.floor(elapsedMs / 1000);+ const mins = Math.floor(secs / 60);+ const remSecs = secs % 60;+ const timeStr = mins > 0 ? `${mins}m ${remSecs}s` : `${secs}s`;+ const stepsStr = stepCount > 0 ? `${stepCount} step${stepCount !== 1 ? 's' : ''}` : '';+ const parts = [stepsStr, timeStr].filter(Boolean).join(' · ');++ const key = targetId || 'notification';+ const history = this.stepHistory.get(key) || [];+ const recentHistory = history.slice(-5);++ const lines = [`✅ *Task complete* (${parts})`];++ if (meta) {+ const formatTokens = (n: number) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`;+ lines.push(`☿ ${meta.model} via ${meta.provider} · ${formatTokens(meta.totalTokens)} tokens`);+ const pct = Math.round(meta.budgetPercentage);+ const barLen = 15;+ const filled = Math.round((pct / 100) * barLen);+ const bar = '█'.repeat(filled) + '░'.repeat(barLen - filled);+ lines.push(`Budget: ${bar} ${pct}% (${formatTokens(meta.budgetUsed)} / ${formatTokens(meta.budgetTotal)})`);+ }++ if (recentHistory.length > 0) {+ lines.push('');+ lines.push(...recentHistory.map(h => ` ✓ ${h}`));+ }++ this.endTask(targetId);++ const deferred = this.deferredResponses.get(key);+ if (deferred && deferred.trim()) {+ this.deferredResponses.delete(key);+ await this.send(deferred, targetId);+ }++ await this.send(lines.join('\n'), targetId);++ this.stepCounters.delete(key);+ this.stepHistory.delete(key);+ this.statusNotices.delete(key);+ }++ async sendGoodbyeMessage(): Promise<void> {+ const { mode, groupId, phoneNumber } = this.config.channels.signal;+ if (!this.rpc) return;++ const message = 'Mercury has been unregistered from this conversation. It will no longer respond here. To reconnect, the admin needs to set up Signal again with: mercury doctor';++ try {+ if (mode === 'group' && groupId) {+ await this.rpc.sendMessage({+ account: phoneNumber,+ message,+ groupId,+ });+ } else {+ const admins = this.config.channels.signal.admins;+ if (admins.length > 0) {+ await this.rpc.sendMessage({+ account: phoneNumber,+ message,+ recipients: [admins[0].phoneNumber],+ });+ }+ }+ } catch (err: any) {+ logger.error({ err: err.message }, 'Failed to send Signal goodbye message');+ }+ }++ private resolveTarget(targetId?: string): string | null {+ const { mode, groupId, phoneNumber } = this.config.channels.signal;++ if (!targetId || targetId === 'notification') {+ if (mode === 'group' && groupId) {+ return groupId;+ }+ const admins = this.config.channels.signal.admins;+ if (admins.length > 0) return admins[0].phoneNumber;+ return null;+ }++ if (targetId.startsWith('signal:')) {+ return targetId.slice(7);+ }+ return targetId;+ }++ private async sendRaw(text: string, target: string): Promise<boolean> {+ if (!this.rpc) return false;++ const { phoneNumber, mode, groupId } = this.config.channels.signal;++ try {+ await this.rpc.sendMessage({+ account: phoneNumber,+ message: text,+ recipients: mode === 'group' && groupId ? undefined : [target],+ groupId: mode === 'group' && groupId ? groupId : undefined,+ });+ return true;+ } catch (err: any) {+ logger.error({ err: err.message, target: redactPhone(target) }, 'Signal send failed');+ return false;+ }+ }++ private async sendToTarget(text: string, target: string): Promise<void> {+ const formatted = mdToSignal(text);+ const chunks = this.splitMessage(formatted, MAX_MESSAGE_LENGTH);+ for (const chunk of chunks) {+ await this.sendRaw(chunk, target);+ if (chunks.length > 1) {+ await this.delay(INTER_MESSAGE_DELAY_MS);+ }+ }+ }++ private async sendToGroup(text: string): Promise<void> {+ const { mode, groupId } = this.config.channels.signal;+ if (mode === 'group' && groupId) {+ await this.sendRaw(mdToSignal(text), groupId);+ }+ }++ private getCommandName(text: string): string {+ return text.trim().split(/\s+/)[0]?.toLowerCase() || '';+ }++ private generatePairingCode(): string {+ return Math.floor(100000 + Math.random() * 900000).toString();+ }++ private splitMessage(text: string, maxLen: number): string[] {+ if (text.length <= maxLen) return [text];+ const chunks: string[] = [];+ let remaining = text;+ while (remaining.length > 0) {+ let splitAt = maxLen;+ if (remaining.length > maxLen) {+ const lastNewline = remaining.lastIndexOf('\n', maxLen);+ if (lastNewline > maxLen * 0.5) {+ splitAt = lastNewline + 1;+ }+ }+ chunks.push(remaining.slice(0, splitAt));+ remaining = remaining.slice(splitAt);+ }+ return chunks;+ }++ private delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+ }++ private reloadConfigFromDisk(): void {+ try {+ this.config = loadConfig();+ } catch {+ // keep using in-memory copy+ }+ }++ private cleanupDedup(): void {+ const now = Date.now();+ for (const [key, ts] of this.processedMessages) {+ if (now - ts > SignalChannel.DEDUP_TTL) {+ this.processedMessages.delete(key);+ }+ }+ }+}\ No newline at end of filediff --git a/src/channels/slack.ts b/src/channels/slack.tsnew file mode 100644index 00000000..ff3ddb8e--- /dev/null+++ b/src/channels/slack.ts@@ -0,0 +1,887 @@+import fs from 'node:fs';+import path from 'node:path';+import { App } from '@slack/bolt';+import type { ChannelMessage } from '../types/channel.js';+import { BaseChannel, type PermissionMode } from './base.js';+import type { MercuryConfig } from '../utils/config.js';+import type { SlackAccessUser } from '../types/channel.js';+import {+ addSlackPendingRequest,+ approveSlackPendingRequest,+ findSlackAdmin,+ findSlackApprovedUser,+ findSlackPendingRequest,+ getSlackAccessSummary,+ getSlackAdmins,+ hasSlackAdmins,+ rejectSlackPendingRequest,+ removeSlackUser,+ saveConfig,+} from '../utils/config.js';+import { logger } from '../utils/logger.js';+import { mdToSlack } from '../utils/markdown.js';+import { formatToolStep, formatToolResult } from '../utils/tool-label.js';++const SLACK_DM_PREFIX = 'slack:dm';+const SLACK_CHANNEL_PREFIX = 'slack';++type ApprovalResolver = () => void;++export class SlackChannel extends BaseChannel {+ readonly type = 'slack' as const;+ private app: App | null = null;+ private lastActiveChannelId: string | null = null;+ private chatCommandContext?: import('../capabilities/registry.js').ChatCommandContext;+ private pendingApprovals: Map<string, ApprovalResolver> = new Map();+ private permissionModes = new Map<string, PermissionMode>();+ private onPermissionMode?: (mode: PermissionMode, channelId: string) => void;++ private statusMessageIds = new Map<string, string>();+ private statusMessageChannels = new Map<string, string>();+ private stepCounters = new Map<string, number>();+ private stepHistory = new Map<string, string[]>();+ private taskActive = new Map<string, boolean>();+ private deferredResponses = new Map<string, string>();+ private statusNotices = new Map<string, string[]>();+ private static readonly MAX_STATUS_NOTICES = 3;++ private userLastMessageTime = new Map<string, number>();+ private static readonly USER_RATE_LIMIT_MS = 30_000;+ private static readonly BUSY_COOLDOWN_MS = 15_000;+ private lastBusyReplyTime = new Map<string, number>();++ private lastMessageMetadata: { isDM: boolean; isAdmin: boolean } | null = null;++ constructor(private config: MercuryConfig) {+ super();+ }++ setChatCommandContext(ctx: import('../capabilities/registry.js').ChatCommandContext): void {+ this.chatCommandContext = ctx;+ }++ beginTask(targetId?: string): void {+ const key = targetId || 'notification';+ this.taskActive.set(key, true);+ this.deferredResponses.delete(key);+ this.statusNotices.delete(key);+ }++ endTask(targetId?: string): void {+ const key = targetId || 'notification';+ this.taskActive.set(key, false);+ }++ isTaskActive(targetId?: string): boolean {+ const key = targetId || 'notification';+ return this.taskActive.get(key) ?? false;+ }++ popDeferredResponse(targetId?: string): string | undefined {+ const key = targetId || 'notification';+ return this.deferredResponses.get(key);+ }++ resetStepCounter(targetId?: string): void {+ const key = targetId || 'notification';+ this.stepCounters.delete(key);+ this.stepHistory.delete(key);+ this.deleteStatusMessage(key);+ }++ setOnPermissionMode(fn: (mode: PermissionMode, channelId: string) => void): void {+ this.onPermissionMode = fn;+ }++ async start(): Promise<void> {+ const slackConfig = this.config.channels.slack;+ if (!slackConfig.botToken || !slackConfig.appToken) {+ throw new Error('Slack bot token and app token are required');+ }++ this.app = new App({+ token: slackConfig.botToken,+ socketMode: true,+ appToken: slackConfig.appToken,+ });++ this.registerHandlers();++ await this.app.start();+ this.ready = true;+ logger.info('Slack channel started (Socket Mode)');+ }++ async stop(): Promise<void> {+ if (this.app) {+ await this.app.stop();+ this.app = null;+ }+ this.ready = false;+ }++ private registerHandlers(): void {+ if (!this.app) return;++ this.app.event('message', async ({ payload }) => {+ const msg = payload as any;+ if (msg.bot_id || msg.subtype) return;++ const userId = msg.user;+ if (!userId) return;++ const channelId = msg.channel;+ if (!channelId.startsWith('D')) return;++ await this.handleDMMessage(msg);+ });++ this.app.event('app_mention', async ({ payload }) => {+ const userId = payload.user;+ if (!userId) return;++ const channelId = payload.channel;+ if (this.config.channels.slack.channelId && channelId !== this.config.channels.slack.channelId) {+ return;+ }++ const text = (payload.text || '').replace(/<@[^>]+>\s*/, '').trim();+ if (!text) return;++ const isAdmin = !!findSlackAdmin(this.config, userId);++ if (!isAdmin) {+ const now = Date.now();+ const lastTime = this.userLastMessageTime.get(userId) || 0;+ if (now - lastTime < SlackChannel.USER_RATE_LIMIT_MS) {+ const remaining = Math.ceil((SlackChannel.USER_RATE_LIMIT_MS - (now - lastTime)) / 1000);+ await this.sendEphemeral(channelId, userId, `Please wait ${remaining}s before sending another message.`);+ return;+ }+ this.userLastMessageTime.set(userId, now);+ }++ this.lastActiveChannelId = channelId;+ this.lastMessageMetadata = { isDM: false, isAdmin };++ if (!this.permissionModes.has(channelId)) {+ this.askPermissionMode(channelId).catch(() => {});+ this.permissionModes.set(channelId, 'ask-me');+ }++ this.emit({+ id: payload.ts,+ channelId: `slack:${channelId}`,+ channelType: 'slack',+ senderId: userId,+ senderName: payload.user,+ content: text,+ timestamp: Math.floor(parseFloat(payload.ts) * 1000),+ metadata: { slackChannelId: channelId, isDM: false, isAdmin },+ });+ });++ this.app.action(/^(slack_perm_|slack_loop_|slack_mode_|slack_access:)/, async ({ ack, body, client }) => {+ await ack();+ if (body.type !== 'block_actions') return;+ const action = (body as any).actions?.[0];+ if (!action) return;++ const actionId: string = action.action_id || action.actionId || '';+ const userId = body.user.id;+ const channel = (body as any).channel?.id;+ const messageTs = (body as any).message?.ts;++ if (actionId.startsWith('slack_access:')) {+ await this.handleAccessButton(actionId, userId, channel, client);+ return;+ }++ const resolver = this.pendingApprovals.get(actionId);+ if (resolver) {+ this.pendingApprovals.delete(actionId);+ for (const suffix of [':yes', ':always', ':no', ':ask-me', ':allow-all']) {+ this.pendingApprovals.delete(actionId.replace(/:(yes|always|no|ask-me|allow-all)$/, suffix));+ }+ resolver();++ if (messageTs && channel) {+ try {+ await client.chat.delete({ channel, ts: messageTs });+ } catch {}+ }+ } else {+ try {+ await client.chat.postEphemeral({+ channel: channel || body.user.id,+ user: userId,+ text: '_This action has expired._',+ });+ } catch {}+ }+ });++ this.app.command('/mercury', async ({ command, ack, client }) => {+ await ack();+ const userId = command.user_id;+ const channelId = command.channel_id;+ const args = (command.text || '').trim();++ if (args === 'start' || args === 'pair') {+ await this.handleStartCommand(userId, channelId, client);+ } else {+ const isAdmin = !!findSlackAdmin(this.config, userId);+ const content = args ? `/mercury ${args}` : '/mercury';+ this.emit({+ id: `slack-cmd-${Date.now()}`,+ channelId: `slack:${channelId}`,+ channelType: 'slack',+ senderId: userId,+ senderName: command.user_name,+ content,+ timestamp: Date.now(),+ metadata: { slackChannelId: channelId, isDM: channelId.startsWith('D'), isAdmin },+ });+ try {+ await client.chat.postEphemeral({+ channel: channelId,+ user: userId,+ text: 'Command received.',+ });+ } catch {}+ }+ });+ }++ private async handleDMMessage(msg: any): Promise<void> {+ const userId = msg.user;+ if (!userId) return;+ const channelId = msg.channel;+ const text = (msg.text || '').replace(/<@[^>]+>\s*/, '').trim();++ if (text === '/start' || text === '/pair' || text === '/mercury start') {+ await this.handleStartCommand(userId, channelId, this.app!.client);+ return;+ }++ if (text === '/unpair') {+ const isAdmin = !!findSlackAdmin(this.config, userId);+ if (isAdmin) {+ const { clearSlackAccess } = await import('../utils/config.js');+ clearSlackAccess(this.config);+ saveConfig(this.config);+ await this.sendDM(userId, 'All Slack access data has been reset.');+ }+ return;+ }++ const isApproved = !!findSlackApprovedUser(this.config, userId);+ if (!isApproved) {+ const existing = findSlackPendingRequest(this.config, userId);+ if (existing) {+ await this.sendDM(userId, 'Your access request is pending. An admin will approve it shortly.');+ } else {+ await this.sendDM(userId, 'You are not authorized. Send `/mercury start` to request access.');+ }+ return;+ }++ const isAdmin = !!findSlackAdmin(this.config, userId);+ this.lastActiveChannelId = channelId;+ this.lastMessageMetadata = { isDM: true, isAdmin };++ this.emit({+ id: msg.ts,+ channelId: `slack:dm:${userId}`,+ channelType: 'slack',+ senderId: userId,+ senderName: msg.user,+ content: text,+ timestamp: Math.floor(parseFloat(msg.ts) * 1000),+ metadata: { slackChannelId: channelId, isDM: true, isAdmin },+ });+ }++ private async handleStartCommand(userId: string, channelId: string, client: any): Promise<void> {+ const existingApproved = findSlackApprovedUser(this.config, userId);+ if (existingApproved) {+ const role = findSlackAdmin(this.config, userId) ? 'admin' : 'member';+ await this.sendDM(userId, `You are already authorized as a ${role}.`);+ return;+ }++ const existingPending = findSlackPendingRequest(this.config, userId);+ if (existingPending) {+ await this.sendDM(userId, 'You already have a pending request. An admin will approve it shortly.');+ return;+ }++ if (!hasSlackAdmins(this.config)) {+ const approved = approveSlackPendingRequest(this.config, userId, 'admin');+ if (!approved) {+ addSlackPendingRequest(this.config, { userId });+ const approvedAgain = approveSlackPendingRequest(this.config, userId, 'admin');+ if (approvedAgain) {+ saveConfig(this.config);+ }+ } else {+ saveConfig(this.config);+ }+ await this.sendDM(userId, ':white_check_mark: You have been approved as the *first admin*! You can now message Mercury.');+ return;+ }++ addSlackPendingRequest(this.config, { userId });+ saveConfig(this.config);++ const admins = getSlackAdmins(this.config);+ for (const admin of admins) {+ try {+ await client.chat.postMessage({+ channel: admin.userId,+ text: `:bell: New Slack access request from <@${userId}>`,+ blocks: [+ { type: 'section', text: { type: 'mrkdwn', text: `:bell: *New Slack access request*\nFrom: <@${userId}>` } },+ { type: 'actions', elements: [+ { type: 'button', text: { type: 'plain_text', text: 'Approve as Admin' }, action_id: `slack_access:approve_admin:${userId}`, style: 'primary' },+ { type: 'button', text: { type: 'plain_text', text: 'Approve as Member' }, action_id: `slack_access:approve_member:${userId}` },+ { type: 'button', text: { type: 'plain_text', text: 'Reject' }, action_id: `slack_access:reject:${userId}`, style: 'danger' },+ ] },+ ],+ });+ } catch (e) {+ logger.warn({ err: e, adminId: admin.userId }, 'Failed to notify Slack admin');+ }+ }+ await this.sendDM(userId, 'Your access request has been sent to the admins. You will be notified when approved.');+ }++ private async handleAccessButton(actionId: string, clickedByUserId: string, channelId: string | undefined, client: any): Promise<void> {+ const parts = actionId.split(':');+ if (parts.length < 3) return;+ const action = parts[1];+ const targetUserId = parts.slice(2).join(':');++ const isAdmin = !!findSlackAdmin(this.config, clickedByUserId);+ if (!isAdmin) {+ if (channelId) {+ await client.chat.postEphemeral({ channel: channelId, user: clickedByUserId, text: 'Only admins can approve access requests.' });+ }+ return;+ }++ if (action === 'approve_admin') {+ const approved = approveSlackPendingRequest(this.config, targetUserId, 'admin');+ if (approved) {+ saveConfig(this.config);+ await this.sendDM(targetUserId, `:white_check_mark: You have been approved as an *admin*! You can now message Mercury.`);+ }+ } else if (action === 'approve_member') {+ const approved = approveSlackPendingRequest(this.config, targetUserId, 'member');+ if (approved) {+ saveConfig(this.config);+ await this.sendDM(targetUserId, `:white_check_mark: You have been approved as a *member*! You can now message Mercury.`);+ }+ } else if (action === 'reject') {+ rejectSlackPendingRequest(this.config, targetUserId);+ saveConfig(this.config);+ await this.sendDM(targetUserId, 'Your access request has been declined.');+ }+ }++ async send(content: string, targetId?: string, _elapsedMs?: number): Promise<void> {+ const channel = this.resolveTargetChannel(targetId);+ if (!channel) return;++ const key = targetId || 'notification';++ if (this.isTaskActive(targetId)) {+ this.deferredResponses.set(key, content);+ return;+ }++ const converted = mdToSlack(content);+ const chunks = this.splitMessage(converted);++ for (const chunk of chunks) {+ try {+ await this.app!.client.chat.postMessage({+ channel,+ text: chunk,+ unfurl_links: false,+ unfurl_media: false,+ });+ } catch (e) {+ logger.warn({ err: e }, 'Slack send failed');+ }+ }+ }++ async sendFile(filePath: string, targetId?: string): Promise<void> {+ const channel = this.resolveTargetChannel(targetId);+ if (!channel) return;++ const resolved = path.resolve(filePath);+ if (!fs.existsSync(resolved)) {+ await this.send(`File not found: ${filePath}`, targetId);+ return;+ }++ const filename = path.basename(resolved);+ const stat = fs.statSync(resolved);++ try {+ const uploadUrlResult = await this.app!.client.files.getUploadURLExternal({+ filename,+ length: stat.size,+ });++ const uploadUrl = (uploadUrlResult as any).upload_url;+ const fileId = (uploadUrlResult as any).file_id;++ const fileBuffer = fs.readFileSync(resolved);+ const response = await fetch(uploadUrl, {+ method: 'POST',+ body: fileBuffer,+ headers: { 'Content-Type': 'application/octet-stream' },+ });++ if (!response.ok) {+ throw new Error(`Upload failed: ${response.status}`);+ }++ await this.app!.client.files.completeUploadExternal({+ files: [{ id: fileId }],+ channel_id: channel,+ initial_comment: `📄 ${filename}`,+ });+ } catch (e) {+ logger.warn({ err: e }, 'Slack file upload failed');+ await this.send(`Failed to send file: ${(e as Error).message}`, targetId);+ }+ }++ async stream(content: AsyncIterable<string>, targetId?: string): Promise<string> {+ const key = targetId || 'notification';++ if (this.isTaskActive(targetId)) {+ let full = '';+ for await (const chunk of content) {+ full += chunk;+ }+ this.deferredResponses.set(key, full);+ return full;+ }++ if (!this.config.channels.slack.streaming) {+ let full = '';+ for await (const chunk of content) {+ full += chunk;+ }+ await this.send(full, targetId);+ return full;+ }++ const channel = this.resolveTargetChannel(targetId);+ if (!channel) {+ let full = '';+ for await (const chunk of content) { full += chunk; }+ return full;+ }++ this.deleteStatusMessage(key);++ let full = '';+ let streamTs: string | null = null;+ let lastEditTime = 0;+ const STREAM_MIN_LENGTH = 20;+ const STREAM_EDIT_INTERVAL = 2000;++ for await (const chunk of content) {+ full += chunk;+ const now = Date.now();++ if (!streamTs && full.length >= STREAM_MIN_LENGTH) {+ try {+ const threadTs = this.lastMessageTs;+ const postArgs: any = {+ channel,+ text: mdToSlack(full) + ' ▌',+ unfurl_links: false,+ unfurl_media: false,+ };+ if (threadTs) {+ postArgs.thread_ts = threadTs;+ }+ const result = await this.app!.client.chat.postMessage(postArgs);+ streamTs = (result as any).ts;+ lastEditTime = now;+ } catch (e) {+ logger.warn({ err: e }, 'Slack stream initial post failed');+ }+ } else if (streamTs && now - lastEditTime >= STREAM_EDIT_INTERVAL) {+ try {+ await this.app!.client.chat.update({+ channel,+ ts: streamTs,+ text: mdToSlack(full) + ' ▌',+ });+ lastEditTime = now;+ } catch (e) {+ // edit failed, may be rate limited+ }+ }+ }++ if (streamTs) {+ const finalChunks = this.splitMessage(mdToSlack(full));+ if (finalChunks.length <= 1) {+ try {+ await this.app!.client.chat.update({+ channel,+ ts: streamTs,+ text: mdToSlack(full),+ });+ } catch (e) {+ logger.warn({ err: e }, 'Slack stream final update failed');+ }+ } else {+ try {+ await this.app!.client.chat.delete({ channel, ts: streamTs });+ } catch {}+ for (const c of finalChunks) {+ try {+ const threadTs = this.lastMessageTs;+ const postArgs: any = { channel, text: c, unfurl_links: false, unfurl_media: false };+ if (threadTs) { postArgs.thread_ts = threadTs; }+ await this.app!.client.chat.postMessage(postArgs);+ } catch (e) {+ logger.warn({ err: e }, 'Slack stream chunk send failed');+ }+ }+ }+ } else {+ const chunks = this.splitMessage(mdToSlack(full));+ for (const c of chunks) {+ try {+ const threadTs = this.lastMessageTs;+ const postArgs: any = { channel, text: c, unfurl_links: false, unfurl_media: false };+ if (threadTs) { postArgs.thread_ts = threadTs; }+ await this.app!.client.chat.postMessage(postArgs);+ } catch (e) {+ logger.warn({ err: e }, 'Slack stream fallback send failed');+ }+ }+ }++ return full;+ }++ async typing(_targetId?: string): Promise<void> {+ // Slack has no direct typing indicator; handled via "Thinking..." in stream+ }++ async askPermission(prompt: string, targetId?: string): Promise<string> {+ const channel = this.resolveTargetChannel(targetId);+ if (!channel) return 'no';++ const id = `slack_perm_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;+ const isDM = targetId?.startsWith(SLACK_DM_PREFIX);+ const isAdmin = this.lastMessageMetadata?.isAdmin ?? false;++ if (isDM || isAdmin) {+ return new Promise<string>((resolve) => {+ for (const suffix of [':yes', ':always', ':no']) {+ this.pendingApprovals.set(`${id}${suffix}`, () => resolve(suffix.slice(1)));+ }++ const blocks: any[] = [+ { type: 'section', text: { type: 'mrkdwn', text: mdToSlack(prompt) } },+ { type: 'actions', elements: [+ { type: 'button', text: { type: 'plain_text', text: 'Allow' }, action_id: `${id}:yes`, style: 'primary' },+ { type: 'button', text: { type: 'plain_text', text: 'Always' }, action_id: `${id}:always` },+ { type: 'button', text: { type: 'plain_text', text: 'Deny' }, action_id: `${id}:no`, style: 'danger' },+ ] },+ ];++ this.app!.client.chat.postMessage({ channel, blocks, text: mdToSlack(prompt) }).catch(() => {});++ setTimeout(() => {+ for (const suffix of [':yes', ':always', ':no']) {+ this.pendingApprovals.delete(`${id}${suffix}`);+ }+ resolve('no');+ }, 120_000);+ });+ }++ return 'no';+ }++ async askToContinue(question: string, targetId?: string): Promise<boolean> {+ const channel = this.resolveTargetChannel(targetId);+ if (!channel) return false;++ const id = `slack_loop_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;++ return new Promise<boolean>((resolve) => {+ this.pendingApprovals.set(`${id}:yes`, () => resolve(true));+ this.pendingApprovals.set(`${id}:no`, () => resolve(false));++ const blocks: any[] = [+ { type: 'section', text: { type: 'mrkdwn', text: mdToSlack(question) } },+ { type: 'actions', elements: [+ { type: 'button', text: { type: 'plain_text', text: 'Continue' }, action_id: `${id}:yes`, style: 'primary' },+ { type: 'button', text: { type: 'plain_text', text: 'Stop' }, action_id: `${id}:no`, style: 'danger' },+ ] },+ ];++ this.app!.client.chat.postMessage({ channel, blocks, text: mdToSlack(question) }).catch(() => {});++ setTimeout(() => {+ this.pendingApprovals.delete(`${id}:yes`);+ this.pendingApprovals.delete(`${id}:no`);+ resolve(false);+ }, 120_000);+ });+ }++ async askPermissionMode(targetId?: string): Promise<PermissionMode> {+ const userId = this.lastMessageMetadata?.isDM+ ? targetId?.replace('slack:dm:', '')+ : undefined;++ if (!userId) return 'ask-me';++ const channel = this.resolveTargetChannel(targetId);+ if (!channel) return 'ask-me';++ const id = `slack_mode_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;++ return new Promise<PermissionMode>((resolve) => {+ this.pendingApprovals.set(`${id}:ask-me`, () => resolve('ask-me'));+ this.pendingApprovals.set(`${id}:allow-all`, () => resolve('allow-all'));++ const blocks: any[] = [+ { type: 'section', text: { type: 'mrkdwn', text: '*Permission Mode*\nHow should Mercury handle risky actions this session?\n\n:lock: *Ask Me* — confirm before file writes, commands, and scope changes\n:white_check_mark: *Allow All* — auto-approve everything' } },+ { type: 'actions', elements: [+ { type: 'button', text: { type: 'plain_text', text: ':lock: Ask Me' }, action_id: `${id}:ask-me` },+ { type: 'button', text: { type: 'plain_text', text: ':white_check_mark: Allow All' }, action_id: `${id}:allow-all`, style: 'primary' },+ ] },+ ];++ this.app!.client.chat.postMessage({ channel, blocks, text: 'Permission Mode' }).catch(() => {});++ setTimeout(() => {+ this.pendingApprovals.delete(`${id}:ask-me`);+ this.pendingApprovals.delete(`${id}:allow-all`);+ resolve('ask-me');+ }, 120_000);+ });+ }++ async sendToolFeedback(toolName: string, args: Record<string, any>, targetId?: string): Promise<void> {+ const key = targetId || 'notification';+ const counter = (this.stepCounters.get(key) || 0) + 1;+ this.stepCounters.set(key, counter);++ const label = formatToolStep(toolName, args);+ const history = this.stepHistory.get(key) || [];+ const recentHistory = history.slice(-5);++ const descriptionLines = [+ ...recentHistory.map((h) => `:white_check_mark: ${h}`),+ `:hourglass: ${label}…`,+ ];++ this.updateStatusBlock(key, `:gear: Mercury working (step ${counter})`, descriptionLines.join('\n'));+ }++ async sendStepDone(toolName: string, result: any, targetId?: string): Promise<void> {+ const key = targetId || 'notification';+ const counter = this.stepCounters.get(key) || 0;+ const label = formatToolStep(toolName, {});+ const summary = formatToolResult(toolName, result);+ const doneLine = summary ? `${label} · ${summary}` : label;++ const history = this.stepHistory.get(key) || [];+ history.push(doneLine);+ this.stepHistory.set(key, history);++ const recentHistory = history.slice(-5);+ const descriptionLines = recentHistory.map((h) => `:white_check_mark: ${h}`);++ this.updateStatusBlock(key, `:gear: Mercury working (${counter} steps done)`, descriptionLines.join('\n'));+ }++ async sendCompletion(elapsedMs: number, stepCount: number, targetId?: string, meta?: { provider?: string; model?: string; inputTokens?: number; outputTokens?: number; totalTokens?: number; budgetUsed?: number; budgetTotal?: number; budgetPercentage?: number }): Promise<void> {+ const key = targetId || 'notification';+ this.endTask(targetId);+ await this.deleteStatusMessage(key);++ const deferred = this.deferredResponses.get(key);+ if (deferred) {+ this.deferredResponses.delete(key);+ await this.send(deferred, targetId);+ }++ if (!meta || stepCount < 2) {+ this.resetStepCounter(targetId);+ return;+ }++ const channel = this.resolveTargetChannel(targetId);+ if (!channel) { this.resetStepCounter(targetId); return; }++ const seconds = (elapsedMs / 1000).toFixed(1);+ const fields: any[] = [+ { type: 'mrkdwn', text: `*Provider:* ${meta.provider || 'unknown'}` },+ { type: 'mrkdwn', text: `*Model:* ${meta.model || 'unknown'}` },+ ];++ if (meta.totalTokens) {+ fields.push({ type: 'mrkdwn', text: `*Tokens:* ${meta.totalTokens.toLocaleString()}` });+ }+ if (meta.budgetUsed !== undefined) {+ fields.push({ type: 'mrkdwn', text: `*Budget:* ${meta.budgetPercentage?.toFixed(1)}% used` });+ }++ try {+ await this.app!.client.chat.postMessage({+ channel,+ text: `:white_check_mark: *Done* — ${stepCount} steps in ${seconds}s`,+ blocks: [+ { type: 'section', text: { type: 'mrkdwn', text: `:white_check_mark: *Done* — ${stepCount} steps in ${seconds}s` } },+ { type: 'section', fields: fields.map((f) => ({ type: 'mrkdwn', text: f.text })) },+ ],+ unfurl_links: false,+ unfurl_media: false,+ });+ } catch (e) {+ logger.warn({ err: e }, 'Slack sendCompletion failed');+ }++ this.resetStepCounter(targetId);+ }++ private async updateStatusBlock(key: string, title: string, description: string): Promise<void> {+ const channel = this.statusMessageChannels.get(key) || this.lastActiveChannelId || this.config.channels.slack.channelId;+ if (!channel) return;++ const existingTs = this.statusMessageIds.get(key);++ const blocks: any[] = [+ { type: 'section', text: { type: 'mrkdwn', text: `*${title}*\n${description}` } },+ ];++ if (existingTs) {+ try {+ await this.app!.client.chat.update({+ channel,+ ts: existingTs,+ blocks,+ text: title,+ });+ return;+ } catch {+ this.statusMessageIds.delete(key);+ }+ }++ try {+ const result = await this.app!.client.chat.postMessage({+ channel,+ blocks,+ text: title,+ unfurl_links: false,+ unfurl_media: false,+ });+ this.statusMessageIds.set(key, (result as any).ts);+ this.statusMessageChannels.set(key, channel);+ } catch (e) {+ logger.warn({ err: e }, 'Slack status block post failed');+ }+ }++ private async deleteStatusMessage(key: string): Promise<void> {+ const ts = this.statusMessageIds.get(key);+ const channel = this.statusMessageChannels.get(key);+ if (ts && channel) {+ try {+ await this.app!.client.chat.delete({ channel, ts });+ } catch {}+ }+ this.statusMessageIds.delete(key);+ this.statusMessageChannels.delete(key);+ }++ private async sendDM(userId: string, text: string): Promise<void> {+ try {+ const im = await this.app!.client.conversations.open({ users: userId });+ const dmChannel = (im as any).channel?.id;+ if (dmChannel) {+ await this.app!.client.chat.postMessage({ channel: dmChannel, text, unfurl_links: false, unfurl_media: false });+ }+ } catch (e) {+ logger.warn({ err: e, userId }, 'Slack sendDM failed');+ }+ }++ private async sendEphemeral(channel: string, userId: string, text: string): Promise<void> {+ try {+ await this.app!.client.chat.postEphemeral({ channel, user: userId, text });+ } catch (e) {+ logger.warn({ err: e }, 'Slack sendEphemeral failed');+ }+ }++ private resolveTargetChannel(targetId?: string): string | null {+ if (!targetId || targetId === 'notification') {+ return this.lastActiveChannelId || this.config.channels.slack.channelId || null;+ }++ if (targetId.startsWith(SLACK_DM_PREFIX)) {+ const userId = targetId.slice(SLACK_DM_PREFIX.length + 1);+ return userId;+ }++ if (targetId.startsWith('slack:')) {+ return targetId.slice(6);+ }++ return targetId;+ }++ private splitMessage(text: string, maxLength: number = 40000): string[] {+ if (text.length <= maxLength) return [text];++ const chunks: string[] = [];+ let remaining = text;++ while (remaining.length > 0) {+ if (remaining.length <= maxLength) {+ chunks.push(remaining);+ break;+ }++ let splitAt = remaining.lastIndexOf('\n', maxLength);+ if (splitAt <= 0) {+ splitAt = remaining.lastIndexOf(' ', maxLength);+ }+ if (splitAt <= 0) {+ splitAt = maxLength;+ }++ chunks.push(remaining.slice(0, splitAt));+ remaining = remaining.slice(splitAt).trimStart();+ }++ return chunks;+ }++ private get lastMessageTs(): string | undefined {+ return this._lastMessageTs;+ }++ private _lastMessageTs: string | undefined;+}\ No newline at end of filediff --git a/src/cli/daemon.ts b/src/cli/daemon.tsindex d553868e..e05a67dd 100644--- a/src/cli/daemon.ts+++ b/src/cli/daemon.ts@@ -4,6 +4,7 @@ import { join } from 'node:path';import process from 'node:process';import chalk from 'chalk';import { getMercuryHome } from '../utils/config.js';+import { killStaleSignalCliProcesses } from '../signal/jsonrpc.js';/*** Detect whether Mercury is running from a standalone, single-file binary@@ -134,20 +135,22 @@ export function startBackground(): void {}}-export function stopDaemon(): void {+export async function stopDaemon(): Promise<void> {const status = getDaemonStatus();if (!status.pid) {console.log(chalk.yellow(' Mercury is not running as a daemon.'));+ killStaleSignalCliProcesses();console.log('');- process.exit(0);+ return;}if (!status.running) {console.log(chalk.yellow(` Stale PID file found (PID: ${status.pid} is not running). Cleaning up.`));try { unlinkSync(pidPath()); } catch {}+ killStaleSignalCliProcesses();console.log('');- process.exit(0);+ return;}try {@@ -156,34 +159,43 @@ export function stopDaemon(): void {} else {process.kill(status.pid, 'SIGTERM');}- console.log(chalk.green(` Mercury stopped (PID: ${status.pid})`));} catch {console.log(chalk.red(` Failed to stop PID ${status.pid}. You may need to kill it manually.`));+ try { unlinkSync(pidPath()); } catch {}+ killStaleSignalCliProcesses();+ console.log('');+ return;+ }++ console.log(chalk.dim(` Stopping Mercury (PID: ${status.pid})...`));++ // Wait up to 5 seconds for the process to exit+ const deadline = Date.now() + 5000;+ while (Date.now() < deadline) {+ if (!isProcessRunning(status.pid)) break;+ await new Promise(resolve => setTimeout(resolve, 200));+ }++ if (isProcessRunning(status.pid)) {+ console.log(chalk.yellow(' Mercury did not exit gracefully, forcing...'));+ try {+ process.kill(status.pid, 'SIGKILL');+ } catch { /* already dead */ }+ // Wait briefly for SIGKILL to take effect+ await new Promise(resolve => setTimeout(resolve, 500));}try { unlinkSync(pidPath()); } catch {}++ killStaleSignalCliProcesses();++ console.log(chalk.green(` Mercury stopped (PID: ${status.pid})`));console.log('');}export async function restartDaemon(): Promise<void> {- const status = getDaemonStatus();-- if (status.running && status.pid) {- console.log(chalk.yellow(` Stopping Mercury (PID: ${status.pid})...`));- try {- if (process.platform === 'win32') {- process.kill(status.pid);- } else {- process.kill(status.pid, 'SIGTERM');- }- } catch {- // process may have already exited- }- try { unlinkSync(pidPath()); } catch {}- console.log(chalk.green(' Mercury stopped.'));- // Wait for port release before restarting- const waitMs = process.platform === 'win32' ? 2000 : 1000;- await new Promise((resolve) => setTimeout(resolve, waitMs));+ if (getDaemonStatus().running) {+ await stopDaemon();}console.log(chalk.yellow(' Starting Mercury...'));diff --git a/src/core/agent.ts b/src/core/agent.tsindex c2fbc7c8..ea18956f 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -22,8 +22,11 @@ import type { SkillLoader } from '../skills/loader.js';import { logger } from '../utils/logger.js';import { CLIChannel } from '../channels/cli.js';import { TelegramChannel } from '../channels/telegram.js';+import { SignalChannel } from '../channels/signal.js';+import { DiscordChannel } from '../channels/discord.js';+import { SlackChannel } from '../channels/slack.js';import { formatToolStep, formatNarrative, type NarrativeStep } from '../utils/tool-label.js';-import { getTelegramHelp } from '../utils/manual.js';+import { getTelegramHelp, getDiscordHelp, getSlackHelp } from '../utils/manual.js';import { WebChannel } from '../channels/web.js';import type { ArrowSelectOption } from '../utils/arrow-select.js';import { setAskUserHandler } from '../capabilities/interaction/ask-user.js';@@ -42,6 +45,22 @@ import {removeTelegramUser,saveConfig,getActiveProviders,+ getDiscordAccessSummary,+ hasDiscordAdmins,+ findDiscordPendingRequest,+ approveDiscordPendingRequest,+ approveDiscordPendingRequestByPairingCode,+ rejectDiscordPendingRequest as rejectDiscordPendingRequestConfig,+ removeDiscordUser,+ clearDiscordAccess,+ getSlackAccessSummary,+ hasSlackAdmins,+ findSlackPendingRequest,+ approveSlackPendingRequest,+ approveSlackPendingRequestByPairingCode,+ rejectSlackPendingRequest as rejectSlackPendingRequestConfig,+ removeSlackUser,+ clearSlackAccess,} from '../utils/config.js';class ToolCallLoopDetector {@@ -784,6 +803,14 @@ export class Agent {if (tgCh) {tgCh.send(message).catch((e) => logger.warn({ e }, 'channel send failed'));}+ const dcCh = this.channels.get('discord');+ if (dcCh) {+ dcCh.send(message).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ const slCh = this.channels.get('slack');+ if (slCh) {+ slCh.send(message).catch((e) => logger.warn({ e }, 'channel send failed'));+ }this.syncBgTasksToTui();}@@ -932,10 +959,11 @@ export class Agent {this.telegramStreaming = !this.telegramStreaming;}const ch = this.channels.get(msg.channelType as any);+ const streamingLabel = msg.channelType === 'discord' ? 'Discord' : msg.channelType === 'slack' ? 'Slack' : 'Telegram';if (ch) await ch.send(this.telegramStreaming- ? 'Telegram streaming enabled. Responses will appear progressively.'- : 'Telegram streaming disabled. Responses will arrive as a single message.',+ ? `${streamingLabel} streaming enabled. Responses will appear progressively.`+ : `${streamingLabel} streaming disabled. Responses will arrive as a single message.`,msg.channelId,);this.lifecycle.transition('idle');@@ -1221,7 +1249,7 @@ export class Agent {}}, MAX_FOREGROUND_WALL_MS);- const canStream = msg.channelType === 'cli' || msg.channelType === 'web' || (msg.channelType === 'telegram' && this.telegramStreaming);+ const canStream = msg.channelType === 'cli' || msg.channelType === 'web' || (msg.channelType === 'telegram' && this.telegramStreaming) || msg.channelType === 'signal' || (msg.channelType === 'discord' && this.config.channels.discord.streaming) || (msg.channelType === 'slack' && this.config.channels.slack.streaming);const tgChannel = this.channels.get('telegram');if (msg.channelType === 'telegram' && tgChannel) {@@ -1229,6 +1257,22 @@ export class Agent {(tgChannel as TelegramChannel).beginTask(msg.channelId);}+ const sigChannel = this.channels.get('signal');+ if (msg.channelType === 'signal' && sigChannel) {+ (sigChannel as SignalChannel).resetStepCounter(msg.channelId);+ (sigChannel as SignalChannel).beginTask(msg.channelId);+ }++ const dcChannel = this.channels.get('discord');+ if (msg.channelType === 'discord' && dcChannel) {+ (dcChannel as DiscordChannel).beginTask(msg.channelId);+ }++ const slChannel = this.channels.get('slack');+ if (msg.channelType === 'slack' && slChannel) {+ (slChannel as SlackChannel).beginTask(msg.channelId);+ }+// Saver-mode-aware request limits. When saver is off these resolve to// the original constants (byte-identical to pre-saver behavior).const effectiveMaxOutputTokens = this.saverMode.adjustMaxOutputTokens(MAX_RESPONSE_TOKENS);@@ -1411,6 +1455,20 @@ export class Agent {}}}+ } else if (channel instanceof SignalChannel) {+ const sigCh = channel as SignalChannel;+ for (const tc of toolCalls) {+ void sigCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ if (toolResults) {+ for (let i = 0; i < toolResults.length; i++) {+ const tr = toolResults[i] as any;+ const tcName = toolCalls[i]?.toolName as string | undefined;+ if (tcName) {+ await sigCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ }+ }} else if (channel instanceof WebChannel) {const webCh = channel as WebChannel;for (const tc of toolCalls) {@@ -1425,6 +1483,34 @@ export class Agent {}}}+ } else if (channel instanceof DiscordChannel) {+ const dcCh = channel as DiscordChannel;+ for (const tc of toolCalls) {+ void dcCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ if (toolResults) {+ for (let i = 0; i < toolResults.length; i++) {+ const tr = toolResults[i] as any;+ const tcName = toolCalls[i]?.toolName as string | undefined;+ if (tcName) {+ await dcCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ }+ }+ } else if (channel instanceof SlackChannel) {+ const slCh = channel as SlackChannel;+ for (const tc of toolCalls) {+ slCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId);+ }+ if (toolResults) {+ for (let i = 0; i < toolResults.length; i++) {+ const tr = toolResults[i] as any;+ const tcName = toolCalls[i]?.toolName as string | undefined;+ if (tcName) {+ await slCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId);+ }+ }+ }} else {await channel.send(` [Using: ${names}]`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}@@ -1654,6 +1740,20 @@ export class Agent {}}}+ } else if (channel instanceof SignalChannel) {+ const sigCh = channel as SignalChannel;+ for (const tc of toolCalls) {+ void sigCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ if (toolResults) {+ for (let i = 0; i < toolResults.length; i++) {+ const tr = toolResults[i] as any;+ const tcName = toolCalls[i]?.toolName as string | undefined;+ if (tcName) {+ await sigCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ }+ }} else if (channel instanceof WebChannel) {const webCh = channel as WebChannel;for (const tc of toolCalls) {@@ -1668,6 +1768,34 @@ export class Agent {}}}+ } else if (channel instanceof DiscordChannel) {+ const dcCh = channel as DiscordChannel;+ for (const tc of toolCalls) {+ void dcCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ if (toolResults) {+ for (let i = 0; i < toolResults.length; i++) {+ const tr = toolResults[i] as any;+ const tcName = toolCalls[i]?.toolName as string | undefined;+ if (tcName) {+ await dcCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ }+ }+ } else if (channel instanceof SlackChannel) {+ const slCh = channel as SlackChannel;+ for (const tc of toolCalls) {+ slCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId);+ }+ if (toolResults) {+ for (let i = 0; i < toolResults.length; i++) {+ const tr = toolResults[i] as any;+ const tcName = toolCalls[i]?.toolName as string | undefined;+ if (tcName) {+ await slCh.sendStepDone(tcName, tr.result ?? tr, msg.channelId);+ }+ }+ }} else {await channel.send(` [Using: ${names}]`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}@@ -1745,6 +1873,15 @@ export class Agent {if (channel instanceof TelegramChannel) {(channel as TelegramChannel).endTask(msg.channelId);(channel as TelegramChannel).resetStepCounter(msg.channelId);+ } else if (channel instanceof SignalChannel) {+ (channel as SignalChannel).endTask(msg.channelId);+ (channel as SignalChannel).resetStepCounter(msg.channelId);+ } else if (channel instanceof DiscordChannel) {+ (channel as DiscordChannel).endTask(msg.channelId);+ (channel as DiscordChannel).resetStepCounter(msg.channelId);+ } else if (channel instanceof SlackChannel) {+ (channel as SlackChannel).endTask(msg.channelId);+ (channel as SlackChannel).resetStepCounter(msg.channelId);}await channel.send(errMsg, msg.channelId);}@@ -1853,6 +1990,79 @@ export class Agent {(channel as TelegramChannel).resetStepCounter(msg.channelId);}this.markProgress();+ } else if (channel instanceof SignalChannel) {+ // For Signal tasks: end task, flush deferred, send completion banner for substantial tasks+ const sigCh = channel as SignalChannel;+ if (isSubstantialTask) {+ const completionMeta = {+ provider: usedProvider?.name ?? 'unknown',+ model: usedProvider?.model ?? 'unknown',+ inputTokens: result.usage?.inputTokens ?? 0,+ outputTokens: result.usage?.outputTokens ?? 0,+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),+ budgetUsed: this.tokenBudget.getDailyUsed(),+ budgetTotal: this.tokenBudget.getBudget(),+ budgetPercentage: this.tokenBudget.getUsagePercentage(),+ };+ await sigCh.sendCompletion(elapsed, stepCount, msg.channelId, completionMeta);+ } else {+ sigCh.endTask(msg.channelId);+ const deferred = sigCh.popDeferredResponse(msg.channelId);+ const responseText = deferred || (!streamedText && finalText ? finalText : null);+ if (responseText && responseText.trim()) {+ await channel.send(responseText, msg.channelId, elapsed);+ }+ sigCh.resetStepCounter(msg.channelId);+ this.markProgress();+ }+ } else if (channel instanceof DiscordChannel) {+ const dcCh = channel as DiscordChannel;+ if (isSubstantialTask) {+ const completionMeta = {+ provider: usedProvider?.name ?? 'unknown',+ model: usedProvider?.model ?? 'unknown',+ inputTokens: result.usage?.inputTokens ?? 0,+ outputTokens: result.usage?.outputTokens ?? 0,+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),+ budgetUsed: this.tokenBudget.getDailyUsed(),+ budgetTotal: this.tokenBudget.getBudget(),+ budgetPercentage: this.tokenBudget.getUsagePercentage(),+ };+ await dcCh.sendCompletion(elapsed, stepCount, msg.channelId, completionMeta);+ } else {+ dcCh.endTask(msg.channelId);+ const deferred = dcCh.popDeferredResponse(msg.channelId);+ const responseText = deferred || (!streamedText && finalText ? finalText : null);+ if (responseText && responseText.trim()) {+ await channel.send(responseText, msg.channelId, elapsed);+ }+ dcCh.resetStepCounter(msg.channelId);+ this.markProgress();+ }+ } else if (channel instanceof SlackChannel) {+ const slCh = channel as SlackChannel;+ if (isSubstantialTask) {+ const completionMeta = {+ provider: usedProvider?.name ?? 'unknown',+ model: usedProvider?.model ?? 'unknown',+ inputTokens: result.usage?.inputTokens ?? 0,+ outputTokens: result.usage?.outputTokens ?? 0,+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),+ budgetUsed: this.tokenBudget.getDailyUsed(),+ budgetTotal: this.tokenBudget.getBudget(),+ budgetPercentage: this.tokenBudget.getUsagePercentage(),+ };+ await slCh.sendCompletion(elapsed, stepCount, msg.channelId, completionMeta);+ } else {+ slCh.endTask(msg.channelId);+ const deferred = slCh.popDeferredResponse(msg.channelId);+ const responseText = deferred || (!streamedText && finalText ? finalText : null);+ if (responseText && responseText.trim()) {+ await channel.send(responseText, msg.channelId, elapsed);+ }+ slCh.resetStepCounter(msg.channelId);+ this.markProgress();+ }} else {// CLI or other channels — original flowif (streamedText && streamedText.trim()) {@@ -2765,7 +2975,7 @@ Is this productive iteration or a stuck loop?`,if (!ctx) return false;if (cmd === '/help') {- const helpText = channelType === 'telegram' ? getTelegramHelp() : ctx.manual();+ const helpText = channelType === 'telegram' ? getTelegramHelp() : channelType === 'discord' ? getDiscordHelp() : channelType === 'slack' ? getSlackHelp() : ctx.manual();await channel.send(helpText, channelId);return true;}@@ -2832,6 +3042,10 @@ Is this productive iteration or a stuck loop?`,`Provider: ${config.providers.default}`,`Telegram: ${config.channels.telegram.enabled ? 'enabled' : 'disabled'}`,`Telegram access: ${getTelegramAccessSummary(config)}`,+ `Discord: ${config.channels.discord.enabled ? 'enabled' : 'disabled'}`,+ `Discord access: ${getDiscordAccessSummary(config)}`,+ `Slack: ${config.channels.slack.enabled ? 'enabled' : 'disabled'}`,+ `Slack access: ${getSlackAccessSummary(config)}`,`Budget: ${budget.getStatusText()}`,saverLine,`Skills: ${ctx.skillNames().length > 0 ? ctx.skillNames().join(', ') : 'none'}`,@@ -3114,6 +3328,298 @@ Is this productive iteration or a stuck loop?`,return true;}+ if (cmd.startsWith('/discord')) {+ if (channelType !== 'cli') {+ await channel.send('`/discord` is only available from the Mercury CLI chat.', channelId);+ return true;+ }++ const config = ctx.config();+ const rawSubcommand = trimmed.slice('/discord'.length).trim();+ const parts = rawSubcommand.split(/\s+/).filter(Boolean);+ const action = parts[0]?.toLowerCase() || 'help';+ const formatDiscordUser = (user: {+ userId: string;+ username?: string;+ displayName?: string;+ pairingCode?: string;+ }) => {+ const username = user.username ? ` (@${user.username})` : '';+ const displayName = user.displayName ? ` ${user.displayName}` : '';+ const pairingCode = user.pairingCode ? ` [code: ${user.pairingCode}]` : '';+ return `${user.userId}${username}${displayName}${pairingCode}`;+ };++ const sendDiscordOverview = async () => {+ const lines = [+ '**Discord Management**',+ '',+ `Access: ${getDiscordAccessSummary(config)}`,+ `Admins: ${config.channels.discord.admins.length > 0 ? config.channels.discord.admins.map(formatDiscordUser).join(', ') : 'none'}`,+ `Members: ${config.channels.discord.members.length > 0 ? config.channels.discord.members.map(formatDiscordUser).join(', ') : 'none'}`,+ `Pending: ${config.channels.discord.pending.length > 0 ? config.channels.discord.pending.map(formatDiscordUser).join(', ') : 'none'}`,+ '',+ 'Commands:',+ '\u2022 `/discord pending`',+ '\u2022 `/discord users`',+ '\u2022 `/discord approve <pairing-code|user-id>`',+ '\u2022 `/discord reject <user-id>`',+ '\u2022 `/discord remove <user-id>`',+ '\u2022 `/discord reset`',+ ];+ await channel.send(lines.join('\n'), channelId);+ };++ if (action === 'help' || action === 'status') {+ await sendDiscordOverview();+ return true;+ }++ if (action === 'pending') {+ const pending = config.channels.discord.pending;+ const lines = [+ '**Discord Pending Requests**',+ '',+ pending.length > 0 ? pending.map(formatDiscordUser).join('\n') : 'No pending Discord requests.',+ ];+ await channel.send(lines.join('\n'), channelId);+ return true;+ }++ if (action === 'users') {+ const lines = [+ '**Discord Approved Users**',+ '',+ `Admins: ${config.channels.discord.admins.length > 0 ? config.channels.discord.admins.map(formatDiscordUser).join(', ') : 'none'}`,+ `Members: ${config.channels.discord.members.length > 0 ? config.channels.discord.members.map(formatDiscordUser).join(', ') : 'none'}`,+ '',+ `Total approved: ${config.channels.discord.admins.length + config.channels.discord.members.length}`,+ ];+ await channel.send(lines.join('\n'), channelId);+ return true;+ }++ if (action === 'approve') {+ const value = parts[1];+ if (!value) {+ await channel.send('Usage: `/discord approve <pairing-code|user-id>`', channelId);+ return true;+ }++ let approved = approveDiscordPendingRequestByPairingCode(config, value);+ let resultLabel = value;++ if (!approved) {+ approved = approveDiscordPendingRequest(config, value, 'member');+ resultLabel = value;+ }++ if (!approved) {+ await channel.send(`No pending Discord request found for \`${resultLabel}\`.`, channelId);+ return true;+ }++ saveConfig(config);+ await channel.send(`Approved Discord user ${formatDiscordUser(approved)}.`, channelId);+ return true;+ }++ if (action === 'reject') {+ const value = parts[1];+ if (!value) {+ await channel.send('Usage: `/discord reject <user-id>`', channelId);+ return true;+ }++ const rejected = rejectDiscordPendingRequestConfig(config, value);+ if (!rejected) {+ await channel.send(`No pending Discord request found for \`${value}\`.`, channelId);+ return true;+ }++ saveConfig(config);+ await channel.send(`Rejected Discord request for ${formatDiscordUser(rejected)}.`, channelId);+ return true;+ }++ if (action === 'remove') {+ const value = parts[1];+ if (!value) {+ await channel.send('Usage: `/discord remove <user-id>`', channelId);+ return true;+ }++ const removed = removeDiscordUser(config, value);+ if (!removed) {+ await channel.send(`No approved Discord user found for \`${value}\`.`, channelId);+ return true;+ }++ saveConfig(config);+ await channel.send(`Removed Discord access for ${formatDiscordUser(removed)}.`, channelId);+ return true;+ }++ if (action === 'reset' || action === 'unpair') {+ clearDiscordAccess(config);+ saveConfig(config);+ await channel.send('Discord access reset. New users can send /start in a DM to begin pairing again.', channelId);+ return true;+ }++ await channel.send(+ `Unknown Discord command "${action}". Try \`/discord\`, \`/discord pending\`, or \`/discord users\`.`,+ channelId,+ );+ return true;+ }++ if (cmd.startsWith('/slack')) {+ if (channelType !== 'cli') {+ await channel.send('`/slack` is only available from the Mercury CLI chat.', channelId);+ return true;+ }++ const config = ctx.config();+ const rawSubcommand = trimmed.slice('/slack'.length).trim();+ const parts = rawSubcommand.split(/\s+/).filter(Boolean);+ const action = parts[0]?.toLowerCase() || 'help';+ const formatSlackUser = (user: {+ userId: string;+ userName?: string;+ displayName?: string;+ pairingCode?: string;+ }) => {+ const userName = user.userName ? ` (@${user.userName})` : '';+ const displayName = user.displayName ? ` ${user.displayName}` : '';+ const pairingCode = user.pairingCode ? ` [code: ${user.pairingCode}]` : '';+ return `${user.userId}${userName}${displayName}${pairingCode}`;+ };++ const sendSlackOverview = async () => {+ const lines = [+ '**Slack Management**',+ '',+ `Access: ${getSlackAccessSummary(config)}`,+ `Admins: ${config.channels.slack.admins.length > 0 ? config.channels.slack.admins.map(formatSlackUser).join(', ') : 'none'}`,+ `Members: ${config.channels.slack.members.length > 0 ? config.channels.slack.members.map(formatSlackUser).join(', ') : 'none'}`,+ `Pending: ${config.channels.slack.pending.length > 0 ? config.channels.slack.pending.map(formatSlackUser).join(', ') : 'none'}`,+ '',+ 'Commands:',+ '\u2022 `/slack pending`',+ '\u2022 `/slack users`',+ '\u2022 `/slack approve <pairing-code|user-id>`',+ '\u2022 `/slack reject <user-id>`',+ '\u2022 `/slack remove <user-id>`',+ '\u2022 `/slack reset`',+ ];+ await channel.send(lines.join('\n'), channelId);+ };++ if (action === 'help' || action === 'status') {+ await sendSlackOverview();+ return true;+ }++ if (action === 'pending') {+ const pending = config.channels.slack.pending;+ const lines = [+ '**Slack Pending Requests**',+ '',+ pending.length > 0 ? pending.map(formatSlackUser).join('\n') : 'No pending Slack requests.',+ ];+ await channel.send(lines.join('\n'), channelId);+ return true;+ }++ if (action === 'users') {+ const lines = [+ '**Slack Approved Users**',+ '',+ `Admins: ${config.channels.slack.admins.length > 0 ? config.channels.slack.admins.map(formatSlackUser).join(', ') : 'none'}`,+ `Members: ${config.channels.slack.members.length > 0 ? config.channels.slack.members.map(formatSlackUser).join(', ') : 'none'}`,+ '',+ `Total approved: ${config.channels.slack.admins.length + config.channels.slack.members.length}`,+ ];+ await channel.send(lines.join('\n'), channelId);+ return true;+ }++ if (action === 'approve') {+ const value = parts[1];+ if (!value) {+ await channel.send('Usage: `/slack approve <pairing-code|user-id>`', channelId);+ return true;+ }++ let approved = approveSlackPendingRequestByPairingCode(config, value);+ let resultLabel = value;++ if (!approved) {+ approved = approveSlackPendingRequest(config, value, 'member');+ resultLabel = value;+ }++ if (!approved) {+ await channel.send(`No pending Slack request found for \`${resultLabel}\`.`, channelId);+ return true;+ }++ saveConfig(config);+ await channel.send(`Approved Slack user ${formatSlackUser(approved)}.`, channelId);+ return true;+ }++ if (action === 'reject') {+ const value = parts[1];+ if (!value) {+ await channel.send('Usage: `/slack reject <user-id>`', channelId);+ return true;+ }++ const rejected = rejectSlackPendingRequestConfig(config, value);+ if (!rejected) {+ await channel.send(`No pending Slack request found for \`${value}\`.`, channelId);+ return true;+ }++ saveConfig(config);+ await channel.send(`Rejected Slack request for ${formatSlackUser(rejected)}.`, channelId);+ return true;+ }++ if (action === 'remove') {+ const value = parts[1];+ if (!value) {+ await channel.send('Usage: `/slack remove <user-id>`', channelId);+ return true;+ }++ const removed = removeSlackUser(config, value);+ if (!removed) {+ await channel.send(`No approved Slack user found for \`${value}\`.`, channelId);+ return true;+ }++ saveConfig(config);+ await channel.send(`Removed Slack access for ${formatSlackUser(removed)}.`, channelId);+ return true;+ }++ if (action === 'reset' || action === 'unpair') {+ clearSlackAccess(config);+ saveConfig(config);+ await channel.send('Slack access reset. New users can send /mercury start in a DM to begin pairing again.', channelId);+ return true;+ }++ await channel.send(+ `Unknown Slack command "${action}". Try \`/slack\`, \`/slack pending\`, or \`/slack users\`.`,+ channelId,+ );+ return true;+ }+if ((cmd === '/' || cmd === '/menu') && channelType === 'cli' && channel instanceof CLIChannel) {await this.openCliCommandMenu(channel, channelId);return true;diff --git a/src/index.ts b/src/index.tsindex 4404aa11..fc7d63f3 100644--- a/src/index.ts+++ b/src/index.ts@@ -23,10 +23,30 @@ import {promoteTelegramUserToAdmin,demoteTelegramAdmin,hasTelegramAdmins,+ getSignalAccessSummary,+ hasSignalAdmins as hasSignalAdminsFn,+ findSignalPendingRequest,+ approveSignalPendingRequestByPairingCode,+ clearSignalAccess,+ getDiscordAccessSummary,+ hasDiscordAdmins as hasDiscordAdminsFn,+ findDiscordPendingRequest,+ approveDiscordPendingRequest,+ approveDiscordPendingRequestByPairingCode,+ rejectDiscordPendingRequest,+ removeDiscordUser,+ clearDiscordAccess,+ getSlackAccessSummary,+ findSlackPendingRequest,+ approveSlackPendingRequest,+ rejectSlackPendingRequest,+ removeSlackUser,+ clearSlackAccess,} from './utils/config.js';import type { MercuryConfig } from './utils/config.js';import type { ProviderName } from './utils/config.js';import { logger } from './utils/logger.js';+import { redactPhone } from './utils/redact.js';import { Identity } from './soul/identity.js';import { ShortTermMemory, LongTermMemory, EpisodicMemory, migrateLegacyMemory } from './memory/store.js';import { UserMemoryStore } from './memory/user-memory.js';@@ -40,13 +60,15 @@ import { SpotifyClient } from './spotify/client.js';import { ChannelRegistry } from './channels/registry.js';import { CLIChannel } from './channels/cli.js';import { TelegramChannel } from './channels/telegram.js';+import { SignalChannel } from './channels/signal.js';+import { DiscordChannel } from './channels/discord.js';import { WebChannel } from './channels/web.js';import { TokenBudget } from './utils/tokens.js';import { CapabilityRegistry } from './capabilities/registry.js';import { SkillLoader } from './skills/loader.js';import { registerSkillsCommand } from './skills/cli.js';import { getManual } from './utils/manual.js';-import { startBackground, stopDaemon, showLogs, getDaemonStatus, restartDaemon, tryAutoDaemonize } from './cli/daemon.js';+import { startBackground, stopDaemon, showLogs, getDaemonStatus, restartDaemon, tryAutoDaemonize, isStandaloneBinary } from './cli/daemon.js';import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';import { runWithWatchdog } from './cli/watchdog.js';import { setGitHubToken } from './utils/github.js';@@ -571,6 +593,35 @@ function formatTelegramUser(user: {return `${user.userId}${username}${firstName}`;}+function formatSignalUser(user: {+ phoneNumber: string;+ name?: string;+ role?: string;+}): string {+ const name = user.name ? ` (${user.name})` : '';+ const role = user.role ? ` [${user.role}]` : '';+ return `${redactPhone(user.phoneNumber)}${name}${role}`;+}++function printSignalAccessState(config: MercuryConfig): void {+ const admins = config.channels.signal.admins;+ const members = config.channels.signal.members;+ const pending = config.channels.signal.pending;+ const pendingSummary = pending.length > 0+ ? pending.map((entry) => `${entry.phoneNumber} [code: ${entry.pairingCode}]`).join(', ')+ : '';++ console.log('');+ console.log(` Signal Access: ${chalk.white(getSignalAccessSummary(config))}`);+ console.log(` Mode: ${chalk.white(config.channels.signal.mode)}`);+ if (config.channels.signal.groupId) {+ console.log(` Group: ${chalk.white(config.channels.signal.groupName || config.channels.signal.groupId)}`);+ }+ console.log(` Admins: ${admins.length > 0 ? chalk.green(admins.map(formatSignalUser).join(', ')) : chalk.dim('none')}`);+ console.log(` Members: ${members.length > 0 ? chalk.green(members.map(formatSignalUser).join(', ')) : chalk.dim('none')}`);+ console.log(` Pending: ${pending.length > 0 ? chalk.yellow(pendingSummary) : chalk.dim('none')}`);+}+function printTelegramAccessState(config: MercuryConfig): void {const admins = config.channels.telegram.admins;const members = config.channels.telegram.members;@@ -589,6 +640,72 @@ function printTelegramAccessState(config: MercuryConfig): void {console.log(` Pending: ${pending.length > 0 ? chalk.yellow(pendingSummary) : chalk.dim('none')}`);}+function formatDiscordUser(user: {+ userId: string;+ username?: string;+ displayName?: string;+ role?: string;+}): string {+ const username = user.username ? ` (@${user.username})` : '';+ const displayName = user.displayName ? ` ${user.displayName}` : '';+ const role = user.role ? ` [${user.role}]` : '';+ return `${user.userId}${username}${displayName}${role}`;+}++function printDiscordAccessState(config: MercuryConfig): void {+ const admins = config.channels.discord.admins;+ const members = config.channels.discord.members;+ const pending = config.channels.discord.pending;+ const pendingSummary = pending.length > 0+ ? pending.map((entry) => {+ const code = entry.pairingCode ? ` [code: ${entry.pairingCode}]` : '';+ return `${formatDiscordUser(entry)}${code}`;+ }).join(', ')+ : '';++ console.log('');+ console.log(` Discord Access: ${chalk.white(getDiscordAccessSummary(config))}`);+ if (config.channels.discord.guildId) {+ console.log(` Guild: ${chalk.white(config.channels.discord.guildId)}`);+ }+ if (config.channels.discord.channelId) {+ console.log(` Channel: ${chalk.white(config.channels.discord.channelId)}`);+ }+ if (config.channels.discord.adminRoleName) {+ console.log(` Admin Role: ${chalk.white(config.channels.discord.adminRoleName)}`);+ }+ console.log(` Admins: ${admins.length > 0 ? chalk.green(admins.map(formatDiscordUser).join(', ')) : chalk.dim('none')}`);+ console.log(` Members: ${members.length > 0 ? chalk.green(members.map(formatDiscordUser).join(', ')) : chalk.dim('none')}`);+ console.log(` Pending: ${pending.length > 0 ? chalk.yellow(pendingSummary) : chalk.dim('none')}`);+}++function formatSlackUser(user: { userId: string; userName?: string; displayName?: string }): string {+ const userName = user.userName ? ` (@${user.userName})` : '';+ const displayName = user.displayName ? ` ${user.displayName}` : '';+ return `${user.userId}${userName}${displayName}`;+}++function printSlackAccessState(config: MercuryConfig): void {+ const admins = config.channels.slack.admins;+ const members = config.channels.slack.members;+ const pending = config.channels.slack.pending;+ const pendingSummary = pending.length > 0+ ? pending.map((entry) => formatSlackUser(entry)).join(', ')+ : '';++ console.log('');+ console.log(` Slack Access: ${chalk.white(getSlackAccessSummary(config))}`);+ if (config.channels.slack.teamId) {+ console.log(` Team: ${chalk.white(config.channels.slack.teamId)}`);+ }+ if (config.channels.slack.channelId) {+ console.log(` Channel: ${chalk.white(config.channels.slack.channelId)}`);+ }+ console.log(` Admins: ${admins.length > 0 ? chalk.green(admins.map(formatSlackUser).join(', ')) : chalk.dim('none')}`);+ console.log(` Members: ${members.length > 0 ? chalk.green(members.map(formatSlackUser).join(', ')) : chalk.dim('none')}`);+ console.log(` Pending: ${pending.length > 0 ? chalk.yellow(pendingSummary) : chalk.dim('none')}`);+}+function restartDaemonIfRunning(message?: string): void {const daemon = getDaemonStatus();if (!daemon.running) return;@@ -645,6 +762,294 @@ async function completeInitialTelegramPairing(config: MercuryConfig): Promise<vo}}+async function completeInitialSignalSetup(config: MercuryConfig): Promise<void> {+ if (!config.channels.signal.enabled || !config.channels.signal.phoneNumber) {+ return;+ }++ // Already paired+ if (hasSignalAdminsFn(config)) {+ console.log(chalk.green(' ✓ Signal already paired.'));+ if (config.channels.signal.mode === 'group' && config.channels.signal.groupName) {+ console.log(chalk.dim(` Group: ${config.channels.signal.groupName}`));+ }+ console.log(chalk.dim(' To unregister, run: mercury signal unregister'));+ console.log('');+ const keepConfig = await ask(chalk.white(' Keep the existing configuration? (Y/n): '));+ if (keepConfig.toLowerCase() !== 'n' && keepConfig.toLowerCase() !== 'no') {+ return;+ }+ // Clear pairing data but keep phone number — fall through to fresh pairing+ config.channels.signal.admins = [];+ config.channels.signal.members = [];+ config.channels.signal.pending = [];+ config.channels.signal.groupId = undefined;+ config.channels.signal.groupName = undefined;++ // Re-ask mode since we're starting fresh+ const modeAnswer = await ask(chalk.white(' Mode — group or private? [group]: '));+ config.channels.signal.mode = modeAnswer.toLowerCase().startsWith('private') ? 'private' : 'group';+ saveConfig(config);+ console.log(chalk.dim(' Configuration cleared. Starting fresh pairing...'));++ // Kill any running signal-cli daemon so group list is fresh+ try {+ const { killStaleSignalCliProcesses } = await import('./signal/jsonrpc.js');+ killStaleSignalCliProcesses();+ } catch { /* ignore */ }+ }++ console.log('');+ console.log(chalk.bold.white(' Signal Setup'));++ const { ensureSignalCli, checkJavaAvailable, isNativeAvailable } = await import('./signal/binary.js');+ const { checkSignalSetup, registerSignalNumber, verifySignalNumber, startLinking, waitForLinkCompletion, cancelLinking, printQrCode } = await import('./signal/setup.js');++ // Step 1: Check Java if needed (macOS/Windows have no native binary)+ if (!isNativeAvailable() && !checkJavaAvailable()) {+ console.log(chalk.red(' ✗ Java (JRE 17+) is required for Signal on this platform.'));+ console.log(chalk.dim(' No native signal-cli binary is available for macOS/Windows.'));+ console.log(chalk.dim(' Install Java: https://adoptium.net/ or run: brew install openjdk'));+ console.log(chalk.dim(' Then re-run: mercury doctor'));+ return;+ }++ // Step 2: Download signal-cli binary+ try {+ const binaryPath = await ensureSignalCli();+ const { isWrapperScript, isJarBinary: isJar } = await import('./signal/binary.js');+ const binaryType = isWrapperScript(binaryPath) ? 'JAR (wrapper)'+ : isJar(binaryPath) ? 'JAR'+ : 'native binary';+ console.log(chalk.green(` ✓ signal-cli installed (${binaryType})`));+ } catch (err: any) {+ console.log(chalk.red(` ✗ Failed to download signal-cli: ${err.message}`));+ if (!isNativeAvailable()) {+ console.log(chalk.dim(' Make sure Java (JRE 17+) is installed and accessible.'));+ }+ console.log(chalk.dim(' You can try again later with: mercury doctor'));+ return;+ }++ // Step 3: Check if already linked+ const status = await checkSignalSetup(config);+ if (status.linked) {+ console.log(chalk.green(' ✓ Signal device is already linked.'));+ } else {+ // Step 3b: Register number if needed+ if (!status.registered) {+ console.log(chalk.yellow(' This phone number is not registered with Signal.'));+ console.log(chalk.dim(' You need to register it first:'));++ const registerAnswer = await ask(chalk.white(' Register this number with Signal? (y/N): '));+ if (registerAnswer.toLowerCase() !== 'y' && registerAnswer.toLowerCase() !== 'yes') {+ console.log(chalk.dim(' You can register later by running: mercury signal register'));+ return;+ }++ const voice = await ask(chalk.white(' Verify via SMS or voice call? (sms/voice) [sms]: '));+ const useVoice = voice.toLowerCase().startsWith('voice');++ console.log(chalk.dim(' Sending verification code...'));+ const regResult = await registerSignalNumber(config.channels.signal.phoneNumber, useVoice);+ if (!regResult.success) {+ console.log(chalk.red(` ✗ Registration failed: ${regResult.error}`));+ return;+ }+ console.log(chalk.green(' ✓ Verification code sent.'));++ const code = await ask(chalk.white(' Enter the verification code: '));+ if (!code) {+ console.log(chalk.red(' Verification code is required.'));+ return;+ }++ const verifyResult = await verifySignalNumber(config.channels.signal.phoneNumber, code.trim());+ if (!verifyResult.success) {+ console.log(chalk.red(` ✗ Verification failed: ${verifyResult.error}`));+ return;+ }+ console.log(chalk.green(' ✓ Number verified.'));+ }++ // Step 4: Link as secondary device+ console.log('');+ console.log(chalk.dim(' Linking Mercury as a secondary device on your Signal account.'));+ console.log(chalk.dim(' 1. Open Signal on your phone'));+ console.log(chalk.dim(' 2. Go to Settings > Linked Devices'));+ console.log(chalk.dim(' 3. Tap "+" to add a new device'));+ console.log('');++ const linkAnswer = await ask(chalk.white(' Ready to link? Press Enter to generate a QR code...'));+ const session = await startLinking();+ if (!session) {+ console.log(chalk.red(' ✗ Failed to generate linking URI.'));+ console.log(chalk.dim(' Make sure signal-cli is installed and Java is available.'));+ return;+ }++ console.log('');+ console.log(chalk.cyan(' Scan this QR code with Signal:'));+ console.log('');+ printQrCode(session.uri);+ console.log('');+ console.log(chalk.dim(' Mercury is waiting for you to complete the link...'));++ const linked = await waitForLinkCompletion(session, 120_000);+ if (linked) {+ console.log(chalk.green(' ✓ Signal device linked successfully.'));+ } else {+ console.log(chalk.yellow(' Linking timed out or failed.'));+ console.log(chalk.dim(' Run mercury doctor to try again.'));+ return;+ }+ }++ // Step 5: Pairing — start daemon and wait for pairing code+ console.log('');+ console.log(chalk.bold.white(' Signal Pairing'));++ const signalChannel = new SignalChannel(config);+ try {+ await signalChannel.start();+ } catch (err: any) {+ console.log(chalk.red(` ✗ Failed to start Signal daemon: ${err.message}`));+ console.log(chalk.dim(' Make sure signal-cli is working by running: mercury signal status'));+ console.log(chalk.dim(' You can pair manually by sending /pair in Signal and running: mercury signal approve <code>'));+ return;+ }++ if (!signalChannel.running) {+ console.log(chalk.red(' ✗ Signal daemon did not start.'));+ console.log(chalk.dim(' You can pair manually by sending /pair in Signal and running: mercury signal approve <code>'));+ return;+ }++ // Detect Mercury group now that the daemon is running+ let groupFound = false;+ if (config.channels.signal.mode === 'group') {+ if (config.channels.signal.groupId) {+ groupFound = true;+ console.log(chalk.dim(' Your Mercury group is already configured.'));+ } else {+ console.log(chalk.dim(' Searching for "Mercury" group...'));+ try {+ const group = await signalChannel.listGroups();+ if (group) {+ config.channels.signal.groupId = group.groupId;+ config.channels.signal.groupName = group.groupName;+ saveConfig(config);+ groupFound = true;+ console.log(chalk.green(` ✓ Found group: ${group.groupName}`));+ }+ } catch {+ // Group search may fail+ }+ }++ if (groupFound) {+ console.log(chalk.dim(' Send /pair in the Mercury group to get a pairing code.'));+ } else {+ console.log(chalk.dim(' 1. Create a Signal group named "Mercury" (or use an existing one)'));+ console.log(chalk.dim(' 2. Add your linked number to the group'));+ console.log(chalk.dim(' 3. Send /pair in the group'));+ }+ } else {+ // Private mode: auto-pair the linked number as admin+ // In private mode, the linked number IS the admin — no need for a pairing code+ if (!hasSignalAdminsFn(config) && config.channels.signal.phoneNumber) {+ config.channels.signal.admins.push({+ phoneNumber: config.channels.signal.phoneNumber,+ role: 'admin',+ pairedAt: new Date().toISOString(),+ });+ saveConfig(config);+ console.log(chalk.green(' ✓ Auto-paired as admin (private mode).'));+ console.log(chalk.dim(' Mercury will respond to messages in your "Note to Self" chat.'));+ console.log('');+ await signalChannel.stop();+ saveConfig(config);+ return;+ }+ console.log(chalk.dim(' Send /pair in your Signal "Note to Self" chat to get a pairing code.'));+ }+ console.log('');++ try {+ while (true) {+ const pairingCode = await ask(chalk.white(' Signal Pairing Code (or press Enter to skip): '));+ if (!pairingCode) {+ console.log(chalk.dim(' You can pair later by sending /pair in Signal and running: mercury signal approve <code>'));+ break;+ }++ // Reload config from disk — SignalChannel may have saved the pending request+ const freshConfig = loadConfig();+ const approved = approveSignalPendingRequestByPairingCode(freshConfig, pairingCode.trim());+ if (!approved) {+ console.log(chalk.red(' That pairing code is not valid. Make sure you sent /pair in Signal and enter the exact code.'));+ continue;+ }++ Object.assign(config, freshConfig);+ saveConfig(config);+ console.log(chalk.green(` ✓ Signal paired. First admin: ${formatSignalUser(approved)}.`));+ console.log('');+ break;+ }+ } finally {+ await signalChannel.stop();+ }++ saveConfig(config);+}++async function completeInitialDiscordPairing(config: MercuryConfig): Promise<void> {+ if (!config.channels.discord.enabled || !config.channels.discord.botToken || hasDiscordAdminsFn(config)) {+ return;+ }++ console.log('');+ console.log(chalk.bold.white(' Discord Pairing'));+ console.log(chalk.dim(' 1. Open Discord and DM your bot.'));+ console.log(chalk.dim(' 2. Send /start to receive your pairing code.'));+ console.log(chalk.dim(' 3. Paste that pairing code below to finish setup.'));+ console.log('');++ const discordChannel = new DiscordChannel(config);+ try {+ await discordChannel.start();+ } catch (err: any) {+ console.log(chalk.red(`\n ✗ ${err.message || err}`));+ console.log('');+ await discordChannel.stop();+ return;+ }++ try {+ while (true) {+ const pairingCode = await ask(chalk.white(' Discord Pairing Code: '));+ if (!pairingCode) {+ console.log(chalk.red(' Discord pairing code is required to continue.'));+ continue;+ }++ const approved = approveDiscordPendingRequestByPairingCode(config, pairingCode.trim());+ if (!approved) {+ console.log(chalk.red(' That pairing code is not valid yet. Send /start in Discord, then paste the exact code here.'));+ continue;+ }++ saveConfig(config);+ console.log(chalk.green(` ✓ Discord paired. First admin: ${formatDiscordUser(approved)}.`));+ console.log('');+ break;+ }+ } finally {+ await discordChannel.stop();+ }+}+async function configure(existingConfig?: MercuryConfig): Promise<void> {const isReconfig = !!existingConfig;const config = existingConfig ?? loadConfig();@@ -1054,64 +1459,353 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {hr();console.log('');- console.log(chalk.bold.white(' GitHub Integration (optional)'));- console.log(chalk.dim(' Connect Mercury to GitHub so it can create PRs, manage issues,'));- console.log(chalk.dim(' review code, and co-author commits on your behalf.'));- console.log(chalk.dim(' You can add it later with mercury doctor.'));+ console.log(chalk.bold.white(' Signal (optional)'));+ if (isReconfig && config.channels.signal.phoneNumber) {+ console.log(chalk.dim(' Leave empty to keep current number. Enter "none" to disable Signal.'));+ console.log(chalk.dim(' Enter "reset" to start fresh (clear config, optionally delete binary).'));+ console.log(chalk.dim(' Enter "unregister" to unlink this device from Signal and clear all data.'));+ } else {+ console.log(chalk.dim(' Leave empty to skip. You can add it later with mercury doctor.'));+ console.log(chalk.dim(' Include country code, e.g. +1 for US, +44 for UK, +91 for India.'));+ console.log(chalk.dim(' Signal lets you chat with Mercury through a Signal group or private chat.'));+ }console.log('');- const ghSetup = await ask(chalk.white(' Configure GitHub? (y/N): '));- if (ghSetup.toLowerCase() === 'y' || ghSetup.toLowerCase() === 'yes') {- const ghUserCurrent = isReconfig && config.github.username ? ` [${config.github.username}]` : '';- const ghUsername = await ask(chalk.white(` 1. Your GitHub username${ghUserCurrent}: `));- if (ghUsername) config.github.username = ghUsername;+ const signalPhoneCurrent = isReconfig && config.channels.signal.phoneNumber ? ` [${redactPhone(config.channels.signal.phoneNumber)}]` : '';+ const signalPhoneInput = await ask(chalk.white(` Signal phone number${signalPhoneCurrent}: `));- if (!config.github.email) {- config.github.email = '[email protected]';+ if (isReconfig && signalPhoneInput.toLowerCase() === 'none') {+ config.channels.signal.enabled = false;+ config.channels.signal.phoneNumber = '';+ clearSignalAccess(config);+ saveConfig(config);+ } else if (isReconfig && signalPhoneInput.toLowerCase() === 'unregister') {+ console.log('');+ console.log(chalk.yellow(' ⚠️ This will unlink this device from Signal and clear all Mercury Signal data.'));+ console.log(chalk.yellow(' Mercury will no longer be able to send or receive Signal messages.'));+ console.log('');+ const confirmUnregister = await ask(chalk.white(' Continue? (y/N): '));+ if (confirmUnregister.toLowerCase() !== 'y' && confirmUnregister.toLowerCase() !== 'yes') {+ console.log(chalk.dim(' Cancelled.'));+ } else {+ const phoneNumberToDelete = config.channels.signal.phoneNumber;++ // Send goodbye message (best effort, skip if signal-cli not installed or target gone)+ const { findSignalCli, sendSignalMessage } = await import('./signal/setup.js');+ if (findSignalCli()) {+ const target: { groupId?: string; recipient?: string } = {};+ if (config.channels.signal.mode === 'group' && config.channels.signal.groupId) {+ target.groupId = config.channels.signal.groupId;+ } else if (config.channels.signal.admins.length > 0) {+ target.recipient = config.channels.signal.admins[0].phoneNumber;+ }+ if (target.groupId || target.recipient) {+ try {+ await sendSignalMessage(config.channels.signal.phoneNumber, 'Mercury has been unregistered from this conversation. It will no longer respond here. To reconnect, the admin needs to set up Signal again with: mercury doctor', target);+ } catch { /* best effort */ }+ }+ }++ const { killStaleSignalCliProcesses } = await import('./signal/jsonrpc.js');+ killStaleSignalCliProcesses();++ // Unregister from Signal server+ console.log(chalk.dim(' Unlinking device from Signal...'));+ const { unregisterSignalNumber } = await import('./signal/setup.js');+ const unregResult = await unregisterSignalNumber(config.channels.signal.phoneNumber);+ if (unregResult.success) {+ console.log(chalk.green(' ✓ Device unlinked from Signal server.'));+ } else {+ console.log(chalk.yellow(' ⚠ Could not reach Signal server to unlink device.'));+ console.log(chalk.dim(' Local data has been cleared. The device will be unlinked automatically.'));+ }++ clearSignalAccess(config);+ config.channels.signal.enabled = false;+ config.channels.signal.phoneNumber = '';+ config.channels.signal.groupId = undefined;+ config.channels.signal.groupName = undefined;+ saveConfig(config);++ const { deleteSignalCliAccountData } = await import('./signal/setup.js');+ if (phoneNumberToDelete) {+ deleteSignalCliAccountData(phoneNumberToDelete);+ }++ console.log(chalk.green(' ✓ Signal data cleared.'));++ const setupNew = await ask(chalk.white(' Set up Signal with a new number now? (y/N): '));+ if (setupNew.toLowerCase() === 'y' || setupNew.toLowerCase() === 'yes') {+ const newPhone = await ask(chalk.white(' New Signal phone number (e.g. +1234567890): '));+ if (newPhone) {+ config.channels.signal.phoneNumber = newPhone.trim();+ config.channels.signal.enabled = true;+ const modeAnswer = await ask(chalk.white(' Mode — group or private? [group]: '));+ config.channels.signal.mode = modeAnswer.toLowerCase().startsWith('private') ? 'private' : 'group';+ saveConfig(config);+ }+ }}+ } else if (isReconfig && signalPhoneInput.toLowerCase() === 'reset') {+ clearSignalAccess(config);+ config.channels.signal.enabled = false;+ config.channels.signal.phoneNumber = '';+ saveConfig(config);console.log('');- console.log(chalk.dim(' You need a Personal Access Token (PAT) with repo access.'));- console.log(chalk.dim(' Fine-grained (recommended): github.com/settings/personal-access-tokens/new'));- console.log(chalk.dim(' → Permissions: Contents (R/W), Pull requests (R/W), Issues (R/W)'));- console.log(chalk.dim(' Classic: github.com/settings/tokens/new'));- console.log(chalk.dim(' → Scope: repo (full control)'));- const ghTokenCurrent = process.env.GITHUB_TOKEN ? ` [${maskKey(process.env.GITHUB_TOKEN)}]` : '';- const ghToken = await ask(chalk.white(` 2. GitHub PAT${ghTokenCurrent}: `));- if (ghToken) {- appendToEnv('GITHUB_TOKEN', ghToken);+ console.log(chalk.yellow(' ⚠️ This will clear all Signal access and group connection.'));+ const deleteBinary = await ask(chalk.white(' Also delete the signal-cli binary? (y/N): '));+ if (deleteBinary.toLowerCase() === 'y' || deleteBinary.toLowerCase() === 'yes') {+ const { removeSignalCli, getSignalCliDir } = await import('./signal/setup.js');+ const { existsSync } = await import('node:fs');+ if (existsSync(getSignalCliDir())) {+ removeSignalCli();+ console.log(chalk.green(' ✓ Signal binary removed.'));+ }}- if (config.github.username || process.env.GITHUB_TOKEN) {- console.log('');- console.log(chalk.dim(' Set a default repo so you can say "create an issue" without'));- console.log(chalk.dim(' specifying the repo every time. Enter owner/name or a full URL.'));- console.log(chalk.dim(' Example: hotheadhacker/mercury-agent'));- console.log(chalk.dim(' Example: https://github.com/hotheadhacker/mercury-agent'));- const ghOwnerCurrent = isReconfig && config.github.defaultOwner ? ` [${config.github.defaultOwner}/${config.github.defaultRepo}]` : '';- const ghRepoInput = await ask(chalk.white(` 3. Default repo${ghOwnerCurrent}: `));- if (ghRepoInput) {- const parsed = parseGithubRepo(ghRepoInput);- if (parsed) {- config.github.defaultOwner = parsed.owner;- config.github.defaultRepo = parsed.repo;- } else {- console.log(chalk.yellow(' Could not parse repo. Use format: owner/repo or a GitHub URL.'));- }- }+ console.log(chalk.green(' ✓ Signal config reset.'));+ console.log(chalk.dim(' Continue below to set up Signal with a new number.'));+ console.log('');++ const newPhone = await ask(chalk.white(' New Signal phone number (e.g. +1234567890): '));+ if (newPhone) {+ config.channels.signal.phoneNumber = newPhone.trim();+ config.channels.signal.enabled = true;++ const modeAnswer = await ask(chalk.white(' Mode — group or private? [group]: '));+ config.channels.signal.mode = modeAnswer.toLowerCase().startsWith('private') ? 'private' : 'group';++ saveConfig(config);+ }+ } else if (signalPhoneInput) {+ if (signalPhoneInput !== config.channels.signal.phoneNumber) {+ clearSignalAccess(config);}+ config.channels.signal.phoneNumber = signalPhoneInput.trim();+ config.channels.signal.enabled = true;++ const modeAnswer = await ask(chalk.white(' Mode — group or private? [group]: '));+ config.channels.signal.mode = modeAnswer.toLowerCase().startsWith('private') ? 'private' : 'group';++ saveConfig(config);+ } else if (!config.channels.signal.phoneNumber) {+ config.channels.signal.enabled = false;+ saveConfig(config);}+ await completeInitialSignalSetup(config);+hr();console.log('');- console.log(chalk.bold.white(' Spotify Integration (optional)'));- console.log(chalk.dim(' Connect Mercury to your Spotify so it can play music,'));- console.log(chalk.dim(' manage playlists, and act as your DJ on any of your devices.'));- console.log(chalk.dim(' You can add it later with mercury doctor.'));+ console.log(chalk.bold.white(' Discord (optional)'));+ if (isReconfig) {+ console.log(chalk.dim(' Leave empty to keep current value. Enter "none" to disable.'));+ } else {+ console.log(chalk.dim(' Leave empty to skip. You can add it later.'));+ }+ console.log(chalk.dim(' To create a Discord bot:'));+ console.log(chalk.dim(' 1. Go to https://discord.com/developers/applications'));+ console.log(chalk.dim(' 2. Click "New Application" → give it a name'));+ console.log(chalk.dim(' 3. Navigate to Bot → Click "Reset Token" → Copy the token'));+ console.log(chalk.dim(' 4. Enable Privileged Gateway Intents:'));+ console.log(chalk.dim(' - Message Content Intent'));+ console.log(chalk.dim(' 5. Go to OAuth2 → URL Generator:'));+ console.log(chalk.dim(' Scopes: bot, applications.commands'));+ console.log(chalk.dim(' Bot Permissions: Send Messages, Read Message History,'));+ console.log(chalk.dim(' Use Slash Commands, Attach Files, Embed Links'));+ console.log(chalk.dim(' 6. Open the generated URL to invite the bot to your server'));+ console.log(chalk.dim(' 7. Optionally create a "Mercury Admin" role in your server'));+ console.log(chalk.dim(' Guild members can chat openly. DMs require pairing (like Telegram).'));console.log('');- const spotifySetup = await ask(chalk.white(' Configure Spotify? (y/N): '));- if (spotifySetup.toLowerCase() === 'y' || spotifySetup.toLowerCase() === 'yes') {+ const dcMask = isReconfig && config.channels.discord.botToken ? ` [${maskKey(config.channels.discord.botToken)}]` : '';+ const discordToken = await ask(chalk.white(` Discord Bot Token${dcMask}: `));+ if (isReconfig && discordToken.toLowerCase() === 'none') {+ config.channels.discord.enabled = false;+ config.channels.discord.botToken = '';+ clearDiscordAccess(config);+ } else if (discordToken) {+ if (discordToken !== config.channels.discord.botToken) {+ clearDiscordAccess(config);+ }+ config.channels.discord.botToken = discordToken;+ appendToEnv('DISCORD_BOT_TOKEN', discordToken);+ config.channels.discord.enabled = true;+ }++ if (config.channels.discord.enabled && config.channels.discord.botToken) {+ if (!config.channels.discord.guildId) {+ console.log('');+ console.log(chalk.dim(' To find your Server ID: in Discord, go to Settings → App Settings →'));+ console.log(chalk.dim(' Advanced → toggle Developer Mode ON. Then right-click your server'));+ console.log(chalk.dim(' name in the sidebar → Copy Server ID.'));+ const guildId = await ask(chalk.white(' Discord Guild/Server ID (optional — leave empty for all servers): '));+ if (guildId.trim()) {+ config.channels.discord.guildId = guildId.trim();+ }+ }++ if (!config.channels.discord.channelId) {+ console.log(chalk.dim(' To find a Channel ID: right-click the channel name in the sidebar → Copy Channel ID.'));+ const channelId = await ask(chalk.white(' Discord Channel ID (optional — leave empty for all channels): '));+ if (channelId.trim()) {+ config.channels.discord.channelId = channelId.trim();+ }+ }++ const adminRoleCurrent = isReconfig && config.channels.discord.adminRoleName ? ` [${config.channels.discord.adminRoleName}]` : '';+ const adminRoleName = await ask(chalk.white(` Admin role name${adminRoleCurrent} [Mercury Admin]: `));+ if (adminRoleName.trim()) {+ config.channels.discord.adminRoleName = adminRoleName.trim();+ } else if (!config.channels.discord.adminRoleName) {+ config.channels.discord.adminRoleName = 'Mercury Admin';+ }++ saveConfig(config);+ } else if (!config.channels.discord.botToken) {+ config.channels.discord.enabled = false;+ saveConfig(config);+ }++ await completeInitialDiscordPairing(config);++ hr();+ console.log('');+ console.log(chalk.bold.white(' Slack (optional)'));+ if (isReconfig) {+ console.log(chalk.dim(' Leave empty to keep current value. Enter "none" to disable.'));+ } else {+ console.log(chalk.dim(' Leave empty to skip. You can add it later.'));+ }+ console.log(chalk.dim(' To create a Slack app:'));+ console.log(chalk.dim(' 1. Go to https://api.slack.com/apps → Create New App → From scratch'));+ console.log(chalk.dim(' 2. Under "Socket Mode", enable it and generate an App-Level Token'));+ console.log(chalk.dim(' with connections:write scope → copy the xapp- token'));+ console.log(chalk.dim(' 3. Under "OAuth & Permissions", add Bot Token Scopes:'));+ console.log(chalk.dim(' chat:write, chat:write.public, chat:write.customize,'));+ console.log(chalk.dim(' channels:history, groups:history, im:history, im:write,'));+ console.log(chalk.dim(' files:write, commands, app_mentions:read'));+ console.log(chalk.dim(' 4. Install app to workspace → copy Bot User OAuth Token (xoxb-)'));+ console.log(chalk.dim(' 5. Under "Event Subscriptions", enable and subscribe to:'));+ console.log(chalk.dim(' message.channels, message.groups, message.im, app_mention'));+ console.log(chalk.dim(' 6. Under "Interactivity & Shortcuts", enable interactivity'));+ console.log(chalk.dim(' 7. Under "Slash Commands", create /mercury command'));+ console.log(chalk.dim(' 8. Under "App Home", check "Allow users to send Slash commands'));+ console.log(chalk.dim(' and messages from the messages tab"'));+ console.log(chalk.dim(' 9. Invite the bot to your channel: /invite @Mercury'));+ console.log(chalk.dim(' 10. DM the bot /mercury start to become the first admin.'));+ console.log(chalk.dim(' Channel members can chat openly. DMs require admin approval.'));++ const slMask = isReconfig && config.channels.slack.botToken ? ` [${maskKey(config.channels.slack.botToken)}]` : '';+ const slackBotToken = await ask(chalk.white(` Slack Bot Token${slMask} (starts with xoxb-): `));+ if (isReconfig && slackBotToken.toLowerCase() === 'none') {+ config.channels.slack.enabled = false;+ config.channels.slack.botToken = '';+ clearSlackAccess(config);+ } else if (slackBotToken) {+ if (slackBotToken !== config.channels.slack.botToken) {+ clearSlackAccess(config);+ }+ config.channels.slack.botToken = slackBotToken;+ appendToEnv('SLACK_BOT_TOKEN', slackBotToken);+ }++ if (config.channels.slack.enabled || config.channels.slack.botToken) {+ const slAppMask = isReconfig && config.channels.slack.appToken ? ` [${maskKey(config.channels.slack.appToken)}]` : '';+ const slackAppToken = await ask(chalk.white(` Slack App-Level Token${slAppMask} (starts with xapp-): `));+ if (slackAppToken && slackAppToken.toLowerCase() !== 'none') {+ config.channels.slack.appToken = slackAppToken;+ appendToEnv('SLACK_APP_TOKEN', slackAppToken);+ } else if (slackAppToken.toLowerCase() === 'none') {+ config.channels.slack.appToken = '';+ }++ if (config.channels.slack.botToken) {+ config.channels.slack.enabled = true;++ if (!config.channels.slack.channelId) {+ console.log(chalk.dim(' To find a Channel ID: right-click the channel name → Copy Channel ID.'));+ const slChannelId = await ask(chalk.white(' Slack Channel ID (optional — leave empty for all channels): '));+ if (slChannelId.trim()) {+ config.channels.slack.channelId = slChannelId.trim();+ }+ }++ if (!config.channels.slack.teamId) {+ const slTeamId = await ask(chalk.white(' Slack Team/Workspace ID (optional): '));+ if (slTeamId.trim()) {+ config.channels.slack.teamId = slTeamId.trim();+ }+ }++ saveConfig(config);+ }+ } else if (!config.channels.slack.botToken) {+ config.channels.slack.enabled = false;+ saveConfig(config);+ }++ hr();+ console.log('');+ console.log(chalk.bold.white(' GitHub Integration (optional)'));+ console.log(chalk.dim(' Connect Mercury to GitHub so it can create PRs, manage issues,'));+ console.log(chalk.dim(' review code, and co-author commits on your behalf.'));+ console.log(chalk.dim(' You can add it later with mercury doctor.'));+ console.log('');++ const ghSetup = await ask(chalk.white(' Configure GitHub? (y/N): '));+ if (ghSetup.toLowerCase() === 'y' || ghSetup.toLowerCase() === 'yes') {+ const ghUserCurrent = isReconfig && config.github.username ? ` [${config.github.username}]` : '';+ const ghUsername = await ask(chalk.white(` 1. Your GitHub username${ghUserCurrent}: `));+ if (ghUsername) config.github.username = ghUsername;++ if (!config.github.email) {+ config.github.email = '[email protected]';+ }++ console.log('');+ console.log(chalk.dim(' You need a Personal Access Token (PAT) with repo access.'));+ console.log(chalk.dim(' Fine-grained (recommended): github.com/settings/personal-access-tokens/new'));+ console.log(chalk.dim(' → Permissions: Contents (R/W), Pull requests (R/W), Issues (R/W)'));+ console.log(chalk.dim(' Classic: github.com/settings/tokens/new'));+ console.log(chalk.dim(' → Scope: repo (full control)'));+ const ghTokenCurrent = process.env.GITHUB_TOKEN ? ` [${maskKey(process.env.GITHUB_TOKEN)}]` : '';+ const ghToken = await ask(chalk.white(` 2. GitHub PAT${ghTokenCurrent}: `));+ if (ghToken) {+ appendToEnv('GITHUB_TOKEN', ghToken);+ }++ if (config.github.username || process.env.GITHUB_TOKEN) {+ console.log('');+ console.log(chalk.dim(' Set a default repo so you can say "create an issue" without'));+ console.log(chalk.dim(' specifying the repo every time. Enter owner/name or a full URL.'));+ console.log(chalk.dim(' Example: hotheadhacker/mercury-agent'));+ console.log(chalk.dim(' Example: https://github.com/hotheadhacker/mercury-agent'));+ const ghOwnerCurrent = isReconfig && config.github.defaultOwner ? ` [${config.github.defaultOwner}/${config.github.defaultRepo}]` : '';+ const ghRepoInput = await ask(chalk.white(` 3. Default repo${ghOwnerCurrent}: `));+ if (ghRepoInput) {+ const parsed = parseGithubRepo(ghRepoInput);+ if (parsed) {+ config.github.defaultOwner = parsed.owner;+ config.github.defaultRepo = parsed.repo;+ } else {+ console.log(chalk.yellow(' Could not parse repo. Use format: owner/repo or a GitHub URL.'));+ }+ }+ }+ }++ hr();+ console.log('');+ console.log(chalk.bold.white(' Spotify Integration (optional)'));+ console.log(chalk.dim(' Connect Mercury to your Spotify so it can play music,'));+ console.log(chalk.dim(' manage playlists, and act as your DJ on any of your devices.'));+ console.log(chalk.dim(' You can add it later with mercury doctor.'));+ console.log('');++ const spotifySetup = await ask(chalk.white(' Configure Spotify? (y/N): '));+ if (spotifySetup.toLowerCase() === 'y' || spotifySetup.toLowerCase() === 'yes') {console.log('');console.log(chalk.dim(' 1. Go to developer.spotify.com/dashboard'));console.log(chalk.dim(' 2. Click "Create app" — set name: Mercury'));@@ -1434,20 +2128,41 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {memoryGetSubconscious: (limit?: number) => userMemory ? userMemory.getSubconscious(limit) : [],});- capabilities.setSendFileHandler(async (filePath: string) => {+ capabilities.setSendFileHandler(async (filePath: string, channel?: string) => {const { channelId, channelType } = capabilities.getChannelContext();const telegram = channels.get('telegram');+ const signal = channels.get('signal');++ // Explicit channel override from the user+ if (channel === 'signal' && signal) {+ await signal.sendFile(filePath, channelType === 'signal' ? channelId : undefined);+ return;+ }+ if (channel === 'telegram' && telegram) {+ await telegram.sendFile(filePath, channelType === 'telegram' ? channelId : undefined);+ return;+ }if (channelType === 'telegram' && telegram) {await telegram.sendFile(filePath, channelId);return;}+ if (channelType === 'signal' && signal) {+ await signal.sendFile(filePath, channelId);+ return;+ }+if (config.channels.telegram.enabled && telegram && getTelegramApprovedUsers(config).length > 0) {await telegram.sendFile(filePath);return;}+ if (config.channels.signal.enabled && signal && hasSignalAdminsFn(config)) {+ await signal.sendFile(filePath);+ return;+ }+const cli = channels.get('cli');if (cli) {await cli.sendFile(filePath);@@ -1553,11 +2268,16 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {const cliChannel = channels.get('cli') as CLIChannel | undefined;const tgChannel = channels.get('telegram') as TelegramChannel | undefined;+ const sigChannel = channels.get('signal') as SignalChannel | undefined;if (tgChannel) {tgChannel.setChatCommandContext(capabilities.getChatCommandContext()!);}+ if (sigChannel) {+ sigChannel.setChatCommandContext(capabilities.getChatCommandContext()!);+ }+setWebWebChannel(webChannel);setWebProgrammingMode(agent.programmingMode);setWebBgTasks(agent.backgroundTasks);@@ -1736,6 +2456,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {if (channelType === 'telegram' && tgChannel) {return tgChannel.askPermission(prompt);}+ if (channelType === 'signal' && channels.get('signal')) {+ return (channels.get('signal') as SignalChannel).askPermission(prompt);+ }if (channelType === 'web' && webChannel) {return webChannel.askPermission(prompt);}@@ -1755,6 +2478,16 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {});}+ if (sigChannel) {+ sigChannel.setOnPermissionMode((mode) => {+ if (mode === 'allow-all') {+ capabilities.permissions.setAutoApproveAll(true);+ capabilities.permissions.addTempScope('/', true, true);+ logger.info('Signal: Allow All mode set for session');+ }+ });+ }+const activeCh = channels.getActiveChannels();const toolNames = capabilities.getToolNames();@@ -1911,8 +2644,8 @@ programprogram.command('stop').description('Stop a background Mercury process')- .action(() => {- stopDaemon();+ .action(async () => {+ await stopDaemon();});program@@ -2002,6 +2735,18 @@ programconsole.log(` Provider: ${chalk.white(getProviderLabel(config.providers.default))}`);console.log(` Telegram: ${config.channels.telegram.enabled ? chalk.green('enabled') : chalk.dim('disabled')}`);console.log(` Telegram Access: ${chalk.white(getTelegramAccessSummary(config))}`);+ console.log(` Signal: ${config.channels.signal.enabled ? chalk.green('enabled') : chalk.dim('disabled')}`);+ if (config.channels.signal.phoneNumber) {+ console.log(` Signal Access: ${chalk.white(getSignalAccessSummary(config))}`);+ }+ console.log(` Discord: ${config.channels.discord.enabled ? chalk.green('enabled') : chalk.dim('disabled')}`);+ if (config.channels.discord.botToken) {+ console.log(` Discord Access: ${chalk.white(getDiscordAccessSummary(config))}`);+ }+ console.log(` Slack: ${config.channels.slack.enabled ? chalk.green('enabled') : chalk.dim('disabled')}`);+ if (config.channels.slack.botToken) {+ console.log(` Slack Access: ${chalk.white(getSlackAccessSummary(config))}`);+ }console.log(` Web: ${config.web.enabled ? chalk.green(`enabled (http://localhost:${config.web.port})`) : chalk.dim('disabled')}`);console.log(` Skills: ${skills.length > 0 ? chalk.green(skills.map(s => s.name).join(', ')) : chalk.dim('none')}`);console.log(` Budget: ${chalk.white(config.tokens.dailyBudget.toLocaleString())} tokens/day`);@@ -2021,6 +2766,15 @@ programconsole.log(` Daemon: ${daemon.running ? chalk.green(`running (PID: ${daemon.pid})`) : chalk.dim('not running')}`);console.log(` Home: ${chalk.dim(home)}`);printTelegramAccessState(config);+ if (config.channels.signal.phoneNumber) {+ printSignalAccessState(config);+ }+ if (config.channels.discord.botToken) {+ printDiscordAccessState(config);+ }+ if (config.channels.slack.botToken) {+ printSlackAccessState(config);+ }console.log('');});@@ -2230,6 +2984,517 @@ telegramCmdconsole.log('');});+const signalCmd = program+ .command('signal')+ .description('Manage Signal channel access and setup');++signalCmd+ .command('approve <code>')+ .description('Approve a pending Signal pairing request by code')+ .action(async (code: string) => {+ const config = loadConfig();++ if (!hasSignalAdminsFn(config)) {+ const approved = approveSignalPendingRequestByPairingCode(config, code.trim());+ if (!approved) {+ console.log('');+ console.log(chalk.red(` No pending Signal pairing found for code ${code.trim()}.`));+ console.log('');+ return;+ }++ saveConfig(config);+ console.log('');+ console.log(chalk.green(` ✓ Approved first Signal admin ${approved.phoneNumber}.`));+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ return;+ }++ const pending = findSignalPendingRequest(config, code.trim());+ if (!pending) {+ console.log('');+ console.log(chalk.red(` No pending Signal pairing found for ${code.trim()}.`));+ console.log('');+ return;+ }++ console.log('');+ console.log(chalk.yellow(` A Signal admin already exists. New members must be approved by an admin in Signal.`));+ console.log('');+ });++signalCmd+ .command('unpair')+ .description('Reset all Signal access and group connection')+ .action(() => {+ const config = loadConfig();+ const hasAny = config.channels.signal.admins.length > 0+ || config.channels.signal.members.length > 0+ || config.channels.signal.pending.length > 0;++ if (!hasAny) {+ console.log('');+ console.log(chalk.dim(' Signal access is already empty.'));+ console.log('');+ return;+ }++ clearSignalAccess(config);+ saveConfig(config);++ console.log('');+ console.log(chalk.green(' ✓ Signal access reset.'));+ console.log(chalk.dim(' Send /pair in Signal to reconnect.'));+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ });++signalCmd+ .command('reset')+ .description('Full reset: clear Signal access, delete binary, and unlink device')+ .option('--keep-binary', 'Keep the signal-cli binary (only clear config)')+ .action(async (opts) => {+ const { removeSignalCli, getSignalCliDir, checkJavaAvailable, ensureSignalCli } = await import('./signal/setup.js');+ const config = loadConfig();++ console.log('');+ console.log(chalk.yellow(' ⚠️ This will:'));+ console.log(chalk.yellow(' • Clear all Signal access (admins, members, pending)'));+ console.log(chalk.yellow(' • Remove group connection'));+ console.log(chalk.yellow(' • Disable the Signal channel'));+ if (!opts.keepBinary) {+ console.log(chalk.yellow(' • Delete the signal-cli binary from disk'));+ }+ console.log('');++ const answer = await ask(chalk.white(' Continue? [y/N] '));+ if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {+ console.log(chalk.dim(' Cancelled.'));+ console.log('');+ return;+ }++ clearSignalAccess(config);+ config.channels.signal.enabled = false;+ saveConfig(config);++ if (!opts.keepBinary) {+ const signalDir = getSignalCliDir();+ const { existsSync } = await import('node:fs');+ if (existsSync(signalDir)) {+ removeSignalCli();+ console.log(chalk.green(' ✓ Signal binary removed.'));+ }+ }++ console.log(chalk.green(' ✓ Signal reset complete.'));+ console.log(chalk.dim(' Run `mercury doctor` to set up Signal again.'));+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ });++signalCmd+ .command('status')+ .description('Show Signal configuration and connection status')+ .action(async () => {+ const config = loadConfig();+ const { checkSignalSetup } = await import('./signal/setup.js');++ console.log('');+ console.log(chalk.bold.white(' Signal Status'));+ console.log('');++ if (!config.channels.signal.phoneNumber) {+ console.log(chalk.dim(' Not configured. Run `mercury doctor` to set up Signal.'));+ console.log('');+ return;+ }++ console.log(` Phone: ${chalk.white(config.channels.signal.phoneNumber)}`);+ console.log(` Mode: ${chalk.white(config.channels.signal.mode)}`);+ console.log(` Enabled: ${config.channels.signal.enabled ? chalk.green('yes') : chalk.dim('no')}`);+ console.log(` Paired: ${hasSignalAdminsFn(config) ? chalk.green('yes') : chalk.dim('no')}`);+ console.log(` Access: ${chalk.white(getSignalAccessSummary(config))}`);++ if (config.channels.signal.mode === 'group') {+ console.log(` Group: ${chalk.white(config.channels.signal.groupName || config.channels.signal.groupId || 'Not set')}`);+ }++ const status = await checkSignalSetup(config);+ console.log(` Binary: ${status.binaryOk ? chalk.green('found') : chalk.red('not found')}`);+ console.log(` Linked: ${status.linked ? chalk.green('yes') : chalk.red('no')}`);++ if (status.errors.length > 0) {+ console.log('');+ for (const err of status.errors) {+ console.log(chalk.red(` • ${err}`));+ }+ }++ console.log('');+ });++signalCmd+ .command('register')+ .description('Register a phone number with Signal (sends verification code)')+ .action(async () => {+ const config = loadConfig();+ if (!config.channels.signal.phoneNumber) {+ console.log('');+ console.log(chalk.red(' No Signal phone number configured. Run mercury doctor first.'));+ console.log('');+ return;+ }++ const { registerSignalNumber, verifySignalNumber } = await import('./signal/setup.js');+ console.log('');+ console.log(chalk.bold.white(' Signal Registration'));+ console.log(chalk.dim(` Phone: ${redactPhone(config.channels.signal.phoneNumber)}`));+ console.log('');++ const voice = await ask(chalk.white(' Verify via SMS or voice call? (sms/voice) [sms]: '));+ const useVoice = voice.toLowerCase().startsWith('voice');++ console.log(chalk.dim(' Sending verification code...'));+ const result = await registerSignalNumber(config.channels.signal.phoneNumber, useVoice);+ if (!result.success) {+ console.log(chalk.red(` ✗ Registration failed: ${result.error}`));+ return;+ }+ console.log(chalk.green(' ✓ Verification code sent.'));++ const code = await ask(chalk.white(' Enter the verification code: '));+ if (!code) {+ console.log(chalk.red(' Verification code is required.'));+ return;+ }++ const verifyResult = await verifySignalNumber(config.channels.signal.phoneNumber, code.trim());+ if (!verifyResult.success) {+ console.log(chalk.red(` ✗ Verification failed: ${verifyResult.error}`));+ return;+ }+ console.log(chalk.green(' ✓ Number verified and registered.'));+ console.log('');+ });++signalCmd+ .command('unregister')+ .description('Unlink this device from Signal and clear all Mercury Signal data')+ .action(async () => {+ const config = loadConfig();+ if (!config.channels.signal.phoneNumber) {+ console.log('');+ console.log(chalk.dim(' No Signal phone number configured.'));+ console.log('');+ return;+ }++ console.log('');+ console.log(chalk.yellow(' ⚠️ This will:'));+ console.log(chalk.yellow(' • Send a goodbye message to your Signal group/chat'));+ console.log(chalk.yellow(' • Unlink this device from the Signal server'));+ console.log(chalk.yellow(' • Clear all Signal access data (admins, members, group connection)'));+ console.log('');++ const answer = await ask(chalk.white(' Continue? (y/N): '));+ if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {+ console.log(chalk.dim(' Cancelled.'));+ console.log('');+ return;+ }++ // Send goodbye message (best effort, skip if signal-cli not installed)+ const { findSignalCli } = await import('./signal/setup.js');+ const { sendSignalMessage } = await import('./signal/setup.js');+ if (findSignalCli()) {+ const target: { groupId?: string; recipient?: string } = {};+ if (config.channels.signal.mode === 'group' && config.channels.signal.groupId) {+ target.groupId = config.channels.signal.groupId;+ } else if (config.channels.signal.admins.length > 0) {+ target.recipient = config.channels.signal.admins[0].phoneNumber;+ }+ if (target.groupId || target.recipient) {+ try {+ await sendSignalMessage(config.channels.signal.phoneNumber, 'Mercury has been unregistered from this conversation. It will no longer respond here. To reconnect, the admin needs to set up Signal again with: mercury doctor', target);+ } catch { /* best effort */ }+ }+ }++ const { killStaleSignalCliProcesses } = await import('./signal/jsonrpc.js');+ killStaleSignalCliProcesses();++ // Unregister from Signal server+ console.log(chalk.dim(' Unlinking device from Signal...'));+ const { unregisterSignalNumber } = await import('./signal/setup.js');+ const result = await unregisterSignalNumber(config.channels.signal.phoneNumber);+ if (result.success) {+ console.log(chalk.green(' ✓ Device unlinked from Signal server.'));+ } else {+ console.log(chalk.yellow(' ⚠ Could not reach Signal server to unlink device.'));+ console.log(chalk.dim(' Local data has been cleared. The device will be unlinked automatically.'));+ }++ // Delete signal-cli local account data so checkLocalAccountData returns false+ const phoneNumberToDelete = config.channels.signal.phoneNumber;+ clearSignalAccess(config);+ config.channels.signal.enabled = false;+ config.channels.signal.phoneNumber = '';+ config.channels.signal.groupId = undefined;+ config.channels.signal.groupName = undefined;+ saveConfig(config);++ const { deleteSignalCliAccountData } = await import('./signal/setup.js');+ if (phoneNumberToDelete) {+ deleteSignalCliAccountData(phoneNumberToDelete);+ }++ console.log(chalk.green(' ✓ Signal data cleared.'));+ console.log(chalk.dim(' Run mercury doctor to set up Signal again.'));+ console.log('');++ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ });++const discordCmd = program+ .command('discord')+ .description('Manage Discord channel access and setup');++discordCmd+ .command('list')+ .description('Show approved Discord users and pending access requests')+ .action(() => {+ const config = loadConfig();+ console.log('');+ printDiscordAccessState(config);+ console.log('');+ });++discordCmd+ .command('approve <code>')+ .description('Approve a pending Discord pairing request by code')+ .action(async (code: string) => {+ const config = loadConfig();++ if (!hasDiscordAdminsFn(config)) {+ const approved = approveDiscordPendingRequestByPairingCode(config, code.trim());+ if (!approved) {+ console.log('');+ console.log(chalk.red(` No pending Discord pairing found for code ${code.trim()}.`));+ console.log('');+ return;+ }++ saveConfig(config);+ console.log('');+ console.log(chalk.green(` ✓ Approved first Discord admin ${formatDiscordUser(approved)}.`));+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ return;+ }++ const pending = findDiscordPendingRequest(config, code.trim());+ if (!pending) {+ console.log('');+ console.log(chalk.red(` No pending Discord request found for ${code.trim()}.`));+ console.log('');+ return;+ }++ const approved = approveDiscordPendingRequest(config, pending.userId);+ if (!approved) {+ console.log(chalk.red(' Failed to approve request.'));+ return;+ }++ saveConfig(config);+ console.log('');+ console.log(chalk.green(` ✓ Approved Discord user ${formatDiscordUser(approved)}.`));+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ });++discordCmd+ .command('reject <userId>')+ .description('Reject a pending Discord access request')+ .action(async (userId: string) => {+ const config = loadConfig();+ const rejected = rejectDiscordPendingRequest(config, userId.trim());+ if (!rejected) {+ console.log('');+ console.log(chalk.red(` No pending Discord request found for ${userId.trim()}.`));+ console.log('');+ return;+ }++ saveConfig(config);+ console.log('');+ console.log(chalk.green(` ✓ Rejected Discord request for ${formatDiscordUser(rejected)}.`));+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ });++discordCmd+ .command('remove <userId>')+ .description('Remove an approved Discord user')+ .action(async (userId: string) => {+ const config = loadConfig();+ const removed = removeDiscordUser(config, userId.trim());+ if (!removed) {+ console.log('');+ console.log(chalk.red(` No Discord user found with ID ${userId.trim()}.`));+ console.log('');+ return;+ }++ saveConfig(config);+ console.log('');+ console.log(chalk.green(` ✓ Removed Discord access for ${formatDiscordUser(removed)}.`));+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ });++discordCmd+ .command('reset')+ .description('Clear all Discord access data')+ .action(async () => {+ const config = loadConfig();+ clearDiscordAccess(config);+ config.channels.discord.enabled = false;+ saveConfig(config);+ console.log('');+ console.log(chalk.green(' ✓ Discord access reset complete.'));+ console.log(chalk.dim(' Run `mercury doctor` to set up Discord again.'));+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ });++discordCmd+ .command('status')+ .description('Show Discord configuration and connection status')+ .action(() => {+ const config = loadConfig();++ console.log('');+ console.log(chalk.bold.white(' Discord Status'));+ console.log('');++ if (!config.channels.discord.botToken) {+ console.log(chalk.dim(' Not configured. Run `mercury doctor` to set up Discord.'));+ console.log('');+ return;+ }++ console.log(` Enabled: ${config.channels.discord.enabled ? chalk.green('yes') : chalk.dim('no')}`);+ console.log(` Paired: ${hasDiscordAdminsFn(config) ? chalk.green('yes') : chalk.dim('no')}`);+ console.log(` Access: ${chalk.white(getDiscordAccessSummary(config))}`);+ if (config.channels.discord.guildId) {+ console.log(` Guild: ${chalk.white(config.channels.discord.guildId)}`);+ }+ if (config.channels.discord.channelId) {+ console.log(` Channel: ${chalk.white(config.channels.discord.channelId)}`);+ }+ if (config.channels.discord.adminRoleName) {+ console.log(` Admin Role: ${chalk.white(config.channels.discord.adminRoleName)}`);+ }+ console.log(` Streaming: ${config.channels.discord.streaming ? chalk.green('yes') : chalk.dim('no')}`);++ console.log('');+ });++const slackCmd = program+ .command('slack')+ .description('Manage Slack channel access and setup');++slackCmd+ .command('list')+ .description('Show approved Slack users and pending access requests')+ .action(() => {+ const config = loadConfig();+ printSlackAccessState(config);+ });++slackCmd+ .command('approve <userId>')+ .description('Approve a pending Slack access request')+ .action((userId: string) => {+ const config = loadConfig();++ const approved = approveSlackPendingRequest(config, userId);++ if (!approved) {+ console.log(chalk.red(`No pending Slack request found for "${userId}".`));+ process.exit(1);+ }++ saveConfig(config);+ console.log(chalk.green(`Approved Slack user ${formatSlackUser(approved)}.`));+ });++slackCmd+ .command('reject <userId>')+ .description('Reject a pending Slack access request')+ .action((userId: string) => {+ const config = loadConfig();++ const rejected = rejectSlackPendingRequest(config, userId);+ if (!rejected) {+ console.log(chalk.red(`No pending Slack request found for "${userId}".`));+ process.exit(1);+ }++ saveConfig(config);+ console.log(chalk.yellow(`Rejected Slack request for ${formatSlackUser(rejected)}.`));+ });++slackCmd+ .command('remove <userId>')+ .description('Remove an approved Slack user')+ .action((userId: string) => {+ const config = loadConfig();++ const removed = removeSlackUser(config, userId);+ if (!removed) {+ console.log(chalk.red(`No approved Slack user found for "${userId}".`));+ process.exit(1);+ }++ saveConfig(config);+ console.log(chalk.yellow(`Removed Slack access for ${formatSlackUser(removed)}.`));+ });++slackCmd+ .command('reset')+ .description('Clear all Slack access data and disable Slack')+ .action(() => {+ const config = loadConfig();+ clearSlackAccess(config);+ config.channels.slack.enabled = false;+ saveConfig(config);+ console.log(chalk.yellow('Slack access reset. Channel disabled.'));+ });++slackCmd+ .command('status')+ .description('Show Slack configuration and connection status')+ .action(() => {+ const config = loadConfig();+ console.log(` Enabled: ${config.channels.slack.enabled ? chalk.green('yes') : chalk.dim('no')}`);+ if (!config.channels.slack.botToken) {+ console.log(chalk.dim(' Not configured. Run mercury doctor to set up Slack.'));+ }+ if (config.channels.slack.channelId) {+ console.log(` Channel: ${chalk.white(config.channels.slack.channelId)}`);+ }+ if (config.channels.slack.teamId) {+ console.log(` Team: ${chalk.white(config.channels.slack.teamId)}`);+ }+ console.log(` Streaming: ${config.channels.slack.streaming ? chalk.green('yes') : chalk.dim('no')}`);+ console.log(` Access: ${chalk.white(getSlackAccessSummary(config))}`);+ console.log('');+ });+const serviceCmd = program.command('service').description('Manage Mercury as a system service (auto-start, crash recovery)');@@ -2255,9 +3520,9 @@ serviceCmdshowServiceStatus();});-program+ program.command('upgrade')- .description('Upgrade Mercury to the latest version from npm')+ .description('Upgrade Mercury to the latest version').action(async () => {console.log('');console.log(chalk.cyan(` Mercury ${chalk.white(`v${pkgVersion}`)}`));@@ -2266,11 +3531,47 @@ programconst daemon = getDaemonStatus();if (daemon.running) {console.log(chalk.dim(' Stopping background daemon...'));- stopDaemon();- await new Promise((r) => setTimeout(r, 1000));+ await stopDaemon();console.log(chalk.green(' ✓ Daemon stopped'));}+ const standalone = isStandaloneBinary();++ if (standalone) {+ // Standalone binary: re-run the installer script which downloads the+ // latest release from GitHub and replaces the binary in-place.+ console.log(chalk.dim(' Standalone binary detected — re-running installer...'));+ console.log('');++ const { execSync } = await import('node:child_process');+ const platform = process.platform;+ const binPath = process.execPath;++ if (platform === 'win32') {+ // Windows: use PowerShell installer+ const psCmd = `irm https://mercuryagent.sh/install.ps1 | iex`;+ try {+ execSync(psCmd, { stdio: 'inherit', shell: 'powershell.exe' });+ } catch {+ console.log(chalk.red(' ✗ Upgrade failed. Try manually:'));+ console.log(chalk.dim(' irm https://mercuryagent.sh/install.ps1 | iex'));+ }+ } else {+ // macOS / Linux: use shell installer+ const shCmd = 'curl -fsSL https://mercuryagent.sh/install.sh | sh';+ try {+ execSync(shCmd, { stdio: 'inherit' });+ } catch {+ console.log(chalk.red(' ✗ Upgrade failed. Try manually:'));+ console.log(chalk.dim(' curl -fsSL https://mercuryagent.sh/install.sh | sh'));+ }+ }++ console.log('');+ return;+ }++ // npm install: use npm to upgrade.console.log(chalk.dim(' Checking for latest version...'));const { execSync } = await import('node:child_process');diff --git a/src/memory/store.ts b/src/memory/store.tsindex 9abcff94..5ccc7d0e 100644--- a/src/memory/store.ts+++ b/src/memory/store.ts@@ -53,6 +53,10 @@ export interface EpisodicEvent {metadata?: Record<string, unknown>;}+function sanitizeId(id: string): string {+ return id.replace(/[^a-zA-Z0-9_:-]/g, '_');+}+export class ShortTermMemory {private dir: string;private maxMessages: number;@@ -64,6 +68,10 @@ export class ShortTermMemory {mkdirSync(this.dir, { recursive: true });}+ private filePath(conversationId: string): string {+ return join(this.dir, `${sanitizeId(conversationId)}.json`);+ }+add(conversationId: string, entry: MemoryEntry): void {if (!this.conversations.has(conversationId)) {this.conversations.set(conversationId, this.loadFromDisk(conversationId));@@ -86,20 +94,20 @@ export class ShortTermMemory {clear(conversationId: string): void {this.conversations.delete(conversationId);- const filepath = join(this.dir, `${conversationId}.json`);+ const filepath = this.filePath(conversationId);if (existsSync(filepath)) unlinkSync(filepath);}clearAll(): void {for (const conversationId of this.conversations.keys()) {- const filepath = join(this.dir, `${conversationId}.json`);+ const filepath = this.filePath(conversationId);if (existsSync(filepath)) unlinkSync(filepath);}this.conversations.clear();}private loadFromDisk(conversationId: string): MemoryEntry[] {- const filepath = join(this.dir, `${conversationId}.json`);+ const filepath = this.filePath(conversationId);if (!existsSync(filepath)) return [];try {return JSON.parse(readFileSync(filepath, 'utf-8'));@@ -109,7 +117,7 @@ export class ShortTermMemory {}private saveToDisk(conversationId: string, messages: MemoryEntry[]): void {- const filepath = join(this.dir, `${conversationId}.json`);+ const filepath = this.filePath(conversationId);writeFileSync(filepath, JSON.stringify(messages), 'utf-8');}}diff --git a/src/signal/binary.ts b/src/signal/binary.tsnew file mode 100644index 00000000..3fd821e2--- /dev/null+++ b/src/signal/binary.ts@@ -0,0 +1,364 @@+import fs from 'node:fs';+import path from 'node:path';+import { execSync } from 'node:child_process';+import { createWriteStream, existsSync, mkdirSync, rmSync } from 'node:fs';+import { Readable } from 'node:stream';+import { homedir } from 'node:os';+import chalk from 'chalk';+import { logger } from '../utils/logger.js';++const SIGNAL_CLI_VERSION = '0.14.5';+const MERCURY_HOME = () => process.env.MERCURY_HOME || path.join(homedir(), '.mercury');+const SIGNAL_CLI_DIR = () => path.join(MERCURY_HOME(), 'signal-cli');++const NATIVE_PLATFORMS: Record<string, string> = {+ 'linux-arm64': `signal-cli-${SIGNAL_CLI_VERSION}-Linux-native-arm64.tar.gz`,+ 'linux-x64': `signal-cli-${SIGNAL_CLI_VERSION}-Linux-native.tar.gz`,+};++function getPlatformKey(): string {+ return `${process.platform}-${process.arch}`;+}++export function isNativeAvailable(): boolean {+ return getPlatformKey() in NATIVE_PLATFORMS;+}++function getNativeArchiveName(): string | null {+ return NATIVE_PLATFORMS[getPlatformKey()] ?? null;+}++function getDownloadUrl(archiveName: string): string {+ return `https://github.com/AsamK/signal-cli/releases/download/v${SIGNAL_CLI_VERSION}/${archiveName}`;+}++function getBinaryPath(): string {+ const dir = SIGNAL_CLI_DIR();+ if (process.platform === 'win32') {+ return path.join(dir, 'bin', 'signal-cli.exe');+ }+ return path.join(dir, 'bin', 'signal-cli');+}++function getJarPath(): string {+ return path.join(SIGNAL_CLI_DIR(), 'lib', `signal-cli-${SIGNAL_CLI_VERSION}.jar`);+}++export function findSignalCli(): string | null {+ const binaryPath = getBinaryPath();+ if (existsSync(binaryPath)) {+ return binaryPath;+ }++ const jarPath = getJarPath();+ if (existsSync(jarPath)) {+ return jarPath;+ }++ const whichCmd = process.platform === 'win32' ? 'where' : 'which';+ try {+ const systemPath = execSync(`${whichCmd} signal-cli 2>/dev/null`, { encoding: 'utf-8', stdio: 'pipe' }).trim();+ if (systemPath) return systemPath;+ } catch { /* not on PATH */ }++ return null;+}++export function isNativeBinary(binaryPath: string): boolean {+ return !binaryPath.endsWith('.jar') && !binaryPath.endsWith('.sh');+}++export function isJarBinary(binaryPath: string): boolean {+ return binaryPath.endsWith('.jar');+}++export function isWrapperScript(binaryPath: string): boolean {+ return binaryPath.endsWith('/bin/signal-cli') || binaryPath.endsWith('\\bin\\signal-cli.bat');+}++export function getSignalCliCommand(binaryPath: string): string[] {+ if (isWrapperScript(binaryPath)) {+ return [binaryPath];+ }+ if (isJarBinary(binaryPath)) {+ const javaPath = findJavaPath() || 'java';+ return [javaPath, '-jar', binaryPath];+ }+ return [binaryPath];+}++export function getSignalCliEnv(): Record<string, string> {+ const javaPath = findJavaPath();+ if (!javaPath) return {};++ const javaDir = path.dirname(javaPath);+ const javaHome = path.dirname(javaDir);+ return { JAVA_HOME: javaHome };+}++export function buildSignalCliArgs(+ binaryPath: string,+ phoneNumber: string,+ command: string,+ extraArgs: string[] = [],+ configDir?: string,+): string[] {+ const cmd = getSignalCliCommand(binaryPath);+ const args: string[] = [...cmd.slice(1)];+ if (configDir) {+ args.push('--config', configDir);+ }+ args.push('-u', phoneNumber, command, ...extraArgs);+ return args;+}++export function getSignalCliExecEnv(): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [key, value] of Object.entries(process.env)) {+ if (value !== undefined) {+ env[key] = value;+ }+ }+ return { ...env, ...getSignalCliEnv() };+}++function formatBytes(bytes: number): string {+ if (bytes < 1024) return `${bytes}B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;+}++function renderProgressBar(downloaded: number, total: number | null): string {+ const BAR_WIDTH = 20;+ if (total && total > 0) {+ const pct = Math.min(downloaded / total, 1);+ const filled = Math.round(pct * BAR_WIDTH);+ const empty = BAR_WIDTH - filled;+ const bar = chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));+ return `${bar} ${formatBytes(downloaded)} / ${formatBytes(total)} (${Math.round(pct * 100)}%)`;+ }+ return `${formatBytes(downloaded)}`;+}++async function downloadWithProgress(url: string, destPath: string): Promise<void> {+ const response = await fetch(url, { redirect: 'follow' });+ if (!response.ok) {+ throw new Error(`Failed to download signal-cli: ${response.status} ${response.statusText}`);+ }++ if (!response.body) {+ throw new Error('Download response had no body');+ }++ const contentLength = response.headers.get('content-length');+ const total = contentLength ? parseInt(contentLength, 10) : null;++ const nodeStream = Readable.fromWeb(response.body as any);+ const fileStream = createWriteStream(destPath);++ let downloaded = 0;+ let lastUpdate = 0;++ nodeStream.on('data', (chunk: Buffer) => {+ downloaded += chunk.length;+ const now = Date.now();+ if (now - lastUpdate >= 100) {+ lastUpdate = now;+ process.stdout.write(`\r ${renderProgressBar(downloaded, total)}`);+ }+ });++ await new Promise<void>((resolve, reject) => {+ nodeStream.pipe(fileStream);+ fileStream.on('finish', () => {+ process.stdout.write(`\r ${renderProgressBar(downloaded, total)}\n`);+ resolve();+ });+ fileStream.on('error', reject);+ nodeStream.on('error', reject);+ });+}++async function downloadAndExtract(url: string, archivePath: string, dir: string): Promise<void> {+ logger.info({ url }, 'Downloading signal-cli...');++ const tmpArchive = archivePath + '.tmp';+ try {+ await downloadWithProgress(url, tmpArchive);++ process.stdout.write(' Extracting signal-cli...\r');+ mkdirSync(path.join(dir, 'bin'), { recursive: true });+ mkdirSync(path.join(dir, 'lib'), { recursive: true });++ execSync(`tar -xzf "${tmpArchive}" -C "${dir}" --strip-components=1`, { stdio: 'pipe' });+ process.stdout.write(' Extracting signal-cli... done\n');+ } catch (err: any) {+ logger.error({ err: err?.message }, 'Failed to extract signal-cli archive');+ throw new Error(`Failed to extract signal-cli: ${err?.message || err}`);+ } finally {+ try { fs.unlinkSync(tmpArchive); } catch { /* ignore */ }+ }+}++export async function downloadSignalCli(preferNative: boolean = true): Promise<string> {+ const dir = SIGNAL_CLI_DIR();+ const expectedBinary = getBinaryPath();+ const expectedJar = getJarPath();++ if (!existsSync(dir)) {+ mkdirSync(dir, { recursive: true });+ }++ if (existsSync(expectedBinary)) {+ logger.info({ path: expectedBinary }, 'Signal CLI native binary already exists');+ return expectedBinary;+ }+ if (existsSync(expectedJar)) {+ logger.info({ path: expectedJar }, 'Signal CLI JAR already exists');+ return expectedJar;+ }++ const useNative = preferNative && isNativeAvailable();++ if (useNative) {+ logger.info({ platform: getPlatformKey() }, 'Native binary available — no Java required');+ const archiveName = getNativeArchiveName()!;+ const url = getDownloadUrl(archiveName);+ const archivePath = path.join(dir, archiveName);++ try {+ await downloadAndExtract(url, archivePath, dir);++ const binaryPath = getBinaryPath();+ if (!existsSync(binaryPath)) {+ throw new Error(`Native binary not found after extraction at ${binaryPath}`);+ }+ try { fs.chmodSync(binaryPath, 0o755); } catch { /* ignore */ }+ logger.info({ path: binaryPath }, 'Signal CLI native binary installed');+ return binaryPath;+ } catch (nativeErr: any) {+ logger.warn({ err: nativeErr?.message }, 'Native binary download failed, falling back to JAR mode');+ // Clean up partial extraction so JAR extraction can start fresh+ try { rmSync(path.join(dir, 'bin'), { recursive: true, force: true }); } catch { /* ignore */ }+ try { rmSync(path.join(dir, 'lib'), { recursive: true, force: true }); } catch { /* ignore */ }+ }+ }++ // JAR mode (fallback or non-native platform)+ if (!checkJavaAvailable()) {+ throw new Error(+ 'Signal CLI requires Java (JRE 17+) on this platform.\n' ++ 'No native binary is available for macOS/Windows, and Java was not found.\n' ++ 'Install Java: https://adoptium.net/ or `brew install openjdk`\n' ++ 'Then run: mercury doctor'+ );+ }++ logger.info('Using JAR mode — Java runtime found');+ const jarArchiveName = `signal-cli-${SIGNAL_CLI_VERSION}.tar.gz`;+ const url = getDownloadUrl(jarArchiveName);+ const archivePath = path.join(dir, jarArchiveName);++ await downloadAndExtract(url, archivePath, dir);++ const jarPath = getJarPath();+ if (!existsSync(jarPath)) {+ throw new Error(`JAR not found after extraction at ${jarPath}`);+ }++ // Prefer the wrapper script which handles classpath and JAVA_HOME+ const binaryPath = getBinaryPath();+ if (existsSync(binaryPath)) {+ try { fs.chmodSync(binaryPath, 0o755); } catch { /* ignore */ }+ logger.info({ path: binaryPath }, 'Signal CLI installed (wrapper script + JAR)');+ return binaryPath;+ }++ logger.info({ path: jarPath }, 'Signal CLI JAR installed');+ return jarPath;+}++export async function ensureSignalCli(): Promise<string> {+ const existing = findSignalCli();+ if (existing) {+ logger.info({ path: existing }, 'Signal CLI found');+ return existing;+ }++ logger.info('Signal CLI not found, downloading...');+ return downloadSignalCli(true);+}++export function removeSignalCli(): boolean {+ const dir = SIGNAL_CLI_DIR();+ if (!existsSync(dir)) return false;++ try {+ rmSync(dir, { recursive: true, force: true });+ logger.info({ dir }, 'Signal CLI directory removed');+ return true;+ } catch (err: any) {+ logger.error({ err: err?.message }, 'Failed to remove Signal CLI directory');+ return false;+ }+}++const HOMEBREW_JAVA_PATHS = [+ '/opt/homebrew/opt/openjdk/bin/java',+ '/usr/local/opt/openjdk/bin/java',+];++let cachedJavaPath: string | null | undefined;++function verifyJavaWorks(javaPath: string): boolean {+ try {+ execSync(`"${javaPath}" -version 2>&1`, { encoding: 'utf-8', stdio: 'pipe', timeout: 5000 });+ return true;+ } catch {+ return false;+ }+}++export function findJavaPath(): string | null {+ if (cachedJavaPath !== undefined) return cachedJavaPath;++ // Check Homebrew paths first — they're known-good installations+ for (const candidate of HOMEBREW_JAVA_PATHS) {+ if (existsSync(candidate) && verifyJavaWorks(candidate)) {+ cachedJavaPath = candidate;+ return candidate;+ }+ }++ // Then check system PATH — but skip macOS stubs like /usr/bin/java+ try {+ const whichCmd = process.platform === 'win32' ? 'where' : 'which';+ const systemPath = execSync(`${whichCmd} java 2>/dev/null`, { encoding: 'utf-8', stdio: 'pipe' }).trim();+ if (systemPath && verifyJavaWorks(systemPath)) {+ cachedJavaPath = systemPath;+ return systemPath;+ }+ } catch { /* not on PATH or doesn't work */ }++ cachedJavaPath = null;+ return null;+}++export function checkJavaAvailable(): boolean {+ return findJavaPath() !== null;+}++export function getSignalCliVersion(binaryPath: string): string | null {+ const cmd = getSignalCliCommand(binaryPath);+ const env = getSignalCliExecEnv();+ try {+ const output = execSync(`${cmd.join(' ')} --version`, { encoding: 'utf-8', timeout: 10000, env });+ return output.trim();+ } catch {+ return null;+ }+}++export function getSignalCliDir(): string {+ return SIGNAL_CLI_DIR();+}\ No newline at end of filediff --git a/src/signal/jsonrpc.ts b/src/signal/jsonrpc.tsnew file mode 100644index 00000000..beb5066e--- /dev/null+++ b/src/signal/jsonrpc.ts@@ -0,0 +1,375 @@+import { spawn, execSync, type ChildProcess } from 'node:child_process';+import { createInterface } from 'node:readline';+import { logger } from '../utils/logger.js';+import { getSignalCliCommand, getSignalCliExecEnv } from './binary.js';+import type { JsonRpcEnvelope } from './process.js';++export function killStaleSignalCliProcesses(): void {+ try {+ const result = execSync('pgrep -f "org.asamk.signal.Main"', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();+ if (!result) return;+ const pids = result.split('\n').map(p => p.trim()).filter(Boolean);+ for (const pid of pids) {+ try {+ process.kill(Number(pid), 'SIGKILL');+ logger.info({ pid }, 'Killed stale signal-cli process');+ } catch { /* already dead */ }+ }+ } catch { /* no processes found */ }+}++export interface JsonRpcClientOptions {+ binaryPath: string;+ phoneNumber: string;+ configDir?: string;+}++type PendingRequest = {+ resolve: (value: unknown) => void;+ reject: (reason: unknown) => void;+ timeout: NodeJS.Timeout;+};++type EnvelopeHandler = (envelope: JsonRpcEnvelope) => void;++let requestId = 0;++const BASE_RECONNECT_DELAY = 2000;+const MAX_RECONNECT_DELAY = 60000;+const RECONNECT_MULTIPLIER = 1.5;+const STARTUP_TIMEOUT = 60_000;++export class JsonRpcClient {+ private process: ChildProcess | null = null;+ private pending = new Map<number, PendingRequest>();+ private envelopeHandler?: EnvelopeHandler;+ private running = false;+ private readline: ReturnType<typeof createInterface> | null = null;+ private requestTimeout: number;+ private reconnectAttempts = 0;+ private shouldReconnect = false;+ private reconnectTimer: NodeJS.Timeout | null = null;++ constructor(+ private options: JsonRpcClientOptions,+ requestTimeoutMs: number = 30_000,+ ) {+ this.requestTimeout = requestTimeoutMs;+ }++ onEnvelope(handler: EnvelopeHandler): void {+ this.envelopeHandler = handler;+ }++ async start(): Promise<void> {+ if (this.running) return;++ this.shouldReconnect = true;+ await this.spawnProcess();+ }++ private async spawnProcess(): Promise<void> {+ killStaleSignalCliProcesses();++ const cmd = getSignalCliCommand(this.options.binaryPath);+ const args = [...cmd.slice(1), '-u', this.options.phoneNumber, 'jsonRpc', '--receive-mode', 'on-start'];++ if (this.options.configDir) {+ args.unshift('--config', this.options.configDir);+ }++ const env = getSignalCliExecEnv();+ if (this.options.configDir) {+ env.SIGNAL_CLI_CONFIG_DIR = this.options.configDir;+ }++ logger.info({ cmd: cmd[0], phone: this.options.phoneNumber.slice(0, 6) + '***' }, 'Starting signal-cli JSON-RPC daemon');++ this.process = spawn(cmd[0], args, {+ stdio: ['pipe', 'pipe', 'pipe'],+ env,+ });++ this.process.on('error', (err) => {+ logger.error({ err: err.message }, 'signal-cli JSON-RPC process error');+ this.handleProcessExit();+ });++ this.process.on('exit', (code, signal) => {+ logger.warn({ code, signal }, 'signal-cli JSON-RPC process exited');+ this.handleProcessExit();+ });++ this.process.stderr?.on('data', (data: Buffer) => {+ const line = data.toString().trim();+ if (line) {+ logger.debug({ stderr: line }, 'signal-cli stderr');+ }+ });++ this.readline = createInterface({ input: this.process.stdout! });+ this.readline.on('line', (line) => {+ this.handleLine(line);+ });++ await this.waitForReady();++ this.running = true;+ this.reconnectAttempts = 0;+ logger.info('signal-cli JSON-RPC daemon connected');+ }++ private async waitForReady(): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ const timeout = setTimeout(() => {+ reject(new Error('Timed out waiting for signal-cli daemon to start'));+ }, STARTUP_TIMEOUT);++ let resolved = false;++ const checkReady = async () => {+ try {+ await this.send('version', {});+ if (!resolved) {+ resolved = true;+ clearTimeout(timeout);+ resolve();+ }+ } catch {+ if (!resolved && this.shouldReconnect) {+ setTimeout(checkReady, 1000);+ }+ }+ };++ setTimeout(checkReady, 500);+ });+ }++ private handleProcessExit(): void {+ this.running = false;+ this.process = null;++ if (this.readline) {+ this.readline.close();+ this.readline = null;+ }++ for (const [, pending] of this.pending) {+ clearTimeout(pending.timeout);+ pending.reject(new Error('signal-cli process exited'));+ }+ this.pending.clear();++ if (this.shouldReconnect) {+ this.scheduleReconnect();+ }+ }++ private scheduleReconnect(): void {+ const delay = Math.min(+ BASE_RECONNECT_DELAY * Math.pow(RECONNECT_MULTIPLIER, this.reconnectAttempts),+ MAX_RECONNECT_DELAY,+ );+ this.reconnectAttempts++;++ if (this.reconnectAttempts > 50) {+ logger.error('Max reconnect attempts (50) reached for signal-cli daemon');+ return;+ }++ if (this.reconnectAttempts > 20) {+ logger.warn({ attempt: this.reconnectAttempts, delay: Math.round(delay) }, 'signal-cli reconnecting (throttled)');+ } else {+ logger.info({ attempt: this.reconnectAttempts, delay: Math.round(delay) }, 'signal-cli reconnecting');+ }++ this.reconnectTimer = setTimeout(async () => {+ this.reconnectTimer = null;+ try {+ await this.spawnProcess();+ } catch (err: any) {+ logger.error({ err: err.message }, 'Failed to reconnect signal-cli daemon');+ }+ }, delay);+ }++ async send(method: string, params: Record<string, unknown>): Promise<unknown> {+ if (!this.process || this.process.exitCode !== null) {+ throw new Error('signal-cli JSON-RPC client not running');+ }++ const id = ++requestId;+ const request = {+ jsonrpc: '2.0',+ method,+ params,+ id,+ };++ return new Promise((resolve, reject) => {+ const timeout = setTimeout(() => {+ this.pending.delete(id);+ reject(new Error(`JSON-RPC request timed out: ${method}`));+ }, this.requestTimeout);++ this.pending.set(id, { resolve, reject, timeout });++ const line = JSON.stringify(request) + '\n';+ try {+ this.process!.stdin!.write(line);+ } catch (err: any) {+ clearTimeout(timeout);+ this.pending.delete(id);+ reject(new Error(`Failed to write to signal-cli stdin: ${err.message}`));+ }+ });+ }++ async sendMessage(params: {+ account: string;+ message: string;+ recipients?: string[];+ groupId?: string;+ attachments?: string[];+ }): Promise<unknown> {+ const sendParams: Record<string, unknown> = {+ account: params.account,+ message: params.message,+ };++ if (params.recipients && params.recipients.length > 0) {+ sendParams.recipients = params.recipients;+ }+ if (params.groupId) {+ sendParams.groupId = params.groupId;+ }+ if (params.attachments && params.attachments.length > 0) {+ sendParams.attachments = params.attachments;+ }++ return this.send('send', sendParams);+ }++ async sendTyping(params: { account: string; recipient?: string; groupId?: string }): Promise<unknown> {+ return this.send('sendTyping', params as Record<string, unknown>);+ }++ async listGroups(params: { account: string }): Promise<unknown> {+ return this.send('listGroups', params as Record<string, unknown>);+ }++ async listContacts(params: { account: string }): Promise<unknown> {+ return this.send('listContacts', params as Record<string, unknown>);+ }++ async getProfile(params: { account: string; recipient?: string; profileName?: string }): Promise<unknown> {+ return this.send('getProfile', params as Record<string, unknown>);+ }++ async register(params: { account: string; voice?: boolean }): Promise<unknown> {+ return this.send('register', params as Record<string, unknown>);+ }++ async verify(params: { account: string; code: string }): Promise<unknown> {+ return this.send('verify', params as Record<string, unknown>);+ }++ async stop(): Promise<void> {+ this.shouldReconnect = false;+ this.running = false;++ if (this.reconnectTimer) {+ clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ }++ if (this.readline) {+ this.readline.close();+ this.readline = null;+ }++ for (const [, pending] of this.pending) {+ clearTimeout(pending.timeout);+ pending.reject(new Error('Client stopped'));+ }+ this.pending.clear();++ if (this.process) {+ try {+ this.process.kill('SIGTERM');+ } catch { /* already dead */ }++ await new Promise<void>((resolve) => {+ const timeout = setTimeout(() => {+ try { this.process?.kill('SIGKILL'); } catch { /* already dead */ }+ resolve();+ }, 3000);++ this.process!.on('exit', () => {+ clearTimeout(timeout);+ resolve();+ });++ if (this.process!.exitCode !== null) {+ clearTimeout(timeout);+ resolve();+ }+ });++ this.process = null;+ }+ }++ isRunning(): boolean {+ return this.running && this.process !== null && this.process.exitCode === null;+ }++ private handleLine(line: string): void {+ if (!line.trim()) return;++ try {+ const parsed = JSON.parse(line);++ if (parsed.error && parsed.id) {+ const id = parsed.id;+ const pending = this.pending.get(id);+ if (pending) {+ clearTimeout(pending.timeout);+ this.pending.delete(id);+ pending.reject(new Error(parsed.error.message || `JSON-RPC error ${parsed.error.code}`));+ } else {+ logger.warn({ id, error: parsed.error.message }, 'Received JSON-RPC error for unknown request');+ }+ return;+ }++ if (parsed.id != null && parsed.result !== undefined) {+ const id = parsed.id;+ const pending = this.pending.get(id);+ if (pending) {+ clearTimeout(pending.timeout);+ this.pending.delete(id);+ pending.resolve(parsed.result);+ } else {+ logger.debug({ id }, 'Received JSON-RPC result for unknown request');+ }+ return;+ }++ if (parsed.method === 'receive' && parsed.params?.envelope) {+ logger.info({ source: parsed.params.envelope.source, hasData: !!parsed.params.envelope.dataMessage }, 'Signal: received envelope from signal-cli');+ try {+ const envelope = parsed.params.envelope as JsonRpcEnvelope;+ this.envelopeHandler?.(envelope);+ } catch (err: any) {+ logger.error({ err: err.message }, 'Error handling signal-cli envelope');+ }+ } else if (parsed.method) {+ logger.debug({ method: parsed.method }, 'Received JSON-RPC notification with unknown method');+ }+ } catch {+ logger.debug({ line: line.slice(0, 200) }, 'Non-JSON line from signal-cli');+ }+ }+}\ No newline at end of filediff --git a/src/signal/process.ts b/src/signal/process.tsnew file mode 100644index 00000000..66b6655e--- /dev/null+++ b/src/signal/process.ts@@ -0,0 +1,90 @@+export interface JsonRpcEnvelope {+ source: string;+ sourceNumber?: string;+ sourceUuid?: string;+ sourceName?: string;+ sourceDevice?: number;+ timestamp: number;+ dataMessage?: {+ timestamp: number;+ message?: string;+ groupInfo?: {+ groupId: string;+ groupName?: string;+ groupType?: string;+ };+ expiresInSeconds?: number;+ attachments?: Array<{+ id: string;+ filename?: string;+ contentType?: string;+ size?: number;+ }>;+ quote?: {+ id: number;+ author?: string;+ text?: string;+ };+ sticker?: {+ packId?: string;+ packKey?: string;+ stickerId?: number;+ };+ remoteDelete?: {+ targetSentTimestamp: number;+ };+ };+ syncMessage?: {+ sentMessage?: {+ timestamp: number;+ message?: string;+ destination?: string;+ destinationNumber?: string;+ groupInfo?: {+ groupId: string;+ groupName?: string;+ };+ expiresInSeconds?: number;+ };+ };+ typingMessage?: {+ groupId?: string;+ action: 'STARTED' | 'STOPPED';+ };+ receiptMessage?: {+ type: number;+ timestamps: number[];+ };+ callMessage?: {+ type?: string;+ };+}++export function buildJsonRpcRequest(method: string, params: Record<string, unknown>, id: number): string {+ return JSON.stringify({+ jsonrpc: '2.0',+ method,+ params,+ id,+ });+}++export function parseJsonRpcResponse(data: string): { id?: number; result?: unknown; error?: { code: number; message: string } } | null {+ try {+ return JSON.parse(data);+ } catch {+ return null;+ }+}++export function parseJsonRpcNotification(data: string): { method: string; params: Record<string, unknown> } | null {+ try {+ const parsed = JSON.parse(data);+ if (parsed.method && !parsed.id) {+ return { method: parsed.method, params: parsed.params || {} };+ }+ return null;+ } catch {+ return null;+ }+}\ No newline at end of filediff --git a/src/signal/setup.ts b/src/signal/setup.tsnew file mode 100644index 00000000..2dafa6d1--- /dev/null+++ b/src/signal/setup.ts@@ -0,0 +1,457 @@+import { execSync, spawn, type ChildProcess } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import qrcode from 'qrcode-terminal';+import { logger } from '../utils/logger.js';+import { ensureSignalCli, findSignalCli, getSignalCliCommand, removeSignalCli, getSignalCliDir, checkJavaAvailable, isNativeAvailable, findJavaPath, getSignalCliExecEnv } from './binary.js';+import { JsonRpcClient } from './jsonrpc.js';+import type { MercuryConfig } from '../utils/config.js';+import { saveConfig, loadConfig, hasSignalAdmins } from '../utils/config.js';+import { redactPhone } from '../utils/redact.js';++export function printQrCode(text: string): void {+ qrcode.generate(text, { small: true });+}++export interface SignalSetupResult {+ success: boolean;+ phoneNumber?: string;+ mode?: string;+ groupId?: string;+ error?: string;+}++export async function checkSignalSetup(config: MercuryConfig): Promise<{+ binaryOk: boolean;+ binaryPath?: string;+ registered: boolean;+ linked: boolean;+ mode: string;+ groupId?: string;+ phoneNumber?: string;+ errors: string[];+}> {+ const errors: string[] = [];+ const result = {+ binaryOk: false as boolean,+ binaryPath: undefined as string | undefined,+ registered: false as boolean,+ linked: false as boolean,+ mode: config.channels.signal.mode || 'group',+ groupId: config.channels.signal.groupId,+ phoneNumber: config.channels.signal.phoneNumber,+ errors,+ };++ try {+ const binaryPath = await ensureSignalCli();+ result.binaryOk = true;+ result.binaryPath = binaryPath;+ logger.info({ path: binaryPath }, 'Signal CLI binary found');+ } catch (err: any) {+ errors.push(`signal-cli not found: ${err.message}`);+ return result;+ }++ if (!config.channels.signal.phoneNumber) {+ errors.push('Signal phone number not configured. Set SIGNAL_PHONE_NUMBER in environment or mercury.yaml');+ return result;+ }++ result.registered = true;++ // Check for local account data — if accounts.json exists with this number,+ // the device has been linked+ const hasLocalData = checkLocalAccountData(config.channels.signal.phoneNumber);+ if (hasLocalData) {+ result.linked = true;+ } else {+ errors.push('Signal device not linked. Run signal setup to link your device.');+ }++ return result;+}++function checkLocalAccountData(phoneNumber: string): boolean {+ const dataDir = process.env.SIGNAL_CLI_CONFIG_DIR || path.join(os.homedir(), '.local', 'share', 'signal-cli');+ const accountsPath = path.join(dataDir, 'data', 'accounts.json');++ if (!fs.existsSync(accountsPath)) return false;++ try {+ const content = fs.readFileSync(accountsPath, 'utf-8');+ const accounts = JSON.parse(content);+ const normalized = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;+ const account = accounts.accounts?.find((a: any) => a.number === normalized);+ if (!account) return false;++ const accountDataPath = path.join(dataDir, 'data', account.path);+ if (fs.existsSync(accountDataPath)) {+ try {+ const accountData = JSON.parse(fs.readFileSync(accountDataPath, 'utf-8'));+ if (accountData.registered === false) {+ logger.info({ phone: redactPhone(phoneNumber) }, 'Signal account found but registered=false, treating as not linked');+ return false;+ }+ } catch { /* ignore parse errors, assume linked */ }+ }++ return true;+ } catch {+ return false;+ }+}++export function deleteSignalCliAccountData(phoneNumber: string): boolean {+ const dataDir = process.env.SIGNAL_CLI_CONFIG_DIR || path.join(os.homedir(), '.local', 'share', 'signal-cli');+ const accountsPath = path.join(dataDir, 'data', 'accounts.json');++ if (!fs.existsSync(accountsPath)) return true;++ try {+ const content = fs.readFileSync(accountsPath, 'utf-8');+ const accounts = JSON.parse(content);+ const normalized = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;+ const account = accounts.accounts?.find((a: any) => a.number === normalized);+ if (!account) return true;++ const accountId = account.path;+ if (accountId) {+ const accountDataFile = path.join(dataDir, 'data', accountId);+ const accountDataDir = path.join(dataDir, 'data', `${accountId}.d`);++ if (fs.existsSync(accountDataFile)) {+ fs.rmSync(accountDataFile, { force: true });+ logger.info({ file: accountDataFile }, 'Deleted signal-cli account data file');+ }+ if (fs.existsSync(accountDataDir)) {+ fs.rmSync(accountDataDir, { recursive: true, force: true });+ logger.info({ dir: accountDataDir }, 'Deleted signal-cli account data directory');+ }+ }++ accounts.accounts = accounts.accounts.filter((a: any) => a.number !== normalized);+ fs.writeFileSync(accountsPath, JSON.stringify(accounts, null, 2));+ logger.info({ phone: redactPhone(phoneNumber) }, 'Removed signal-cli account entry from accounts.json');++ return true;+ } catch (err: any) {+ logger.error({ err: err.message }, 'Failed to delete signal-cli account data');+ return false;+ }+}++export async function verifySignalLinking(phoneNumber: string, binaryPath?: string): Promise<boolean> {+ const binary = binaryPath || await ensureSignalCli();+ const cmd = getSignalCliCommand(binary);+ const env = getSignalCliExecEnv();++ try {+ const result = execSync(+ `${cmd.join(' ')} -u ${phoneNumber} listDevices`,+ { encoding: 'utf-8', timeout: 15000, env, stdio: ['pipe', 'pipe', 'pipe'] },+ );+ return result.trim().length > 0;+ } catch {+ return false;+ }+}++export async function registerSignalNumber(phoneNumber: string, voice: boolean = false, binaryPath?: string): Promise<{ success: boolean; error?: string }> {+ const binary = binaryPath || await ensureSignalCli();+ const cmd = getSignalCliCommand(binary);+ const env = getSignalCliExecEnv();++ try {+ const args = voice ? '--voice' : '';+ execSync(+ `${cmd.join(' ')} -u ${phoneNumber} register ${args} 2>&1`,+ { encoding: 'utf-8', timeout: 30_000, env },+ );+ return { success: true };+ } catch (err: any) {+ return { success: false, error: err.message };+ }+}++export async function verifySignalNumber(phoneNumber: string, code: string, binaryPath?: string): Promise<{ success: boolean; error?: string }> {+ const binary = binaryPath || await ensureSignalCli();+ const cmd = getSignalCliCommand(binary);+ const env = getSignalCliExecEnv();++ try {+ execSync(+ `${cmd.join(' ')} -u ${phoneNumber} verify ${code} 2>&1`,+ { encoding: 'utf-8', timeout: 15_000, env },+ );+ return { success: true };+ } catch (err: any) {+ return { success: false, error: err.message };+ }+}++export interface LinkingSession {+ uri: string;+ process: ChildProcess;+}++export async function startLinking(binaryPath?: string): Promise<LinkingSession | null> {+ const binary = binaryPath || await ensureSignalCli();+ const cmd = getSignalCliCommand(binary);+ const env = getSignalCliExecEnv();++ return new Promise((resolve) => {+ let uri: string | null = null;+ let resolved = false;++ const child = spawn(cmd[0], [...cmd.slice(1), 'link', '-n', 'Mercury'], {+ stdio: ['pipe', 'pipe', 'pipe'],+ env,+ });++ const cleanup = () => {+ if (!resolved) {+ resolved = true;+ resolve(null);+ }+ };++ const checkForUri = (output: string) => {+ if (!uri && output.startsWith('sgnl://')) {+ uri = output;+ logger.info('Signal device linking URI generated');+ if (!resolved) {+ resolved = true;+ resolve({ uri, process: child });+ }+ }+ };++ child.stdout?.on('data', (data: Buffer) => {+ const output = data.toString().trim();+ checkForUri(output);+ });++ child.stderr?.on('data', (data: Buffer) => {+ const line = data.toString().trim();+ if (line) {+ logger.debug({ stderr: line }, 'signal-cli link stderr');+ checkForUri(line);+ }+ });++ child.on('error', (err) => {+ logger.error({ err: err.message }, 'signal-cli link process error');+ cleanup();+ });++ child.on('exit', (code) => {+ if (!resolved) {+ logger.error({ code }, 'signal-cli link process exited before producing URI');+ cleanup();+ }+ });++ // Timeout: if no URI within 60s, kill and return null+ // Java + signal-cli startup can be slow, especially in Docker+ setTimeout(() => {+ if (!resolved) {+ logger.error('Timed out waiting for signal-cli link URI');+ try { child.kill(); } catch { /* already dead */ }+ cleanup();+ }+ }, 60_000);+ });+}++export async function waitForLinkCompletion(session: LinkingSession, timeoutMs: number = 120_000): Promise<boolean> {+ return new Promise((resolve) => {+ let settled = false;++ const cleanup = (result: boolean) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ try { session.process.kill('SIGKILL'); } catch { /* already dead */ }+ resolve(result);+ };++ const timer = setTimeout(() => {+ logger.warn('signal-cli link timed out, killing process');+ cleanup(false);+ }, timeoutMs);++ session.process.on('exit', (code) => {+ cleanup(code === 0);+ });++ session.process.on('error', () => {+ cleanup(false);+ });+ });+}++export function cancelLinking(session: LinkingSession): void {+ try { session.process.kill('SIGKILL'); } catch { /* already dead */ }+}++export async function findMercuryGroup(phoneNumber: string, binaryPath?: string): Promise<{ groupId: string; groupName: string } | null> {+ const binary = binaryPath || await ensureSignalCli();+ const rpc = new JsonRpcClient({ binaryPath: binary, phoneNumber });++ try {+ await rpc.start();+ const groups = await rpc.listGroups({ account: phoneNumber }) as any[];+ await rpc.stop();++ if (!Array.isArray(groups)) return null;++ for (const group of groups) {+ const name = (group.name || group.groupName || '').toLowerCase().trim();+ if (name === 'mercury') {+ return {+ groupId: group.groupId || group.id,+ groupName: group.name || group.groupName || 'Mercury',+ };+ }+ }++ return null;+ } catch (err: any) {+ logger.error({ err: err.message }, 'Failed to list Signal groups');+ try { await rpc.stop(); } catch { /* ignore */ }+ return null;+ }+}++export function completeSignalSetup(+ config: MercuryConfig,+ phoneNumber: string,+ mode: 'private' | 'group',+ groupId?: string,+ groupName?: string,+): SignalSetupResult {+ config.channels.signal.enabled = true;+ config.channels.signal.phoneNumber = phoneNumber;+ config.channels.signal.mode = mode;+ if (groupId) {+ config.channels.signal.groupId = groupId;+ config.channels.signal.groupName = groupName || 'Mercury';+ }+ saveConfig(config);++ logger.info({+ phone: redactPhone(phoneNumber),+ mode,+ groupId: groupId ? redactPhone(groupId) : undefined,+ }, 'Signal setup completed');++ return {+ success: true,+ phoneNumber,+ mode,+ groupId,+ };+}++export function resetSignalSetup(config: MercuryConfig, removeBinary: boolean = false): void {+ config.channels.signal.enabled = false;+ config.channels.signal.phoneNumber = '';+ config.channels.signal.mode = 'group';+ config.channels.signal.groupId = undefined;+ config.channels.signal.groupName = undefined;+ config.channels.signal.admins = [];+ config.channels.signal.members = [];+ config.channels.signal.pending = [];+ saveConfig(config);++ if (removeBinary) {+ removeSignalCli();+ }++ logger.info('Signal setup reset');+}++export function printSetupInstructions(): string {+ return [+ '━━━ Signal Setup Instructions ━━━',+ '',+ '1. Mercury will download signal-cli automatically.',+ '',+ '2. Choose your mode:',+ ' a) Private (Note to Yourself) — 1:1 chat with your own Signal',+ ' b) Group — Create a "Mercury" group in Signal',+ '',+ '3. Link your device:',+ ' a. Open Signal on your phone',+ ' b. Go to Settings > Linked Devices',+ ' c. Tap "+" to add a new device',+ ' d. Scan the QR code shown in the terminal',+ '',+ '4. If using group mode:',+ ' - Create a group named "Mercury" in Signal',+ ' - Add Mercury\'s linked number to the group',+ ' - Send /pair in the group to start pairing',+ '',+ '5. Enter the pairing code shown in the Mercury terminal',+ '',+ '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',+ ].join('\n');+}++export async function unregisterSignalNumber(phoneNumber: string, binaryPath?: string): Promise<{ success: boolean; error?: string }> {+ const binary = binaryPath || findSignalCli();+ if (!binary) {+ return { success: false, error: 'signal-cli not installed' };+ }+ const cmd = getSignalCliCommand(binary);+ const env = getSignalCliExecEnv();++ try {+ execSync(+ `${cmd.join(' ')} -u ${phoneNumber} unregister 2>&1`,+ { encoding: 'utf-8', timeout: 30_000, env },+ );+ logger.info({ phone: redactPhone(phoneNumber) }, 'Signal number unregistered');+ return { success: true };+ } catch (err: any) {+ return { success: false, error: err.message };+ }+}++export async function sendSignalMessage(+ phoneNumber: string,+ message: string,+ target: { groupId?: string; recipient?: string },+ binaryPath?: string,+): Promise<boolean> {+ const binary = binaryPath || findSignalCli();+ if (!binary) return false;++ const cmd = getSignalCliCommand(binary);+ const env = getSignalCliExecEnv();+ const args = [cmd.join(' '), '-u', phoneNumber, 'send'];++ if (target.groupId) {+ args.push('-g', target.groupId);+ } else if (target.recipient) {+ args.push(target.recipient);+ } else {+ return false;+ }++ args.push('-m', `"${message.replace(/"/g, '\\"')}"`);++ try {+ execSync(+ args.join(' ') + ' 2>&1',+ { encoding: 'utf-8', timeout: 15_000, env },+ );+ return true;+ } catch {+ return false;+ }+}++export { ensureSignalCli, findSignalCli, removeSignalCli, getSignalCliDir, checkJavaAvailable, isNativeAvailable, findJavaPath, getSignalCliExecEnv };\ No newline at end of filediff --git a/src/types/channel.ts b/src/types/channel.tsindex 2b9872c7..4ee477e0 100644--- a/src/types/channel.ts+++ b/src/types/channel.ts@@ -52,3 +52,88 @@ export interface TelegramChannelConfig extends ChannelConfig {export interface CLIChannelConfig extends ChannelConfig {type: 'cli';}++export type SignalMode = 'private' | 'group';++export interface SignalAccessUser {+ phoneNumber: string;+ uuid?: string;+ name?: string;+ role: 'admin' | 'member';+ pairedAt: string;+}++export interface SignalPendingRequest {+ phoneNumber: string;+ pairingCode: string;+ requestedAt: string;+ uuid?: string;+ name?: string;+}++export interface SignalChannelConfig extends ChannelConfig {+ type: 'signal';+ phoneNumber: string;+ mode: SignalMode;+ groupId?: string;+ groupName?: string;+ admins: SignalAccessUser[];+ members: SignalAccessUser[];+ pending: SignalPendingRequest[];+}++export interface DiscordAccessUser {+ userId: string;+ username?: string;+ displayName?: string;+ role: 'admin' | 'member';+ approvedAt: string;+}++export interface DiscordPendingRequest {+ userId: string;+ username?: string;+ displayName?: string;+ requestedAt: string;+ pairingCode?: string;+}++export interface DiscordChannelConfig extends ChannelConfig {+ type: 'discord';+ botToken: string;+ guildId?: string;+ channelId?: string;+ adminRoleName?: string;+ streaming?: boolean;+ admins: DiscordAccessUser[];+ members: DiscordAccessUser[];+ pending: DiscordPendingRequest[];+}++export interface SlackAccessUser {+ userId: string;+ userName?: string;+ displayName?: string;+ role: 'admin' | 'member';+ approvedAt: string;+}++export interface SlackPendingRequest {+ userId: string;+ userName?: string;+ displayName?: string;+ requestedAt: string;+ pairingCode?: string;+}++export interface SlackChannelConfig extends ChannelConfig {+ type: 'slack';+ botToken: string;+ appToken: string;+ channelId?: string;+ teamId?: string;+ streaming?: boolean;+ admins: SlackAccessUser[];+ members: SlackAccessUser[];+ pending: SlackPendingRequest[];+}diff --git a/src/utils/config.ts b/src/utils/config.tsindex 53c3dff2..f7ce2b49 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -3,6 +3,7 @@ import { join, resolve } from 'node:path';import { homedir } from 'node:os';import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';import { config as loadDotenv } from 'dotenv';+import type { SignalAccessUser, SignalPendingRequest, DiscordAccessUser, DiscordPendingRequest, SlackAccessUser, SlackPendingRequest } from '../types/channel.js';const MERCURY_HOME = join(homedir(), '.mercury');@@ -93,6 +94,38 @@ export interface MercuryConfig {pairedChatId?: number;pairedUsername?: string;};+ signal: {+ enabled: boolean;+ phoneNumber: string;+ mode: string;+ groupId?: string;+ groupName?: string;+ admins: SignalAccessUser[];+ members: SignalAccessUser[];+ pending: SignalPendingRequest[];+ };+ discord: {+ enabled: boolean;+ botToken: string;+ guildId?: string;+ channelId?: string;+ adminRoleName?: string;+ streaming?: boolean;+ admins: DiscordAccessUser[];+ members: DiscordAccessUser[];+ pending: DiscordPendingRequest[];+ };+ slack: {+ enabled: boolean;+ botToken: string;+ appToken: string;+ channelId?: string;+ teamId?: string;+ streaming?: boolean;+ admins: SlackAccessUser[];+ members: SlackAccessUser[];+ pending: SlackPendingRequest[];+ };};github: {username: string;@@ -263,6 +296,38 @@ export function getDefaultConfig(): MercuryConfig {members: [],pending: [],},+ signal: {+ enabled: getEnvBool('SIGNAL_ENABLED', false),+ phoneNumber: getEnv('SIGNAL_PHONE_NUMBER', ''),+ mode: getEnv('SIGNAL_MODE', 'group'),+ groupId: getEnv('SIGNAL_GROUP_ID', ''),+ groupName: getEnv('SIGNAL_GROUP_NAME', 'Mercury'),+ admins: [],+ members: [],+ pending: [],+ },+ discord: {+ enabled: getEnvBool('DISCORD_ENABLED', false),+ botToken: getEnv('DISCORD_BOT_TOKEN', ''),+ guildId: getEnv('DISCORD_GUILD_ID', ''),+ channelId: getEnv('DISCORD_CHANNEL_ID', ''),+ adminRoleName: getEnv('DISCORD_ADMIN_ROLE_NAME', 'Mercury Admin'),+ streaming: getEnvBool('DISCORD_STREAMING', true),+ admins: [],+ members: [],+ pending: [],+ },+ slack: {+ enabled: getEnvBool('SLACK_ENABLED', false),+ botToken: getEnv('SLACK_BOT_TOKEN', ''),+ appToken: getEnv('SLACK_APP_TOKEN', ''),+ channelId: getEnv('SLACK_CHANNEL_ID', ''),+ teamId: getEnv('SLACK_TEAM_ID', ''),+ streaming: getEnvBool('SLACK_STREAMING', true),+ admins: [],+ members: [],+ pending: [],+ },},github: {username: getEnv('GITHUB_USERNAME', ''),@@ -315,13 +380,19 @@ export function loadConfig(): MercuryConfig {const raw = readFileSync(CONFIG_PATH, 'utf-8');const fileConfig = parseYaml(raw) as Partial<MercuryConfig>;const defaults = getDefaultConfig();- return migrateLegacyOllamaLocalBaseUrl(- migrateLegacyOllamaCloudBaseUrl(- migrateLegacyTelegramAccess(deepMerge(defaults, fileConfig)),+ return migrateLegacyDiscordAccess(+ migrateLegacyOllamaLocalBaseUrl(+ migrateLegacyOllamaCloudBaseUrl(+ migrateLegacySignalAccess(+ migrateLegacyTelegramAccess(deepMerge(defaults, fileConfig)),+ ),+ ),),);}- return migrateLegacyTelegramAccess(getDefaultConfig());+ return migrateLegacyDiscordAccess(+ migrateLegacyTelegramAccess(getDefaultConfig()),+ );}export function saveConfig(config: MercuryConfig): void {@@ -621,3 +692,453 @@ export function migrateLegacyOllamaLocalBaseUrl(config: MercuryConfig): MercuryC}return config;}++// ── Signal access helpers ────────────────────────────────────────++export function getSignalApprovedUsers(config: MercuryConfig): SignalAccessUser[] {+ return [...config.channels.signal.admins, ...config.channels.signal.members];+}++export function findSignalAdmin(config: MercuryConfig, phoneNumber: string): SignalAccessUser | undefined {+ return config.channels.signal.admins.find((u) => u.phoneNumber === phoneNumber);+}++export function findSignalApprovedUser(config: MercuryConfig, phoneNumber: string): SignalAccessUser | undefined {+ return getSignalApprovedUsers(config).find((u) => u.phoneNumber === phoneNumber);+}++export function findSignalPendingRequest(config: MercuryConfig, phoneNumber: string): SignalPendingRequest | undefined {+ return config.channels.signal.pending.find((r) => r.phoneNumber === phoneNumber);+}++export function findSignalPendingRequestByPairingCode(config: MercuryConfig, pairingCode: string): SignalPendingRequest | undefined {+ return config.channels.signal.pending.find((r) => r.pairingCode === pairingCode);+}++export function hasSignalAdmins(config: MercuryConfig): boolean {+ return config.channels.signal.admins.length > 0;+}++export function getSignalAccessSummary(config: MercuryConfig): string {+ return `${config.channels.signal.admins.length} admin${config.channels.signal.admins.length === 1 ? '' : 's'}, `+ + `${config.channels.signal.members.length} member${config.channels.signal.members.length === 1 ? '' : 's'}, `+ + `${config.channels.signal.pending.length} pending`;+}++export function addSignalPendingRequest(+ config: MercuryConfig,+ request: Omit<SignalPendingRequest, 'requestedAt'> & { requestedAt?: string },+): SignalPendingRequest {+ const existing = findSignalPendingRequest(config, request.phoneNumber);+ if (existing) {+ existing.pairingCode = request.pairingCode || existing.pairingCode;+ if (request.uuid) existing.uuid = request.uuid;+ if (request.name) existing.name = request.name;+ return existing;+ }++ const created: SignalPendingRequest = {+ ...request,+ requestedAt: request.requestedAt || new Date().toISOString(),+ };+ config.channels.signal.pending.push(created);+ return created;+}++export function approveSignalPendingRequest(+ config: MercuryConfig,+ phoneNumber: string,+ role: 'admin' | 'member' = 'member',+): SignalAccessUser | null {+ const request = findSignalPendingRequest(config, phoneNumber);+ if (!request) return null;++ const approvedUser: SignalAccessUser = {+ phoneNumber: request.phoneNumber,+ role,+ pairedAt: new Date().toISOString(),+ };++ config.channels.signal.pending = config.channels.signal.pending+ .filter((r) => r.phoneNumber !== phoneNumber);+ config.channels.signal.admins = config.channels.signal.admins+ .filter((u) => u.phoneNumber !== phoneNumber);+ config.channels.signal.members = config.channels.signal.members+ .filter((u) => u.phoneNumber !== phoneNumber);++ if (role === 'admin') {+ config.channels.signal.admins.push(approvedUser);+ } else {+ config.channels.signal.members.push(approvedUser);+ }++ return approvedUser;+}++export function approveSignalPendingRequestByPairingCode(+ config: MercuryConfig,+ pairingCode: string,+): SignalAccessUser | null {+ const request = findSignalPendingRequestByPairingCode(config, pairingCode);+ if (!request) return null;+ const role = hasSignalAdmins(config) ? 'member' : 'admin';+ return approveSignalPendingRequest(config, request.phoneNumber, role);+}++export function rejectSignalPendingRequest(config: MercuryConfig, phoneNumber: string): SignalPendingRequest | null {+ const request = findSignalPendingRequest(config, phoneNumber);+ if (!request) return null;+ config.channels.signal.pending = config.channels.signal.pending+ .filter((r) => r.phoneNumber !== phoneNumber);+ return request;+}++export function clearSignalAccess(config: MercuryConfig): MercuryConfig {+ config.channels.signal.admins = [];+ config.channels.signal.members = [];+ config.channels.signal.pending = [];+ delete config.channels.signal.groupId;+ delete config.channels.signal.groupName;+ return config;+}++export function migrateLegacySignalAccess(config: MercuryConfig): MercuryConfig {+ const signal = config.channels.signal;+ if (!signal) return config;+ signal.admins = signal.admins || [];+ signal.members = signal.members || [];+ signal.pending = signal.pending || [];+ return config;+}++// ── Discord access helpers ────────────────────────────────────────++export function getDiscordApprovedUsers(config: MercuryConfig): DiscordAccessUser[] {+ return [...config.channels.discord.admins, ...config.channels.discord.members];+}++export function getDiscordAdmins(config: MercuryConfig): DiscordAccessUser[] {+ return config.channels.discord.admins;+}++export function getDiscordPendingRequests(config: MercuryConfig): DiscordPendingRequest[] {+ return config.channels.discord.pending;+}++export function findDiscordApprovedUser(config: MercuryConfig, userId: string): DiscordAccessUser | undefined {+ return getDiscordApprovedUsers(config).find((u) => u.userId === userId);+}++export function findDiscordAdmin(config: MercuryConfig, userId: string): DiscordAccessUser | undefined {+ return config.channels.discord.admins.find((u) => u.userId === userId);+}++export function findDiscordPendingRequest(config: MercuryConfig, userId: string): DiscordPendingRequest | undefined {+ return config.channels.discord.pending.find((r) => r.userId === userId);+}++export function findDiscordPendingRequestByPairingCode(config: MercuryConfig, pairingCode: string): DiscordPendingRequest | undefined {+ return config.channels.discord.pending.find((r) => r.pairingCode === pairingCode);+}++export function hasDiscordAdmins(config: MercuryConfig): boolean {+ return config.channels.discord.admins.length > 0;+}++export function getDiscordAccessSummary(config: MercuryConfig): string {+ return `${config.channels.discord.admins.length} admin${config.channels.discord.admins.length === 1 ? '' : 's'}, `+ + `${config.channels.discord.members.length} member${config.channels.discord.members.length === 1 ? '' : 's'}, `+ + `${config.channels.discord.pending.length} pending`;+}++export function addDiscordPendingRequest(+ config: MercuryConfig,+ request: Omit<DiscordPendingRequest, 'requestedAt'> & { requestedAt?: string },+): DiscordPendingRequest {+ const existing = findDiscordPendingRequest(config, request.userId);+ if (existing) {+ existing.username = request.username || existing.username;+ existing.displayName = request.displayName || existing.displayName;+ existing.pairingCode = request.pairingCode || existing.pairingCode;+ return existing;+ }++ const created: DiscordPendingRequest = {+ ...request,+ requestedAt: request.requestedAt || new Date().toISOString(),+ };+ config.channels.discord.pending.push(created);+ return created;+}++export function approveDiscordPendingRequest(+ config: MercuryConfig,+ userId: string,+ role: 'admin' | 'member' = 'member',+): DiscordAccessUser | null {+ const request = findDiscordPendingRequest(config, userId);+ if (!request) return null;++ const approvedUser: DiscordAccessUser = {+ userId: request.userId,+ username: request.username,+ displayName: request.displayName,+ role,+ approvedAt: new Date().toISOString(),+ };++ config.channels.discord.pending = config.channels.discord.pending+ .filter((r) => r.userId !== userId);+ config.channels.discord.admins = config.channels.discord.admins+ .filter((u) => u.userId !== userId);+ config.channels.discord.members = config.channels.discord.members+ .filter((u) => u.userId !== userId);++ if (role === 'admin') {+ config.channels.discord.admins.push(approvedUser);+ } else {+ config.channels.discord.members.push(approvedUser);+ }++ return approvedUser;+}++export function approveDiscordPendingRequestByPairingCode(+ config: MercuryConfig,+ pairingCode: string,+): DiscordAccessUser | null {+ const request = findDiscordPendingRequestByPairingCode(config, pairingCode);+ if (!request) return null;+ const role = hasDiscordAdmins(config) ? 'member' : 'admin';+ return approveDiscordPendingRequest(config, request.userId, role);+}++export function rejectDiscordPendingRequest(config: MercuryConfig, userId: string): DiscordPendingRequest | null {+ const request = findDiscordPendingRequest(config, userId);+ if (!request) return null;+ config.channels.discord.pending = config.channels.discord.pending+ .filter((r) => r.userId !== userId);+ return request;+}++export function removeDiscordUser(config: MercuryConfig, userId: string): DiscordAccessUser | null {+ const admin = config.channels.discord.admins.find((u) => u.userId === userId);+ if (admin) {+ config.channels.discord.admins = config.channels.discord.admins+ .filter((u) => u.userId !== userId);+ return admin;+ }++ const member = config.channels.discord.members.find((u) => u.userId === userId);+ if (member) {+ config.channels.discord.members = config.channels.discord.members+ .filter((u) => u.userId !== userId);+ return member;+ }++ return null;+}++export function promoteDiscordUserToAdmin(config: MercuryConfig, userId: string): DiscordAccessUser | null {+ const member = config.channels.discord.members.find((u) => u.userId === userId);+ if (!member) return null;+ config.channels.discord.members = config.channels.discord.members+ .filter((u) => u.userId !== userId);+ config.channels.discord.admins.push(member);+ return member;+}++export function demoteDiscordAdmin(config: MercuryConfig, userId: string): DiscordAccessUser | null {+ if (config.channels.discord.admins.length <= 1) {+ return null;+ }++ const admin = config.channels.discord.admins.find((u) => u.userId === userId);+ if (!admin) return null;+ config.channels.discord.admins = config.channels.discord.admins+ .filter((u) => u.userId !== userId);+ config.channels.discord.members.push(admin);+ return admin;+}++export function clearDiscordAccess(config: MercuryConfig): MercuryConfig {+ config.channels.discord.admins = [];+ config.channels.discord.members = [];+ config.channels.discord.pending = [];+ return config;+}++export function migrateLegacyDiscordAccess(config: MercuryConfig): MercuryConfig {+ const discord = config.channels.discord;+ if (!discord) return config;+ discord.admins = discord.admins || [];+ discord.members = discord.members || [];+ discord.pending = discord.pending || [];+ return config;+}++// ── Slack access helpers ──────────────────────────────────────────++export function getSlackApprovedUsers(config: MercuryConfig): SlackAccessUser[] {+ return [...config.channels.slack.admins, ...config.channels.slack.members];+}++export function getSlackAdmins(config: MercuryConfig): SlackAccessUser[] {+ return config.channels.slack.admins;+}++export function getSlackPendingRequests(config: MercuryConfig): SlackPendingRequest[] {+ return config.channels.slack.pending;+}++export function findSlackApprovedUser(config: MercuryConfig, userId: string): SlackAccessUser | undefined {+ return getSlackApprovedUsers(config).find((u) => u.userId === userId);+}++export function findSlackAdmin(config: MercuryConfig, userId: string): SlackAccessUser | undefined {+ return config.channels.slack.admins.find((u) => u.userId === userId);+}++export function findSlackPendingRequest(config: MercuryConfig, userId: string): SlackPendingRequest | undefined {+ return config.channels.slack.pending.find((r) => r.userId === userId);+}++export function findSlackPendingRequestByPairingCode(config: MercuryConfig, pairingCode: string): SlackPendingRequest | undefined {+ return config.channels.slack.pending.find((r) => r.pairingCode === pairingCode);+}++export function hasSlackAdmins(config: MercuryConfig): boolean {+ return config.channels.slack.admins.length > 0;+}++export function getSlackAccessSummary(config: MercuryConfig): string {+ return `${config.channels.slack.admins.length} admin${config.channels.slack.admins.length === 1 ? '' : 's'}, `+ + `${config.channels.slack.members.length} member${config.channels.slack.members.length === 1 ? '' : 's'}, `+ + `${config.channels.slack.pending.length} pending`;+}++export function addSlackPendingRequest(+ config: MercuryConfig,+ request: Omit<SlackPendingRequest, 'requestedAt'> & { requestedAt?: string },+): SlackPendingRequest {+ const existing = findSlackPendingRequest(config, request.userId);+ if (existing) {+ existing.userName = request.userName || existing.userName;+ existing.displayName = request.displayName || existing.displayName;+ existing.pairingCode = request.pairingCode || existing.pairingCode;+ return existing;+ }++ const created: SlackPendingRequest = {+ ...request,+ requestedAt: request.requestedAt || new Date().toISOString(),+ };+ config.channels.slack.pending.push(created);+ return created;+}++export function approveSlackPendingRequest(+ config: MercuryConfig,+ userId: string,+ role: 'admin' | 'member' = 'member',+): SlackAccessUser | null {+ const request = findSlackPendingRequest(config, userId);+ if (!request) return null;++ const approvedUser: SlackAccessUser = {+ userId: request.userId,+ userName: request.userName,+ displayName: request.displayName,+ role,+ approvedAt: new Date().toISOString(),+ };++ config.channels.slack.pending = config.channels.slack.pending+ .filter((r) => r.userId !== userId);+ config.channels.slack.admins = config.channels.slack.admins+ .filter((u) => u.userId !== userId);+ config.channels.slack.members = config.channels.slack.members+ .filter((u) => u.userId !== userId);++ if (role === 'admin') {+ config.channels.slack.admins.push(approvedUser);+ } else {+ config.channels.slack.members.push(approvedUser);+ }++ return approvedUser;+}++export function approveSlackPendingRequestByPairingCode(+ config: MercuryConfig,+ pairingCode: string,+): SlackAccessUser | null {+ const request = findSlackPendingRequestByPairingCode(config, pairingCode);+ if (!request) return null;+ const role = hasSlackAdmins(config) ? 'member' : 'admin';+ return approveSlackPendingRequest(config, request.userId, role);+}++export function rejectSlackPendingRequest(config: MercuryConfig, userId: string): SlackPendingRequest | null {+ const request = findSlackPendingRequest(config, userId);+ if (!request) return null;+ config.channels.slack.pending = config.channels.slack.pending+ .filter((r) => r.userId !== userId);+ return request;+}++export function removeSlackUser(config: MercuryConfig, userId: string): SlackAccessUser | null {+ const admin = config.channels.slack.admins.find((u) => u.userId === userId);+ if (admin) {+ config.channels.slack.admins = config.channels.slack.admins+ .filter((u) => u.userId !== userId);+ return admin;+ }++ const member = config.channels.slack.members.find((u) => u.userId === userId);+ if (member) {+ config.channels.slack.members = config.channels.slack.members+ .filter((u) => u.userId !== userId);+ return member;+ }++ return null;+}++export function promoteSlackUserToAdmin(config: MercuryConfig, userId: string): SlackAccessUser | null {+ const member = config.channels.slack.members.find((u) => u.userId === userId);+ if (!member) return null;+ config.channels.slack.members = config.channels.slack.members+ .filter((u) => u.userId !== userId);+ config.channels.slack.admins.push(member);+ return member;+}++export function demoteSlackAdmin(config: MercuryConfig, userId: string): SlackAccessUser | null {+ if (config.channels.slack.admins.length <= 1) {+ return null;+ }++ const admin = config.channels.slack.admins.find((u) => u.userId === userId);+ if (!admin) return null;+ config.channels.slack.admins = config.channels.slack.admins+ .filter((u) => u.userId !== userId);+ config.channels.slack.members.push(admin);+ return admin;+}++export function clearSlackAccess(config: MercuryConfig): MercuryConfig {+ config.channels.slack.admins = [];+ config.channels.slack.members = [];+ config.channels.slack.pending = [];+ return config;+}++export function migrateLegacySlackAccess(config: MercuryConfig): MercuryConfig {+ const slack = config.channels.slack;+ if (!slack) return config;+ slack.admins = slack.admins || [];+ slack.members = slack.members || [];+ slack.pending = slack.pending || [];+ return config;+}diff --git a/src/utils/discord-access.test.ts b/src/utils/discord-access.test.tsnew file mode 100644index 00000000..eb0a7f66--- /dev/null+++ b/src/utils/discord-access.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest';+import {+ addDiscordPendingRequest,+ approveDiscordPendingRequest,+ approveDiscordPendingRequestByPairingCode,+ clearDiscordAccess,+ findDiscordPendingRequestByPairingCode,+ getDefaultConfig,+ getDiscordAccessSummary,+ migrateLegacyDiscordAccess,+ promoteDiscordUserToAdmin,+ demoteDiscordAdmin,+ rejectDiscordPendingRequest,+ removeDiscordUser,+} from './config.js';++describe('discord access config helpers', () => {+ it('migrates legacy Discord access with missing arrays', () => {+ const config = getDefaultConfig();+ config.channels.discord.admins = undefined as any;+ config.channels.discord.members = undefined as any;+ config.channels.discord.pending = undefined as any;++ migrateLegacyDiscordAccess(config);++ expect(config.channels.discord.admins).toEqual([]);+ expect(config.channels.discord.members).toEqual([]);+ expect(config.channels.discord.pending).toEqual([]);+ });++ it('approves pending requests and reports summary counts', () => {+ const config = getDefaultConfig();+ addDiscordPendingRequest(config, { userId: '111', username: 'alpha', displayName: 'Alpha', pairingCode: 'ABC123' });+ addDiscordPendingRequest(config, { userId: '222', username: 'beta' });++ expect(findDiscordPendingRequestByPairingCode(config, 'ABC123')?.userId).toBe('111');+ const admin = approveDiscordPendingRequestByPairingCode(config, 'ABC123');+ const member = approveDiscordPendingRequest(config, '222', 'member');++ expect(admin?.userId).toBe('111');+ expect(member?.userId).toBe('222');+ expect(getDiscordAccessSummary(config)).toBe('1 admin, 1 member, 0 pending');+ });++ it('supports reject, remove, promote, and demote flows', () => {+ const config = getDefaultConfig();+ addDiscordPendingRequest(config, { userId: '111', username: 'alpha' });+ addDiscordPendingRequest(config, { userId: '222', username: 'beta' });+ addDiscordPendingRequest(config, { userId: '333', username: 'gamma' });++ approveDiscordPendingRequest(config, '111', 'admin');+ approveDiscordPendingRequest(config, '222', 'member');+ expect(rejectDiscordPendingRequest(config, '333')?.userId).toBe('333');++ expect(promoteDiscordUserToAdmin(config, '222')?.userId).toBe('222');+ expect(demoteDiscordAdmin(config, '111')?.userId).toBe('111');+ expect(removeDiscordUser(config, '111')?.userId).toBe('111');++ expect(config.channels.discord.admins).toHaveLength(1);+ expect(config.channels.discord.members).toHaveLength(0);+ expect(config.channels.discord.pending).toHaveLength(0);+ });++ it('does not demote the last admin', () => {+ const config = getDefaultConfig();+ addDiscordPendingRequest(config, { userId: '111', username: 'solo' });+ approveDiscordPendingRequest(config, '111', 'admin');++ expect(demoteDiscordAdmin(config, '111')).toBeNull();+ });++ it('clears all Discord access state', () => {+ const config = getDefaultConfig();+ addDiscordPendingRequest(config, { userId: '111', username: 'alpha' });+ approveDiscordPendingRequest(config, '111', 'admin');++ clearDiscordAccess(config);++ expect(config.channels.discord.admins).toEqual([]);+ expect(config.channels.discord.members).toEqual([]);+ expect(config.channels.discord.pending).toEqual([]);+ });+});\ No newline at end of filediff --git a/src/utils/manual.ts b/src/utils/manual.tsindex fe71c3eb..8d855d85 100644--- a/src/utils/manual.ts+++ b/src/utils/manual.ts@@ -85,6 +85,10 @@ export function getManual(): string {['mercury telegram promote <id>', 'Promote a Telegram member to admin'],['mercury telegram demote <id>', 'Demote a Telegram admin to member'],['mercury telegram unpair', 'Reset all Telegram access'],+ ['mercury signal approve <code>', 'Approve a Signal pairing code'],+ ['mercury signal unpair', 'Reset all Signal access'],+ ['mercury signal reset', 'Full reset: clear access, delete binary, unlink device'],+ ['mercury signal status', 'Show Signal configuration and connection status'],['mercury help', 'Show this manual'],['mercury service install', 'Install as system service (auto-start)'],['mercury service uninstall', 'Uninstall system service'],@@ -336,3 +340,79 @@ export function getTelegramHelp(): string {return lines.join('\n');}++export function getDiscordHelp(): string {+ const lines: string[] = [];++ lines.push('\u263f **Mercury \u2014 Discord Commands**');+ lines.push('');+ lines.push('**Guild Channels**');+ lines.push('All guild members can chat in configured channels.');+ lines.push('Admins (guild owner + "Mercury Admin" role) control permissions.');+ lines.push('');++ lines.push('**General**');+ lines.push('/help \u2014 Show this command list');+ lines.push('/status \u2014 Config, budget, and uptime');+ lines.push('/progress \u2014 Live status for the current task');+ lines.push('/permissions \u2014 Switch Ask Me / Allow All mode');+ lines.push('/models \u2014 List providers or switch AI model');+ lines.push('');++ lines.push('**Budget**');+ lines.push('/budget \u2014 Show token budget status');+ lines.push('/budget override \u2014 Allow one request past budget');+ lines.push('/budget reset \u2014 Reset usage to zero');+ lines.push('/budget set <n> \u2014 Set daily token budget');+ lines.push('');++ lines.push('**Token Saver**');+ lines.push('/saver \u2014 Show saver status and tokens saved');+ lines.push('/saver on \u2014 Manually enable Token Saver Mode');+ lines.push('/saver off \u2014 Disable Token Saver Mode');+ lines.push('/saver toggle \u2014 Toggle on/off');+ lines.push('');++ lines.push('**DM Access**');+ lines.push('/start \u2014 Request DM access (send in a DM)');+ lines.push('/unpair \u2014 Reset all Discord DM access (admin only)');++ return lines.join('\n');+}++export function getSlackHelp(): string {+ const lines: string[] = [];++ lines.push('\u263f **Mercury \u2014 Slack Commands**');+ lines.push('');+ lines.push('**Workspace Channels**');+ lines.push('All workspace members can chat in configured channels.');+ lines.push('Admins control DM access permissions.');+ lines.push('');++ lines.push('**General**');+ lines.push('/mercury help \u2014 Show this command list');+ lines.push('/mercury status \u2014 Config, budget, and uptime');+ lines.push('/mercury stop \u2014 Stop all agents');+ lines.push('');++ lines.push('**Budget**');+ lines.push('/mercury budget \u2014 Show token budget status');+ lines.push('/mercury budget override \u2014 Allow one request past budget');+ lines.push('/mercury budget reset \u2014 Reset usage to zero');+ lines.push('/mercury budget set <n> \u2014 Set daily token budget');+ lines.push('');++ lines.push('**Token Saver**');+ lines.push('/mercury saver \u2014 Show saver status and tokens saved');+ lines.push('/mercury saver on \u2014 Manually enable Token Saver Mode');+ lines.push('/mercury saver off \u2014 Disable Token Saver Mode');+ lines.push('/mercury saver toggle \u2014 Toggle on/off');+ lines.push('');++ lines.push('**DM Access**');+ lines.push('/mercury start \u2014 Request DM access');+ lines.push('/mercury unpair \u2014 Reset all Slack DM access (admin only)');++ return lines.join('\n');+}diff --git a/src/utils/markdown.ts b/src/utils/markdown.tsindex 724f51f7..9a92b675 100644--- a/src/utils/markdown.ts+++ b/src/utils/markdown.ts@@ -229,5 +229,148 @@ export function mdToTelegram(text: string): string {out = out.slice(0, 4090) + '...';}+ return out;+}++export function mdToSignal(text: string): string {+ let out = text;++ const codeBlocks: string[] = [];+ out = out.replace(/```(\w*)\n([\s\S]*?)```/g, (_match, _lang, code) => {+ const placeholder = `__CB_${codeBlocks.length}__`;+ codeBlocks.push(code.trim());+ return placeholder;+ });++ const inlineCodes: string[] = [];+ out = out.replace(/`([^`]+)`/g, (_match, code) => {+ const placeholder = `__IC_${inlineCodes.length}__`;+ inlineCodes.push(code);+ return placeholder;+ });++ const links: string[] = [];+ out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, label, href) => {+ const placeholder = `__LK_${links.length}__`;+ links.push(`${label} (${href})`);+ return placeholder;+ });++ out = out.replace(/^### (.+)$/gm, '*$1*');+ out = out.replace(/^## (.+)$/gm, '*$1*');+ out = out.replace(/^# (.+)$/gm, '*$1*');+ out = out.replace(/\*\*([^*]+)\*\*/g, '*$1*');+ out = out.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '_$1_');+ out = out.replace(/~~([^~]+)~~/g, '~$1~');++ for (let i = 0; i < inlineCodes.length; i++) {+ out = out.replace(`__IC_${i}__`, inlineCodes[i]);+ }+ for (let i = 0; i < codeBlocks.length; i++) {+ out = out.replace(`__CB_${i}__`, codeBlocks[i]);+ }+ for (let i = 0; i < links.length; i++) {+ out = out.replace(`__LK_${i}__`, links[i]);+ }++ if (out.length > 4000) {+ out = out.slice(0, 3990) + '...';+ }++ return out;+}++export function mdToDiscord(text: string): string {+ let out = text;++ const codeBlocks: string[] = [];+ out = out.replace(/```(\w*)\n([\s\S]*?)```/g, (_match, lang, code) => {+ const placeholder = `__DCB_${codeBlocks.length}__`;+ codeBlocks.push(`\`\`\`${lang}\n${code.trim()}\n\`\`\``);+ return placeholder;+ });++ const inlineCodes: string[] = [];+ out = out.replace(/`([^`]+)`/g, (_match, code) => {+ const placeholder = `__DIC_${inlineCodes.length}__`;+ inlineCodes.push(`\`${code}\``);+ return placeholder;+ });++ const links: string[] = [];+ out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, label, href) => {+ const placeholder = `__DLK_${links.length}__`;+ links.push(`[${label}](${href})`);+ return placeholder;+ });++ out = out.replace(/^### (.+)$/gm, '__$1__');+ out = out.replace(/^## (.+)$/gm, '**$1**');+ out = out.replace(/^# (.+)$/gm, '**$1**');+ out = out.replace(/~~([^~]+)~~/g, '~~$1~~');++ for (let i = 0; i < inlineCodes.length; i++) {+ out = out.replace(`__DIC_${i}__`, inlineCodes[i]);+ }+ for (let i = 0; i < codeBlocks.length; i++) {+ out = out.replace(`__DCB_${i}__`, codeBlocks[i]);+ }+ for (let i = 0; i < links.length; i++) {+ out = out.replace(`__DLK_${i}__`, links[i]);+ }++ if (out.length > 2000) {+ out = out.slice(0, 1990) + '...';+ }++ return out;+}++export function mdToSlack(text: string): string {+ let out = text;++ const codeBlocks: string[] = [];+ out = out.replace(/```(\w*)\n([\s\S]*?)```/g, (_match, lang, code) => {+ const placeholder = `__SCB_${codeBlocks.length}__`;+ codeBlocks.push(`\`\`\`${lang}\n${code.trim()}\n\`\`\``);+ return placeholder;+ });++ const inlineCodes: string[] = [];+ out = out.replace(/`([^`]+)`/g, (_match, code) => {+ const placeholder = `__SIC_${inlineCodes.length}__`;+ inlineCodes.push(`\`${code}\``);+ return placeholder;+ });++ const links: string[] = [];+ out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, label, href) => {+ const placeholder = `__SLK_${links.length}__`;+ links.push(`<${href}|${label}>`);+ return placeholder;+ });++ out = out.replace(/^### (.+)$/gm, '*$1*');+ out = out.replace(/^## (.+)$/gm, '*$1*');+ out = out.replace(/^# (.+)$/gm, '*$1*');+ out = out.replace(/\*\*([^*]+)\*\*/g, '*$1*');+ out = out.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '_$1_');+ out = out.replace(/~~([^~]+)~~/g, '~$1~');+ out = out.replace(/^- /gm, '• ');++ for (let i = 0; i < inlineCodes.length; i++) {+ out = out.replace(`__SIC_${i}__`, inlineCodes[i]);+ }+ for (let i = 0; i < codeBlocks.length; i++) {+ out = out.replace(`__SCB_${i}__`, codeBlocks[i]);+ }+ for (let i = 0; i < links.length; i++) {+ out = out.replace(`__SLK_${i}__`, links[i]);+ }++ if (out.length > 40000) {+ out = out.slice(0, 39990) + '...';+ }+return out;}\ No newline at end of filediff --git a/src/utils/redact.ts b/src/utils/redact.tsnew file mode 100644index 00000000..6783acbe--- /dev/null+++ b/src/utils/redact.ts@@ -0,0 +1,19 @@+export function redactPhone(phone: string): string {+ if (!phone || phone.length < 6) return '***';+ const visible = phone.slice(0, 4);+ const end = phone.slice(-2);+ return `${visible}***${end}`;+}++export function redactUuid(uuid: string): string {+ if (!uuid || uuid.length < 8) return '***';+ return `${uuid.slice(0, 4)}***`;+}++export function redactIdentity(phone: string, uuid?: string): string {+ const phonePart = redactPhone(phone);+ if (uuid) {+ return `${phonePart} (${redactUuid(uuid)})`;+ }+ return phonePart;+}\ No newline at end of filediff --git a/src/utils/slack-access.test.ts b/src/utils/slack-access.test.tsnew file mode 100644index 00000000..24547dd2--- /dev/null+++ b/src/utils/slack-access.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from 'vitest';+import {+ addSlackPendingRequest,+ approveSlackPendingRequest,+ clearSlackAccess,+ getDefaultConfig,+ getSlackAccessSummary,+ migrateLegacySlackAccess,+ promoteSlackUserToAdmin,+ demoteSlackAdmin,+ rejectSlackPendingRequest,+ removeSlackUser,+} from './config.js';++describe('slack access config helpers', () => {+ it('migrates legacy Slack access with missing arrays', () => {+ const config = getDefaultConfig();+ config.channels.slack.admins = undefined as any;+ config.channels.slack.members = undefined as any;+ config.channels.slack.pending = undefined as any;++ migrateLegacySlackAccess(config);++ expect(config.channels.slack.admins).toEqual([]);+ expect(config.channels.slack.members).toEqual([]);+ expect(config.channels.slack.pending).toEqual([]);+ });++ it('approves pending requests as admin or member and reports summary counts', () => {+ const config = getDefaultConfig();+ addSlackPendingRequest(config, { userId: 'U111', userName: 'alpha', displayName: 'Alpha' });+ addSlackPendingRequest(config, { userId: 'U222', userName: 'beta' });++ const admin = approveSlackPendingRequest(config, 'U111', 'admin');+ const member = approveSlackPendingRequest(config, 'U222', 'member');++ expect(admin?.userId).toBe('U111');+ expect(admin?.role).toBe('admin');+ expect(member?.userId).toBe('U222');+ expect(member?.role).toBe('member');+ expect(getSlackAccessSummary(config)).toBe('1 admin, 1 member, 0 pending');+ });++ it('supports reject, remove, promote, and demote flows', () => {+ const config = getDefaultConfig();+ addSlackPendingRequest(config, { userId: 'U111', userName: 'alpha' });+ addSlackPendingRequest(config, { userId: 'U222', userName: 'beta' });+ addSlackPendingRequest(config, { userId: 'U333', userName: 'gamma' });++ approveSlackPendingRequest(config, 'U111', 'admin');+ approveSlackPendingRequest(config, 'U222', 'member');+ expect(rejectSlackPendingRequest(config, 'U333')?.userId).toBe('U333');++ expect(promoteSlackUserToAdmin(config, 'U222')?.userId).toBe('U222');+ expect(demoteSlackAdmin(config, 'U111')?.userId).toBe('U111');+ expect(removeSlackUser(config, 'U111')?.userId).toBe('U111');++ expect(config.channels.slack.admins).toHaveLength(1);+ expect(config.channels.slack.members).toHaveLength(0);+ expect(config.channels.slack.pending).toHaveLength(0);+ });++ it('does not demote the last admin', () => {+ const config = getDefaultConfig();+ addSlackPendingRequest(config, { userId: 'U111', userName: 'solo' });+ approveSlackPendingRequest(config, 'U111', 'admin');++ expect(demoteSlackAdmin(config, 'U111')).toBeNull();+ });++ it('clears all Slack access state', () => {+ const config = getDefaultConfig();+ addSlackPendingRequest(config, { userId: 'U111', userName: 'alpha' });+ approveSlackPendingRequest(config, 'U111', 'admin');++ clearSlackAccess(config);++ expect(config.channels.slack.admins).toEqual([]);+ expect(config.channels.slack.members).toEqual([]);+ expect(config.channels.slack.pending).toEqual([]);+ });+});\ No newline at end of filediff --git a/src/web/api/auth.ts b/src/web/api/auth.tsindex b42ea39d..78a755c6 100644--- a/src/web/api/auth.ts+++ b/src/web/api/auth.ts@@ -3,10 +3,18 @@ import { setCookie, getCookie, deleteCookie } from 'hono/cookie';import { existsSync, readFileSync } from 'fs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';+import process from 'node:process';import { authenticate, createSession, destroySession, changePassword, changeUsername, getSessionCookieName, getSessionMaxAge } from '../auth.js';-const __authDir = dirname(fileURLToPath(import.meta.url));-const spaLoginIndex = join(__authDir, 'web', 'ui', 'index.html');+function resolveWebDir(...segments: string[]): string {+ const __dirname = dirname(fileURLToPath(import.meta.url));+ if (typeof (process.versions as any).bun === 'string' && __dirname.includes('$bunfs')) {+ return join(dirname(process.execPath), ...segments);+ }+ return join(__dirname, ...segments);+}++const spaLoginIndex = resolveWebDir('web', 'ui', 'index.html');function renderLoginPage(error?: string): string {return `<!DOCTYPE html>diff --git a/src/web/api/brain-fallback.ts b/src/web/api/brain-fallback.tsindex cadfe5d5..7972545a 100644--- a/src/web/api/brain-fallback.ts+++ b/src/web/api/brain-fallback.ts@@ -1,8 +1,19 @@import { readFileSync, existsSync } from 'node:fs';import { join, dirname } from 'node:path';import { fileURLToPath } from 'node:url';+import process from 'node:process';import { getMemoryDir } from '../../utils/config.js';+function resolveAssetPath(...segments: string[]): string {+ const __dirname = dirname(fileURLToPath(import.meta.url));+ // When running as a Bun --compile standalone binary, __dirname points to+ // Bun's virtual filesystem ($bunfs). Resolve assets relative to the binary.+ if (typeof (process.versions as any).bun === 'string' && __dirname.includes('$bunfs')) {+ return join(dirname(process.execPath), ...segments);+ }+ return join(__dirname, ...segments);+}+let sqlJsModule: any = null;let dbInstance: any = null;let dbPath: string = '';@@ -14,7 +25,7 @@ async function getDb(): Promise<any> {try {if (!sqlJsModule) {const initSqlJs = (await import('sql.js')).default;- const wasmPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'web', 'static', 'vendor', 'sql-wasm.wasm');+ const wasmPath = resolveAssetPath('web', 'static', 'vendor', 'sql-wasm.wasm');sqlJsModule = await initSqlJs(existsSync(wasmPath)? { locateFile: (f: string) => existsSync(wasmPath) ? wasmPath : f }: undefined);diff --git a/src/web/server.ts b/src/web/server.tsindex b26bcba9..53bee61e 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -23,8 +23,23 @@ import { isBetterSqlite3Available } from '../memory/second-brain-db.js';const app = new Hono();const __dirname = dirname(fileURLToPath(import.meta.url));-const staticDir = process.env.MERCURY_WEB_STATIC || join(__dirname, 'web', 'static');-const uiDir = process.env.MERCURY_UI_DIR || join(__dirname, 'web', 'ui');++function resolveWebDir(subpath: string): string {+ const envVar = subpath === 'static' ? process.env.MERCURY_WEB_STATIC : process.env.MERCURY_UI_DIR;+ if (envVar) return envVar;++ // When running as a Bun --compile standalone binary, __dirname points to+ // Bun's virtual filesystem ($bunfs). The web assets are shipped alongside+ // the binary in a `web/` directory, so resolve relative to the binary itself.+ if (typeof (process.versions as any).bun === 'string' && __dirname.includes('$bunfs')) {+ return join(dirname(process.execPath), 'web', subpath);+ }++ return join(__dirname, 'web', subpath);+}++const staticDir = resolveWebDir('static');+const uiDir = resolveWebDir('ui');const MIME_TYPES: Record<string, string> = {css: 'text/css',@@ -169,7 +184,7 @@ if (spaAvailable) {// React SPA not built — return helpful message for all routesapp.get('*', (c) => {if (c.req.path.startsWith('/api/')) return c.notFound();- return c.text('Mercury React UI not built. Run: cd ui && npm install && npm run build', 500);+ return c.text('Mercury web UI not found. If running from source, run: npm run build\nIf running a standalone binary, ensure the web/ directory is next to the binary.', 500);});}