> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Channels 概覽 **新增於:** `@mastra/core@1.22.0` Channels 將 Agent 連接至 Slack、Microsoft Teams、Discord、Telegram、WhatsApp、GitHub 和 Linear 等訊息及協作平台。當用戶在平台上傳送訊息或留言時,Agent 會接收內容,透過一般的 Agent pipeline 處理,並將回應以串流方式傳回對話。Mastra 使用 [Chat SDK](https://chat-sdk.dev/) 作為此 Channel 層。 請由你所用平台的頁面開始: - [Slack](https://mastra.zisheng.pro/zh-HK/docs/capabilities/channels/slack) - [Microsoft Teams](https://mastra.zisheng.pro/zh-HK/docs/capabilities/channels/teams) - [Discord](https://mastra.zisheng.pro/zh-HK/docs/capabilities/channels/discord) - [Telegram](https://mastra.zisheng.pro/zh-HK/docs/capabilities/channels/telegram) - [WhatsApp](https://mastra.zisheng.pro/zh-HK/docs/capabilities/channels/whatsapp) - [iMessage](https://mastra.zisheng.pro/zh-HK/docs/capabilities/channels/imessage) [更多平台](https://mastra.zisheng.pro/zh-HK/docs/capabilities/channels/other-adapters)列出了其他平台。除了此處列出的平台,Mastra Channels 亦可配合相容的 [Chat SDK adapters](https://chat-sdk.dev/adapters) 使用,而所有 adapter 均採用相同的 Mastra 配置模式。 ## 何時使用 Channels 當 Agent 需要執行以下操作時,請使用 Channels: - 在用戶慣常溝通或工作的地方與他們互動。 - 在 Slack、Microsoft Teams、Discord、Telegram 和 WhatsApp 等聊天平台回應。 - 支援多人 Agent,讓多名用戶在共享 Channel 或 thread 中與同一個 Agent 互動。 - 與 GitHub issue、pull request thread 和 Linear 留言等協作 Workflow 整合。 ## 配置 Agent Channels 使用 Chat SDK adapters,並遵循相同的 Mastra 端模式:建立 Channel adapter,然後將其加入 Agent。 ```typescript import { Agent } from '@mastra/core/agent' import { createSlackAdapter } from '@chat-adapter/slack' export const yourAgent = new Agent({ id: 'your-agent', name: 'Your Agent', instructions: 'You are a helpful assistant.', model: 'openai/gpt-5.6-sol', channels: { adapters: { slack: createSlackAdapter(), }, }, }) ``` > **備註:** Channel adapters 需要 Provider 特定的環境變數,以提供憑證和驗證請求,例如 bot token、簽署密鑰、app ID 和 webhook 驗證 token。請查閱你所用平台的指南或 [Chat SDK adapter 目錄](https://chat-sdk.dev/adapters),了解確切的變數名稱。 我們建議為 Channels 配置 [storage](https://mastra.zisheng.pro/zh-HK/docs/storage/overview)。Storage 讓 Mastra 可在重新啟動後,仍然保留 Channel 狀態、thread 訂閱、Tool 審批和 memory: ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' import { yourAgent } from './agents/your-agent' export const mastra = new Mastra({ agents: { yourAgent }, storage: new LibSQLStore({ id: 'mastra-storage', url: process.env.DATABASE_URL, }), }) ``` ## Webhook 路由 平台透過 webhook 將 Channel 活動傳送至 Mastra。Webhook 是一個 HTTP endpoint;當有事件發生時,例如收到新訊息、有人提及 Agent,或用戶在互動式 Tool 審批卡上選擇「Approve」,平台便會呼叫此 endpoint。Agent 正是透過這種方式接收新訊息並開始處理,再於同一 Channel 中回應。 Mastra 會為每個已配置的 adapter 註冊 webhook 路由,並代你處理請求: ```text /api/agents//channels//webhook ``` 例如,在 ID 為 `your-agent` 的 Agent 上,Slack adapter 會使用: ```text /api/agents/your-agent/channels/slack/webhook ``` 將平台的 webhook、event 或 interactions URL 指向此路徑。請依照你所用平台的指南或 [Chat SDK 文件](https://chat-sdk.dev/adapters)操作。 在本機開發期間,平台 webhook 需要透過公開 URL 才能連接你的本機伺服器。使用 [cloudflared](https://github.com/cloudflare/cloudflared) 或 [ngrok](https://ngrok.com/) 等 tunnel,公開預設位於 `localhost:4111` 的伺服器: **npm**: ```bash npx cloudflared tunnel --url http://localhost:4111 ``` **pnpm**: ```bash pnpm dlx cloudflared tunnel --url http://localhost:4111 ``` **Yarn**: ```bash yarn dlx cloudflared tunnel --url http://localhost:4111 ``` **Bun**: ```bash bun x cloudflared tunnel --url http://localhost:4111 ``` 使用產生的公開 URL 作為 webhook 路徑的 base URL,例如 `https://abc123.trycloudflare.com/api/agents/your-agent/channels/slack/webhook`。 > **備註:** Tunnel URL 只供本機開發使用。部署 Mastra 伺服器後,請將平台的 webhook、event 或 interactions URL 更新為你的 production URL。 ## Thread context 當用戶在 Channel thread 的對話中途提及 Agent 時,Agent 可能沒有先前的 context。Mastra 預設會在首次被提及時,從平台擷取最近 10 則訊息。 1. Agent 首次在 thread 中被提及時,會從平台擷取最近的訊息。 2. 這些訊息會附加在用戶訊息之前,作為對話 context。 3. Agent 回應後會訂閱該 thread,並透過 Mastra memory 取得完整記錄。 4. 該 thread 的後續訊息不會再次從平台擷取。 設定 `threadContext: { maxMessages: 0 }` 可停用此行為。此設定只適用於非直接訊息 thread。 Mastra 亦會加入一則簡短的 system message,告知 Agent 請求來自哪個 Channel 和平台,例如訊息來自直接訊息還是公開 Channel。設定 `threadContext: { addSystemMessage: false }` 可略過此訊息。 ## Tool 審批 設有 `requireApproval: true` 的 Tool 會顯示為互動式卡片,並附有 Approve 和 Deny 按鈕: ```typescript import { promises as fs } from 'node:fs' import { createTool } from '@mastra/core/tools' import { z } from 'zod' export const deleteFile = createTool({ id: 'delete-file', description: 'Delete a file from the system', inputSchema: z.object({ path: z.string().describe('Path to the file to delete'), }), requireApproval: true, execute: async ({ path }) => { await fs.unlink(path) return { deleted: path } }, }) ``` 當 Agent 呼叫此 Tool 時,用戶會看到一張卡片,當中列出 Tool 名稱、參數,以及 Approve 和 Deny 操作。Tool 只會在獲得批准後執行。 在 adapter 上設定 `toolDisplay: 'text'`,可將 Tool 呼叫顯示為純文字,而非互動式卡片。在 `'hidden'` 模式下,當同一 thread 稍後收到用戶訊息時,`autoResumeSuspendedTools` 可以繼續執行已暫停的 Tool。此功能需要 memory。Hidden 模式只會隱藏審批按鈕。 ## 回應格式 Agent 回應預設以 markdown 發佈。Slack 等原生支援 markdown rendering 的平台會直接呈現粗體文字、連結和表格。其他平台則會將 markdown 轉換為自身的格式。Agent 只需編寫標準 markdown,即可在各平台正確呈現,效果與同一回應在 Studio 中的呈現方式一致。 在 adapter 上設定 `textFormat: 'plain'`,即可改為以純文字原樣發佈回應: ```typescript channels: { adapters: { slack: { adapter: createSlackAdapter(), textFormat: 'plain', }, }, }, ``` 如果系統提示你的 Agent 輸出平台特定語法(例如 Slack mrkdwn),而非標準 markdown,可使用此後備選項。如果你曾為了解決 markdown 被原樣顯示的問題而加入這類 prompt 指示,請改為移除。現在,預設設定已能以原生方式呈現標準 markdown。`textFormat` 只影響最終回應文字,Tool 卡片、錯誤訊息和以原生方式串流的文字均不受影響。 ## 多用戶識別 在群組對話中,Mastra 會在每則訊息前加上傳送者的名稱和平台 ID,讓 Agent 可以分辨不同發言者: ```text [Alice (@U123ABC)]: Can you help me with this? [Bob (@U456DEF)]: I have a question too. ``` ## 多模態內容 Gemini 等 Model 可以原生處理圖片、影片和音訊。結合使用 `inlineMedia` 和 `inlineLinks`,讓用戶可跨平台與你的 Agent 分享多媒體內容: ```typescript import { Agent } from '@mastra/core/agent' import { createDiscordAdapter } from '@chat-adapter/discord' export const visionAgent = new Agent({ id: 'vision-agent', name: 'Vision Agent', instructions: 'You can see images, watch videos, and listen to audio.', model: 'google/gemini-2.5-flash', channels: { adapters: { discord: createDiscordAdapter(), }, inlineMedia: ['image/*', 'video/*', 'audio/*'], inlineLinks: [ { match: 'youtube.com', mimeType: 'video/*' }, { match: 'youtu.be', mimeType: 'video/*' }, 'imgur.com', ], }, }) ``` 採用此配置後: - 用戶上載螢幕截圖後,Agent 會描述圖片內容。 - 用戶上載 `.mp4` 片段後,Agent 會概述影片內容。 - 用戶貼上 YouTube 連結後,Agent 會觀看並討論影片。 - 用戶貼上 imgur 連結後,Agent 可直接查看圖片。 預設只會 inline 傳送圖片(`inlineMedia: ['image/*']`)。不支援的類型會以文字摘要描述,讓 Agent 知道有關檔案,同時避免不接受這些類型的 Model 發生錯誤。所有 `inlineMedia` pattern 可參閱 [Channel 參考資料](https://mastra.zisheng.pro/zh-HK/reference/agents/channels);domain matching、HEAD detection 和 forced MIME type 則可參閱 [inlineLinks 參考資料](https://mastra.zisheng.pro/zh-HK/reference/agents/channels)。 ## Serverless 部署 在 Vercel 等 serverless 平台上,每個請求都會在獨立而短暫的 instance 中執行。要讓 Channels 在此環境可靠運作,需要兩項條件:一種在 Agent 回應期間保持 function 運作的方法,以及共享的 pub/sub,讓各 instance 可以互相協調。 ### 使用 `waitUntil` 保持 function 運作 Channel webhook 會立即傳回 `200` 回應,然後 Agent 在背景執行並發佈回應。在大部分 serverless 平台上,function 會在回應後立即凍結,令執行在 Agent 回答前停止。傳入 `waitUntil` function,平台便會讓 instance 保持運作,直至執行完成。 在 Vercel 上,傳入 `waitUntil`(來自 `@vercel/functions`): ```typescript import { Agent } from '@mastra/core/agent' import { createSlackAdapter } from '@chat-adapter/slack' import { waitUntil } from '@vercel/functions' export const yourAgent = new Agent({ id: 'your-agent', name: 'Your Agent', instructions: 'You are a helpful assistant.', model: 'openai/gpt-5.6-sol', channels: { adapters: { slack: createSlackAdapter(), }, waitUntil, }, }) ``` Vercel 和 AWS Lambda 需要 `waitUntil`,因為它們會在回應送出後立即凍結 function。系統會從 request context 自動偵測 Cloudflare Workers 和 Netlify Functions,因此它們不需要此設定。若 `waitUntil` 位於 request context,但 runtime 不支援自動偵測,請使用 `resolveWaitUntil`。詳情請參閱 [Channel 參考資料](https://mastra.zisheng.pro/zh-HK/reference/agents/channels)。 ### 使用共享 pub/sub 協調 instance Channels 透過 Agent 的 [signal pipeline](https://mastra.zisheng.pro/zh-HK/docs/long-running-agents/signals)路由訊息,而每次執行都會取得其 thread 的 lease,確保同一時間只有一次執行擁有該對話。 預設的記憶體內 pub/sub 無法跨越 instance 邊界,因此在 serverless 環境中,後續訊息可能會路由至與正在執行 Agent 的 instance 不同的另一個 instance。 如沒有共享 pub/sub,該 instance 便無法連接正在執行的流程,並會自行開始另一個流程,令原本的流程不受影響,而同一個 thread 被處理兩次。 在 `Mastra` instance 上配置由 Redis Streams 支援的共享 pub/sub,讓 lease 和 signal 可跨 instance 協調: ```typescript import { Mastra } from '@mastra/core' import { RedisStreamsPubSub } from '@mastra/redis-streams' import { yourAgent } from './agents/your-agent' export const mastra = new Mastra({ agents: { yourAgent }, pubsub: new RedisStreamsPubSub({ url: process.env.REDIS_URL, keyPrefix: 'mastra:my-app', }), }) ``` Vercel 的 managed Redis integration 和 Upstash Redis 都很適合使用。如需進一步了解何時需要 distributed pub/sub,請參閱 [PubSub 指南](https://mastra.zisheng.pro/zh-HK/docs/server/pubsub)和 [`RedisStreamsPubSub` 參考資料](https://mastra.zisheng.pro/zh-HK/reference/pubsub/redis-streams)。 ## 相關內容 - [Channel 參考資料](https://mastra.zisheng.pro/zh-HK/reference/agents/channels) - [AgentController Channel](https://mastra.zisheng.pro/zh-HK/docs/harness/agent-controller) - 📹 [Mastra Channel 工作坊](https://www.youtube.com/watch?v=E9KFsZEnQO8\&t=5s)