Compare commits

..

2 Commits

Author SHA1 Message Date
Kenneth Lien
3d8042f259 Silently return when bot.stop() aborts the setup phase
If bot.stop() is called while bot.start() is still in setup (deleteWebhook/
getMe), grammy rejects with 'Aborted delay'. Expected, not an error.
2026-03-20 11:07:05 -07:00
Kenneth Lien
1daff5f224 telegram: retry on 409 Conflict instead of crashing
During /mcp reload or when a zombie from a previous session still holds
the polling slot, the new process gets 409 Conflict on its first
getUpdates and dies immediately. Retry with backoff until the slot
frees — typically within a second or two.

Also handles the two-sessions case: the second Claude Code instance
keeps retrying (with a clear message about what's happening) and takes
over when the first one exits.

Fixes #804 #794, partial #788 (issue 4)
2026-03-20 10:55:27 -07:00
6 changed files with 51 additions and 53 deletions

View File

@@ -1,20 +1,11 @@
{
"name": "discord",
"description": "Discord channel for Claude Code messaging bridge with built-in access control. Manage pairing, allowlists, and policy via /discord:access.",
"version": "0.0.2",
"description": "Discord channel for Claude Code \u2014 messaging bridge with built-in access control. Manage pairing, allowlists, and policy via /discord:access.",
"version": "0.0.1",
"keywords": [
"discord",
"messaging",
"channel",
"mcp"
],
"userConfig": {
"DISCORD_BOT_TOKEN": {
"type": "string",
"title": "Bot Token",
"description": "Bot token from the Discord Developer Portal. Stored in keychain (macOS) or ~/.claude/.credentials.json with 0600 permissions elsewhere. Never written to settings.json.",
"required": true,
"sensitive": true
}
}
]
}

View File

@@ -2,10 +2,7 @@
"mcpServers": {
"discord": {
"command": "bun",
"args": ["run", "--cwd", "${CLAUDE_PLUGIN_ROOT}", "--shell=bun", "--silent", "start"],
"env": {
"DISCORD_BOT_TOKEN": "${user_config.DISCORD_BOT_TOKEN}"
}
"args": ["run", "--cwd", "${CLAUDE_PLUGIN_ROOT}", "--shell=bun", "--silent", "start"]
}
}
}

View File

@@ -34,12 +34,10 @@ const ACCESS_FILE = join(STATE_DIR, 'access.json')
const APPROVED_DIR = join(STATE_DIR, 'approved')
const ENV_FILE = join(STATE_DIR, '.env')
// Token is injected via ${user_config.DISCORD_BOT_TOKEN} from .mcp.json —
// prompted at enable time, stored in keychain (macOS) or .credentials.json 0600
// elsewhere. The .env file below is a legacy fallback for users configured
// before H1 #3617646 — real env wins, so the injected value takes precedence.
// Load ~/.claude/channels/discord/.env into process.env. Real env wins.
// Plugin-spawned servers don't get an env block — this is where the token lives.
try {
// Defensive chmod for legacy .env files (no-op on Windows).
// Token is a credential — lock to owner. No-op on Windows (would need ACLs).
chmodSync(ENV_FILE, 0o600)
for (const line of readFileSync(ENV_FILE, 'utf8').split('\n')) {
const m = line.match(/^(\w+)=(.*)$/)
@@ -53,8 +51,8 @@ const STATIC = process.env.DISCORD_ACCESS_MODE === 'static'
if (!TOKEN) {
process.stderr.write(
`discord channel: DISCORD_BOT_TOKEN required\n` +
` re-enter via: /plugin manage → discord → Configure options\n` +
` (stored in keychain/credentials.json, not settings.json)\n`,
` set in ${ENV_FILE}\n` +
` format: DISCORD_BOT_TOKEN=MTIz...\n`,
)
process.exit(1)
}

View File

@@ -1,20 +1,11 @@
{
"name": "telegram",
"description": "Telegram channel for Claude Code messaging bridge with built-in access control. Manage pairing, allowlists, and policy via /telegram:access.",
"version": "0.0.2",
"description": "Telegram channel for Claude Code \u2014 messaging bridge with built-in access control. Manage pairing, allowlists, and policy via /telegram:access.",
"version": "0.0.1",
"keywords": [
"telegram",
"messaging",
"channel",
"mcp"
],
"userConfig": {
"TELEGRAM_BOT_TOKEN": {
"type": "string",
"title": "Bot Token",
"description": "Bot token from @BotFather — format is 123456789:AAH... Stored in keychain (macOS) or ~/.claude/.credentials.json with 0600 permissions elsewhere. Never written to settings.json.",
"required": true,
"sensitive": true
}
}
]
}

View File

@@ -2,10 +2,7 @@
"mcpServers": {
"telegram": {
"command": "bun",
"args": ["run", "--cwd", "${CLAUDE_PLUGIN_ROOT}", "--shell=bun", "--silent", "start"],
"env": {
"TELEGRAM_BOT_TOKEN": "${user_config.TELEGRAM_BOT_TOKEN}"
}
"args": ["run", "--cwd", "${CLAUDE_PLUGIN_ROOT}", "--shell=bun", "--silent", "start"]
}
}
}

