feat: 恢复 --channels 能力 (#297)

* feat: 恢复  --channels 能力

* docs: 添加 channels 注释
This commit is contained in:
claude-code-best
2026-04-19 10:24:34 +08:00
committed by GitHub
parent c5edee431f
commit 481e2a58a9
10 changed files with 319 additions and 479 deletions

View File

@@ -22,6 +22,7 @@
| **Langfuse 监控** | 企业级 Agent 监控, 可以清晰看到每次 agent loop 细节, 可以一键转化为数据集 | [文档](https://ccb.agent-aura.top/docs/features/langfuse-monitoring) |
| **Web Search** | 内置网页搜索工具, 支持 bing 和 brave 搜索 | [文档](https://ccb.agent-aura.top/docs/features/web-browser-tool) |
| **Poor Mode** | 穷鬼模式,关闭记忆提取和键入建议,大幅度减少并发请求 | /poor 可以开关 |
| **Channels 频道通知** | MCP 服务器推送外部消息到会话(飞书/Slack/Discord 等),`--channels plugin:name@marketplace` 启用 | [文档](https://ccb.agent-aura.top/docs/features/channels) |
| **自定义模型供应商** | OpenAI/Anthropic/Gemini/Grok 兼容 | [文档](https://ccb.agent-aura.top/docs/features/custom-platform-login) |
| Voice Mode | Push-to-Talk 语音输入 | [文档](https://ccb.agent-aura.top/docs/features/voice-mode) |
| Computer Use | 屏幕截图、键鼠控制 | [文档](https://ccb.agent-aura.top/docs/features/computer-use) |

52
docs/features/channels.md Normal file
View File

@@ -0,0 +1,52 @@
# Channels — 外部频道消息接入
> 启动参数:`--channels` / `--dangerously-load-development-channels`
> 状态:已解除 feature flag 和 OAuth 限制,可直接使用
## 概述
Channel 是一个 MCP 服务器,它将外部事件推送到你运行中的 Claude Code 会话中,以便 Claude 可以在你不在终端时做出反应。详细使用说明请参考以下文档:
- **官方文档**[使用 channels 将事件推送到运行中的会话](https://code.claude.com/docs/zh-CN/channels)
- **飞书插件**[claude-code-feishu-channel](https://github.com/whobot-ai/claude-code-feishu-channel) — 社区首个飞书 Channel 插件,支持双向消息、配对认证、群组聊天、文件附件
## 快速开始
```bash
# 启用频道监听plugin 格式)
ccb --channels plugin:feishu@claude-code-feishu-channel
# 启用频道监听server 格式)
ccb --channels server:my-slack-bridge
# 同时启用多个频道
ccb --channels plugin:feishu@claude-code-feishu-channel --channels server:discord-bot
# 开发模式(跳过 allowlist 检查,用于测试自定义 channel
ccb --dangerously-load-development-channels server:my-custom-channel
```
## 支持的 Channel
| Channel | 说明 | 来源 |
|---------|------|------|
| **Telegram** | 官方 Telegram Bot 集成 | `/plugin install telegram@claude-plugins-official` |
| **Discord** | 官方 Discord Bot 集成 | `/plugin install discord@claude-plugins-official` |
| **iMessage** | macOS 原生消息 | `/plugin install imessage@claude-plugins-official` |
| **飞书 (Feishu/Lark)** | 双向消息、群组聊天、文件附件 | `/plugin install feishu@claude-code-feishu-channel` |
## 相关文件
| 文件 | 职责 |
|------|------|
| `src/services/mcp/channelNotification.ts` | 频道 gate 逻辑、消息包装 |
| `src/services/mcp/channelAllowlist.ts` | 频道开关(已默认开启) |
| `src/services/mcp/useManageMCPConnections.ts` | MCP 连接管理中的频道注册 |
| `src/components/LogoV2/ChannelsNotice.tsx` | 启动时频道状态提示 |
| `src/main.tsx` | `--channels` 参数解析 |
| `src/interactiveHelpers.tsx` | Dev channels 确认对话框 |
## 参考链接
- [官方 Channels 文档](https://code.claude.com/docs/zh-CN/channels) — 完整使用说明、安全性、Enterprise 控制
- [飞书 Channel 插件](https://github.com/whobot-ai/claude-code-feishu-channel) — 安装配置教程、MCP 工具、Skill 命令参考

View File

@@ -135,6 +135,7 @@
"group": "运行模式",
"pages": [
"docs/features/kairos",
"docs/features/channels",
"docs/features/voice-mode",
"docs/features/bridge-mode",
"docs/features/remote-control-self-hosting",

View File

@@ -4948,7 +4948,7 @@ function handleChannelEnable(
function reregisterChannelHandlerAfterReconnect(
connection: MCPServerConnection,
): void {
if (!(feature('KAIROS') || feature('KAIROS_CHANNELS'))) return
// Channels always available — feature flag guard removed
if (connection.type !== 'connected') return
const gate = gateChannelServer(

View File

@@ -12,50 +12,27 @@ import {
getHasDevChannels,
} from '../../bootstrap/state.js'
import { Box, Text } from '@anthropic/ink'
import { isChannelsEnabled } from '../../services/mcp/channelAllowlist.js'
import { getEffectiveChannelAllowlist } from '../../services/mcp/channelNotification.js'
import { getMcpConfigsByScope } from '../../services/mcp/config.js'
import {
getClaudeAIOAuthTokens,
getSubscriptionType,
} from '../../utils/auth.js'
import { loadInstalledPluginsV2 } from '../../utils/plugins/installedPluginsManager.js'
import { getSettingsForSource } from '../../utils/settings/settings.js'
export function ChannelsNotice(): React.ReactNode {
// Snapshot all reads at mount. This notice enters scrollback immediately
// after the logo; any re-render past that point forces a full terminal
// reset. getAllowedChannels (bootstrap state), getSettingsForSource
// (session cache updated by background polling / /login), and
// isChannelsEnabled (GrowthBook 5-min refresh) must be captured once
// so a later re-render cannot flip branches.
const [{ channels, disabled, noAuth, policyBlocked, list, unmatched }] =
// reset.
const [{ channels, list, unmatched }] =
useState(() => {
const ch = getAllowedChannels()
if (ch.length === 0)
return {
channels: ch,
disabled: false,
noAuth: false,
policyBlocked: false,
list: '',
unmatched: [] as Unmatched[],
}
const l = ch.map(formatEntry).join(', ')
const sub = getSubscriptionType()
const managed = sub === 'team' || sub === 'enterprise'
const policy = getSettingsForSource('policySettings')
const allowlist = getEffectiveChannelAllowlist(
sub,
policy?.allowedChannelPlugins,
)
return {
channels: ch,
disabled: !isChannelsEnabled(),
noAuth: !getClaudeAIOAuthTokens()?.accessToken,
policyBlocked: managed && policy?.channelsEnabled !== true,
list: l,
unmatched: findUnmatched(ch, allowlist),
unmatched: findUnmatched(ch),
}
})
if (channels.length === 0) return null
@@ -70,50 +47,6 @@ export function ChannelsNotice(): React.ReactNode {
? '--dangerously-load-development-channels'
: '--channels'
if (disabled) {
return (
<Box paddingLeft={2} flexDirection="column">
<Text color="error">
{flag} ignored ({list})
</Text>
<Text dimColor>Channels are not currently available</Text>
</Box>
)
}
if (noAuth) {
return (
<Box paddingLeft={2} flexDirection="column">
<Text color="error">
{flag} ignored ({list})
</Text>
<Text dimColor>
Channels require claude.ai authentication · run /login, then restart
</Text>
</Box>
)
}
if (policyBlocked) {
return (
<Box paddingLeft={2} flexDirection="column">
<Text color="error">
{flag} blocked by org policy ({list})
</Text>
<Text dimColor>Inbound messages will be silently dropped</Text>
<Text dimColor>
Have an administrator set channelsEnabled: true in managed settings to
enable
</Text>
{unmatched.map(u => (
<Text key={`${formatEntry(u.entry)}:${u.why}`} color="warning">
{formatEntry(u.entry)} · {u.why}
</Text>
))}
</Box>
)
}
// "Listening for" not "active" — at this point we only know the allowlist
// was set. Server connection, capability declaration, and whether the name
// even matches a configured MCP server are all still unknown.
@@ -144,7 +77,6 @@ type Unmatched = { entry: ChannelEntry; why: string }
function findUnmatched(
entries: readonly ChannelEntry[],
allowlist: ReturnType<typeof getEffectiveChannelAllowlist>,
): Unmatched[] {
// Server-kind: build one Set from all scopes up front. getMcpConfigsByScope
// is not cached (project scope walks the dir tree); getMcpConfigByName would
@@ -163,46 +95,17 @@ function findUnmatched(
Object.keys(loadInstalledPluginsV2().plugins),
)
// Plugin-kind allowlist check: same {marketplace, plugin} test as the
// gate at channelNotification.ts. entry.dev bypasses (dev flag opts out
// of the allowlist). Org list replaces ledger when set (team/enterprise).
// GrowthBook _CACHED_MAY_BE_STALE — cold cache yields [] so every plugin
// entry warns; same tradeoff the gate already accepts.
const { entries: allowed, source } = allowlist
// Independent ifs — a plugin entry that's both uninstalled AND
// unlisted shows two lines. Server kind checks config + dev flag.
const out: Unmatched[] = []
for (const entry of entries) {
if (entry.kind === 'server') {
if (!configured.has(entry.name)) {
out.push({ entry, why: 'no MCP server configured with that name' })
}
if (!entry.dev) {
out.push({
entry,
why: 'server: entries need --dangerously-load-development-channels',
})
}
continue
}
if (!installedPluginIds.has(`${entry.name}@${entry.marketplace}`)) {
out.push({ entry, why: 'plugin not installed' })
}
if (
!entry.dev &&
!allowed.some(
e => e.plugin === entry.name && e.marketplace === entry.marketplace,
)
) {
out.push({
entry,
why:
source === 'org'
? "not on your org's approved channels list"
: 'not on the approved channels allowlist',
})
}
}
return out
}

View File

@@ -332,39 +332,7 @@ export async function showSetupScreens(
// dev channels to any --channels list already set in main.tsx. Org policy
// is NOT bypassed — gateChannelServer() still runs; this flag only exists
// to sidestep the --channels approved-server allowlist.
if (feature('KAIROS') || feature('KAIROS_CHANNELS')) {
// gateChannelServer and ChannelsNotice read tengu_harbor after this
// function returns. A cold disk cache (fresh install, or first run after
// the flag was added server-side) defaults to false and silently drops
// channel notifications for the whole session — gh#37026.
// checkGate_CACHED_OR_BLOCKING returns immediately if disk already says
// true; only blocks on a cold/stale-false cache (awaits the same memoized
// initializeGrowthBook promise fired earlier). Also warms the
// isChannelsEnabled() check in the dev-channels dialog below.
if (getAllowedChannels().length > 0 || (devChannels?.length ?? 0) > 0) {
await checkGate_CACHED_OR_BLOCKING('tengu_harbor')
}
if (devChannels && devChannels.length > 0) {
const [{ isChannelsEnabled }, { getClaudeAIOAuthTokens }] =
await Promise.all([
import('./services/mcp/channelAllowlist.js'),
import('./utils/auth.js'),
])
// Skip the dialog when channels are blocked (tengu_harbor off or no
// OAuth) — accepting then immediately seeing "not available" in
// ChannelsNotice is worse than no dialog. Append entries anyway so
// ChannelsNotice renders the blocked branch with the dev entries
// named. dev:true here is for the flag label in ChannelsNotice
// (hasNonDev check); the allowlist bypass it also grants is moot
// since the gate blocks upstream.
if (!isChannelsEnabled() || !getClaudeAIOAuthTokens()?.accessToken) {
setAllowedChannels([
...getAllowedChannels(),
...devChannels.map(c => ({ ...c, dev: true })),
])
setHasDevChannels(true)
} else {
const { DevChannelsDialog } = await import(
'./components/DevChannelsDialog.js'
)
@@ -384,8 +352,6 @@ export async function showSetupScreens(
/>
))
}
}
}
// Show Chrome onboarding for first-time Claude in Chrome users
if (

View File

@@ -2558,7 +2558,6 @@ async function run(): Promise<CommanderCommand> {
// devChannels is deferred: showSetupScreens shows a confirmation dialog
// and only appends to allowedChannels on accept.
let devChannels: ChannelEntry[] | undefined;
if (feature("KAIROS") || feature("KAIROS_CHANNELS")) {
// Parse plugin:name@marketplace / server:Y tags into typed entries.
// Tag decides trust model downstream: plugin-kind hits marketplace
// verification + GrowthBook allowlist, server-kind always fails
@@ -2662,7 +2661,6 @@ async function run(): Promise<CommanderCommand> {
dev_plugins: joinPluginIds(devChannels ?? []),
});
}
}
// SDK opt-in for SendUserMessage via --tools. All sessions require
// explicit opt-in; listing it in --tools signals intent. Runs BEFORE
@@ -5627,7 +5625,6 @@ async function run(): Promise<CommanderCommand> {
).hideHelp(),
);
}
if (feature("KAIROS") || feature("KAIROS_CHANNELS")) {
program.addOption(
new Option(
"--channels <servers...>",
@@ -5640,7 +5637,6 @@ async function run(): Promise<CommanderCommand> {
"Load channel servers not on the approved allowlist. For local channel development only. Shows a confirmation dialog at startup.",
).hideHelp(),
);
}
// Teammate identity options (set by leader when spawning tmux teammates)
// These replace the CLAUDE_CODE_* environment variables

View File

@@ -44,12 +44,10 @@ export function getChannelAllowlist(): ChannelAllowlistEntry[] {
}
/**
* Overall channels on/off. Checked before any per-server gating —
* when false, --channels is a no-op and no handlers register.
* Default false; GrowthBook 5-min refresh.
* Overall channels on/off. Always enabled — GrowthBook gate bypassed.
*/
export function isChannelsEnabled(): boolean {
return getFeatureValue_CACHED_MAY_BE_STALE('tengu_harbor', false)
return true
}
/**

View File

@@ -21,7 +21,6 @@ import { z } from 'zod/v4'
import { type ChannelEntry, getAllowedChannels } from '../../bootstrap/state.js'
import { CHANNEL_TAG } from '../../constants/xml.js'
import {
getClaudeAIOAuthTokens,
getSubscriptionType,
} from '../../utils/auth.js'
import { lazySchema } from '../../utils/lazySchema.js'
@@ -205,45 +204,6 @@ export function gateChannelServer(
}
}
// Overall runtime gate. After capability so normal MCP servers never hit
// this path. Before auth/policy so the killswitch works regardless of
// session state.
if (!isChannelsEnabled()) {
return {
action: 'skip',
kind: 'disabled',
reason: 'channels feature is not currently available',
}
}
// OAuth-only. API key users (console) are blocked — there's no
// channelsEnabled admin surface in console yet, so the policy opt-in
// flow doesn't exist for them. Drop this when console parity lands.
if (!getClaudeAIOAuthTokens()?.accessToken) {
return {
action: 'skip',
kind: 'auth',
reason: 'channels requires claude.ai authentication (run /login)',
}
}
// Teams/Enterprise opt-in. Managed orgs must explicitly enable channels.
// Default OFF — absent or false blocks. Keyed off subscription tier, not
// "policy settings exist" — a team org with zero configured policy keys
// (remote endpoint returns 404) is still a managed org and must not fall
// through to the unmanaged path.
const sub = getSubscriptionType()
const managed = sub === 'team' || sub === 'enterprise'
const policy = managed ? getSettingsForSource('policySettings') : undefined
if (managed && policy?.channelsEnabled !== true) {
return {
action: 'skip',
kind: 'policy',
reason:
'channels not enabled by org policy (set channelsEnabled: true in managed settings)',
}
}
// User-level session opt-in. A server must be explicitly listed in
// --channels to push inbound this session — protects against a trusted
// server surprise-adding the capability.
@@ -275,41 +235,6 @@ export function gateChannelServer(
}
}
// Approved-plugin allowlist. Marketplace gate already verified
// tag == reality, so this is a pure entry check. entry.dev (per-entry,
// not the session-wide bit) bypasses — so accepting the dev dialog for
// one entry doesn't leak allowlist-bypass to --channels entries.
if (!entry.dev) {
const { entries, source } = getEffectiveChannelAllowlist(
sub,
policy?.allowedChannelPlugins,
)
if (
!entries.some(
e => e.plugin === entry.name && e.marketplace === entry.marketplace,
)
) {
return {
action: 'skip',
kind: 'allowlist',
reason:
source === 'org'
? `plugin ${entry.name}@${entry.marketplace} is not on your org's approved channels list (set allowedChannelPlugins in managed settings)`
: `plugin ${entry.name}@${entry.marketplace} is not on the approved channels allowlist (use --dangerously-load-development-channels for local dev)`,
}
}
}
} else {
// server-kind: allowlist schema is {marketplace, plugin} — a server entry
// can never match. Without this, --channels server:plugin:foo:bar would
// match a plugin's runtime name and register with no allowlist check.
if (!entry.dev) {
return {
action: 'skip',
kind: 'allowlist',
reason: `server ${entry.name} is not on the approved channels allowlist (use --dangerously-load-development-channels for local dev)`,
}
}
}
return { action: 'register' }

View File

@@ -470,7 +470,6 @@ export function useManageMCPConnections(
// Channel push: notifications/claude/channel → enqueue().
// Gate decides whether to register the handler; connection stays
// up either way (allowedMcpServers controls that).
if (feature('KAIROS') || feature('KAIROS_CHANNELS')) {
const gate = gateChannelServer(
client.name,
client.capabilities,
@@ -611,7 +610,6 @@ export function useManageMCPConnections(
}
break
}
}
// Register notification handlers for list_changed notifications
// These allow the server to notify us when tools, prompts, or resources change