Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: support Line (#14207)

Rdmclin22eb7ee824f99
diff --git a/docs/usage/channels/line.mdx b/docs/usage/channels/line.mdx
new file mode 100644
index 00000000000..230d6802af6
--- /dev/null
+++ b/docs/usage/channels/line.mdx
@@ -0,0 +1,198 @@
+---
+title: Connect LobeHub to LINE
+description: >-
+ Learn how to connect a LINE Messaging API bot to your LobeHub agent,
+ enabling your AI assistant to chat with users in LINE direct messages and
+ group conversations.
+tags:
+ - LINE
+ - Message Channels
+ - Bot Setup
+ - Integration
+---
+
+# Connect LobeHub to LINE
+
+By connecting a LINE channel to your LobeHub agent, users can interact with the AI assistant through LINE direct messages, group chats, and multi-person rooms. The integration uses the official **LINE Messaging API** — there is no third-party broker between LINE and LobeHub.
+
+## Prerequisites
+
+- A LobeHub account with an active subscription
+- A [LINE Business ID](https://account.line.biz/signup) (sign up with a LINE account or email)
+- A **LINE Official Account** — every Messaging API channel must be attached to one
+
+> **Important change (since 2024-09-04):** LINE no longer lets you create a Messaging API channel directly from the LINE Developers Console. You must first create a LINE Official Account and enable the Messaging API on it from LINE Official Account Manager — the channel then appears automatically in the Developers Console.
+
+## Step 1: Create a LINE Official Account and Enable the Messaging API
+
+<Steps>
+ ### Create a LINE Official Account
+
+ Open [entry.line.biz](https://entry.line.biz/form/entry/unverified) and sign in with your LINE Business ID. Fill in the account name, business category, and region, then submit. Confirm the new account appears in [LINE Official Account Manager](https://manager.line.biz/).
+
+ ### Enable the Messaging API in Official Account Manager
+
+ Open the new account → **Settings → Messaging API** → click **Enable Messaging API**. You will be asked to:
+
+ - Register developer information (first-time only).
+ - Pick a **Provider** that will own this channel in the Developers Console — reuse an existing one, or create a fresh one (e.g. "LobeHub").
+
+ > **Heads-up:** the provider assignment is **permanent**. If you manage multiple unrelated services, give each one its own provider.
+
+ ### Find the channel in the Developers Console
+
+ Sign in to [LINE Developers Console](https://developers.line.biz/console/) with the same LINE Business ID, open the provider you just chose, and the Messaging API channel will appear automatically.
+
+ ### Note the channel identifiers
+
+ Open the **Basic settings** tab and copy the **Channel secret** — LobeHub uses it to verify webhook signatures in Step 4.
+
+ > **Note:** the **"Your user ID"** field on the same tab is **your own** LINE user ID, **not** the bot's destination user ID. Both have the identical `U` + 32 hex format, but LobeHub needs the bot's, which is resolved automatically from the Channel Access Token in Step 4.
+
+ Then open the **Messaging API** tab and note:
+
+ - **Bot basic ID** — the `@xxxx` short ID users will search for.
+</Steps>
+
+## Step 2: Issue a Channel Access Token
+
+<Steps>
+ ### Open the Messaging API tab
+
+ Scroll to the bottom of the **Messaging API** tab. You will see a **Channel access token** section.
+
+ ### Issue a long-lived token
+
+ Click **Issue** under "Channel access token (long-lived)". Copy the token immediately — LINE only shows it once.
+
+ > **Important:** The Channel Access Token and Channel Secret are sensitive credentials. Never commit them to source control or share them in screenshots.
+</Steps>
+
+## Step 3: Disable LINE's Built-in Auto-reply and Greeting
+
+By default the LINE Official Account Manager auto-replies to user messages and sends a greeting on first contact. These compete with LobeHub's responses, so they must be turned off.
+
+<Steps>
+ ### Open the LINE Official Account Manager
+
+ In the **Messaging API** tab, click the **LINE Official Account Manager** link to open the management UI for the channel's Official Account.
+
+ ### Switch the response modes
+
+ Go to **Settings → Messaging API** (or **Response settings**) and set:
+
+ - **Greeting message:** Disabled
+ - **Auto-response messages:** Disabled
+ - **Webhooks:** Enabled
+
+ This leaves your bot to handle every inbound message itself.
+</Steps>
+
+## Step 4: Configure LINE in LobeHub
+
+<Steps>
+ ### Open Channel Settings
+
+ In LobeHub, navigate to your agent's settings, then select the **Channels** tab. Click **LINE** from the platform list.
+
+ ### Fill in the credentials
+
+ Recommended order — paste the token first so LobeHub can auto-fill the Destination User ID:
+
+ 1. **Channel Access Token** — paste the long-lived token issued in Step 2.
+ 2. **Destination User ID** — click **Fetch from LINE** next to this field. LobeHub calls `GET /v2/bot/info` with the token you just pasted and fills in the bot's `userId` (33 chars, starts with `U`) for you. You can also type/paste it manually if you already have it.
+ 3. **Channel Secret** — paste the Channel secret from the **Basic settings** tab.
+
+ > **Why the auto-fetch?** The LINE Developers Console does **not** display the bot's destination user ID anywhere — `/v2/bot/info` is the only way to read it. The **Fetch from LINE** button removes the manual `curl` step.
+ >
+ > <details>
+ > <summary>Manual alternative (if the button is unavailable)</summary>
+ >
+ > ```bash
+ > curl -H "Authorization: Bearer <YOUR_CHANNEL_ACCESS_TOKEN>" \
+ > https://api.line.me/v2/bot/info
+ > ```
+ >
+ > Copy the `userId` field from the response into the **Destination User ID** field.
+ > </details>
+
+ ### Save Configuration
+
+ Click **Save Configuration**. LobeHub will encrypt your credentials, call `GET /v2/bot/info` once to verify the token works and that the bot user ID matches your Destination User ID, and surface a **Webhook URL** for the next step.
+
+ > **Note:** Unlike Telegram, the LINE Messaging API does not allow programmatic webhook registration. LobeHub cannot wire the URL for you — you must paste it in the LINE Developers Console yourself in Step 5.
+</Steps>
+
+## Step 5: Wire the Webhook in the LINE Developers Console
+
+<Steps>
+ ### Copy the Webhook URL
+
+ In LobeHub's LINE channel detail page, copy the **Webhook URL** displayed under the credentials section. It looks like `https://app.lobehub.com/api/agent/webhooks/line/<your-destination-user-id>`.
+
+ ### Paste it in the LINE Developers Console
+
+ Back in the **Messaging API** tab of your channel:
+
+ - **Webhook URL:** paste the LobeHub Webhook URL.
+ - Click **Update**.
+ - Click **Verify**. LINE sends a signed `POST` with `events: []` to LobeHub, which responds 200 if the Channel Secret matches.
+ - Toggle **Use webhook** to **ON**.
+</Steps>
+
+## Step 6: Test the Connection
+
+<Steps>
+ ### Add the bot as a friend
+
+ Open the **Messaging API** tab in the LINE Developers Console and scan the bot's **QR code** with your phone, or search for the **Bot basic ID** (e.g. `@abc1234x`) in LINE.
+
+ ### Send a real message
+
+ Send any message to the bot in LINE. Within a few seconds your LobeHub agent should reply.
+
+ ### Run Test Connection (optional)
+
+ Click **Test Connection** in LobeHub's channel settings to re-verify the token and the bot identity match. Errors are surfaced with the exact LINE error message.
+</Steps>
+
+## Adding the Bot to Group Chats
+
+To use the bot in LINE group chats or multi-person rooms:
+
+1. Add the bot as a friend (Step 6).
+2. Create a group or room and invite the bot, **or** invite the bot to an existing group from the bot's profile screen (`...` → **Invite**).
+3. Mention the bot or send a message — the bot will reply in the group or room.
+
+> **Note:** Allowing your bot to join groups and rooms requires enabling **"Allow bot to join group chats"** in the LINE Official Account Manager (**Response settings**). It is off by default.
+
+## Configuration Reference
+
+| Field | Required | Description |
+| ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| **Destination User ID** | Yes | The bot's user ID (`U` + 32 hex chars). LobeHub auto-fills this via the **Fetch from LINE** button (calls `GET /v2/bot/info` with the access token); the LINE Developers Console UI does not display the value. Used as the bot identity and webhook path segment. |
+| **Channel Access Token** | Yes | Long-lived token issued from the **Messaging API** tab. Used as the bearer header on every LINE API call. |
+| **Channel Secret** | Yes | From the **Basic settings** tab. Used to verify `X-Line-Signature` on every inbound webhook delivery. |
+
+## Feature Notes
+
+LINE's Messaging API has a few specifics that LobeHub maps as follows:
+
+- **Markdown** — LINE renders text messages as **plain text** only. LobeHub strips Markdown markup before sending so emphasis / heading / list markers are removed.
+- **Message editing** — the Messaging API does not support editing sent messages, so LobeHub only sends the **final reply**, not per-step progress edits.
+- **Typing indicator** — the loading animation is shown in 1:1 user chats only. Group and multi-person room threads silently no-op.
+- **Reactions** — LINE bots cannot send message reactions today, so the 👀 / ✏️ status reactions used on Discord and Slack are not surfaced.
+- **Outbound** — LobeHub uses the **push API** (`/v2/bot/message/push`) rather than the reply API, because the reply token expires in \~60s while agent generation can take longer. Push messages count against your channel's monthly quota for paid plans; the free Developer Trial is unlimited.
+- **Attachments** — inbound images, video, audio, and files are downloaded on demand from the LINE data domain and forwarded to the model. Outbound replies are text-only today.
+
+## Troubleshooting
+
+- **"Verify" fails in the LINE Developers Console.** The Channel Secret in LobeHub must match the value shown on the LINE Developers Console **Basic settings** tab exactly. Re-paste it, save, and try again.
+- **`Authentication failed.` on Save / Test Connection.** Your Channel Access Token is invalid or expired. Re-issue the long-lived token in the Messaging API tab and paste the new value into LobeHub.
+- **`Channel access token belongs to bot Uxxx, not Uyyy`.** The Destination User ID does not match the token. Easiest fix: clear the field and click **Fetch from LINE** to re-pull the correct `userId`. The `Uxxx` shown in the error is also the userId the token actually belongs to — you can paste it in directly. (Manual check: `curl -H "Authorization: Bearer <token>" https://api.line.me/v2/bot/info`.)
+- **Webhook delivery is rejected with `401 Invalid signature`.** The Channel Secret in LobeHub doesn't match the one in LINE. Update LobeHub with the correct Channel Secret.
+- **Bot doesn't respond.** Check that:
+ 1. **Use webhook** is toggled **ON** in the Messaging API tab.
+ 2. **Auto-response messages** and **Greeting message** are disabled in the LINE Official Account Manager.
+ 3. The user has added the bot as a friend (LINE will not deliver messages from non-friends).
+- **Bot doesn't respond in groups.** Make sure **"Allow bot to join group chats"** is enabled in the Official Account Manager's **Response settings**, then re-invite the bot to the group.
diff --git a/docs/usage/channels/line.zh-CN.mdx b/docs/usage/channels/line.zh-CN.mdx
new file mode 100644
index 00000000000..ae0748946f0
--- /dev/null
+++ b/docs/usage/channels/line.zh-CN.mdx
@@ -0,0 +1,197 @@
+---
+title: 将 LobeHub 连接到 LINE
+description: >-
+ 学习如何通过 LINE Messaging API 将 LINE 机器人连接到 LobeHub
+ 代理,使您的 AI 助手能够在 LINE 私信和群组对话中与用户互动。
+tags:
+ - LINE
+ - 消息渠道
+ - 机器人设置
+ - 集成
+---
+
+# 将 LobeHub 连接到 LINE
+
+通过将 LINE 渠道连接到您的 LobeHub 代理,用户可以通过 LINE 私信、群组聊天以及多人聊天室与 AI 助手互动。集成使用官方的 **LINE Messaging API**,LINE 与 LobeHub 之间没有第三方中转。
+
+## 前置条件
+
+- 一个拥有有效订阅的 LobeHub 账户
+- 一个 [LINE Business ID](https://account.line.biz/signup)(可用 LINE 账号或邮箱注册)
+- 一个 **LINE Official Account**(Messaging API channel 必须挂在 Official Account 下)
+
+> **重要变化(2024-09-04 起):** LINE 已不再允许直接在 LINE Developers Console 中创建 Messaging API channel。必须先建 LINE Official Account,再在 Official Account Manager 中启用 Messaging API,对应的 channel 才会在 Developers Console 中自动出现。
+
+## 第一步:创建 LINE Official Account 并启用 Messaging API
+
+<Steps>
+ ### 创建 LINE Official Account
+
+ 打开 [entry.line.biz](https://entry.line.biz/form/entry/unverified),用 LINE Business ID 登录,按表单填写账号名称、行业、地区等信息提交。完成后到 [LINE Official Account Manager](https://manager.line.biz/) 确认账号已经出现在列表中。
+
+ ### 在 Account Manager 中启用 Messaging API
+
+ 进入这个 Official Account → **Settings → Messaging API** → 点击 **Enable Messaging API**。系统会让你:
+
+ - 填写开发者信息(首次启用时)。
+ - 选择一个 **Provider**(用来在 Developers Console 中分组 channel)—— 已有的可以复用,没有就新建一个,例如 "LobeHub"。
+
+ > **注意:** Provider 一旦绑定就 **不能修改**。如果同时管理多个不相关业务,建议为每个业务用独立的 Provider。
+
+ ### 在 Developers Console 中找到 channel
+
+ 用同一个 LINE Business ID 登录 [LINE Developers Console](https://developers.line.biz/console/),选中刚才绑的 Provider,对应的 Messaging API channel 会自动出现。
+
+ ### 记录 channel 的关键标识
+
+ 打开 **Basic settings** 选项卡,复制 **Channel secret** —— 用于第四步校验 Webhook 签名。
+
+ > **注意:** 同一选项卡里的 **"Your user ID"** 是**你账号自己的** LINE user ID,**不是** bot 的 destination user ID。两者格式完全一样(都以 `U` 开头共 33 位),但 LobeHub 需要的是 bot 的,会在第四步根据 Channel Access Token 自动解析。
+
+ 然后切到 **Messaging API** 选项卡,记下:
+
+ - **Bot basic ID** —— 用户搜索机器人时使用的 `@xxxx` 短 ID。
+</Steps>
+
+## 第二步:签发 Channel Access Token
+
+<Steps>
+ ### 打开 Messaging API 选项卡
+
+ 滚到 **Messaging API** 选项卡底部的 **Channel access token** 区域。
+
+ ### 签发长期 Token
+
+ 在 "Channel access token (long-lived)" 处点击 **Issue**。立即复制 Token —— LINE 只展示一次。
+
+ > **重要提示:** Channel Access Token 与 Channel Secret 都是敏感凭据,切勿提交到代码仓库或在截图中泄露。
+</Steps>
+
+## 第三步:关闭 LINE 自带的自动回复与欢迎语
+
+LINE Official Account Manager 默认会自动回复用户消息并在第一次接触时发送欢迎语,会与 LobeHub 的回复发生冲突,需要关闭。
+
+<Steps>
+ ### 打开 LINE Official Account Manager
+
+ 在 **Messaging API** 选项卡中,点击 **LINE Official Account Manager** 链接进入对应 Official Account 的管理界面。
+
+ ### 切换 response 模式
+
+ 打开 **设置 → Messaging API**(或 **Response settings**),调整为:
+
+ - **Greeting message:** Disabled
+ - **Auto-response messages:** Disabled
+ - **Webhooks:** Enabled
+
+ 这样所有入站消息都会交给你的机器人处理。
+</Steps>
+
+## 第四步:在 LobeHub 中配置 LINE
+
+<Steps>
+ ### 打开渠道设置
+
+ 在 LobeHub 中,进入您的代理设置,选择 **渠道** 标签。在平台列表中点击 **LINE**。
+
+ ### 填写凭据
+
+ 推荐顺序 —— 先粘贴 Token,LobeHub 会帮你自动填入 Destination User ID:
+
+ 1. **Channel Access Token** —— 粘贴第二步签发的长期 Token。
+ 2. **Destination User ID** —— 点击该字段旁的 **从 LINE 获取** 按钮。LobeHub 会用刚才填入的 Token 调用 `GET /v2/bot/info`,自动取出 bot 的 `userId`(以 `U` 开头共 33 位)并填入。如果你已经拿到这个值,也可以手动粘贴。
+ 3. **Channel Secret** —— 粘贴 **Basic settings** 选项卡的 Channel secret。
+
+ > **为什么需要自动获取?** LINE Developers Console 界面**不展示** bot 的 destination user ID,唯一的获取方式就是调用 `/v2/bot/info`。**从 LINE 获取** 按钮会把这一步 `curl` 替你做掉。
+ >
+ > <details>
+ > <summary>手动备选方案(按钮不可用时)</summary>
+ >
+ > ```bash
+ > curl -H "Authorization: Bearer <你的 channel access token>" \
+ > https://api.line.me/v2/bot/info
+ > ```
+ >
+ > 把返回 JSON 中的 `userId` 字段复制到 **Destination User ID** 即可。
+ > </details>
+
+ ### 保存配置
+
+ 点击 **保存配置**。LobeHub 会加密您的凭据,调用一次 `GET /v2/bot/info` 验证 Token 可用、且返回的 bot user ID 与 Destination User ID 一致,并在凭据下方显示 **Webhook URL** 供下一步使用。
+
+ > **注意:** 与 Telegram 不同,LINE Messaging API 不支持程序化注册 Webhook,LobeHub 无法替您在 LINE Developers Console 中填写 URL,需要您在第五步中自行粘贴。
+</Steps>
+
+## 第五步:在 LINE Developers Console 配置 Webhook
+
+<Steps>
+ ### 复制 Webhook URL
+
+ 在 LobeHub 的 LINE 渠道详情页中,复制凭据区域下方显示的 **Webhook URL**。形如 `https://app.lobehub.com/api/agent/webhooks/line/<your-destination-user-id>`。
+
+ ### 粘贴到 LINE Developers Console
+
+ 回到 channel 的 **Messaging API** 选项卡:
+
+ - **Webhook URL:** 粘贴 LobeHub 的 Webhook URL。
+ - 点击 **Update**。
+ - 点击 **Verify**。LINE 会向 LobeHub 发送一个签名后的 `POST`(`events: []`),Channel Secret 匹配时 LobeHub 返回 200。
+ - 将 **Use webhook** 切到 **ON**。
+</Steps>
+
+## 第六步:测试连接
+
+<Steps>
+ ### 添加机器人为好友
+
+ 在 LINE Developers Console 的 **Messaging API** 选项卡,使用手机扫描机器人的 **QR code**;也可以直接在 LINE 中搜索 **Bot basic ID**(例如 `@abc1234x`)。
+
+ ### 发送一条真实消息
+
+ 在 LINE 里向机器人发送任意消息。几秒内 LobeHub 代理就会回复。
+
+ ### 运行测试连接(可选)
+
+ 在 LobeHub 渠道设置中点击 **测试连接**,再次校验 Token 与 bot 身份是否匹配,错误信息会透传 LINE 返回的具体内容。
+</Steps>
+
+## 在群聊中使用机器人
+
+要在 LINE 群聊或多人聊天室使用机器人:
+
+1. 先按第六步将机器人加为好友。
+2. 创建群组或聊天室并邀请机器人;也可以从机器人个人页(`...` → **Invite**)邀请到已存在的群组。
+3. 在群里 @ 机器人或直接发送消息,机器人会在群组或聊天室中回复。
+
+> **注意:** 允许机器人加入群组与聊天室需要在 LINE Official Account Manager 的 **Response settings** 中启用 **"Allow bot to join group chats"**,默认是关闭的。
+
+## 配置参考
+
+| 字段 | 是否必需 | 描述 |
+| ------------------------ | ---- | ------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Destination User ID** | 是 | 机器人的用户 ID(`U` + 32 位十六进制)。LobeHub 会通过 **从 LINE 获取** 按钮(背后调用 `GET /v2/bot/info`)自动填入;LINE Developers Console 界面不展示这个值。同时作为机器人标识与 Webhook 路径。 |
+| **Channel Access Token** | 是 | **Messaging API** 选项卡中签发的长期 Token,用作每个 LINE API 调用的 bearer 头。 |
+| **Channel Secret** | 是 | **Basic settings** 选项卡中的 Channel secret,用于校验每条入站 Webhook 的 `X-Line-Signature`。 |
+
+## 能力说明
+
+LINE Messaging API 有一些平台层面的限制,LobeHub 的对接行为如下:
+
+- **Markdown** —— LINE 文本消息按 **纯文本** 渲染。LobeHub 在发送前会通过 `stripMarkdown` 去掉强调、标题、列表等标记。
+- **消息编辑** —— Messaging API 不支持编辑已发送消息,因此 LobeHub 只发送 **最终回复**,不会逐步刷新中间进度。
+- **输入提示动画** —— 仅对 1:1 用户聊天有效,群组与多人聊天室静默 no-op。
+- **表情反应** —— LINE 机器人当前不能发送消息反应,Discord/Slack 上使用的 👀 / ✏️ 状态反应不会显示。
+- **出站** —— LobeHub 使用 **push API**(`/v2/bot/message/push`)而非 reply API,因为 reply token 60 秒就过期,而 agent 生成回复可能更慢。Push 消息会消耗付费方案的月度配额,免费的 Developer Trial 实际不限量。
+- **附件** —— 入站的图片、视频、音频、文件会按需通过 LINE 数据子域下载并送给模型;出站消息当前仅支持文本。
+
+## 故障排除
+
+- **LINE Developers Console 的 "Verify" 失败。** LobeHub 中的 Channel Secret 必须与 **Basic settings** 选项卡显示的值完全一致。重新粘贴、保存后再试。
+- **保存或测试连接时出现 `Authentication failed.`。** Channel Access Token 失效或被撤销。在 Messaging API 选项卡里重新签发长期 Token,并把新值粘贴到 LobeHub。
+- **`Channel access token belongs to bot Uxxx, not Uyyy`。** Destination User ID 与 Token 不匹配。最简方式:清空字段后点击 **从 LINE 获取**,让 LobeHub 重新拉到正确的 `userId`。错误消息里的 `Uxxx` 也是 Token 实际归属的 bot userId,直接复制粘贴也可以。(手动核对:`curl -H "Authorization: Bearer <token>" https://api.line.me/v2/bot/info`。)
+- **Webhook 投递返回 `401 Invalid signature`。** LobeHub 中的 Channel Secret 与 LINE 的不一致,更新为正确的 Channel Secret。
+- **机器人不回复。** 请依次确认:
+ 1. Messaging API 选项卡中的 **Use webhook** 已切到 **ON**。
+ 2. LINE Official Account Manager 中的 **Auto-response messages** 与 **Greeting message** 都已禁用。
+ 3. 用户已经把机器人加为好友(非好友消息 LINE 不会推送)。
+- **群聊中机器人不回复。** 确认 LINE Official Account Manager 的 **Response settings** 中已启用 **"Allow bot to join group chats"**,然后将机器人重新邀请进群组。
diff --git a/docs/usage/channels/overview.mdx b/docs/usage/channels/overview.mdx
index 50c28ec7b51..b0e22d6dcbb 100644
--- a/docs/usage/channels/overview.mdx
+++ b/docs/usage/channels/overview.mdx
@@ -2,8 +2,8 @@
title: Channels Overview
description: >-
Connect your LobeHub agents to external messaging platforms like Discord,
- Slack, Telegram, QQ, WeChat, Feishu, and Lark, allowing users to interact with
- AI assistants directly in their favorite chat apps.
+ Slack, Telegram, LINE, QQ, WeChat, Feishu, and Lark, allowing users to
+ interact with AI assistants directly in their favorite chat apps.
tags:
- Channels
- Message Channels
@@ -11,6 +11,7 @@ tags:
- Discord
- Slack
- Telegram
+ - LINE
- QQ
- WeChat
- Feishu
@@ -32,6 +33,7 @@ Channels allow you to connect your LobeHub agents to external messaging platform
| [Discord](/docs/usage/channels/discord) | Connect to Discord servers for channel chat and direct messages |
| [Slack](/docs/usage/channels/slack) | Connect to Slack for channel and direct message conversations |
| [Telegram](/docs/usage/channels/telegram) | Connect to Telegram for private and group conversations |
+| [LINE](/docs/usage/channels/line) | Connect to LINE Messaging API for direct and group chats |
| [QQ](/docs/usage/channels/qq) | Connect to QQ for group chats and direct messages |
| [WeChat (微信)](/docs/usage/channels/wechat) | Connect to WeChat via iLink Bot for private and group chats (requires an active subscription) |
| [Feishu (飞书)](/docs/usage/channels/feishu) | Connect to Feishu for team collaboration (Chinese version) |
@@ -42,7 +44,7 @@ Channels allow you to connect your LobeHub agents to external messaging platform
Each channel integration works by linking a bot account on the target platform to a LobeHub agent. When a user sends a message to the bot, LobeHub processes it through the agent and sends the response back to the same conversation.
- **Per-agent configuration** — Each agent can have its own set of channel connections, so different agents can serve different platforms or communities.
-- **Multiple channels simultaneously** — A single agent can be connected to Discord, Slack, Telegram, QQ, WeChat, Feishu, and Lark at the same time. LobeHub routes messages to the correct agent automatically.
+- **Multiple channels simultaneously** — A single agent can be connected to Discord, Slack, Telegram, LINE, QQ, WeChat, Feishu, and Lark at the same time. LobeHub routes messages to the correct agent automatically.
- **Secure credential storage** — All bot tokens and app secrets are encrypted before being stored.
## Getting Started
@@ -52,6 +54,7 @@ Each channel integration works by linking a bot account on the target platform t
- [Discord](/docs/usage/channels/discord)
- [Slack](/docs/usage/channels/slack)
- [Telegram](/docs/usage/channels/telegram)
+ - [LINE](/docs/usage/channels/line)
- [QQ](/docs/usage/channels/qq)
- [WeChat (微信)](/docs/usage/channels/wechat)
- [Feishu (飞书)](/docs/usage/channels/feishu)
@@ -63,13 +66,13 @@ If you do not see **WeChat** in the channel list, check that your account has an
Text messages are supported across all platforms. Some features vary by platform:
-| Feature | Discord | Slack | Telegram | QQ | WeChat | Feishu | Lark |
-| ---------------------- | ------- | ----- | -------- | --- | ------ | ------- | ------- |
-| Text messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
-| Direct messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
-| Group chats | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
-| Reactions | Yes | Yes | Yes | No | No | Partial | Partial |
-| Image/file attachments | Yes | Yes | Yes | Yes | No | Yes | Yes |
+| Feature | Discord | Slack | Telegram | LINE | QQ | WeChat | Feishu | Lark |
+| ---------------------- | ------- | ----- | -------- | ------- | --- | ------ | ------- | ------- |
+| Text messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
+| Direct messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
+| Group chats | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
+| Reactions | Yes | Yes | Yes | No | No | No | Partial | Partial |
+| Image/file attachments | Yes | Yes | Yes | Inbound | Yes | No | Yes | Yes |
## Allowed Users (global)
diff --git a/docs/usage/channels/overview.zh-CN.mdx b/docs/usage/channels/overview.zh-CN.mdx
index 35c8e10c5a4..53c8da1bc85 100644
--- a/docs/usage/channels/overview.zh-CN.mdx
+++ b/docs/usage/channels/overview.zh-CN.mdx
@@ -1,7 +1,7 @@
---
title: 渠道概览
description: >-
- 将 LobeHub 代理连接到外部消息平台,如 Discord、Slack、Telegram、QQ、微信、飞书和
+ 将 LobeHub 代理连接到外部消息平台,如 Discord、Slack、Telegram、LINE、QQ、微信、飞书和
Lark,让用户可以直接在他们喜欢的聊天应用中与 AI 助手互动。
tags:
- 渠道
@@ -10,6 +10,7 @@ tags:
- Discord
- Slack
- Telegram
+ - LINE
- QQ
- 微信
- 飞书
@@ -26,22 +27,23 @@ tags:
## 支持的平台
-| 平台 | 描述 |
-| ----------------------------------------- | ---------------------------------- |
-| [Discord](/docs/usage/channels/discord) | 连接到 Discord 服务器,用于频道聊天和私信 |
-| [Slack](/docs/usage/channels/slack) | 连接到 Slack,用于频道和私信对话 |
-| [Telegram](/docs/usage/channels/telegram) | 连接到 Telegram,用于私人和群组对话 |
-| [QQ](/docs/usage/channels/qq) | 连接到 QQ,用于群聊和私信 |
-| [微信](/docs/usage/channels/wechat) | 通过 iLink Bot 连接到微信,用于私聊和群聊(需要有效订阅) |
-| [飞书](/docs/usage/channels/feishu) | 连接到飞书,用于团队协作(中国版) |
-| [Lark](/docs/usage/channels/lark) | 连接到 Lark,用于团队协作(国际版) |
+| 平台 | 描述 |
+| ----------------------------------------- | -------------------------------------- |
+| [Discord](/docs/usage/channels/discord) | 连接到 Discord 服务器,用于频道聊天和私信 |
+| [Slack](/docs/usage/channels/slack) | 连接到 Slack,用于频道和私信对话 |
+| [Telegram](/docs/usage/channels/telegram) | 连接到 Telegram,用于私人和群组对话 |
+| [LINE](/docs/usage/channels/line) | 通过 LINE Messaging API 连接到 LINE,支持私聊和群聊 |
+| [QQ](/docs/usage/channels/qq) | 连接到 QQ,用于群聊和私信 |
+| [微信](/docs/usage/channels/wechat) | 通过 iLink Bot 连接到微信,用于私聊和群聊(需要有效订阅) |
+| [飞书](/docs/usage/channels/feishu) | 连接到飞书,用于团队协作(中国版) |
+| [Lark](/docs/usage/channels/lark) | 连接到 Lark,用于团队协作(国际版) |
## 工作原理
每个渠道集成都通过将目标平台上的机器人账户与 LobeHub 代理连接来实现。当用户向机器人发送消息时,LobeHub 会通过代理处理消息并将响应发送回同一对话。
- **按代理配置** — 每个代理可以拥有自己的一组渠道连接,因此不同的代理可以服务于不同的平台或社区。
-- **同时支持多个渠道** — 单个代理可以同时连接到 Discord、Slack、Telegram、QQ、微信、飞书和 Lark。LobeHub 会自动将消息路由到正确的代理。
+- **同时支持多个渠道** — 单个代理可以同时连接到 Discord、Slack、Telegram、LINE、QQ、微信、飞书和 Lark。LobeHub 会自动将消息路由到正确的代理。
- **安全的凭据存储** — 所有机器人令牌和应用密钥在存储前都会被加密。
## 快速开始
@@ -51,6 +53,7 @@ tags:
- [Discord](/docs/usage/channels/discord)
- [Slack](/docs/usage/channels/slack)
- [Telegram](/docs/usage/channels/telegram)
+ - [LINE](/docs/usage/channels/line)
- [QQ](/docs/usage/channels/qq)
- [微信](/docs/usage/channels/wechat)
- [飞书](/docs/usage/channels/feishu)
@@ -62,13 +65,13 @@ tags:
所有平台均支持文本消息。某些功能因平台而异:
-| 功能 | Discord | Slack | Telegram | QQ | 微信 | 飞书 | Lark |
-| --------- | ------- | ----- | -------- | -- | -- | ---- | ---- |
-| 文本消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |
-| 私人消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |
-| 群组聊天 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |
-| 表情反应 | 是 | 是 | 是 | 否 | 否 | 部分支持 | 部分支持 |
-| 图片 / 文件附件 | 是 | 是 | 是 | 是 | 否 | 是 | 是 |
+| 功能 | Discord | Slack | Telegram | LINE | QQ | 微信 | 飞书 | Lark |
+| --------- | ------- | ----- | -------- | ---- | -- | -- | ---- | ---- |
+| 文本消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |
+| 私人消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |
+| 群组聊天 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |
+| 表情反应 | 是 | 是 | 是 | 否 | 否 | 否 | 部分支持 | 部分支持 |
+| 图片 / 文件附件 | 是 | 是 | 是 | 仅入站 | 是 | 否 | 是 | 是 |
## 允许的用户(全局)
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 20c6adc136a..76ee5402da5 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -102,6 +102,19 @@
"channel.importInvalidFormat": "Invalid configuration file format",
"channel.importSuccess": "Configuration imported successfully",
"channel.lark.description": "Connect this assistant to Lark for private and group chats.",
+ "channel.line.channelAccessToken": "Channel Access Token",
+ "channel.line.channelAccessTokenHint": "Long-lived token issued under the Messaging API tab. Token will be encrypted and stored securely.",
+ "channel.line.channelSecret": "Channel Secret",
+ "channel.line.channelSecretHint": "From the Basic settings tab. Required — used to verify X-Line-Signature on every inbound webhook.",
+ "channel.line.description": "Connect this assistant to LINE Messaging API for direct and group chats.",
+ "channel.line.destinationUserId": "Destination User ID",
+ "channel.line.destinationUserIdHint": "The bot's destination user ID (starts with `U`, 33 chars total). The LINE Developers Console does NOT display this value. Issue a Channel Access Token below first, then click \"Fetch from LINE\" to auto-fill this field. Note: \"Your user ID\" in Basic settings is your personal LINE user ID, not the bot's.",
+ "channel.line.destinationUserIdPlaceholder": "e.g. U1234567890abcdef1234567890abcdef",
+ "channel.line.fetchBotInfo": "Fetch from LINE",
+ "channel.line.fetchBotInfoFailed": "Failed to fetch bot info",
+ "channel.line.fetchBotInfoMissingToken": "Enter the Channel Access Token first, then click \"Fetch from LINE\".",
+ "channel.line.fetchBotInfoSuccess": "Destination User ID fetched",
+ "channel.line.webhookManualSetup": "LINE does not allow programmatic webhook registration. Copy this URL into the LINE Developers Console (Messaging API → Webhook URL), click \"Verify\", and enable \"Use webhook\".",
"channel.openPlatform": "Open Platform",
"channel.platforms": "Platforms",
"channel.publicKey": "Public Key",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 76dca3508a3..1ecca54fe1d 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -102,6 +102,19 @@
"channel.importInvalidFormat": "配置文件格式无效",
"channel.importSuccess": "配置导入成功",
"channel.lark.description": "将助手连接到 Lark,支持私聊和群聊。",
+ "channel.line.channelAccessToken": "Channel Access Token",
+ "channel.line.channelAccessTokenHint": "在 Messaging API 选项卡中签发的长期 Token,将被加密并安全存储。",
+ "channel.line.channelSecret": "Channel Secret",
+ "channel.line.channelSecretHint": "Basic settings 选项卡中的密钥。必填 —— 用于校验每条入站 Webhook 的 X-Line-Signature。",
+ "channel.line.description": "通过 LINE Messaging API 将助手接入 LINE,支持私聊和群组对话。",
+ "channel.line.destinationUserId": "Destination User ID",
+ "channel.line.destinationUserIdHint": "机器人的 Destination User ID(以 U 开头,共 33 位)。LINE Developers Console 界面不展示此值。请先在下方填写 Channel Access Token,然后点击「从 LINE 获取」按钮自动填入。注意:Basic settings 中的 \"Your user ID\" 是你账号自己的 LINE user ID,不是 bot 的。",
+ "channel.line.destinationUserIdPlaceholder": "例如 U1234567890abcdef1234567890abcdef",
+ "channel.line.fetchBotInfo": "从 LINE 获取",
+ "channel.line.fetchBotInfoFailed": "获取 Bot 信息失败",
+ "channel.line.fetchBotInfoMissingToken": "请先填写 Channel Access Token,再点击「从 LINE 获取」。",
+ "channel.line.fetchBotInfoSuccess": "已获取 Destination User ID",
+ "channel.line.webhookManualSetup": "LINE 不支持自动注册 Webhook,请将此 URL 粘贴到 LINE Developers Console 的 Messaging API → Webhook URL,点击 \"Verify\" 并启用 \"Use webhook\"。",
"channel.openPlatform": "开放平台",
"channel.platforms": "平台",
"channel.publicKey": "公钥",
diff --git a/package.json b/package.json
index df412ab7d25..1b8831d09ef 100644
--- a/package.json
+++ b/package.json
@@ -238,6 +238,7 @@
"@lobechat/business-const": "workspace:*",
"@lobechat/business-model-runtime": "workspace:*",
"@lobechat/chat-adapter-feishu": "workspace:*",
+ "@lobechat/chat-adapter-line": "workspace:*",
"@lobechat/chat-adapter-qq": "workspace:*",
"@lobechat/chat-adapter-wechat": "workspace:*",
"@lobechat/config": "workspace:*",
diff --git a/packages/chat-adapter-line/package.json b/packages/chat-adapter-line/package.json
new file mode 100644
index 00000000000..51e05650a94
--- /dev/null
+++ b/packages/chat-adapter-line/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "@lobechat/chat-adapter-line",
+ "version": "0.1.0",
+ "description": "LINE Messaging API Bot adapter for chat SDK",
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "files": [
+ "dist"
+ ],
+ "scripts": {
+ "build": "tsup",
+ "clean": "rm -rf dist",
+ "dev": "tsup --watch",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "chat": "^4.23.0",
+ "mime": "^4.1.0"
+ },
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "tsup": "^8.3.5",
+ "typescript": "^5.7.2"
+ }
+}
diff --git a/packages/chat-adapter-line/src/adapter.test.ts b/packages/chat-adapter-line/src/adapter.test.ts
new file mode 100644
index 00000000000..20c768c02aa
--- /dev/null
+++ b/packages/chat-adapter-line/src/adapter.test.ts
@@ -0,0 +1,259 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ createLineAdapter,
+ extractMediaMetadata,
+ getMediaFileNameAndType,
+ LineAdapter,
+ resolveMediaMessageId,
+} from './adapter';
+import { computeSignature } from './api';
+import type { LineMessageEvent, LineWebhookPayload } from './types';
+
+const baseConfig = {
+ channelAccessToken: 'token-test',
+ channelSecret: 'secret-test',
+ destinationUserId: 'Ubotbotbotbotbotbotbotbotbotbotbo',
+};
+
+function makeAdapter(overrides: Partial<typeof baseConfig> = {}) {
+ const adapter = createLineAdapter({ ...baseConfig, ...overrides });
+ const processMessage = vi.fn(
+ async (_adapter: unknown, _threadId: string, factory: () => Promise<unknown> | unknown) =>
+ factory(),
+ );
+ const chat = {
+ getLogger: () => ({
+ child: () => ({}),
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+ getUserName: () => 'line-bot',
+ processMessage,
+ } as any;
+ return { adapter, chat, processMessage };
+}
+
+function buildPayload(eventOverride: Partial<LineMessageEvent>): LineWebhookPayload {
+ const event: LineMessageEvent = {
+ message: { id: '1000', text: 'hi bot', type: 'text' },
+ mode: 'active',
+ source: { type: 'user', userId: 'U1234567890abcdef1234567890abcdef' },
+ timestamp: 1_700_000_000_000,
+ type: 'message',
+ ...(eventOverride as object),
+ } as LineMessageEvent;
+ return {
+ destination: baseConfig.destinationUserId,
+ events: [event],
+ };
+}
+
+function makeRequest(method: string, body: string, headers: Record<string, string> = {}): Request {
+ return new Request('https://example.com/api/agent/webhooks/line/test', {
+ body: method === 'GET' ? undefined : body,
+ headers,
+ method,
+ });
+}
+
+describe('LineAdapter (signature verification)', () => {
+ it('rejects POST with missing signature', async () => {
+ const { adapter, chat } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const body = JSON.stringify(buildPayload({}));
+ const res = await adapter.handleWebhook(makeRequest('POST', body));
+ expect(res.status).toBe(401);
+ });
+
+ it('rejects POST with mismatched signature', async () => {
+ const { adapter, chat } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const body = JSON.stringify(buildPayload({}));
+ const res = await adapter.handleWebhook(
+ makeRequest('POST', body, { 'x-line-signature': 'AAAA=' }),
+ );
+ expect(res.status).toBe(401);
+ });
+
+ it('accepts POST with valid signature and dispatches a message event', async () => {
+ const { adapter, chat, processMessage } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const body = JSON.stringify(buildPayload({}));
+ const sig = computeSignature(body, baseConfig.channelSecret);
+ const res = await adapter.handleWebhook(makeRequest('POST', body, { 'x-line-signature': sig }));
+
+ expect(res.status).toBe(200);
+ expect(processMessage).toHaveBeenCalledTimes(1);
+ const [, threadId] = processMessage.mock.calls[0];
+ expect(threadId).toBe('line:user:U1234567890abcdef1234567890abcdef');
+ });
+
+ it('returns 200 on the empty-events verification ping with a valid signature', async () => {
+ const { adapter, chat, processMessage } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const body = JSON.stringify({ destination: baseConfig.destinationUserId, events: [] });
+ const sig = computeSignature(body, baseConfig.channelSecret);
+ const res = await adapter.handleWebhook(makeRequest('POST', body, { 'x-line-signature': sig }));
+
+ expect(res.status).toBe(200);
+ expect(processMessage).not.toHaveBeenCalled();
+ });
+
+ it('rejects non-POST verbs with 405', async () => {
+ const { adapter, chat } = makeAdapter();
+ await adapter.initialize(chat);
+ const res = await adapter.handleWebhook(makeRequest('GET', ''));
+ expect(res.status).toBe(405);
+ });
+});
+
+describe('LineAdapter (parsing)', () => {
+ it('parses a 1:1 text message into a Message with the right thread id', async () => {
+ const { adapter, chat, processMessage } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const body = JSON.stringify(
+ buildPayload({
+ message: { id: '4242', text: 'Hello bot', type: 'text' },
+ timestamp: 1_700_001_234_000,
+ }),
+ );
+ const sig = computeSignature(body, baseConfig.channelSecret);
+ await adapter.handleWebhook(makeRequest('POST', body, { 'x-line-signature': sig }));
+
+ const factory = processMessage.mock.calls[0][2] as () => Promise<any>;
+ const message = await factory();
+ expect(message.text).toBe('Hello bot');
+ expect(message.id).toBe('4242');
+ expect(message.threadId).toBe('line:user:U1234567890abcdef1234567890abcdef');
+ expect(message.metadata.dateSent.getTime()).toBe(1_700_001_234_000);
+ });
+
+ it('encodes group + room thread ids using groupId / roomId', async () => {
+ const { adapter, chat, processMessage } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const groupBody = JSON.stringify(
+ buildPayload({
+ source: {
+ groupId: 'Cgroupgroupgroupgroupgroupgroupgr',
+ type: 'group',
+ userId: 'U1234567890abcdef1234567890abcdef',
+ },
+ }),
+ );
+ const groupSig = computeSignature(groupBody, baseConfig.channelSecret);
+ await adapter.handleWebhook(makeRequest('POST', groupBody, { 'x-line-signature': groupSig }));
+ expect(processMessage.mock.calls[0][1]).toBe('line:group:Cgroupgroupgroupgroupgroupgroupgr');
+
+ processMessage.mockClear();
+
+ const roomBody = JSON.stringify(
+ buildPayload({
+ source: {
+ roomId: 'Rroomroomroomroomroomroomroomroom',
+ type: 'room',
+ userId: 'U1234567890abcdef1234567890abcdef',
+ },
+ }),
+ );
+ const roomSig = computeSignature(roomBody, baseConfig.channelSecret);
+ await adapter.handleWebhook(makeRequest('POST', roomBody, { 'x-line-signature': roomSig }));
+ expect(processMessage.mock.calls[0][1]).toBe('line:room:Rroomroomroomroomroomroomroomroom');
+ });
+
+ it('extracts metadata-only attachments for image/video/audio/file messages', () => {
+ const image = extractMediaMetadata({ id: 'img-1', type: 'image' });
+ expect(image).toHaveLength(1);
+ expect(image[0].type).toBe('image');
+ expect(image[0].mimeType).toBe('image/jpeg');
+ expect((image[0] as any).raw.id).toBe('img-1');
+
+ const file = extractMediaMetadata({
+ fileName: 'spec.pdf',
+ id: 'doc-1',
+ type: 'file',
+ });
+ expect(file[0].type).toBe('file');
+ expect(file[0].name).toBe('spec.pdf');
+
+ expect(
+ extractMediaMetadata({ id: 's-1', packageId: '1', stickerId: '1', type: 'sticker' }),
+ ).toEqual([]);
+ });
+
+ it('resolveMediaMessageId returns the LINE message id only for downloadable kinds', () => {
+ expect(resolveMediaMessageId({ id: 'img-1', type: 'image' })).toBe('img-1');
+ expect(resolveMediaMessageId({ id: 'vid-1', type: 'video' })).toBe('vid-1');
+ expect(resolveMediaMessageId({ id: 'au-1', type: 'audio' })).toBe('au-1');
+ expect(resolveMediaMessageId({ id: 'f-1', type: 'file' })).toBe('f-1');
+ expect(resolveMediaMessageId({ id: 'txt', text: 'hi', type: 'text' })).toBeUndefined();
+ expect(getMediaFileNameAndType({ fileName: 'a.pdf', id: 'f-1', type: 'file' }).fileName).toBe(
+ 'a.pdf',
+ );
+ });
+});
+
+describe('LineAdapter (outbound)', () => {
+ let fetchSpy: any;
+
+ beforeEach(() => {
+ fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockImplementation(async () => new Response('{}', { status: 200 }));
+ });
+
+ afterEach(() => {
+ fetchSpy.mockRestore();
+ });
+
+ it('postMessage hits /v2/bot/message/push with text payload', async () => {
+ const adapter = new LineAdapter(baseConfig);
+ await adapter.postMessage('line:user:U1234567890abcdef1234567890abcdef', 'hi back' as any);
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe('https://api.line.me/v2/bot/message/push');
+ expect(init.method).toBe('POST');
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer token-test');
+ const body = JSON.parse(init.body as string);
+ expect(body.to).toBe('U1234567890abcdef1234567890abcdef');
+ expect(body.messages).toEqual([{ text: 'hi back', type: 'text' }]);
+ });
+
+ it('startTyping uses loading API only for user threads', async () => {
+ const adapter = new LineAdapter(baseConfig);
+ await adapter.initialize({
+ getLogger: () => ({
+ child: () => ({}),
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+ getUserName: () => 'line-bot',
+ processMessage: vi.fn(),
+ } as any);
+
+ await adapter.startTyping('line:user:U1234567890abcdef1234567890abcdef');
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe('https://api.line.me/v2/bot/chat/loading/start');
+ const body = JSON.parse(init.body as string);
+ expect(body.chatId).toBe('U1234567890abcdef1234567890abcdef');
+
+ fetchSpy.mockClear();
+ await adapter.startTyping('line:group:Cgroupgroupgroupgroupgroupgroupgr');
+ expect(fetchSpy).not.toHaveBeenCalled();
+
+ await adapter.startTyping('line:room:Rroomroomroomroomroomroomroomroom');
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/chat-adapter-line/src/adapter.ts b/packages/chat-adapter-line/src/adapter.ts
new file mode 100644
index 00000000000..9a2f5c29441
--- /dev/null
+++ b/packages/chat-adapter-line/src/adapter.ts
@@ -0,0 +1,501 @@
+import type {
+ Adapter,
+ AdapterPostableMessage,
+ Attachment,
+ Author,
+ ChatInstance,
+ EmojiValue,
+ FetchOptions,
+ FetchResult,
+ FormattedContent,
+ Logger,
+ RawMessage,
+ ThreadInfo,
+ WebhookOptions,
+} from 'chat';
+import { Message, parseMarkdown } from 'chat';
+
+import { LineApiClient, verifySignature } from './api';
+import { LineFormatConverter } from './format-converter';
+import type {
+ LineAdapterConfig,
+ LineMessage,
+ LineMessageEvent,
+ LineSource,
+ LineThreadId,
+ LineWebhookPayload,
+} from './types';
+
+/**
+ * Pull user-visible text from an inbound message. We surface placeholders
+ * for non-text payloads so the LLM still has something to react to (and
+ * a sticker's `text`/keywords stand in as a hint of intent).
+ */
+function extractText(message: LineMessage): string {
+ switch (message.type) {
+ case 'text': {
+ return message.text ?? '';
+ }
+ case 'sticker': {
+ // LINE returns either an explicit `text` for branded stickers or a
+ // keyword list — fall through `text` first, then keywords.
+ if (message.text) return message.text;
+ if (message.keywords?.length) return `[sticker: ${message.keywords.join(', ')}]`;
+ return '[sticker]';
+ }
+ case 'location': {
+ const parts = [message.title, message.address].filter(Boolean);
+ return parts.length > 0 ? `[location: ${parts.join(', ')}]` : '[location]';
+ }
+ case 'image':
+ case 'video':
+ case 'audio':
+ case 'file': {
+ // Captions are not part of LINE message payloads — surface a marker
+ // so the model knows the user attached something.
+ const fileName = (message as { fileName?: string }).fileName;
+ return fileName ? `[${message.type}: ${fileName}]` : '';
+ }
+ default: {
+ return '';
+ }
+ }
+}
+
+function chatAttachmentType(type: 'audio' | 'file' | 'image' | 'video'): string {
+ switch (type) {
+ case 'image': {
+ return 'image';
+ }
+ case 'video': {
+ return 'video';
+ }
+ case 'audio': {
+ return 'audio';
+ }
+ case 'file':
+ default: {
+ return 'file';
+ }
+ }
+}
+
+function defaultMimeForType(type: string | undefined): string {
+ switch (type) {
+ case 'image': {
+ return 'image/jpeg';
+ }
+ case 'video': {
+ return 'video/mp4';
+ }
+ case 'audio': {
+ return 'audio/m4a';
+ }
+ default: {
+ return 'application/octet-stream';
+ }
+ }
+}
+
+function defaultNameForType(type: string | undefined, fileName?: string): string {
+ if (fileName) return fileName;
+ switch (type) {
+ case 'image': {
+ return 'image.jpg';
+ }
+ case 'video': {
+ return 'video.mp4';
+ }
+ case 'audio': {
+ return 'audio.m4a';
+ }
+ default: {
+ return 'file.bin';
+ }
+ }
+}
+
+/**
+ * Walk a raw LINE message into metadata-only attachments. Bytes are
+ * downloaded later, on demand, by the platform client's `extractFiles`
+ * via the data-domain content endpoint.
+ */
+export function extractMediaMetadata(message: LineMessage): Attachment[] {
+ const attachments: Attachment[] = [];
+ if (
+ message.type !== 'image' &&
+ message.type !== 'video' &&
+ message.type !== 'audio' &&
+ message.type !== 'file'
+ ) {
+ return attachments;
+ }
+ const mimeType = defaultMimeForType(message.type);
+ attachments.push({
+ mimeType,
+ name: defaultNameForType(message.type, (message as { fileName?: string }).fileName),
+ type: chatAttachmentType(message.type),
+ url: '',
+ // Spread the raw payload (already carries `id`) and tack the inferred
+ // mimeType on top so server-side `extractFiles` can find both.
+ raw: { ...message, mimeType },
+ } as Attachment);
+ return attachments;
+}
+
+function sourceTypeFromEvent(source: LineSource): LineThreadId['type'] {
+ return source.type;
+}
+
+function sourceIdFromEvent(source: LineSource): string {
+ switch (source.type) {
+ case 'group': {
+ return source.groupId ?? source.userId ?? '';
+ }
+ case 'room': {
+ return source.roomId ?? source.userId ?? '';
+ }
+ case 'user':
+ default: {
+ return source.userId ?? '';
+ }
+ }
+}
+
+/**
+ * LINE Messaging API adapter for Chat SDK.
+ *
+ * Owns:
+ * - POST signature verification (`X-Line-Signature` = base64 HMAC-SHA256)
+ * - Per-event fan-out for `type: "message"` events
+ * - Outbound text via the Messaging API push endpoint
+ * - 1:1 typing indicator (loading animation API)
+ *
+ * Does NOT own:
+ * - Media binary download — handled by the server-side platform client
+ * because `Message.toJSON` strips buffers across the Redis queue.
+ * - Reply-token-based responses — `replyToken` expires in ~60s, so we
+ * always push instead.
+ * - Editing / deleting — LINE doesn't expose either.
+ */
+export class LineAdapter implements Adapter<LineThreadId, LineMessage> {
+ readonly name = 'line';
+
+ private readonly api: LineApiClient;
+ private readonly formatConverter: LineFormatConverter;
+ private readonly channelSecret: string;
+ private readonly destinationUserId: string;
+
+ private _userName: string;
+ private chat!: ChatInstance;
+ private logger!: Logger;
+
+ constructor(config: LineAdapterConfig & { userName?: string }) {
+ if (!config.channelAccessToken) throw new Error('LINE adapter requires channelAccessToken');
+ if (!config.channelSecret) throw new Error('LINE adapter requires channelSecret');
+ if (!config.destinationUserId) throw new Error('LINE adapter requires destinationUserId');
+
+ this.api = new LineApiClient({
+ accessToken: config.channelAccessToken,
+ baseUrl: config.apiBaseUrl,
+ dataBaseUrl: config.apiDataBaseUrl,
+ });
+ this.formatConverter = new LineFormatConverter();
+ this.channelSecret = config.channelSecret;
+ this.destinationUserId = config.destinationUserId;
+ this._userName = config.userName || 'line-bot';
+ }
+
+ get userName(): string {
+ return this._userName;
+ }
+
+ get botUserId(): string {
+ return this.destinationUserId;
+ }
+
+ async initialize(chat: ChatInstance): Promise<void> {
+ this.chat = chat;
+ this.logger = chat.getLogger(this.name);
+ this._userName = chat.getUserName();
+ this.logger.info('Initialized LINE adapter (destination=%s)', this.destinationUserId);
+ }
+
+ // ------------------------------------------------------------------
+ // Webhook handling
+ // ------------------------------------------------------------------
+
+ async handleWebhook(request: Request, options?: WebhookOptions): Promise<Response> {
+ if (request.method !== 'POST') {
+ return new Response('Method not allowed', { status: 405 });
+ }
+
+ const bodyText = await request.text();
+ const signature = request.headers.get('x-line-signature');
+ if (!verifySignature(bodyText, signature, this.channelSecret)) {
+ this.logger.warn('Rejected LINE webhook with invalid X-Line-Signature');
+ return new Response('Invalid signature', { status: 401 });
+ }
+
+ let payload: LineWebhookPayload;
+ try {
+ payload = JSON.parse(bodyText);
+ } catch {
+ return new Response('Invalid JSON', { status: 400 });
+ }
+
+ if (!Array.isArray(payload?.events)) {
+ // The "Verify" button in the LINE Developers Console fires a POST
+ // with `events: []` — we accept it so the verification handshake
+ // succeeds without dispatching to the SDK.
+ return Response.json({ ok: true });
+ }
+
+ for (const event of payload.events) {
+ if (event.type === 'message') {
+ await this.dispatchMessageEvent(event as LineMessageEvent, options);
+ }
+ }
+
+ return Response.json({ ok: true });
+ }
+
+ private async dispatchMessageEvent(
+ event: LineMessageEvent,
+ options?: WebhookOptions,
+ ): Promise<void> {
+ const message = event.message;
+ const source = event.source;
+ if (!message?.id || !source) return;
+
+ const sourceId = sourceIdFromEvent(source);
+ if (!sourceId) return;
+
+ const threadId = this.encodeThreadId({ id: sourceId, type: sourceTypeFromEvent(source) });
+ const senderUserId = source.userId ?? sourceId;
+ const messageFactory = async () => this.parseInbound(event, threadId, senderUserId);
+ this.chat.processMessage(this, threadId, messageFactory, options);
+ }
+
+ // ------------------------------------------------------------------
+ // Message operations
+ // ------------------------------------------------------------------
+
+ async postMessage(
+ threadId: string,
+ message: AdapterPostableMessage,
+ ): Promise<RawMessage<LineMessage>> {
+ const { id: to } = this.decodeThreadId(threadId);
+ const text = this.formatConverter.renderPostable(message);
+ await this.api.pushText(to, text);
+
+ const localId = `local_${Date.now()}`;
+ return {
+ id: localId,
+ raw: {
+ id: localId,
+ text,
+ type: 'text',
+ },
+ threadId,
+ };
+ }
+
+ async editMessage(
+ threadId: string,
+ _messageId: string,
+ message: AdapterPostableMessage,
+ ): Promise<RawMessage<LineMessage>> {
+ // LINE does not support editing — fall back to a new push.
+ return this.postMessage(threadId, message);
+ }
+
+ async deleteMessage(_threadId: string, _messageId: string): Promise<void> {
+ this.logger.warn('Message deletion not supported for LINE');
+ }
+
+ async fetchMessages(
+ _threadId: string,
+ _options?: FetchOptions,
+ ): Promise<FetchResult<LineMessage>> {
+ return { messages: [], nextCursor: undefined };
+ }
+
+ async fetchThread(threadId: string): Promise<ThreadInfo> {
+ const { id, type } = this.decodeThreadId(threadId);
+ return {
+ channelId: threadId,
+ id: threadId,
+ isDM: type === 'user',
+ metadata: { id, type },
+ };
+ }
+
+ // ------------------------------------------------------------------
+ // Reactions & typing
+ // ------------------------------------------------------------------
+
+ async addReaction(
+ _threadId: string,
+ _messageId: string,
+ _emoji: EmojiValue | string,
+ ): Promise<void> {
+ // LINE bots cannot send reactions today — keep a no-op.
+ }
+
+ async removeReaction(
+ _threadId: string,
+ _messageId: string,
+ _emoji: EmojiValue | string,
+ ): Promise<void> {}
+
+ async startTyping(threadId: string): Promise<void> {
+ const { id, type } = this.decodeThreadId(threadId);
+ if (type !== 'user') {
+ // The loading animation API is only valid for 1:1 user chats.
+ return;
+ }
+ try {
+ await this.api.startLoading(id);
+ } catch (err) {
+ this.logger.warn('startTyping failed: %s', err);
+ }
+ }
+
+ // ------------------------------------------------------------------
+ // Message parsing
+ // ------------------------------------------------------------------
+
+ parseMessage(raw: LineMessage, threadId?: string): Message<LineMessage> {
+ const text = extractText(raw);
+ const formatted = parseMarkdown(text);
+
+ return new Message({
+ attachments: extractMediaMetadata(raw),
+ author: {
+ fullName: this.destinationUserId,
+ isBot: false,
+ isMe: false,
+ userId: this.destinationUserId,
+ userName: this.destinationUserId,
+ },
+ formatted,
+ id: raw.id,
+ metadata: { dateSent: new Date(), edited: false },
+ raw,
+ text,
+ threadId: threadId ?? this.encodeThreadId({ id: this.destinationUserId, type: 'user' }),
+ });
+ }
+
+ private parseInbound(
+ event: LineMessageEvent,
+ threadId: string,
+ senderUserId: string,
+ ): Message<LineMessage> {
+ const text = extractText(event.message);
+ const formatted = parseMarkdown(text);
+
+ const author: Author = {
+ fullName: senderUserId,
+ isBot: false,
+ isMe: false,
+ userId: senderUserId,
+ userName: senderUserId,
+ };
+
+ return new Message({
+ attachments: extractMediaMetadata(event.message),
+ author,
+ formatted,
+ id: event.message.id,
+ metadata: {
+ dateSent: new Date(event.timestamp || Date.now()),
+ edited: false,
+ },
+ raw: event.message,
+ text,
+ threadId,
+ });
+ }
+
+ // ------------------------------------------------------------------
+ // Thread ID encoding
+ // ------------------------------------------------------------------
+
+ encodeThreadId(data: LineThreadId): string {
+ return `line:${data.type}:${data.id}`;
+ }
+
+ decodeThreadId(threadId: string): LineThreadId {
+ const parts = threadId.split(':');
+ if (parts.length < 3 || parts[0] !== 'line') {
+ return { id: threadId, type: 'user' };
+ }
+ const type = parts[1] as LineThreadId['type'];
+ return {
+ id: parts.slice(2).join(':'),
+ type: type === 'group' || type === 'room' ? type : 'user',
+ };
+ }
+
+ channelIdFromThreadId(threadId: string): string {
+ return threadId;
+ }
+
+ isDM(threadId: string): boolean {
+ return this.decodeThreadId(threadId).type === 'user';
+ }
+
+ // ------------------------------------------------------------------
+ // Format rendering
+ // ------------------------------------------------------------------
+
+ renderFormatted(content: FormattedContent): string {
+ return this.formatConverter.fromAst(content);
+ }
+}
+
+export function createLineAdapter(config: LineAdapterConfig & { userName?: string }): LineAdapter {
+ return new LineAdapter(config);
+}
+
+/**
+ * Server-side helper: given a raw LINE message, return its `messageId` if it
+ * is a downloadable media payload. Used by the platform client's
+ * `extractFiles` to know whether to call `LineApiClient.downloadContent`.
+ */
+export function resolveMediaMessageId(raw: LineMessage | undefined): string | undefined {
+ if (!raw) return undefined;
+ switch (raw.type) {
+ case 'image':
+ case 'video':
+ case 'audio':
+ case 'file': {
+ return raw.id;
+ }
+ default: {
+ return undefined;
+ }
+ }
+}
+
+export function getMediaFileNameAndType(raw: LineMessage | undefined): {
+ fileName?: string;
+ type?: 'audio' | 'file' | 'image' | 'video';
+} {
+ if (!raw) return {};
+ switch (raw.type) {
+ case 'image':
+ case 'video':
+ case 'audio': {
+ return { type: raw.type };
+ }
+ case 'file': {
+ return { fileName: raw.fileName, type: 'file' };
+ }
+ default: {
+ return {};
+ }
+ }
+}
diff --git a/packages/chat-adapter-line/src/api.test.ts b/packages/chat-adapter-line/src/api.test.ts
new file mode 100644
index 00000000000..0c56af6b559
--- /dev/null
+++ b/packages/chat-adapter-line/src/api.test.ts
@@ -0,0 +1,93 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { computeSignature, LineApiClient, verifySignature } from './api';
+
+const fetchSpy = vi.spyOn(globalThis, 'fetch');
+
+afterEach(() => {
+ fetchSpy.mockReset();
+});
+
+describe('computeSignature / verifySignature', () => {
+ it('round-trips on matching body + secret using base64', () => {
+ const body = '{"hello":"world"}';
+ const secret = 'shh';
+ const sig = computeSignature(body, secret);
+ // LINE uses base64 (not hex / not "sha256=" prefix).
+ expect(sig).toMatch(/^[A-Z0-9+/=]+$/i);
+ expect(verifySignature(body, sig, secret)).toBe(true);
+ });
+
+ it('rejects tampered body, wrong secret, missing header', () => {
+ const body = '{"hello":"world"}';
+ const sig = computeSignature(body, 'shh');
+ expect(verifySignature('tampered', sig, 'shh')).toBe(false);
+ expect(verifySignature(body, sig, 'other')).toBe(false);
+ expect(verifySignature(body, null, 'shh')).toBe(false);
+ expect(verifySignature(body, sig, '')).toBe(false);
+ });
+});
+
+describe('LineApiClient', () => {
+ beforeEach(() => {
+ fetchSpy.mockResolvedValue(new Response('{}', { status: 200 }));
+ });
+
+ it('pushText posts to /v2/bot/message/push with bearer header + text envelope', async () => {
+ const api = new LineApiClient({ accessToken: 't' });
+ await api.pushText('U-target', 'hello');
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe('https://api.line.me/v2/bot/message/push');
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer t');
+ const body = JSON.parse(init.body as string);
+ expect(body).toEqual({
+ messages: [{ text: 'hello', type: 'text' }],
+ to: 'U-target',
+ });
+ });
+
+ it('startLoading defaults to 20 seconds', async () => {
+ const api = new LineApiClient({ accessToken: 't' });
+ await api.startLoading('U-target');
+
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe('https://api.line.me/v2/bot/chat/loading/start');
+ const body = JSON.parse(init.body as string);
+ expect(body).toEqual({ chatId: 'U-target', loadingSeconds: 20 });
+ });
+
+ it('downloadContent hits the data subdomain with bearer header', async () => {
+ fetchSpy.mockResolvedValueOnce(new Response(new Uint8Array([1, 2, 3]), { status: 200 }));
+ const api = new LineApiClient({ accessToken: 't' });
+ const buf = await api.downloadContent('msg-1');
+
+ expect(buf).toEqual(Buffer.from([1, 2, 3]));
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe('https://api-data.line.me/v2/bot/message/msg-1/content');
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer t');
+ });
+
+ it('getBotInfo throws with the LINE error envelope message on failure', async () => {
+ fetchSpy.mockResolvedValueOnce(
+ new Response(JSON.stringify({ message: 'Authentication failed.' }), { status: 401 }),
+ );
+ const api = new LineApiClient({ accessToken: 'bad' });
+ await expect(api.getBotInfo()).rejects.toThrow('Authentication failed.');
+ });
+
+ it('pushText surfaces details[0].message when the API returns a 4xx', async () => {
+ fetchSpy.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ details: [{ message: 'Invalid recipient', property: 'to' }],
+ message: 'Bad request',
+ }),
+ { status: 400 },
+ ),
+ );
+ const api = new LineApiClient({ accessToken: 't' });
+ await expect(api.pushText('U-target', 'hi')).rejects.toThrow(/Invalid recipient/);
+ });
+});
diff --git a/packages/chat-adapter-line/src/api.ts b/packages/chat-adapter-line/src/api.ts
new file mode 100644
index 00000000000..fa18e777cfc
--- /dev/null
+++ b/packages/chat-adapter-line/src/api.ts
@@ -0,0 +1,178 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+import type {
+ LineApiError,
+ LineBotInfoResponse,
+ LineLoadingStartRequest,
+ LinePushMessageRequest,
+} from './types';
+
+export const DEFAULT_API_BASE_URL = 'https://api.line.me';
+export const DEFAULT_API_DATA_BASE_URL = 'https://api-data.line.me';
+
+/**
+ * LINE Messaging API REST client.
+ *
+ * Stateless — instances are cheap to create and reuse. All methods throw on
+ * HTTP failure with the LINE error envelope's `message` field, including
+ * the first detail from `details[]` when present so 400 / 401 surface a
+ * useful operator-facing reason.
+ */
+export class LineApiClient {
+ readonly accessToken: string;
+ readonly baseUrl: string;
+ readonly dataBaseUrl: string;
+
+ constructor(options: { accessToken: string; baseUrl?: string; dataBaseUrl?: string }) {
+ this.accessToken = options.accessToken;
+ this.baseUrl = stripTrailingSlashes(options.baseUrl || DEFAULT_API_BASE_URL);
+ this.dataBaseUrl = stripTrailingSlashes(options.dataBaseUrl || DEFAULT_API_DATA_BASE_URL);
+ }
+
+ private get authHeaders(): Record<string, string> {
+ return {
+ 'Authorization': `Bearer ${this.accessToken}`,
+ 'Content-Type': 'application/json',
+ };
+ }
+
+ /**
+ * Send a plain-text push message. We always use push (not reply) because
+ * LINE's `replyToken` expires in ~60 s and the agent's response can take
+ * longer than that. Push counts against the channel quota for paid plans;
+ * for the free Developer Trial it's effectively unlimited.
+ * @see https://developers.line.biz/en/reference/messaging-api/#send-push-message
+ */
+ async pushText(to: string, body: string): Promise<void> {
+ const payload: LinePushMessageRequest = {
+ messages: [{ text: body, type: 'text' }],
+ to,
+ };
+ await this.post('/v2/bot/message/push', payload);
+ }
+
+ /**
+ * Surface the typing-style "loading" animation in a 1:1 user chat. LINE
+ * does not expose this for groups or multi-person rooms — callers must
+ * already have decided the recipient is a user. Returns silently on
+ * non-user recipients to keep the messenger interface uniform.
+ * @see https://developers.line.biz/en/reference/messaging-api/#display-a-loading-indicator
+ */
+ async startLoading(chatId: string, loadingSeconds = 20): Promise<void> {
+ const payload: LineLoadingStartRequest = { chatId, loadingSeconds };
+ await this.post('/v2/bot/chat/loading/start', payload);
+ }
+
+ /**
+ * Resolve binary content for a media `messageId`. The response is the raw
+ * bytes — the call is on the data-domain host, not the API host.
+ * @see https://developers.line.biz/en/reference/messaging-api/#get-content
+ */
+ async downloadContent(messageId: string): Promise<Buffer> {
+ const url = `${this.dataBaseUrl}/v2/bot/message/${encodeURIComponent(messageId)}/content`;
+ const res = await fetch(url, {
+ headers: { Authorization: `Bearer ${this.accessToken}` },
+ method: 'GET',
+ });
+ if (!res.ok) {
+ const detail = await safeReadError(res);
+ throw new Error(detail || `downloadContent ${messageId} failed with HTTP ${res.status}`);
+ }
+ return Buffer.from(await res.arrayBuffer());
+ }
+
+ /**
+ * Verify the access token + bot identity. Used both by the lobehub
+ * `validateCredentials` flow and by the platform client `start()` to
+ * guard against a clearly-broken provider reaching the connected state.
+ * @see https://developers.line.biz/en/reference/messaging-api/#get-bot-info
+ */
+ async getBotInfo(): Promise<LineBotInfoResponse> {
+ const res = await fetch(`${this.baseUrl}/v2/bot/info`, {
+ headers: { Authorization: `Bearer ${this.accessToken}` },
+ method: 'GET',
+ });
+ return parseResponse<LineBotInfoResponse>(res, 'getBotInfo');
+ }
+
+ private async post(path: string, body: unknown): Promise<void> {
+ const res = await fetch(`${this.baseUrl}${path}`, {
+ body: JSON.stringify(body),
+ headers: this.authHeaders,
+ method: 'POST',
+ });
+ if (!res.ok) {
+ const detail = await safeReadError(res);
+ throw new Error(detail || `${path} failed with HTTP ${res.status}`);
+ }
+ }
+}
+
+/**
+ * Compute the expected `X-Line-Signature` value for an inbound webhook body.
+ * LINE signs the **raw bytes** of the request body with the channel secret
+ * and emits the digest in **base64** (not hex like WhatsApp).
+ */
+export function computeSignature(body: string, channelSecret: string): string {
+ const hmac = createHmac('sha256', channelSecret);
+ hmac.update(body, 'utf8');
+ return hmac.digest('base64');
+}
+
+/**
+ * Validate an `X-Line-Signature` header. Returns false on missing / malformed
+ * / mismatched signatures — never throws.
+ */
+export function verifySignature(
+ body: string,
+ signatureHeader: string | null | undefined,
+ channelSecret: string,
+): boolean {
+ if (!signatureHeader || !channelSecret) return false;
+ const expected = computeSignature(body, channelSecret);
+ const expectedBuf = Buffer.from(expected);
+ const actualBuf = Buffer.from(signatureHeader);
+ if (expectedBuf.length !== actualBuf.length) return false;
+ return timingSafeEqual(expectedBuf, actualBuf);
+}
+
+function stripTrailingSlashes(url: string): string {
+ let end = url.length;
+ while (end > 0 && url[end - 1] === '/') end--;
+ return url.slice(0, end);
+}
+
+async function parseResponse<T>(response: Response, label: string): Promise<T> {
+ const text = await response.text();
+ let payload: T | undefined;
+ try {
+ payload = text ? (JSON.parse(text) as T) : undefined;
+ } catch {
+ payload = undefined;
+ }
+
+ if (!response.ok) {
+ const errMsg = readErrorMessage(payload as LineApiError | undefined);
+ throw new Error(errMsg || `${label} failed with HTTP ${response.status}`);
+ }
+
+ return (payload ?? ({} as T)) as T;
+}
+
+async function safeReadError(response: Response): Promise<string | undefined> {
+ try {
+ const text = await response.text();
+ if (!text) return undefined;
+ const payload = JSON.parse(text) as LineApiError;
+ return readErrorMessage(payload);
+ } catch {
+ return undefined;
+ }
+}
+
+function readErrorMessage(payload: LineApiError | undefined): string | undefined {
+ if (!payload) return undefined;
+ const detailMsg = payload.details?.[0]?.message;
+ if (payload.message && detailMsg) return `${payload.message}: ${detailMsg}`;
+ return payload.message ?? detailMsg;
+}
diff --git a/packages/chat-adapter-line/src/format-converter.ts b/packages/chat-adapter-line/src/format-converter.ts
new file mode 100644
index 00000000000..ff51a1090a0
--- /dev/null
+++ b/packages/chat-adapter-line/src/format-converter.ts
@@ -0,0 +1,19 @@
+import type { Root } from 'chat';
+import { BaseFormatConverter, parseMarkdown, stringifyMarkdown } from 'chat';
+
+/**
+ * LINE's Messaging API renders text messages as **plain text** — no markdown,
+ * no HTML, no rich blocks (rich content uses Flex Messages, which we don't
+ * use here). The format converter therefore round-trips through
+ * `stringifyMarkdown`, and the platform client further runs `stripMarkdown`
+ * before sending so emphasis / heading / list markers are removed.
+ */
+export class LineFormatConverter extends BaseFormatConverter {
+ fromAst(ast: Root): string {
+ return stringifyMarkdown(ast);
+ }
+
+ toAst(text: string): Root {
+ return parseMarkdown(text.trim());
+ }
+}
diff --git a/packages/chat-adapter-line/src/index.ts b/packages/chat-adapter-line/src/index.ts
new file mode 100644
index 00000000000..8774d3627cd
--- /dev/null
+++ b/packages/chat-adapter-line/src/index.ts
@@ -0,0 +1,35 @@
+export {
+ createLineAdapter,
+ extractMediaMetadata,
+ getMediaFileNameAndType,
+ LineAdapter,
+ resolveMediaMessageId,
+} from './adapter';
+export {
+ computeSignature,
+ DEFAULT_API_BASE_URL,
+ DEFAULT_API_DATA_BASE_URL,
+ LineApiClient,
+ verifySignature,
+} from './api';
+export { LineFormatConverter } from './format-converter';
+export type {
+ LineAdapterConfig,
+ LineApiError,
+ LineBotInfoResponse,
+ LineGenericEvent,
+ LineLoadingStartRequest,
+ LineLocationMessage,
+ LineMediaMessage,
+ LineMessage,
+ LineMessageContentType,
+ LineMessageEvent,
+ LinePushMessageRequest,
+ LineSource,
+ LineSourceType,
+ LineStickerMessage,
+ LineTextMessage,
+ LineThreadId,
+ LineWebhookEvent,
+ LineWebhookPayload,
+} from './types';
diff --git a/packages/chat-adapter-line/src/types.ts b/packages/chat-adapter-line/src/types.ts
new file mode 100644
index 00000000000..aa7c9e44fba
--- /dev/null
+++ b/packages/chat-adapter-line/src/types.ts
@@ -0,0 +1,177 @@
+// ---------- Adapter config ----------
+
+export interface LineAdapterConfig {
+ /**
+ * Optional Messaging API base URL override (default `https://api.line.me`).
+ */
+ apiBaseUrl?: string;
+ /**
+ * Optional content (binary download) base URL override
+ * (default `https://api-data.line.me`).
+ */
+ apiDataBaseUrl?: string;
+ /**
+ * Long-lived **Channel Access Token** issued from the LINE Developers
+ * Console (Messaging API tab → "Issue token").
+ */
+ channelAccessToken: string;
+ /**
+ * **Channel Secret** from the same console page. Used to validate
+ * `X-Line-Signature` on every inbound webhook delivery.
+ */
+ channelSecret: string;
+ /**
+ * The bot's destination user ID (`U` + 32 hex chars). Available from
+ * `GET /v2/bot/info` and from every webhook payload's `destination`
+ * field. Used as the bot identity and as the route segment.
+ */
+ destinationUserId: string;
+}
+
+export interface LineThreadId {
+ /** Original id from `event.source` (userId / groupId / roomId). */
+ id: string;
+ /** LINE chat type. */
+ type: 'group' | 'room' | 'user';
+}
+
+// ---------- Webhook payload types (subset of LINE's spec we use) ----------
+
+export type LineSourceType = 'group' | 'room' | 'user';
+
+export interface LineSource {
+ /** Group ID — only when `type === 'group'`. */
+ groupId?: string;
+ /** Room ID — only when `type === 'room'`. */
+ roomId?: string;
+ type: LineSourceType;
+ /** User ID of the sender. Always present for messages. */
+ userId?: string;
+}
+
+export type LineMessageContentType =
+ | 'audio'
+ | 'file'
+ | 'image'
+ | 'location'
+ | 'sticker'
+ | 'text'
+ | 'video';
+
+export interface LineTextMessage {
+ id: string;
+ text: string;
+ type: 'text';
+}
+
+export interface LineMediaMessage {
+ contentProvider?: {
+ originalContentUrl?: string;
+ previewImageUrl?: string;
+ type: 'external' | 'line';
+ };
+ /** Audio / Video duration in ms. */
+ duration?: number;
+ /** File messages only. */
+ fileName?: string;
+ /** File size in bytes. */
+ fileSize?: number;
+ id: string;
+ type: 'audio' | 'file' | 'image' | 'video';
+}
+
+export interface LineStickerMessage {
+ id: string;
+ /** Sticker keyword(s) the sender intended (LINE may attach multiple). */
+ keywords?: string[];
+ packageId: string;
+ stickerId: string;
+ /** Optional human-readable text alternative. */
+ text?: string;
+ type: 'sticker';
+}
+
+export interface LineLocationMessage {
+ address?: string;
+ id: string;
+ latitude: number;
+ longitude: number;
+ title?: string;
+ type: 'location';
+}
+
+export type LineMessage =
+ | LineLocationMessage
+ | LineMediaMessage
+ | LineStickerMessage
+ | LineTextMessage;
+
+export interface LineMessageEvent {
+ deliveryContext?: { isRedelivery: boolean };
+ message: LineMessage;
+ mode: 'active' | 'standby';
+ /** Quoted message context (LINE's reply-to indicator). */
+ quotedMessageId?: string;
+ /** `replyToken` is single-use and expires in ~60s. We rely on push API
+ * instead for outbound, so we treat this as informational. */
+ replyToken?: string;
+ source: LineSource;
+ /** Unix milliseconds. */
+ timestamp: number;
+ type: 'message';
+ webhookEventId?: string;
+}
+
+export interface LineGenericEvent {
+ // Other event types (follow / unfollow / join / leave / postback / memberJoined
+ // / memberLeft / accountLink / things / videoPlayComplete / unsend) carry
+ // their own fields. The adapter only consumes `message` events today; we
+ // keep this open type so future extensions don't need a new enum.
+ [extra: string]: unknown;
+ deliveryContext?: { isRedelivery: boolean };
+ source: LineSource;
+ timestamp: number;
+ type: string;
+ webhookEventId?: string;
+}
+
+export type LineWebhookEvent = LineGenericEvent | LineMessageEvent;
+
+export interface LineWebhookPayload {
+ /** Bot's userId (matches `LineAdapterConfig.destinationUserId`). */
+ destination: string;
+ events: LineWebhookEvent[];
+}
+
+// ---------- Outbound API ----------
+
+export interface LinePushMessageRequest {
+ messages: Array<{ text: string; type: 'text' }>;
+ /** Optional notification disabling. */
+ notificationDisabled?: boolean;
+ /** Recipient: userId / groupId / roomId. */
+ to: string;
+}
+
+export interface LineApiError {
+ details?: Array<{ message?: string; property?: string }>;
+ message?: string;
+}
+
+export interface LineBotInfoResponse {
+ basicId?: string;
+ chatMode?: string;
+ displayName?: string;
+ markAsReadMode?: string;
+ pictureUrl?: string;
+ premiumId?: string;
+ /** Bot's userId — matches the `destination` field on inbound webhooks. */
+ userId?: string;
+}
+
+export interface LineLoadingStartRequest {
+ /** Recipient userId. The loading animation only works for 1:1 user chats. */
+ chatId: string;
+ /** 5–60 seconds, multiples of 5. */
+ loadingSeconds?: number;
+}
diff --git a/packages/chat-adapter-line/tsconfig.json b/packages/chat-adapter-line/tsconfig.json
new file mode 100644
index 00000000000..5c90650b8ae
--- /dev/null
+++ b/packages/chat-adapter-line/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "lib": ["ES2022"]
+ },
+ "exclude": ["node_modules", "dist"],
+ "include": ["src/**/*"]
+}
diff --git a/packages/chat-adapter-line/tsup.config.ts b/packages/chat-adapter-line/tsup.config.ts
new file mode 100644
index 00000000000..d4c69d1df67
--- /dev/null
+++ b/packages/chat-adapter-line/tsup.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from 'tsup';
+
+export default defineConfig({
+ dts: true,
+ entry: ['src/index.ts'],
+ format: ['esm'],
+ sourcemap: true,
+});
diff --git a/packages/chat-adapter-line/vitest.config.mts b/packages/chat-adapter-line/vitest.config.mts
new file mode 100644
index 00000000000..5b40bc079f3
--- /dev/null
+++ b/packages/chat-adapter-line/vitest.config.mts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ all: false,
+ },
+ environment: 'node',
+ },
+});
diff --git a/packages/database/src/models/__tests__/agentBotProvider.test.ts b/packages/database/src/models/__tests__/agentBotProvider.test.ts
index 1b920ed78a8..0be01164902 100644
--- a/packages/database/src/models/__tests__/agentBotProvider.test.ts
+++ b/packages/database/src/models/__tests__/agentBotProvider.test.ts
@@ -368,18 +368,25 @@ describe('AgentBotProviderModel', () => {
expect(results[0].credentials.signingSecret).toBe('ss-123');
});
- it('should skip providers without botToken', async () => {
+ it('should return providers regardless of credential field shape (platform validates its own fields)', async () => {
await serverDB.insert(agentBotProviders).values({
agentId,
- applicationId: 'no-token-app',
- credentials: JSON.stringify({ publicKey: 'pk-only' }),
+ applicationId: 'line-app',
+ credentials: JSON.stringify({
+ channelAccessToken: 'cat-123',
+ channelSecret: 'cs-456',
+ }),
enabled: true,
- platform: 'discord',
+ platform: 'line',
userId,
});
- const results = await AgentBotProviderModel.findEnabledByPlatform(serverDB, 'discord');
- expect(results).toHaveLength(0);
+ const results = await AgentBotProviderModel.findEnabledByPlatform(serverDB, 'line');
+ expect(results).toHaveLength(1);
+ expect(results[0].credentials).toEqual({
+ channelAccessToken: 'cat-123',
+ channelSecret: 'cs-456',
+ });
});
it('should skip providers with null credentials', async () => {
diff --git a/packages/database/src/models/agentBotProvider.ts b/packages/database/src/models/agentBotProvider.ts
index ae0679a4f6c..43407833e91 100644
--- a/packages/database/src/models/agentBotProvider.ts
+++ b/packages/database/src/models/agentBotProvider.ts
@@ -172,8 +172,6 @@ export class AgentBotProviderModel {
? JSON.parse((await gateKeeper.decrypt(r.credentials)).plaintext)
: JSON.parse(r.credentials);
- if (!credentials.botToken && !credentials.appSecret) continue;
-
decrypted.push({ ...r, credentials });
} catch {
// skip rows with invalid / undecryptable credentials
diff --git a/src/locales/default/agent.ts b/src/locales/default/agent.ts
index ae621f72f57..041a597bb80 100644
--- a/src/locales/default/agent.ts
+++ b/src/locales/default/agent.ts
@@ -50,6 +50,25 @@ export default {
'channel.feishu.webhookMigrationDesc':
'WebSocket mode provides real-time event delivery without needing a public callback URL. To migrate, switch the Connection Mode to WebSocket in Advanced Settings. No additional configuration is needed on the Feishu/Lark Open Platform.',
'channel.lark.description': 'Connect this assistant to Lark for private and group chats.',
+ 'channel.line.description':
+ 'Connect this assistant to LINE Messaging API for direct and group chats.',
+ 'channel.line.destinationUserId': 'Destination User ID',
+ 'channel.line.destinationUserIdHint':
+ 'The bot\'s destination user ID (starts with `U`, 33 chars total). The LINE Developers Console does NOT display this value. Issue a Channel Access Token below first, then click "Fetch from LINE" to auto-fill this field. Note: "Your user ID" in Basic settings is your personal LINE user ID, not the bot\'s.',
+ 'channel.line.fetchBotInfo': 'Fetch from LINE',
+ 'channel.line.fetchBotInfoSuccess': 'Destination User ID fetched',
+ 'channel.line.fetchBotInfoFailed': 'Failed to fetch bot info',
+ 'channel.line.fetchBotInfoMissingToken':
+ 'Enter the Channel Access Token first, then click "Fetch from LINE".',
+ 'channel.line.destinationUserIdPlaceholder': 'e.g. U1234567890abcdef1234567890abcdef',
+ 'channel.line.channelAccessToken': 'Channel Access Token',
+ 'channel.line.channelAccessTokenHint':
+ 'Long-lived token issued under the Messaging API tab. Token will be encrypted and stored securely.',
+ 'channel.line.channelSecret': 'Channel Secret',
+ 'channel.line.channelSecretHint':
+ 'From the Basic settings tab. Required — used to verify X-Line-Signature on every inbound webhook.',
+ 'channel.line.webhookManualSetup':
+ 'LINE does not allow programmatic webhook registration. Copy this URL into the LINE Developers Console (Messaging API → Webhook URL), click "Verify", and enable "Use webhook".',
'channel.openPlatform': 'Open Platform',
'channel.platforms': 'Platforms',
'channel.publicKey': 'Public Key',
diff --git a/src/routes/(main)/agent/channel/const.ts b/src/routes/(main)/agent/channel/const.ts
index f1412a5d195..b588ed123e4 100644
--- a/src/routes/(main)/agent/channel/const.ts
+++ b/src/routes/(main)/agent/channel/const.ts
@@ -6,6 +6,7 @@ const ICON_NAMES = [
'Discord',
'GoogleChat',
'Lark',
+ 'Line',
'MicrosoftTeams',
'QQ',
'Slack',
diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsx
index e828caa43ed..e6fdbac7094 100644
--- a/src/routes/(main)/agent/channel/detail/Body.tsx
+++ b/src/routes/(main)/agent/channel/detail/Body.tsx
@@ -23,7 +23,7 @@ import type {
} from '@/server/services/bot/platforms/types';
import { isDev } from '@/utils/env';
-import { platformCredentialBodyMap } from '../platform/registry';
+import { platformCredentialBodyMap, platformCredentialExtrasMap } from '../platform/registry';
import { extractSettingsDefaults } from './formState';
import type { ChannelFormValues } from './index';
@@ -351,6 +351,7 @@ const Body = memo<BodyProps>(({ platformDef, form, hasConfig, currentConfig, onA
const t = _t as (key: string) => string;
const CustomCredentialBody = platformCredentialBodyMap[platformDef.id];
+ const CredentialExtras = platformCredentialExtrasMap[platformDef.id];
const applicationIdField = useMemo(
() => platformDef.schema.find((f) => f.key === 'applicationId'),
@@ -415,6 +416,7 @@ const Body = memo<BodyProps>(({ platformDef, form, hasConfig, currentConfig, onA
parentKey="credentials"
/>
))}
+ {CredentialExtras && <CredentialExtras />}
</>
)}
{settingsFields.length > 0 && (
diff --git a/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx b/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx
new file mode 100644
index 00000000000..1b59cd8fd66
--- /dev/null
+++ b/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx
@@ -0,0 +1,63 @@
+'use client';
+
+import { App, Button, Form as AntdForm } from 'antd';
+import { Download } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentStore } from '@/store/agent';
+
+const CredentialExtras = memo(() => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+ const { message } = App.useApp();
+ const form = AntdForm.useFormInstance();
+ const channelAccessToken = AntdForm.useWatch(['credentials', 'channelAccessToken'], form) as
+ | string
+ | undefined;
+ const [loading, setLoading] = useState(false);
+
+ const lineFetchBotInfo = useAgentStore((s) => s.lineFetchBotInfo);
+
+ const handleFetch = async () => {
+ const token = channelAccessToken?.trim();
+ if (!token) {
+ message.warning(t('channel.line.fetchBotInfoMissingToken'));
+ return;
+ }
+ setLoading(true);
+ try {
+ const info = await lineFetchBotInfo(token);
+ form.setFieldValue('applicationId', info.userId);
+ // Trigger validation/dirty state on the field so the form save button
+ // recognises the auto-filled value as a real change.
+ form.validateFields(['applicationId']).catch(() => undefined);
+ message.success(
+ info.displayName
+ ? `${t('channel.line.fetchBotInfoSuccess')} (${info.displayName})`
+ : t('channel.line.fetchBotInfoSuccess'),
+ );
+ } catch (error) {
+ const text = error instanceof Error ? error.message : String(error);
+ message.error(`${t('channel.line.fetchBotInfoFailed')}: ${text}`);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Button
+ disabled={!channelAccessToken?.trim()}
+ icon={<Download size={14} />}
+ loading={loading}
+ size="small"
+ style={{ alignSelf: 'flex-start', marginBlockStart: 4 }}
+ type="default"
+ onClick={handleFetch}
+ >
+ {t('channel.line.fetchBotInfo')}
+ </Button>
+ );
+});
+
+export default CredentialExtras;
diff --git a/src/routes/(main)/agent/channel/platform/registry.ts b/src/routes/(main)/agent/channel/platform/registry.ts
index c5537b86c5c..df9e9e31194 100644
--- a/src/routes/(main)/agent/channel/platform/registry.ts
+++ b/src/routes/(main)/agent/channel/platform/registry.ts
@@ -1,5 +1,6 @@
import type { ComponentType } from 'react';
+import LineCredentialExtras from './line/CredentialExtras';
import type { PlatformCredentialBodyProps } from './types';
import WechatCredentialBody from './wechat/CredentialBody';
@@ -9,3 +10,14 @@ export const platformCredentialBodyMap: Record<
> = {
wechat: WechatCredentialBody,
};
+
+/**
+ * Components rendered after the default credential block (i.e. when no
+ * `platformCredentialBodyMap` override is in effect). Use this for small
+ * platform-specific helpers like LINE's "fetch destination user ID from
+ * /v2/bot/info" button — anything that augments the auto-generated form
+ * without replacing it wholesale.
+ */
+export const platformCredentialExtrasMap: Record<string, ComponentType> = {
+ line: LineCredentialExtras,
+};
diff --git a/src/routes/(main)/home/index.tsx b/src/routes/(main)/home/index.tsx
index 40608d8b5d0..52f2ba9bed1 100644
--- a/src/routes/(main)/home/index.tsx
+++ b/src/routes/(main)/home/index.tsx
@@ -17,8 +17,12 @@ const Home: FC = () => {
<>
{isHomeRoute && <PageTitle title="" />}
<HomePageTracker />
- <NavHeader right={<Flexbox horizontal align="center" />} />
- <Flexbox height={'100%'} style={{ overflowY: 'auto', paddingBottom: '16vh' }} width={'100%'}>
+ <NavHeader />
+ <Flexbox
+ height={'100%'}
+ style={{ overflowY: 'auto', paddingBlock: '44px 16vh' }}
+ width={'100%'}
+ >
<WideScreenContainer>
<HomeContent />
</WideScreenContainer>
diff --git a/src/server/routers/lambda/agentBotProvider.ts b/src/server/routers/lambda/agentBotProvider.ts
index a7b54ba15a8..1c82a8c1c40 100644
--- a/src/server/routers/lambda/agentBotProvider.ts
+++ b/src/server/routers/lambda/agentBotProvider.ts
@@ -1,3 +1,4 @@
+import { LineApiClient } from '@lobechat/chat-adapter-line';
import { fetchQrCode, pollQrStatus } from '@lobechat/chat-adapter-wechat';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -208,6 +209,38 @@ export const agentBotProviderRouter = router({
return { valid: true };
}),
+ /**
+ * Resolve the bot's `userId` (destination user ID) from a channel access
+ * token by calling LINE's `/v2/bot/info`. The LINE Developers Console UI
+ * does not surface this value, so the operator either runs `curl` themselves
+ * or lets the form pre-fill the field via this procedure.
+ */
+ lineFetchBotInfo: authedProcedure
+ .input(z.object({ channelAccessToken: z.string().min(1) }))
+ .mutation(async ({ input }) => {
+ const api = new LineApiClient({ accessToken: input.channelAccessToken });
+ try {
+ const info = await api.getBotInfo();
+ if (!info.userId) {
+ throw new TRPCError({
+ code: 'BAD_GATEWAY',
+ message: 'LINE /v2/bot/info returned no userId',
+ });
+ }
+ return {
+ basicId: info.basicId,
+ displayName: info.displayName,
+ userId: info.userId,
+ };
+ } catch (error) {
+ if (error instanceof TRPCError) throw error;
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: error instanceof Error ? error.message : 'Failed to fetch bot info from LINE',
+ });
+ }
+ }),
+
wechatGetQrCode: authedProcedure.mutation(async () => {
return fetchQrCode();
}),
diff --git a/src/server/services/bot/platforms/index.ts b/src/server/services/bot/platforms/index.ts
index 7d964334a46..9c62fa7cf82 100644
--- a/src/server/services/bot/platforms/index.ts
+++ b/src/server/services/bot/platforms/index.ts
@@ -3,6 +3,7 @@
import { discord } from './discord/definition';
import { feishu } from './feishu/definitions/feishu';
import { lark } from './feishu/definitions/lark';
+import { line } from './line/definition';
import { qq } from './qq/definition';
import { PlatformRegistry } from './registry';
import { slack } from './slack/definition';
@@ -73,6 +74,7 @@ export {
export { discord } from './discord/definition';
export { feishu } from './feishu/definitions/feishu';
export { lark } from './feishu/definitions/lark';
+export { line } from './line/definition';
export { qq } from './qq/definition';
export { slack } from './slack/definition';
export { telegram } from './telegram/definition';
@@ -87,3 +89,4 @@ platformRegistry.register(feishu);
platformRegistry.register(lark);
platformRegistry.register(qq);
platformRegistry.register(wechat);
+platformRegistry.register(line);
diff --git a/src/server/services/bot/platforms/line/client.test.ts b/src/server/services/bot/platforms/line/client.test.ts
new file mode 100644
index 00000000000..2c15bc37068
--- /dev/null
+++ b/src/server/services/bot/platforms/line/client.test.ts
@@ -0,0 +1,228 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { LineClientFactory } from './client';
+
+const fetchSpy = vi.spyOn(globalThis, 'fetch');
+
+const APPLICATION_ID = 'Ubotbotbotbotbotbotbotbotbotbotbo';
+
+const createClient = () =>
+ new LineClientFactory().createClient(
+ {
+ applicationId: APPLICATION_ID,
+ credentials: {
+ channelAccessToken: 'token-test',
+ channelSecret: 'secret-test',
+ },
+ platform: 'line',
+ settings: {},
+ },
+ {},
+ );
+
+beforeEach(() => {
+ vi.mock('@/server/services/gateway/runtimeStatus', () => ({
+ BOT_RUNTIME_STATUSES: {
+ connected: 'connected',
+ disconnected: 'disconnected',
+ failed: 'failed',
+ starting: 'starting',
+ },
+ getRuntimeStatusErrorMessage: (e: unknown) => (e instanceof Error ? e.message : 'unknown'),
+ updateBotRuntimeStatus: vi.fn().mockResolvedValue(undefined),
+ }));
+});
+
+afterEach(() => {
+ fetchSpy.mockReset();
+});
+
+describe('LineWebhookClient', () => {
+ it('formatMarkdown strips Markdown to plain text via stripMarkdown', () => {
+ const client = createClient();
+ expect(client.formatMarkdown!('**hi**')).toBe('hi');
+ expect(client.formatMarkdown!('# Title')).toBe('Title');
+ });
+
+ it('extractChatId pulls the recipient id out of all three thread variants', () => {
+ const client = createClient();
+ expect(client.extractChatId('line:user:U1234567890abcdef1234567890abcdef')).toBe(
+ 'U1234567890abcdef1234567890abcdef',
+ );
+ expect(client.extractChatId('line:group:Cgroupgroupgroupgroupgroupgroupgr')).toBe(
+ 'Cgroupgroupgroupgroupgroupgroupgr',
+ );
+ expect(client.extractChatId('line:room:Rroomroomroomroomroomroomroomroom')).toBe(
+ 'Rroomroomroomroomroomroomroomroom',
+ );
+ });
+
+ it('createAdapter wires the credentials into the SDK adapter', () => {
+ const client = createClient();
+ const adapter = client.createAdapter();
+ expect(adapter.line).toBeDefined();
+ expect((adapter.line as any).botUserId).toBe(APPLICATION_ID);
+ });
+
+ it('messenger.createMessage POSTs to /v2/bot/message/push', async () => {
+ fetchSpy.mockResolvedValue(new Response('{}', { status: 200 }));
+ const client = createClient();
+ const messenger = client.getMessenger('line:user:U1234567890abcdef1234567890abcdef');
+ await messenger.createMessage('hi back');
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe('https://api.line.me/v2/bot/message/push');
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer token-test');
+ const body = JSON.parse(init.body as string);
+ expect(body.to).toBe('U1234567890abcdef1234567890abcdef');
+ expect(body.messages).toEqual([{ text: 'hi back', type: 'text' }]);
+ });
+
+ it('messenger.triggerTyping is a no-op for group + room threads', async () => {
+ fetchSpy.mockResolvedValue(new Response('{}', { status: 200 }));
+ const client = createClient();
+ const groupMessenger = client.getMessenger('line:group:Cgroupgroupgroupgroupgroupgroupgr');
+ await groupMessenger.triggerTyping!();
+ const roomMessenger = client.getMessenger('line:room:Rroomroomroomroomroomroomroomroom');
+ await roomMessenger.triggerTyping!();
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('messenger.triggerTyping calls the loading API for user threads', async () => {
+ fetchSpy.mockResolvedValue(new Response('{}', { status: 200 }));
+ const client = createClient();
+ const messenger = client.getMessenger('line:user:U1234567890abcdef1234567890abcdef');
+ await messenger.triggerTyping!();
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe('https://api.line.me/v2/bot/chat/loading/start');
+ const body = JSON.parse(init.body as string);
+ expect(body.chatId).toBe('U1234567890abcdef1234567890abcdef');
+ });
+
+ it('extractFiles downloads media for each merged attachment, even when message.raw is text', async () => {
+ // Simulates BotMessageRouter.mergeSkippedMessages: user sent an image then a
+ // text immediately after. The merged Message has the image attachment but
+ // its `raw` now points at the trailing text event.
+ fetchSpy
+ .mockResolvedValueOnce(new Response(Buffer.from('image-bytes'), { status: 200 }))
+ .mockResolvedValueOnce(new Response(Buffer.from('audio-bytes'), { status: 200 }));
+
+ const client = createClient();
+ const merged = {
+ attachments: [
+ {
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ raw: { id: 'line-image-1', mimeType: 'image/jpeg', type: 'image' },
+ type: 'image',
+ url: '',
+ },
+ {
+ mimeType: 'audio/m4a',
+ name: 'audio.m4a',
+ raw: { id: 'line-audio-1', mimeType: 'audio/m4a', type: 'audio' },
+ type: 'audio',
+ url: '',
+ },
+ ],
+ id: 'merged',
+ raw: { id: 'line-text-1', text: 'follow-up text', type: 'text' },
+ };
+
+ const sources = await (client as any).extractFiles(merged);
+ expect(sources).toHaveLength(2);
+ expect(sources[0].name).toBe('image.jpg');
+ expect(sources[0].mimeType).toBe('image/jpeg');
+ expect(sources[0].buffer.toString()).toBe('image-bytes');
+ expect(sources[1].name).toBe('audio.m4a');
+ expect(sources[1].buffer.toString()).toBe('audio-bytes');
+
+ const urls = fetchSpy.mock.calls.map((c) => c[0]);
+ expect(urls).toEqual([
+ 'https://api-data.line.me/v2/bot/message/line-image-1/content',
+ 'https://api-data.line.me/v2/bot/message/line-audio-1/content',
+ ]);
+ });
+
+ it('extractFiles returns undefined when no attachments carry a media id', async () => {
+ const client = createClient();
+ const result = await (client as any).extractFiles({
+ attachments: [],
+ id: 'm',
+ raw: { id: 'line-text-1', text: 'hello', type: 'text' },
+ });
+ expect(result).toBeUndefined();
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('formatReply appends usage stats only when showUsageStats=true', () => {
+ const factory = new LineClientFactory();
+ const baseConfig = {
+ applicationId: APPLICATION_ID,
+ credentials: { channelAccessToken: 't', channelSecret: 's' },
+ platform: 'line',
+ };
+ const off = factory.createClient({ ...baseConfig, settings: {} }, {});
+ const on = factory.createClient({ ...baseConfig, settings: { showUsageStats: true } }, {});
+
+ const stats = { elapsedMs: 1234, totalCost: 0.01, totalTokens: 42 };
+ expect(off.formatReply!('body', stats)).toBe('body');
+ expect(on.formatReply!('body', stats).startsWith('body\n\n')).toBe(true);
+ });
+});
+
+describe('LineClientFactory.validateCredentials', () => {
+ it('reports missing fields without hitting the network', async () => {
+ const factory = new LineClientFactory();
+ const result = await factory.validateCredentials({});
+ expect(result.valid).toBe(false);
+ const fields = (result.errors ?? []).map((e) => e.field).sort();
+ expect(fields).toEqual(['applicationId', 'channelAccessToken', 'channelSecret']);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('returns valid=true when getBotInfo matches the configured applicationId', async () => {
+ fetchSpy.mockResolvedValueOnce(
+ new Response(JSON.stringify({ userId: APPLICATION_ID }), { status: 200 }),
+ );
+ const factory = new LineClientFactory();
+ const result = await factory.validateCredentials(
+ { channelAccessToken: 'good', channelSecret: 's' },
+ undefined,
+ APPLICATION_ID,
+ );
+ expect(result.valid).toBe(true);
+ });
+
+ it('rejects when the token belongs to a different bot than configured', async () => {
+ fetchSpy.mockResolvedValueOnce(
+ new Response(JSON.stringify({ userId: 'Uotherbotid' }), { status: 200 }),
+ );
+ const factory = new LineClientFactory();
+ const result = await factory.validateCredentials(
+ { channelAccessToken: 'good', channelSecret: 's' },
+ undefined,
+ APPLICATION_ID,
+ );
+ expect(result.valid).toBe(false);
+ expect(result.errors?.[0]?.field).toBe('applicationId');
+ expect(result.errors?.[0]?.message).toContain('Uotherbotid');
+ });
+
+ it('surfaces the LINE error envelope message when the token is rejected', async () => {
+ fetchSpy.mockResolvedValueOnce(
+ new Response(JSON.stringify({ message: 'Authentication failed.' }), { status: 401 }),
+ );
+ const factory = new LineClientFactory();
+ const result = await factory.validateCredentials(
+ { channelAccessToken: 'bad', channelSecret: 's' },
+ undefined,
+ APPLICATION_ID,
+ );
+ expect(result.valid).toBe(false);
+ expect(result.errors?.[0]?.message).toContain('Authentication failed.');
+ });
+});
diff --git a/src/server/services/bot/platforms/line/client.ts b/src/server/services/bot/platforms/line/client.ts
new file mode 100644
index 00000000000..0e71b7a8323
--- /dev/null
+++ b/src/server/services/bot/platforms/line/client.ts
@@ -0,0 +1,309 @@
+import {
+ createLineAdapter,
+ getMediaFileNameAndType,
+ LineApiClient,
+ type LineMessage,
+ resolveMediaMessageId,
+} from '@lobechat/chat-adapter-line';
+import type { Message } from 'chat';
+import debug from 'debug';
+
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
+import {
+ BOT_RUNTIME_STATUSES,
+ getRuntimeStatusErrorMessage,
+ updateBotRuntimeStatus,
+} from '@/server/services/gateway/runtimeStatus';
+
+import { stripMarkdown } from '../stripMarkdown';
+import {
+ type BotPlatformRuntimeContext,
+ type BotProviderConfig,
+ ClientFactory,
+ type PlatformClient,
+ type PlatformMessenger,
+ type UsageStats,
+ type ValidationResult,
+} from '../types';
+import { formatUsageStats } from '../utils';
+
+const log = debug('bot-platform:line:bot');
+
+interface DecodedThread {
+ id: string;
+ type: 'group' | 'room' | 'user';
+}
+
+function decodeThread(platformThreadId: string): DecodedThread {
+ // line:<type>:<id>
+ const parts = platformThreadId.split(':');
+ if (parts.length < 3 || parts[0] !== 'line') {
+ return { id: platformThreadId, type: 'user' };
+ }
+ const type = parts[1];
+ return {
+ id: parts.slice(2).join(':'),
+ type: type === 'group' || type === 'room' ? (type as 'group' | 'room') : 'user',
+ };
+}
+
+function defaultMimeForType(type: string | undefined): string {
+ switch (type) {
+ case 'image': {
+ return 'image/jpeg';
+ }
+ case 'video': {
+ return 'video/mp4';
+ }
+ case 'audio': {
+ return 'audio/m4a';
+ }
+ default: {
+ return 'application/octet-stream';
+ }
+ }
+}
+
+function defaultNameForType(type: string | undefined, fileName?: string): string {
+ if (fileName) return fileName;
+ switch (type) {
+ case 'image': {
+ return 'image.jpg';
+ }
+ case 'video': {
+ return 'video.mp4';
+ }
+ case 'audio': {
+ return 'audio.m4a';
+ }
+ default: {
+ return 'file.bin';
+ }
+ }
+}
+
+class LineWebhookClient implements PlatformClient {
+ readonly id = 'line';
+ readonly applicationId: string;
+
+ private config: BotProviderConfig;
+ private context: BotPlatformRuntimeContext;
+ private api: LineApiClient;
+
+ constructor(config: BotProviderConfig, context: BotPlatformRuntimeContext) {
+ this.config = config;
+ this.context = context;
+ this.applicationId = config.applicationId;
+ this.api = new LineApiClient({ accessToken: config.credentials.channelAccessToken });
+ }
+
+ // --- Lifecycle ---
+
+ async start(): Promise<void> {
+ log('Starting LineBot appId=%s', this.applicationId);
+ await updateBotRuntimeStatus({
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.starting,
+ });
+
+ try {
+ // LINE has no programmatic webhook registration — operators paste the
+ // URL into the LINE Developers Console. We can still verify the token
+ // and confirm the bot identity matches the configured applicationId
+ // (destination userId) so a clearly-wrong provider doesn't reach the
+ // connected state silently.
+ const info = await this.api.getBotInfo();
+ if (info.userId && info.userId !== this.applicationId) {
+ throw new Error(
+ `Channel access token resolves to bot ${info.userId}, ` +
+ `but the configured destination userId is ${this.applicationId}`,
+ );
+ }
+
+ await updateBotRuntimeStatus({
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.connected,
+ });
+
+ log(
+ 'LineBot appId=%s ready (operator must wire webhook in LINE console)',
+ this.applicationId,
+ );
+ } catch (error) {
+ await updateBotRuntimeStatus({
+ applicationId: this.applicationId,
+ errorMessage: getRuntimeStatusErrorMessage(error),
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.failed,
+ });
+ throw error;
+ }
+ }
+
+ async stop(): Promise<void> {
+ log('Stopping LineBot appId=%s', this.applicationId);
+ await updateBotRuntimeStatus({
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.disconnected,
+ });
+ }
+
+ // --- Runtime Operations ---
+
+ createAdapter(): Record<string, any> {
+ return {
+ line: createLineAdapter({
+ channelAccessToken: this.config.credentials.channelAccessToken,
+ channelSecret: this.config.credentials.channelSecret,
+ destinationUserId: this.applicationId,
+ }),
+ };
+ }
+
+ getMessenger(platformThreadId: string): PlatformMessenger {
+ const { id: recipient, type } = decodeThread(platformThreadId);
+ return {
+ createMessage: async (content) => {
+ await this.api.pushText(recipient, content);
+ },
+ // LINE does not support editing — `supportsMessageEdit: false` makes the
+ // bridge skip the per-step progress edit, but we still implement this
+ // path so any unexpected caller falls back to a fresh push.
+ editMessage: async (_messageId, content) => {
+ await this.api.pushText(recipient, content);
+ },
+ removeReaction: () => Promise.resolve(),
+ triggerTyping: async () => {
+ // LINE's loading animation API is only valid for 1:1 user chats.
+ if (type !== 'user') return;
+ try {
+ await this.api.startLoading(recipient);
+ } catch (err) {
+ log('triggerTyping failed: %O', err);
+ }
+ },
+ };
+ }
+
+ /**
+ * Resolve attachments on an inbound LINE message. LINE sends only the
+ * media `messageId` on the webhook — we have to call the data subdomain's
+ * `/v2/bot/message/<id>/content` endpoint with the bearer header to get
+ * the bytes. Done on demand to avoid wasted downloads in groups.
+ *
+ * Reads each attachment's own `raw` rather than `message.raw`: when the
+ * bot router merges debounced/queued messages, attachments are concatenated
+ * but `message.raw` holds only the latest event (which may now be text).
+ */
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ const attachments = ((message as any).attachments ?? []) as Array<{ raw?: LineMessage }>;
+
+ const candidates = attachments
+ .map((attachment) => ({
+ messageId: resolveMediaMessageId(attachment.raw),
+ raw: attachment.raw,
+ }))
+ .filter((entry): entry is { messageId: string; raw: LineMessage } =>
+ Boolean(entry.messageId && entry.raw),
+ );
+
+ if (candidates.length === 0) return undefined;
+
+ log(
+ 'extractFiles: msgId=%s lineMsgIds=%o',
+ (message as any).id,
+ candidates.map((c) => c.messageId),
+ );
+
+ const results = await Promise.all(
+ candidates.map(async ({ messageId, raw }): Promise<AttachmentSource | undefined> => {
+ try {
+ const buffer = await this.api.downloadContent(messageId);
+ const meta = getMediaFileNameAndType(raw);
+ return {
+ buffer,
+ mimeType: defaultMimeForType(meta.type),
+ name: defaultNameForType(meta.type, meta.fileName),
+ size: buffer.length,
+ };
+ } catch (err) {
+ log('extractFiles: downloadContent failed for messageId=%s: %O', messageId, err);
+ return undefined;
+ }
+ }),
+ );
+
+ const sources = results.filter((source): source is AttachmentSource => Boolean(source));
+ return sources.length > 0 ? sources : undefined;
+ }
+
+ extractChatId(platformThreadId: string): string {
+ return decodeThread(platformThreadId).id;
+ }
+
+ formatMarkdown(markdown: string): string {
+ return stripMarkdown(markdown);
+ }
+
+ formatReply(body: string, stats?: UsageStats): string {
+ if (!stats || !this.config.settings?.showUsageStats) return body;
+ return `${body}\n\n${formatUsageStats(stats)}`;
+ }
+
+ parseMessageId(compositeId: string): string {
+ return compositeId;
+ }
+}
+
+export class LineClientFactory extends ClientFactory {
+ createClient(config: BotProviderConfig, context: BotPlatformRuntimeContext): PlatformClient {
+ return new LineWebhookClient(config, context);
+ }
+
+ async validateCredentials(
+ credentials: Record<string, string>,
+ _settings?: Record<string, unknown>,
+ applicationId?: string,
+ ): Promise<ValidationResult> {
+ const errors: Array<{ field: string; message: string }> = [];
+ if (!credentials.channelAccessToken) {
+ errors.push({ field: 'channelAccessToken', message: 'Channel Access Token is required' });
+ }
+ if (!credentials.channelSecret) {
+ errors.push({ field: 'channelSecret', message: 'Channel Secret is required' });
+ }
+ if (!applicationId) {
+ errors.push({ field: 'applicationId', message: 'Destination User ID is required' });
+ }
+ if (errors.length > 0) {
+ return { errors, valid: false };
+ }
+
+ try {
+ const api = new LineApiClient({ accessToken: credentials.channelAccessToken });
+ const info = await api.getBotInfo();
+ if (info.userId && info.userId !== applicationId) {
+ return {
+ errors: [
+ {
+ field: 'applicationId',
+ message: `Channel access token belongs to bot ${info.userId}, not ${applicationId}`,
+ },
+ ],
+ valid: false,
+ };
+ }
+ return { valid: true };
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : 'Failed to authenticate with LINE Messaging API';
+ return {
+ errors: [{ field: 'channelAccessToken', message }],
+ valid: false,
+ };
+ }
+ }
+}
diff --git a/src/server/services/bot/platforms/line/definition.ts b/src/server/services/bot/platforms/line/definition.ts
new file mode 100644
index 00000000000..513a45b0c5a
--- /dev/null
+++ b/src/server/services/bot/platforms/line/definition.ts
@@ -0,0 +1,19 @@
+import type { PlatformDefinition } from '../types';
+import { LineClientFactory } from './client';
+import { schema } from './schema';
+
+export const line: PlatformDefinition = {
+ id: 'line',
+ name: 'LINE',
+ connectionMode: 'webhook',
+ description: 'Connect a LINE Messaging API bot for direct and group chats.',
+ documentation: {
+ portalUrl: 'https://developers.line.biz/console/',
+ setupGuideUrl: 'https://lobehub.com/docs/usage/channels/line',
+ },
+ schema,
+ showWebhookUrl: true,
+ supportsMarkdown: false,
+ supportsMessageEdit: false,
+ clientFactory: new LineClientFactory(),
+};
diff --git a/src/server/services/bot/platforms/line/protocol-spec.md b/src/server/services/bot/platforms/line/protocol-spec.md
new file mode 100644
index 00000000000..ad6e850b9f7
--- /dev/null
+++ b/src/server/services/bot/platforms/line/protocol-spec.md
@@ -0,0 +1,105 @@
+# LINE Messaging API – Bot Integration Notes
+
+Quick orientation map for engineers working on the LINE adapter.
+Authoritative documentation:
+
+- Messaging API overview: <https://developers.line.biz/en/docs/messaging-api/>
+- Webhook reference: <https://developers.line.biz/en/reference/messaging-api/#webhooks>
+- Get bot info: <https://developers.line.biz/en/reference/messaging-api/#get-bot-info>
+- Send push message: <https://developers.line.biz/en/reference/messaging-api/#send-push-message>
+- Display loading indicator: <https://developers.line.biz/en/reference/messaging-api/#display-a-loading-indicator>
+- Get content: <https://developers.line.biz/en/reference/messaging-api/#get-content>
+
+## Credentials
+
+| Field | Source | Notes |
+| -------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `applicationId` | `GET https://api.line.me/v2/bot/info` → `userId` | The bot's destination user ID (`U` + 32 hex chars), also the `destination` field on every webhook payload. **The LINE Developers Console UI does not surface this value** — the "Your user ID" on the channel's Basic settings tab is the **operator's own** LINE user ID, not the bot's. Operators must call the API (or rely on `validateCredentials` echoing the correct value back in the `Channel access token belongs to bot Uxxx` error). |
+| `channelAccessToken` | LINE Developers Console → Messaging API tab → "Issue token" | Long-lived. Bearer header for every API call. |
+| `channelSecret` | LINE Developers Console → Basic settings tab | Used to validate `X-Line-Signature` on every inbound POST. **Required**, no fallback. |
+
+## Webhook lifecycle
+
+1. **No GET handshake.** LINE Developers Console verifies the webhook URL by
+ sending a `POST` with `{ destination, events: [] }` when the operator
+ clicks the "Verify" button. We accept that ping (200 OK) once the
+ signature checks out — the empty `events` array is what makes it harmless.
+2. **POST notification** – LINE sends a JSON body with `destination` and one
+ or more `events[]`. We only handle `event.type === "message"`.
+3. **Signature validation** – every POST must carry an `X-Line-Signature`
+ header equal to **base64**(HMAC-SHA256(rawBody, channelSecret)). Note the
+ base64 encoding (WhatsApp uses hex with `sha256=` prefix). Mismatched or
+ missing signatures get a 401 and are dropped.
+
+## Payload shape (inbound)
+
+```jsonc
+{
+ "destination": "U<bot-user-id>",
+ "events": [
+ {
+ "type": "message",
+ "mode": "active",
+ "timestamp": 1700000000000,
+ "source": { "type": "user", "userId": "Uabc..." },
+ "webhookEventId": "01H...",
+ "deliveryContext": { "isRedelivery": false },
+ "replyToken": "...",
+ "message": { "type": "text", "id": "1000", "text": "hi bot" },
+ },
+ ],
+}
+```
+
+`source.type` ∈ `user` / `group` / `room`. We encode the platform thread id
+as `line:<type>:<sourceId>` where `sourceId` is `userId` / `groupId` /
+`roomId` respectively. The thread id determines whether typing indicators
+are available (only `user`).
+
+Media messages (`image`, `video`, `audio`, `file`) carry only `id` —
+no caption, no inline mime. `file` additionally carries `fileName` and
+`fileSize`. Bytes are fetched on demand by the platform client's
+`extractFiles` via `GET <data-host>/v2/bot/message/<id>/content` with the
+bearer header.
+
+`replyToken` is **single-use and expires in \~60 seconds**. We always use
+the push API instead because the agent's response can take longer than
+that. Push messages count against the channel's monthly quota for paid
+plans; for the free Developer Trial it's effectively unlimited.
+
+## Outbound
+
+`POST /v2/bot/message/push` with
+
+```json
+{
+ "messages": [{ "type": "text", "text": "…" }],
+ "to": "<wa_id>"
+}
+```
+
+`to` is the recipient's `userId` / `groupId` / `roomId`, decoded from the
+platform thread id.
+
+## Capabilities
+
+- **No edit / no delete** – Messaging API has no edit endpoint. The platform
+ definition sets `supportsMessageEdit: false`; the bridge therefore skips
+ per-step progress edits and only emits the final reply.
+- **Markdown** – LINE renders text as plain text only. The platform client's
+ `formatMarkdown` runs `stripMarkdown` to strip emphasis / heading / list
+ markers before sending.
+- **Typing indicator** – `POST /v2/bot/chat/loading/start` with
+ `{ chatId, loadingSeconds }`. Only valid for 1:1 user chats — `group`
+ and `room` threads silently no-op.
+- **Reactions** – LINE does not let bots send reactions; the messenger's
+ reaction methods are no-ops.
+
+## Operator-facing setup
+
+Webhook URL must be configured manually in the LINE Developers Console
+(`Messaging API → Webhook settings → Webhook URL`). After pasting it the
+operator presses "Verify" — that fires a signed POST with `events: []`
+to our endpoint. Operator must also enable "Use webhook" and disable the
+LINE Official Account Manager "Auto-reply messages" / "Greeting messages"
+to prevent the platform from competing with our bot's responses.
diff --git a/src/server/services/bot/platforms/line/schema.ts b/src/server/services/bot/platforms/line/schema.ts
new file mode 100644
index 00000000000..186dbad5ee8
--- /dev/null
+++ b/src/server/services/bot/platforms/line/schema.ts
@@ -0,0 +1,81 @@
+import { DEFAULT_BOT_DEBOUNCE_MS, MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';
+
+import { displayToolCallsField, makeUserIdField } from '../const';
+import type { FieldSchema } from '../types';
+
+export const schema: FieldSchema[] = [
+ {
+ key: 'applicationId',
+ description: 'channel.line.destinationUserIdHint',
+ label: 'channel.line.destinationUserId',
+ placeholder: 'channel.line.destinationUserIdPlaceholder',
+ required: true,
+ type: 'string',
+ },
+ {
+ key: 'credentials',
+ label: 'channel.credentials',
+ properties: [
+ {
+ key: 'channelAccessToken',
+ description: 'channel.line.channelAccessTokenHint',
+ label: 'channel.line.channelAccessToken',
+ required: true,
+ type: 'password',
+ },
+ {
+ key: 'channelSecret',
+ description: 'channel.line.channelSecretHint',
+ label: 'channel.line.channelSecret',
+ required: true,
+ type: 'password',
+ },
+ ],
+ type: 'object',
+ },
+ {
+ key: 'settings',
+ label: 'channel.settings',
+ properties: [
+ {
+ key: 'charLimit',
+ default: 5000,
+ description: 'channel.charLimitHint',
+ label: 'channel.charLimit',
+ // LINE Messaging API enforces a 5,000-character cap per text message.
+ maximum: 5000,
+ minimum: 100,
+ type: 'number',
+ },
+ {
+ key: 'concurrency',
+ default: 'queue',
+ description: 'channel.concurrencyHint',
+ enum: ['queue', 'debounce'],
+ enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
+ label: 'channel.concurrency',
+ type: 'string',
+ },
+ {
+ key: 'debounceMs',
+ default: DEFAULT_BOT_DEBOUNCE_MS,
+ description: 'channel.debounceMsHint',
+ label: 'channel.debounceMs',
+ maximum: MAX_BOT_DEBOUNCE_MS,
+ minimum: 100,
+ type: 'number',
+ visibleWhen: { field: 'concurrency', value: 'debounce' },
+ },
+ {
+ key: 'showUsageStats',
+ default: false,
+ description: 'channel.showUsageStatsHint',
+ label: 'channel.showUsageStats',
+ type: 'boolean',
+ },
+ displayToolCallsField,
+ makeUserIdField('line'),
+ ],
+ type: 'object',
+ },
+];
diff --git a/src/services/agentBotProvider.ts b/src/services/agentBotProvider.ts
index 7ef95453da0..c054d7c7fe9 100644
--- a/src/services/agentBotProvider.ts
+++ b/src/services/agentBotProvider.ts
@@ -68,6 +68,10 @@ class AgentBotProviderService {
return lambdaClient.agentBotProvider.testConnection.mutate(params);
};
+ lineFetchBotInfo = async (channelAccessToken: string) => {
+ return lambdaClient.agentBotProvider.lineFetchBotInfo.mutate({ channelAccessToken });
+ };
+
wechatGetQrCode = async () => {
return lambdaClient.agentBotProvider.wechatGetQrCode.mutate();
};
diff --git a/src/store/agent/slices/bot/action.ts b/src/store/agent/slices/bot/action.ts
index 4c11c1b9d65..911037c963f 100644
--- a/src/store/agent/slices/bot/action.ts
+++ b/src/store/agent/slices/bot/action.ts
@@ -57,6 +57,10 @@ export class BotSliceActionImpl {
return agentBotProviderService.testConnection(params);
};
+ lineFetchBotInfo = async (channelAccessToken: string) => {
+ return agentBotProviderService.lineFetchBotInfo(channelAccessToken);
+ };
+
deleteAllBotProviders = async (agentId: string) => {
const providers = await agentBotProviderService.getByAgentId(agentId);
await Promise.all(providers.map((p) => agentBotProviderService.delete(p.id)));