View File

@@ -15,7 +15,7 @@ import {
ListToolsRequestSchema,
CallToolRequestSchema,
} from '@modelcontextprotocol/sdk/types.js'
import { Bot, InputFile, type Context } from 'grammy'
import { Bot, GrammyError, InputFile, type Context } from 'grammy'
import type { ReactionTypeEmoji } from 'grammy/types'
import { randomBytes } from 'crypto'
import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, statSync, renameSync, realpathSync, chmodSync } from 'fs'
@@ -27,12 +27,10 @@ const ACCESS_FILE = join(STATE_DIR, 'access.json')
const APPROVED_DIR = join(STATE_DIR, 'approved')
const ENV_FILE = join(STATE_DIR, '.env')
// Token is injected via ${user_config.TELEGRAM_BOT_TOKEN} from .mcp.json —
// prompted at enable time, stored in keychain (macOS) or .credentials.json 0600
// elsewhere. The .env file below is a legacy fallback for users configured
// before H1 #3617646 — real env wins, so the injected value takes precedence.
// Load ~/.claude/channels/telegram/.env into process.env. Real env wins.
// Plugin-spawned servers don't get an env block — this is where the token lives.
try {
// Defensive chmod for legacy .env files (no-op on Windows).
// Token is a credential — lock to owner. No-op on Windows (would need ACLs).
chmodSync(ENV_FILE, 0o600)
for (const line of readFileSync(ENV_FILE, 'utf8').split('\n')) {
const m = line.match(/^(\w+)=(.*)$/)
@@ -46,8 +44,8 @@ const STATIC = process.env.TELEGRAM_ACCESS_MODE === 'static'
if (!TOKEN) {
process.stderr.write(
`telegram channel: TELEGRAM_BOT_TOKEN required\n` +
` re-enter via: /plugin manage → telegram → Configure options\n` +
` (stored in keychain/credentials.json, not settings.json)\n`,
` set in ${ENV_FILE}\n` +
` format: TELEGRAM_BOT_TOKEN=123456789:AAH...\n`,
)
process.exit(1)
}
@@ -595,9 +593,35 @@ async function handleInbound(
})
}
void bot.start({
onStart: info => {
botUsername = info.username
process.stderr.write(`telegram channel: polling as @${info.username}\n`)
},
})
// 409 Conflict = another getUpdates consumer is still active (zombie from a
// previous session, or a second Claude Code instance). Retry with backoff
// until the slot frees up instead of crashing on the first rejection.
void (async () => {
for (let attempt = 1; ; attempt++) {
try {
await bot.start({
onStart: info => {
botUsername = info.username
process.stderr.write(`telegram channel: polling as @${info.username}\n`)
},
})
return // bot.stop() was called — clean exit from the loop
} catch (err) {
if (err instanceof GrammyError && err.error_code === 409) {
const delay = Math.min(1000 * attempt, 15000)
const detail = attempt === 1
? ' — another instance is polling (zombie session, or a second Claude Code running?)'
: ''
process.stderr.write(
`telegram channel: 409 Conflict${detail}, retrying in ${delay / 1000}s\n`,
)
await new Promise(r => setTimeout(r, delay))
continue
}
// bot.stop() mid-setup rejects with grammy's "Aborted delay" — expected, not an error.
if (err instanceof Error && err.message === 'Aborted delay') return
process.stderr.write(`telegram channel: polling failed: ${err}\n`)
return
}
}
})()