# Integrating Lark with Vercel Chat SDK

## What is Vercel Chat SDK

[Vercel Chat SDK](https://chat-sdk.dev) is a multi-platform chatbot framework that provides unified Channel / Thread / Message abstractions. With this SDK, developers can build bots that work across Slack, Microsoft Teams, Discord, Telegram, WhatsApp, GitHub, Linear, and more — all from a single codebase.

Its core design is the **Channel abstraction**: platform-specific authentication, message I/O, and state management are encapsulated in the adapter layer, while business code only deals with `Channel` / `Thread` / `Message`. Each new platform is supported by a dedicated **adapter**.

## Lark official adapter

Lark has published an official adapter for Vercel Chat SDK — [@larksuite/vercel-chat-adapter](https://www.npmjs.com/package/@larksuite/vercel-chat-adapter) — so products built on Chat SDK can integrate with Lark out of the box.
Capabilities supported by the adapter:
- Native cardkit typewriter streaming (no `post + edit` polling)
- Full interactive cards (buttons, link buttons, select menus, fields, images)
- Message edit / delete / reactions
- Historical message retrieval (covers Lark's 20+ native message types)
- Group chat / DM detection + mention handling
- WebSocket long-connection transport
- Scan-to-create app onboarding via `registerLarkApp`
The adapter is built on top of Lark Channel SDK (see "How the adapter is built" below).

## How to use

### Create a Lark app

#### Option 1: Scan-to-create (recommended)

Call `registerLarkApp` to trigger Lark's official scan-to-create flow. It generates a one-time URL; once the user scans and approves on the Lark mobile app, it returns `client_id` / `client_secret` with all the permissions and event subscriptions this adapter needs pre-configured.

```typescript
import { registerLarkApp } from "@larksuite/vercel-chat-adapter";
import qrcode from "qrcode-terminal"; // pnpm add -D qrcode-terminal
const { client_id, client_secret } = await registerLarkApp({
  onQRCodeReady: ({ url }) => {
    console.log("Scan this QR with your Lark / Lark mobile app:");
    qrcode.generate(url, { small: true });
  },
  onStatusChange: ({ status }) => console.log("status:", status),
});
console.log("LARK_APP_ID=", client_id);
console.log("LARK_APP_SECRET=", client_secret);
```

Run this once. Persist the returned `client_id` / `client_secret` and feed them back via `LARK_APP_ID` / `LARK_APP_SECRET` on subsequent runs.

#### Option 2: Developer console (manual)

Create an app at [open.larksuite.com/app](https://open.larksuite.com/app) (Lark) or [open.feishu.cn/app](https://open.larksuite.com/app) (Lark), and copy the `client_id` / `client_secret`.

### Install

```bash
pnpm add @larksuite/vercel-chat-adapter chat @chat-adapter/state-memory
```

### Minimal runnable example

```typescript
import { Chat } from "chat";
import { createMemoryState } from "@chat-adapter/state-memory";
import { createLarkAdapter } from "@larksuite/vercel-chat-adapter";
const bot = new Chat({
  userName: "mybot",
  adapters: {
    lark: createLarkAdapter({
      appId: process.env.LARK_APP_ID!,
      appSecret: process.env.LARK_APP_SECRET!,
    }),
  },
  state: createMemoryState(),
});
bot.onNewMention(async (thread, message) => {
  await thread.subscribe();
  await thread.post(`Got it: ${message.text}`);
});
bot.onDirectMessage(async (thread, message) => {
  await thread.post(`DM received: ${message.text}`);
});
await bot.initialize();
```
`bot.initialize()` opens the WebSocket long connection and keeps the Node.js process alive until `bot.shutdown()` is called.

### Configuration

If `appId` / `appSecret` are not passed explicitly, the adapter auto-detects them from the following environment variables:
- `LARK_APP_ID` — Lark App ID
- `LARK_APP_SECRET` — Lark App Secret

## How the adapter is built

The adapter is built on [Lark Channel SDK](https://github.com/larksuite/node-sdk) (`LarkChannel` in `@larksuiteoapi/node-sdk`). Channel SDK is Lark's high-level SDK and encapsulates:

- Event subscription and signature verification
- WebSocket long-connection with heartbeat and auto-reconnect
- Normalization of 20+ native message types (unified output via `normalize()`)
- Cardkit streaming API
- Historical message retrieval
- App credentials management (auto token refresh)
- 
Adapter authors only need to do **interface translation** — mapping the Channel SDK surface to Vercel Chat SDK's `Adapter` interface. Below is a simplified version of the core mapping:

```typescript
import { LarkChannel } from "@larksuiteoapi/node-sdk";
import type { Adapter, Message } from "chat";
export const createLarkAdapter = (config?: LarkConfig): Adapter => {
  const channel = new LarkChannel({
    appId: config?.appId ?? process.env.LARK_APP_ID,
    appSecret: config?.appSecret ?? process.env.LARK_APP_SECRET,
    safety: { enabled: false }, // Chat SDK already handles dedup / locking
  });
  return {
    name: "lark",
    async initialize() {
      // Inbound messages: Channel SDK has already normalized them;
      // the adapter only maps formats.
      channel.on("message", (normalized) => {
        const threadId = encodeThreadId(normalized.chatId, normalized.rootId);
        chat.handleIncomingMessage({
          text: normalized.text,
          threadId,
          author: {
            id: normalized.senderId,
            isMe: normalized.senderId === botIdentity.openId,
          },
          raw: normalized,
        });
      });
      await channel.connect();
    },
    async post(threadId, message: Message) {
      const { chatId, rootId } = decodeThreadId(threadId);
      return channel.send({
        chatId,
        content: renderMarkdown(message),
        replyTo: rootId,
      });
    },
    async stream(threadId, handler) {
      const { chatId, rootId } = decodeThreadId(threadId);
      // Uses native cardkit typewriter, not post + edit polling.
      return channel.cardkit.stream({
        chatId,
        replyTo: rootId,
        produce: handler,
      });
    },
    async fetchMessages(threadId) {
      const { chatId, rootId } = decodeThreadId(threadId);
      const history = await channel.getHistoricalMessages({ chatId, rootId });
      return history.map(toMessage);
    },
  };
};
```

The adapter's core control flow is well under 100 lines — Channel SDK already handles most of the Lark-specific complexity, so the adapter only does **interface translation**.

## References

- [@larksuite/vercel-chat-adapter on npm](https://www.npmjs.com/package/@larksuite/vercel-chat-adapter)