Files
程序员阿江(Relakkes) 814c02a786 feat(im): add scan-to-create Feishu bots plus WeCom, QQ and Slack adapters
Connecting Feishu meant creating a bot by hand on the open platform and
pasting an App ID and App Secret back. Feishu also exposes an RFC 8628
device-authorization flow, so the desktop can now render a QR code, and
confirming it in the app creates the bot and stores its credentials
directly. `adapters/feishu/registration.ts` implements that protocol
rather than importing `registerApp` from `@larksuiteoapi/node-sdk@1.73`:
the repository pins 1.60 for the chat client, and the SDK runs the whole
poll inside one un-cancellable promise where the desktop needs the
stateless begin/poll pair the DingTalk registration already uses. The
scan is create-only, so it can never rewrite the configuration of a bot
the user already runs, and it pre-fills exactly the scopes, events and
callbacks this adapter calls. International tenants finish on Lark's
domain, which is now persisted and honoured by the client.

WeCom, QQ and Slack join the same session model. WeCom and QQ bind by
scanning; Slack has no scan flow, so it uses an app manifest that
pre-fills the scopes and Socket Mode. All three run over long
connections, so no public callback URL is needed, and all three accept
private chats only — pairing authorizes one person, and answering in a
group would extend that authorization to everyone else in the room.

They are built on a new `adapters/common/chat-runtime.ts` instead of a
fourth copy of the loop the five existing adapters each carry. A platform
supplies a `ChatPort` — how to say something, how to open a streaming
reply, optionally how to send an image — and the runtime owns pairing,
command routing, session restore, permission bookkeeping and the
translation of the server's stream. The existing five are deliberately
left on their own copies; migrating them is a separate change with its
own regression surface.

Attachments are downloaded through a deferred loader that runs after the
pairing gate and inside the per-chat queue. Resolving them eagerly would
let an unpaired stranger make the adapter fetch bytes and write them
under ~/.claude/im-downloads — on Slack with the bot token attached —
and would let a slow attachment overtake a text message sent after it.

The sidecar launcher's per-adapter branches become one table. It is
declared above the mode dispatch on purpose: `runAdapters` is hoisted and
runs at module top level, so a table declared below it is still in its
temporal dead zone when the adapters mode reads it — which type checks,
lints and unit tests all miss, and only the compiled binary reveals.

Verified with the checks `check:impact` selects: adapters, server,
desktop, electron, policy, chat-contract, agent-flow, docs, native
(sidecar compile, packaging and an adapters-mode smoke against the real
binary) and coverage. The scan flows themselves are not verified against
live platforms — that needs real WeCom, QQ and Slack accounts and would
create real bots.

Claude-Session: https://claude.ai/code/session_01CCGoP316AK7wdQG3Ms6Uwq
2026-09-05 23:46:50 +08:00

117 lines
3.4 KiB
TypeScript

/**
* Normalize one inbound Slack event.
*
* Slack pushes far more than user messages down the same socket: edits,
* deletions, joins, the bot's own replies, and channel traffic. Everything the
* adapter must *not* answer is filtered here, in one testable place.
*/
export type SlackFile = {
id?: string
name?: string
title?: string
mimetype?: string
size?: number
url_private_download?: string
url_private?: string
}
export type SlackEvent = {
type?: string
subtype?: string
channel?: string
channel_type?: string
user?: string
bot_id?: string
app_id?: string
text?: string
ts?: string
thread_ts?: string
client_msg_id?: string
files?: SlackFile[]
hidden?: boolean
}
export type SlackInboundPayload = {
chatId: string
userId: string
text: string
dedupKey: string
threadTs?: string
files: SlackFile[]
}
/**
* Slack escapes exactly three characters in message text, and nothing else.
*
* Skipping this corrupts every message containing them — for a coding agent
* that means `a && b` arriving as `a &amp;&amp; b`, and any `<`/`>` in a shell
* redirect, comparison, JSX tag or generic silently mangled.
*/
function decodeSlackEntities(text: string): string {
return text
.replaceAll('&lt;', '<')
.replaceAll('&gt;', '>')
// `&amp;` last: decoding it first would turn `&amp;lt;` into `<`.
.replaceAll('&amp;', '&')
}
/** `<@U123>` and `<#C123|name>` are Slack's wire format for mentions. */
function stripSlackMarkup(text: string): string {
return decodeSlackEntities(
text
.replace(/<@([A-Z0-9]+)(\|[^>]*)?>/g, '')
.replace(/<#([A-Z0-9]+)\|([^>]*)>/g, '#$2')
.replace(/<(https?:\/\/[^|>]+)\|([^>]*)>/g, '$2')
.replace(/<(https?:\/\/[^|>]+)>/g, '$1'),
).trim()
}
/**
* Subtypes that still carry a real user message.
*
* Every other subtype is an edit, a deletion, a join or another non-message
* event. `file_share` is the exception that matters: Slack delivers a DM with
* an attachment as a subtyped message, so treating all subtypes as noise drops
* the attachment *and* the caption the user typed with it.
*/
const USER_MESSAGE_SUBTYPES = new Set(['file_share'])
export type ExtractSlackOptions = {
/** The bot's own user id, so its replies are never treated as input. */
botUserId?: string
}
export function extractSlackPayload(
event: SlackEvent | undefined,
options: ExtractSlackOptions = {},
): SlackInboundPayload | null {
if (!event) return null
if (event.type !== 'message') return null
if (event.subtype && !USER_MESSAGE_SUBTYPES.has(event.subtype)) return null
if (event.hidden) return null
// Bot messages include our own replies; answering them is an infinite loop.
if (event.bot_id) return null
// Direct messages only: pairing authorizes one person, and a channel would
// extend that person's authorization to everyone else in it.
if (event.channel_type !== 'im') return null
const chatId = event.channel?.trim()
const userId = event.user?.trim()
if (!chatId || !userId) return null
if (options.botUserId && userId === options.botUserId) return null
const files = (event.files ?? []).filter((file) => Boolean(file?.url_private_download || file?.url_private))
const text = stripSlackMarkup(event.text ?? '')
if (!text && files.length === 0) return null
return {
chatId,
userId,
text,
dedupKey: event.client_msg_id?.trim() || `${chatId}:${event.ts ?? ''}`,
threadTs: event.thread_ts,
files,
}
}