Chat with Claude Code from Feishu/Lark: two-way chat, images, permission and question cards, slash commands — via lark-cli

Chat with Claude Code from Feishu / Lark. Messages you send the bot become turns in the Claude Code session running on your machine, and each answer comes back as a reply in Feishu. Permission prompts and questions show up as interactive cards you can answer from your phone.
This is a Claude Code mod (a function-hooks plugin) built on lark-cli.
💻 电脑端), and their answers are posted there as well./tmp/feishu-mod/<message_id>/, and Claude reads them from there. If an answer mentions a local image by its absolute path, that image is sent back.AskUserQuestion (single choice, multiple choice, or free text) is sent as a Feishu form card at the same time as the local dialog./compact, /doctor, a skill name, and so on. Commands that would open a panel at the computer are adapted for Feishu instead:/config and /model open a live settings card. Toggles become buttons and choices become selects; each click applies immediately and the card redraws./cost, /usage, /context, /stats, /status and /help are answered as text./resume, /mcp, /login, /theme, …) are not run; Feishu is told to use the computer.Typing reaction while Claude works on them. It is removed when the reply is sent, and CrossMark marks a failure.In a Claude Code terminal session:
/plugin install feishu-mod --marketplace Jianyuuuuu/claude-code-feishu-mod
Answer y to Add marketplace?, then pick a scope (user is the default).
npm i -g @larksuite/cliclaude-code profile. The command prints a sign-in link and a QR code: lark-cli config init --new --name claude-code
im.message.receive_v1;card.action.trigger). Without it, card buttons do nothing;im:message, im:message:readonly, im:message.p2p_msg:readonly, im:message:send_as_bot, im:message.reactions:write_only;To check the setup: lark-cli --profile claude-code event consume card.action.trigger --as bot --dry-run should report every precondition as ok.
Use a dedicated app. When several long-connection clients subscribe to the same app, each event is delivered to only one of them at random.
| Command | What it does |
|---|---|
/feishu on | Start the bridge in this session (the status line shows 飞书 ● 在线) |
/feishu off | Stop it |
/feishu status | Connection, allowed users, the Feishu chat in use, cards waiting |
/feishu allow last | Allow the most recent unknown sender (or pass an ou_… open_id) |
/feishu deny ou_xxx | Remove a user from the allow list |
First run: /feishu on, send the bot a direct message, run /feishu allow last, then message it again. Your last direct chat with the bot becomes the chat that cards and mirrored prompts go to.
To keep the allow list across reinstalls and new sessions, set it in ~/.claude/settings.json (or /config):
"pluginConfigs": {
"feishu-mod@jianyuuuuu": {
"options": { "allowedUsers": "ou_xxx,ou_yyy", "homeChat": "oc_xxx" }
}
}
allowedUsers adds to the users allowed with /feishu allow; homeChat is used until a direct message sets the chat.
lark-cli … event consume im.message.receive_v1 runs in the background and streams NDJSON events. If it exits, it reconnects after 5 seconds.message_id and submitted with $.prompt.submit. While the session is busy they queue.[飞书消息 om_…]) ties each turn to its message. On turn.complete, the answer is sent with im +messages-reply --markdown, split into chunks with idempotency keys.classic.PermissionRequest hook, which runs while the local dialog is open. The hook sends a card and waits for a matching card.action.trigger in 60-second slices. The answer comes back as the hook's decision (updatedPermissions with destination: session for "don't ask again", or updatedInput.answers for questions). If the call is settled at the computer first, a tool.call hook marks the card as handled there.lark-cli (installed by you, with the claude-code profile) as a child process: one long-lived event consume listener, plus one call per reply, reaction, card or download. It also runs sh, mkdir, ls and date locally, for the files below and the time zone./tmp/feishu-mod/<message_id>/, a debug log to /tmp/feishu-mod/debug.log, and card clicks to /tmp/feishu-mod/clicks.hooks/lib.ts sets this.claude plugin validate .
claude plugin test .
claude --plugin-dir .
MIT
hooks/register.ts 715 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { FeishuArmed, FeishuMirrored, FeishuModStatus, FeishuPendingCard } from '../types'
5import {
6 answersFromForm,
7 answersMarkdown,
8 approvalCard,
9 configCard,
10 questionCard,
11 statusCard,
12 resolvedCard,
13 type ApprovalChoice,
14 type AskQuestion,
15 type Card,
16 type ConfigRowView,
17} from './cards'
18import {
19 buildPrompt,
20 chunkReply,
21 describeToolInput,
22 findResources,
23 formatUsage,
24 LIMIT_NAMES,
25 localTime,
26 tokens,
27 isChatId,
28 isMessageId,
29 isOpenId,
30 localImages,
31 markerOf,
32 MEDIA_TYPES,
33 parseEvent,
34 parseObject,
35 parseSlash,
36 REPLY_GUIDE,
37 safeName,
38 sentMessageId,
39 splitLines,
40 type FeishuMessage,
41} from './lib'
42
43const PLUGIN = 'feishu-mod'
44const PROFILE = 'claude-code'
45const LARK = 'lark-cli'
46const ALLOW_KEY = 'allow'
47const LAST_KEY = 'lastUnknownSender'
48const HOME_KEY = 'homeChat'
49const DOWNLOADS = '/tmp/feishu-mod'
50/** How long a card waits for a click, in short slices so a local answer stops the wait. */
51const CARD_WAIT_S = 1800
52const CARD_SLICE_S = 30
53
54const isOn = atom({ plugin: 'feishu-mod', key: 'isOn' } as const, false)
55const status = atom({ plugin: 'feishu-mod', key: 'status' } as const, 'off' as FeishuModStatus)
56const turns = atom({ plugin: 'feishu-mod', key: 'turns' } as const, {} as Record<string, string>)
57const said = atom({ plugin: 'feishu-mod', key: 'said' } as const, {} as Record<string, string[]>)
58const seen = atom({ plugin: 'feishu-mod', key: 'seen' } as const, [] as string[])
59const mirrored = atom({ plugin: 'feishu-mod', key: 'mirrored' } as const, [] as FeishuMirrored[])
60const armed = atom({ plugin: 'feishu-mod', key: 'armed' } as const, null as FeishuArmed | null)
61const pending = atom({ plugin: 'feishu-mod', key: 'pending' } as const, {} as Record<string, FeishuPendingCard>)
62const typing = atom({ plugin: 'feishu-mod', key: 'typing' } as const, {} as Record<string, string>)
63const model = atom({ plugin: 'feishu-mod', key: 'model' } as const, '')
64
65type $ = EngineInterface
66
67// The running consumers of this module load; a reload drops them with the module.
68const consumers = new Set<AsyncGenerator<unknown, unknown>>()
69let loopId = 0
70const warnedSenders = new Set<string>()
71
72const STATUS_TEXT: Record<FeishuModStatus, string | undefined> = {
73 off: undefined,
74 starting: '飞书 ⋯ 连接中',
75 listening: '飞书 ● 在线',
76 error: '飞书 ✕ 断开,重连中',
77}
78
79const DEBUG_LOG = `${DOWNLOADS}/debug.log`
80const CLICKS = `${DOWNLOADS}/clicks`
81
82/** To Claude Code's debug log, and to /tmp/feishu-mod/debug.log for when no --debug is on. */
83function debug($: $, text: string): void {
84 $.ui.log(`${PLUGIN}: ${text}`, { to: 'debug' })
85 void $.process.run(['sh', '-c', 'mkdir -p "$1" && cat >> "$2"', 'sh', DOWNLOADS, DEBUG_LOG], {
86 stdin: `${new Date().toISOString()} ${text}\n`,
87 }).catch(() => undefined)
88}
89const rid = () => crypto.randomUUID().replace(/-/g, '').slice(0, 16)
90
91async function setStatus($: $, next: FeishuModStatus): Promise<void> {
92 await update($, status, () => next)
93 $.ui.status(STATUS_TEXT[next])
94}
95
96/** Users and chat from settings (`pluginConfigs`), which outlive the store when the plugin is reinstalled. */
97let configAllow: string[] = []
98let configHome: string | null = null
99
100async function allowList($: $): Promise<string[]> {
101 const value = await $.store.get(ALLOW_KEY)
102 const stored = Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
103 return [...new Set([...configAllow, ...stored])]
104}
105
106async function homeChat($: $): Promise<string | null> {
107 const value = await $.store.get(HOME_KEY)
108 return typeof value === 'string' && isChatId(value) ? value : configHome
109}
110
111/** The bridge routes to Feishu only while it is on and knows where to send. */
112async function remoteChat($: $): Promise<string | null> {
113 return (await read($, isOn)) ? homeChat($) : null
114}
115
116// ── lark-cli ────────────────────────────────────────────────────────────────
117
118function lark($: $, args: string[], init: { cwd?: string; timeoutMs?: number } = {}) {
119 return $.process.run([LARK, '--profile', PROFILE, ...args], { timeoutMs: 60_000, ...init })
120}
121
122async function react($: $, messageId: string, emoji: string): Promise<string | null> {
123 const res = await lark($, [
124 'api', 'POST', `/open-apis/im/v1/messages/${messageId}/reactions`, '--as', 'bot',
125 '--data', JSON.stringify({ reaction_type: { emoji_type: emoji } }),
126 ]).catch(() => undefined)
127 if (res && res.exitCode !== 0) debug($, `reaction failed: ${res.stderr || res.stdout}`)
128 return res ? (/"reaction_id"\s*:\s*"([^"]+)"/.exec(res.stdout)?.[1] ?? null) : null
129}
130
131/** Hermes' processing badge: Typing while working, removed on reply, CrossMark on failure. */
132async function startWorking($: $, messageId: string): Promise<void> {
133 const id = await react($, messageId, 'Typing')
134 if (id) await update($, typing, map => ({ ...map, [messageId]: id }))
135}
136
137async function stopWorking($: $, messageId: string, isFailed: boolean): Promise<void> {
138 const id = (await read($, typing))[messageId]
139 if (id) {
140 await update($, typing, map => {
141 const { [messageId]: _, ...rest } = map
142 return rest
143 })
144 await lark($, ['api', 'DELETE', `/open-apis/im/v1/messages/${messageId}/reactions/${id}`, '--as', 'bot']).catch(() => undefined)
145 }
146 if (isFailed) await react($, messageId, 'CrossMark')
147}
148
149async function reply($: $, messageId: string, text: string): Promise<boolean> {
150 for (const [i, piece] of chunkReply(text).entries()) {
151 const res = await lark($, [
152 'im', '+messages-reply', '--as', 'bot', '--message-id', messageId,
153 '--markdown', piece, '--idempotency-key', `${messageId}-${i}`.slice(0, 50),
154 ])
155 if (res.exitCode !== 0) {
156 $.ui.toast(`飞书回复失败:${(res.stderr || res.stdout).slice(0, 300)}`)
157 return false
158 }
159 }
160 return true
161}
162
163async function replyImage($: $, messageId: string, path: string): Promise<void> {
164 const cut = path.lastIndexOf('/')
165 const res = await lark($, ['im', '+messages-reply', '--as', 'bot', '--message-id', messageId, '--image', path.slice(cut + 1)], {
166 cwd: path.slice(0, cut) || '/',
167 })
168 if (res.exitCode !== 0) debug($, `image reply failed: ${res.stderr || res.stdout}`)
169}
170
171async function sendMarkdown($: $, chatId: string, text: string): Promise<string | null> {
172 const res = await lark($, ['im', '+messages-send', '--as', 'bot', '--chat-id', chatId, '--markdown', text])
173 if (res.exitCode !== 0) debug($, `send failed: ${res.stderr || res.stdout}`)
174 return sentMessageId(res.stdout)
175}
176
177async function sendCard($: $, chatId: string, card: Card): Promise<string | null> {
178 const res = await lark($, [
179 'im', '+messages-send', '--as', 'bot', '--chat-id', chatId,
180 '--msg-type', 'interactive', '--content', JSON.stringify(card),
181 ])
182 if (res.exitCode !== 0) $.ui.toast(`飞书卡片发送失败:${(res.stderr || res.stdout).slice(0, 300)}`)
183 return sentMessageId(res.stdout)
184}
185
186async function patchCard($: $, messageId: string, card: Card): Promise<void> {
187 const res = await lark($, [
188 'api', 'PATCH', `/open-apis/im/v1/messages/${messageId}`, '--as', 'bot',
189 '--data', JSON.stringify({ content: JSON.stringify(card) }),
190 ]).catch(() => undefined)
191 if (res && res.exitCode !== 0) debug($, `card update failed: ${res.stderr || res.stdout}`)
192}
193
194/**
195 * Waits for a click on the card tagged `id` by an allowed user. Feishu lets one
196 * consumer hold card.action.trigger, so the standing listener writes each click
197 * to CLICKS/<id>.json and this waits for that file in a shell `$.process.run`,
198 * which costs the calling hook none of its own time budget.
199 */
200async function waitCardAction($: $, id: string, seconds: number): Promise<Record<string, unknown> | null> {
201 const deadline = (await $.clock.now()) + seconds * 1000
202 const file = `${CLICKS}/${id}.json`
203 for (;;) {
204 // The card was settled at the computer, or the bridge went off: stop waiting.
205 if (!(await read($, pending))[id] || !(await read($, isOn))) return null
206 const left = Math.floor((deadline - (await $.clock.now())) / 1000)
207 if (left < 2) return null
208 const slice = Math.min(left, CARD_SLICE_S)
209 const res = await $.process.run(
210 ['sh', '-c', 'i=0; while [ "$i" -lt "$2" ]; do if [ -f "$1" ]; then cat "$1"; rm -f "$1"; exit 0; fi; sleep 1; i=$((i+1)); done', 'sh', file, String(slice)],
211 { timeoutMs: slice * 1000 + 15_000 },
212 ).catch(err => {
213 debug($, `card wait failed: ${String(err)}`)
214 return null
215 })
216 if (!res || res.exitCode !== 0) return null
217 const ev = parseObject(res.stdout.trim())
218 if (!ev) continue
219 if ((await allowList($)).includes(String(ev.operator_id ?? ''))) return ev
220 debug($, `ignored a card click by ${String(ev.operator_id)}`)
221 }
222}
223
224/** Every card click arrives here: settings act at once, the rest go to their waiter. */
225async function handleCardClick($: $, ev: Record<string, unknown>): Promise<void> {
226 const value = parseObject(String(ev.action_value ?? '')) ?? {}
227 debug($, `card click kind=${String(value.kind)} by ${String(ev.operator_id)}`)
228 if (value.kind === 'config') return handleConfigClick($, ev)
229 const id = typeof value.rid === 'string' && /^[0-9a-f]{16}$/.test(value.rid) ? value.rid : null
230 if (!id || !(await read($, pending))[id]) return
231 await $.process.run(['sh', '-c', 'mkdir -p "$1" && cat > "$2.tmp" && mv "$2.tmp" "$2"', 'sh', CLICKS, `${CLICKS}/${id}.json`], {
232 stdin: JSON.stringify(ev),
233 })
234}
235
236async function forget($: $, id: string): Promise<FeishuPendingCard | undefined> {
237 const card = (await read($, pending))[id]
238 await update($, pending, map => {
239 const { [id]: _, ...rest } = map
240 return rest
241 })
242 return card
243}
244
245// ── inbound ─────────────────────────────────────────────────────────────────
246
247async function downloadResources($: $, m: FeishuMessage): Promise<string[]> {
248 if (!MEDIA_TYPES.has(m.messageType)) return []
249 const raw = await lark($, ['api', 'GET', `/open-apis/im/v1/messages/${m.messageId}`, '--as', 'bot'])
250 const data = parseObject(raw.stdout)?.data as { items?: Array<{ body?: { content?: string } }> } | undefined
251 const body = parseObject(data?.items?.[0]?.body?.content ?? '')
252 const resources = findResources(body).slice(0, 10)
253 if (!resources.length) return []
254 const dir = `${DOWNLOADS}/${m.messageId}`
255 await $.process.run(['mkdir', '-p', dir])
256 for (const r of resources) {
257 const res = await lark($, [
258 'im', '+messages-resources-download', '--as', 'bot', '--message-id', m.messageId,
259 '--file-key', r.key, '--type', r.type, '--output', `${dir}/${safeName(r)}`,
260 ], { timeoutMs: 120_000 })
261 if (res.exitCode !== 0 && r.type === 'image') {
262 debug($, `download ${r.key} as image failed, retrying as file`)
263 await lark($, [
264 'im', '+messages-resources-download', '--as', 'bot', '--message-id', m.messageId,
265 '--file-key', r.key, '--type', 'file', '--output', `${dir}/${safeName(r)}`,
266 ], { timeoutMs: 120_000 })
267 } else if (res.exitCode !== 0) debug($, `download ${r.key} failed: ${res.stderr || res.stdout}`)
268 }
269 const listed = await $.process.run(['ls', '-1', dir])
270 return listed.stdout.split('\n').map(f => f.trim()).filter(Boolean).map(f => `${dir}/${f}`)
271}
272
273/** Commands that open a panel at the computer: answered here from the session's own figures. */
274/** The machine's offset from UTC in minutes, from `date +%z` (the module's own clock may run in UTC). */
275async function localOffset($: $): Promise<number> {
276 const out = (await $.process.run(['date', '+%z']).catch(() => null))?.stdout.trim() ?? ''
277 const m = /^([+-])(\d{2})(\d{2})$/.exec(out)
278 return m ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3])) : 0
279}
280
281/** /status, /cost and /usage as a card (text when the card is refused), from the session's own figures. */
282async function sendUsage($: $, m: FeishuMessage, full: boolean): Promise<void> {
283 const u = await $.session.usage()
284 const now = await $.clock.now()
285 const offset = await localOffset($)
286 const cwd = full ? await $.session.cwd() : undefined
287 const home = cwd ? /^\/(?:Users|home)\/[^/]+/.exec(cwd)?.[0] : undefined
288 const version = full ? (await $.session.version()).version : undefined
289 const usedModel = (await read($, model)) || undefined
290 const pct = u.context.percent ?? (u.context.tokens !== undefined ? (u.context.tokens / u.context.window) * 100 : undefined)
291 const card = statusCard({
292 title: full && version ? `Claude Code ${version}` : 'Claude Code',
293 costUsd: u.cost?.usd,
294 contextPercent: pct,
295 contextText: `${tokens(u.context.tokens)} / ${tokens(u.context.window)}`,
296 model: usedModel,
297 limits: u.rateLimits.map(r => ({
298 name: LIMIT_NAMES[r.kind] ?? r.kind,
299 percent: r.percentUsed,
300 reset: r.resetsAt ? `${localTime(r.resetsAt, offset)} 重置` : undefined,
301 })),
302 footnote: cwd ? (home && cwd.startsWith(home) ? `~${cwd.slice(home.length)}` : cwd) : undefined,
303 })
304 if (await sendCard($, m.chatId, card)) return
305 await reply($, m.messageId, formatUsage({ version, cwd, home, model: usedModel, costUsd: u.cost?.usd, context: u.context, rateLimits: u.rateLimits }, now, offset, full))
306}
307
308const USAGE_COMMANDS = new Set(['cost', 'usage', 'context', 'stats'])
309/** Panels that only make sense at the computer: not run from Feishu at all. */
310const LOCAL_ONLY = new Set([
311 'resume', 'mcp', 'agents', 'plugin', 'plugins', 'permissions', 'hooks', 'memory', 'login', 'logout',
312 'theme', 'ide', 'rewind', 'tasks', 'bashes', 'export', 'terminal-setup', 'vim', 'keybindings',
313 'privacy-settings', 'output-style', 'statusline', 'add-dir', 'install-github-app', 'feedback', 'upgrade',
314])
315
316async function configRows($: $, command: string): Promise<ConfigRowView[]> {
317 const rows = (await $.config.list()).map(r => ({
318 key: r.key, label: r.label, kind: r.kind, value: r.value, options: r.options, isLocked: r.isLocked,
319 }))
320 if (command === 'model') return rows.filter(r => r.key === 'model')
321 return rows.filter(r => r.kind === 'boolean' || r.kind === 'choice').slice(0, 40)
322}
323
324const configTitle = (view: string) => (view === 'model' ? '模型' : '设置')
325
326/** /config and /model as a card; its clicks are handled by the standing listener, so it never expires. */
327async function configSession($: $, m: FeishuMessage, command: string): Promise<void> {
328 const rows = await configRows($, command)
329 if (command === 'model' && !rows.length) {
330 await reply($, m.messageId, '这里读不到模型设置,请在电脑上用 /model 切换。')
331 return
332 }
333 await sendCard($, m.chatId, configCard(command, configTitle(command), rows, '点按钮或下拉框,立即生效。'))
334}
335
336/** One click on any settings card: set the row, then redraw that card. */
337async function handleConfigClick($: $, ev: Record<string, unknown>): Promise<void> {
338 if (!(await allowList($)).includes(String(ev.operator_id ?? ''))) return
339 const value = parseObject(String(ev.action_value ?? '')) ?? {}
340 const view = value.view === 'model' ? 'model' : 'config'
341 const key = typeof value.key === 'string' ? value.key : ''
342 const raw = typeof value.set === 'string' ? value.set : String(ev.option ?? '')
343 const row = (await configRows($, view)).find(r => r.key === key)
344 let note = ''
345 if (row && raw) {
346 const res = await $.config.set({ key, value: row.kind === 'boolean' ? raw === 'true' : raw })
347 note = res.deny ? `没改成:${res.deny}` : `已把 **${row.label}** 设为 ${String(res.value)}`
348 $.ui.toast(`飞书:${note.replace(/\*\*/g, '')}`)
349 }
350 const cardId = String(ev.message_id ?? '')
351 if (isMessageId(cardId)) await patchCard($, cardId, configCard(view, configTitle(view), await configRows($, view), note))
352}
353
354async function helpText($: $): Promise<string> {
355 const list = await $.command.list()
356 return list.slice(0, 80).map(c => `/${c.name} — ${c.description.slice(0, 60)}`).join('\n')
357}
358const COMMAND_WAIT_MS = 30_000
359
360async function runSlash($: $, m: FeishuMessage, command: string, args: string): Promise<void> {
361 if (command === 'feishu') {
362 await reply($, m.messageId, await feishuCommand($, args))
363 return
364 }
365 if (USAGE_COMMANDS.has(command)) {
366 await sendUsage($, m, false)
367 return
368 }
369 if (command === 'config' || command === 'model') return configSession($, m, command)
370 if (command === 'status') return sendUsage($, m, true)
371 if (command === 'help') return void (await reply($, m.messageId, await helpText($)))
372 if (LOCAL_ONLY.has(command)) {
373 await reply($, m.messageId, `/${command} 是电脑上的交互界面,需要在电脑上操作。`)
374 return
375 }
376 await startWorking($, m.messageId)
377 // A command that starts a turn (a skill, a prompt command) answers there.
378 await update($, armed, () => ({ messageId: m.messageId, until: Date.now() + 60_000 }))
379 try {
380 const ran = $.command.run({ command, args }).then(r => (r.text ?? '').trim())
381 const out = await Promise.race([ran, $.clock.sleep(COMMAND_WAIT_MS).then(() => null)])
382 if (out === null) {
383 void ran.catch(() => undefined)
384 await update($, armed, a => (a?.messageId === m.messageId ? null : a))
385 await reply($, m.messageId, `/${command} 在电脑上打开了交互界面,飞书里显示不了,请到电脑上查看(按 Esc 关闭)。`)
386 await stopWorking($, m.messageId, false)
387 return
388 }
389 if (out) await reply($, m.messageId, '```\n' + out.slice(0, 6000) + '\n```')
390 // A turn the command started took the armed message and answers it; otherwise we are done.
391 const startedTurn = Object.values(await read($, turns)).includes(m.messageId)
392 if (!startedTurn) {
393 await update($, armed, a => (a?.messageId === m.messageId ? null : a))
394 if (!out) await reply($, m.messageId, `/${command} 已执行。`)
395 await stopWorking($, m.messageId, false)
396 }
397 } catch (err) {
398 await update($, armed, () => null)
399 await reply($, m.messageId, `/${command} 执行失败:${String(err).slice(0, 500)}`)
400 await stopWorking($, m.messageId, true)
401 }
402}
403
404async function handle($: $, m: FeishuMessage): Promise<void> {
405 debug($, `event ${m.messageId} from ${m.senderId} (${m.chatType}/${m.messageType})`)
406 if (m.senderType && m.senderType !== 'user') return
407 if ((await read($, seen)).includes(m.messageId)) return
408 await update($, seen, list => [...list, m.messageId].slice(-200))
409
410 if (!(await allowList($)).includes(m.senderId)) {
411 await $.store.set(LAST_KEY, m.senderId)
412 if (!warnedSenders.has(m.senderId)) {
413 warnedSenders.add(m.senderId)
414 $.ui.toast(`飞书:未授权的发送者 ${m.senderId}。确认是你本人后运行 /feishu allow last`)
415 }
416 return
417 }
418 if (m.chatType === 'p2p' && isChatId(m.chatId)) await $.store.set(HOME_KEY, m.chatId)
419
420 const slash = m.messageType === 'text' ? parseSlash(m.content) : null
421 if (slash) {
422 void runSlash($, m, slash.command, slash.args).catch(err => debug($, `slash: ${String(err)}`))
423 return
424 }
425
426 await startWorking($, m.messageId)
427 const files = await downloadResources($, m).catch(err => {
428 debug($, `download: ${String(err)}`)
429 return [] as string[]
430 })
431 if (!m.content.trim() && !files.length) return stopWorking($, m.messageId, false)
432 await $.prompt.submit({ text: buildPrompt(m, files), asUser: true })
433}
434
435/** Keeps one `lark-cli event consume` running while the bridge is on, line by line. */
436async function runStream(
437 $: $,
438 id: number,
439 args: string[],
440 onLine: (line: string) => Promise<void>,
441 isPrimary: boolean,
442): Promise<void> {
443 while (id === loopId && (await read($, isOn))) {
444 if (isPrimary) await setStatus($, 'starting')
445 let buffer = ''
446 try {
447 // An unbounded consume exits when stdin closes; a timeout makes it ignore that.
448 const stream = $.process.spawn({ argv: [LARK, '--profile', PROFILE, 'event', 'consume', ...args, '--as', 'bot', '--timeout', '720h'] })
449 consumers.add(stream)
450 try {
451 for await (const chunk of stream) {
452 if (id !== loopId) break
453 if (isPrimary && (await read($, status)) !== 'listening') await setStatus($, 'listening')
454 if (chunk.stream === 'stderr') {
455 debug($, chunk.text.trim())
456 continue
457 }
458 const { lines, rest } = splitLines(buffer, chunk.text)
459 buffer = rest
460 for (const line of lines) await onLine(line).catch(err => debug($, String(err)))
461 }
462 } finally {
463 consumers.delete(stream)
464 }
465 } catch (err) {
466 debug($, `consumer ${args[0]} failed: ${String(err)}`)
467 }
468 if (id !== loopId || !(await read($, isOn))) break
469 if (isPrimary) await setStatus($, 'error')
470 await $.clock.sleep(5000)
471 }
472}
473
474async function runConsumer($: $): Promise<void> {
475 const id = ++loopId
476 await Promise.all([
477 runStream($, id, ['im.message.receive_v1'], async line => {
478 const message = parseEvent(line)
479 if (message) await handle($, message)
480 }, true),
481 runStream($, id, ['card.action.trigger'], async line => {
482 const ev = parseObject(line)
483 if (ev) await handleCardClick($, ev)
484 }, false),
485 ])
486}
487
488async function stopConsumer($: $): Promise<void> {
489 loopId++
490 const running = [...consumers]
491 consumers.clear()
492 await Promise.all(running.map(s => s.return(undefined).catch(() => undefined)))
493 await setStatus($, 'off')
494}
495
496// ── /feishu ─────────────────────────────────────────────────────────────────
497
498async function feishuCommand($: $, argText: string): Promise<string> {
499 const [verb = 'status', arg = ''] = argText.trim().split(/\s+/)
500 switch (verb) {
501 case 'on': {
502 if (await read($, isOn)) return '飞书桥接已经开着。'
503 await update($, isOn, () => true)
504 void runConsumer($).catch(() => undefined)
505 const allowed = await allowList($)
506 return allowed.length
507 ? `飞书桥接已开启(profile ${PROFILE}),授权用户 ${allowed.length} 个。`
508 : `飞书桥接已开启(profile ${PROFILE})。还没有授权用户:先给机器人发一条消息,再运行 /feishu allow last。`
509 }
510 case 'off':
511 await update($, isOn, () => false)
512 await stopConsumer($)
513 return '飞书桥接已关闭。'
514 case 'allow':
515 case 'deny': {
516 const last = await $.store.get(LAST_KEY)
517 const target = arg === 'last' && typeof last === 'string' ? last : arg
518 if (!isOpenId(target)) return '需要一个 open_id(ou_xxx),或用 last 表示最近一个未授权的发送者。'
519 const list = await allowList($)
520 const nextList = verb === 'allow' ? [...new Set([...list, target])] : list.filter(x => x !== target)
521 await $.store.set(ALLOW_KEY, nextList)
522 if (verb === 'deny' && configAllow.includes(target))
523 return `${target} 写在设置的 allowedUsers 里,仍然有效;要移除请改 settings.json 的 pluginConfigs。`
524 return `${verb === 'allow' ? '已授权' : '已移除'} ${target}。当前授权:${nextList.join(', ') || '无'}`
525 }
526 default:
527 return [
528 `状态:${await read($, status)}(profile ${PROFILE})`,
529 `授权用户:${(await allowList($)).join(', ') || '无'}`,
530 `飞书会话:${(await homeChat($)) ?? '未知(先在飞书私聊机器人一次)'}`,
531 `等待中的飞书卡片:${Object.keys(await read($, pending)).length}`,
532 `最近未授权的发送者:${String((await $.store.get(LAST_KEY)) ?? '无')}`,
533 ].join('\n')
534 }
535}
536
537// ── hooks ───────────────────────────────────────────────────────────────────
538
539export const register: Register = (on, options) => {
540 configAllow = String(options.allowedUsers ?? '')
541 .split(',')
542 .map(v => v.trim())
543 .filter(isOpenId)
544 const home = String(options.homeChat ?? '').trim()
545 configHome = isChatId(home) ? home : null
546 on('session.start', async ($, e, next) => {
547 await $.command.register({
548 name: 'feishu',
549 description: '飞书桥接:on | off | status | allow <open_id|last> | deny <open_id>',
550 argumentHint: 'on|off|status|allow <ou_…|last>|deny <ou_…>',
551 })
552 const started = await next(e)
553 // A reload keeps $.state: resume a bridge that was on.
554 if (await read($, isOn)) void runConsumer($).catch(() => undefined)
555 return started
556 })
557
558 on('command.run', { command: 'feishu' }, async ($, e) => ({ text: await feishuCommand($, e.args) }))
559
560 on('prompt.submit', async ($, e, next) => {
561 // Our own submissions carry the reply rules as context the person never sees.
562 if (e.origin?.kind === 'plugin' && e.origin.name === PLUGIN && markerOf(e.text)) {
563 return next({ ...e, context: [...(e.context ?? []), REPLY_GUIDE] })
564 }
565 // A prompt typed at the computer is mirrored to Feishu, and its answer follows it there.
566 const chat = e.origin?.kind === 'composer' ? await remoteChat($) : null
567 if (chat && e.text.trim()) {
568 const messageId = await sendMarkdown($, chat, `💻 **电脑端**\n${e.text.slice(0, 3000)}`)
569 if (messageId && e.turnId) {
570 const turnId = e.turnId
571 await update($, turns, map => (map[turnId] ? map : { ...map, [turnId]: messageId }))
572 } else if (messageId) {
573 await update($, mirrored, list => [...list, { text: e.text, messageId }].slice(-20))
574 }
575 }
576 return next(e)
577 }).catch(($, e, next) => next(e))
578
579 on('turn.start', async ($, e, next) => {
580 let messageId = markerOf(e.text)
581 if (!messageId) {
582 const queue = await read($, mirrored)
583 const hit = queue.find(q => q.text === e.text || e.text.startsWith(q.text))
584 if (hit) {
585 messageId = hit.messageId
586 await update($, mirrored, list => list.filter(q => q !== hit && q.messageId !== hit.messageId))
587 }
588 }
589 if (!messageId) {
590 const pending = await read($, armed)
591 if (pending && pending.until > Date.now()) messageId = pending.messageId
592 if (pending) await update($, armed, () => null)
593 }
594 if (messageId) {
595 const id = messageId
596 await update($, turns, map => ({ ...map, [e.turnId]: id }))
597 }
598 return next(e)
599 })
600
601 // turn.complete's answer is only the last message; the text written between
602 // tool calls is collected here, step by step, so Feishu gets all of it.
603 on('turn.step', async function* ($, e, next) {
604 const result = yield* next(e)
605 const text = result.answer.trim()
606 if (e.agentId || !text) return result
607 if (!(await read($, turns))[e.turnId]) return result
608 await update($, said, map => ({ ...map, [e.turnId]: [...(map[e.turnId] ?? []), text] }))
609 return result
610 })
611
612 on('turn.complete', async ($, e, next) => {
613 const result = await next(e)
614 if (e.agentId) return result
615 const used = e.usage?.model
616 if (used) await update($, model, () => used)
617 const messageId = (await read($, turns))[e.turnId]
618 if (!messageId) return result
619 const parts = [...((await read($, said))[e.turnId] ?? [])]
620 await update($, turns, map => {
621 const { [e.turnId]: _, ...rest } = map
622 return rest
623 })
624 await update($, said, map => {
625 const { [e.turnId]: _, ...rest } = map
626 return rest
627 })
628
629 const final = e.answer.trim()
630 if (final && parts[parts.length - 1] !== final) parts.push(final)
631 const body = parts.join('\n\n')
632 const note =
633 e.reason === 'answer' ? ''
634 : e.reason === 'aborted' ? '(这一轮在电脑上被中断了)'
635 : e.reason === 'refusal' ? '(这一轮被模型拒绝了)'
636 : '(这一轮因 API 错误中断)'
637 const text = [body, note].filter(Boolean).join('\n\n') || '(本轮没有文字回答)'
638 const ok = await reply($, messageId, text)
639 if (e.reason === 'answer') {
640 for (const path of localImages(body)) {
641 const st = await $.fs.stat(path).catch(() => null)
642 if (st) await replyImage($, messageId, path)
643 }
644 }
645 await stopWorking($, messageId, !ok || e.reason !== 'answer')
646 return result
647 })
648
649 // A permission ask (AskUserQuestion included) goes to Feishu while the dialog
650 // stays up at the computer: whichever answers first settles it.
651 on('classic.PermissionRequest', async ($, e, next) => {
652 const chat = await remoteChat($)
653 if (!chat) return next(e)
654 const input = (typeof e.tool_input === 'object' && e.tool_input !== null ? e.tool_input : {}) as Record<string, unknown>
655 const isQuestion = e.tool_name === 'AskUserQuestion' && Array.isArray(input.questions)
656 const questions = (isQuestion ? input.questions : []) as AskQuestion[]
657 const summary = isQuestion ? '' : describeToolInput(e.tool_name, input)
658
659 const id = rid()
660 await update($, pending, map => ({ ...map, [id]: { cardId: '', tool: e.tool_name } }))
661 const click = waitCardAction($, id, CARD_WAIT_S)
662 const cardId = await sendCard($, chat, isQuestion ? questionCard(id, questions) : approvalCard(id, e.tool_name, summary))
663 if (!cardId) {
664 await forget($, id)
665 return next(e)
666 }
667 await update($, pending, map => (map[id] ? { ...map, [id]: { cardId, tool: e.tool_name } } : map))
668
669 const ev = await click
670 if (!(await forget($, id)) || !ev) {
671 // Settled at the computer (its card is updated there), or timed out.
672 if (ev === null && (await read($, isOn))) {
673 await patchCard($, cardId, resolvedCard('已超时', 'grey', '回到电脑上处理。'))
674 }
675 return next(e)
676 }
677
678 if (isQuestion) {
679 const answers = answersFromForm(questions, parseObject(String(ev.form_value ?? '')) ?? {})
680 await patchCard($, cardId, resolvedCard('已回答', 'green', answersMarkdown(answers)))
681 $.ui.toast('飞书:已回答问题')
682 return { decision: { behavior: 'allow' as const, updatedInput: { ...input, answers } } }
683 }
684
685 const choice = (parseObject(String(ev.action_value ?? ''))?.choice ?? 'deny') as ApprovalChoice
686 const label = choice === 'once' ? '已允许一次' : choice === 'session' ? '本会话不再询问' : '已拒绝'
687 await patchCard($, cardId, resolvedCard(`${label}:${e.tool_name}`, choice === 'deny' ? 'red' : 'green', summary))
688 $.ui.toast(`飞书:${label} ${e.tool_name}`)
689 if (choice === 'deny') return { decision: { behavior: 'deny' as const, message: '用户在飞书上拒绝了这次操作。' } }
690 if (choice === 'once') return { decision: { behavior: 'allow' as const } }
691 const rules = (e.permission_suggestions ?? []).filter(u => u.type === 'addRules')
692 const updatedPermissions = rules.length
693 ? rules.map(u => ({ ...u, destination: 'session' as const }))
694 : [{ type: 'addRules' as const, rules: [{ toolName: e.tool_name }], behavior: 'allow' as const, destination: 'session' as const }]
695 return { decision: { behavior: 'allow' as const, updatedPermissions } }
696 }).catch(($, e, next) => next(e))
697
698 // Once a tool call settles, any of its cards still waiting were answered at the computer.
699 on('tool.call', async ($, e, next) => {
700 const result = await next(e)
701 const waiting = Object.entries(await read($, pending)).filter(([, card]) => card.tool === e.tool && card.cardId)
702 for (const [id, card] of waiting) {
703 await forget($, id)
704 await patchCard($, card.cardId, resolvedCard(`已在电脑上处理:${e.tool}`, 'grey', '这张卡片不再需要操作。'))
705 }
706 return result
707 })
708
709 on('session.end', async ($, e, next) => {
710 // A /clear ends the conversation, not the session: keep listening.
711 if (e.reason !== 'clear') await stopConsumer($)
712 return next(e)
713 })
714}
715hooks/cards.ts 204 lines1// Feishu interactive cards, as plain JSON. Pure: the tests build and read them.
2
3export type Card = Record<string, unknown>
4
5export type AskQuestion = {
6 question: string
7 header?: string
8 multiSelect?: boolean
9 options?: ReadonlyArray<{ label: string; description?: string }>
10}
11
12const text = (content: string) => ({ tag: 'plain_text', content })
13
14function card1(title: string, template: string, markdown: string, actions?: Card[]): Card {
15 const elements: Card[] = [{ tag: 'markdown', content: markdown }]
16 if (actions?.length) elements.push({ tag: 'action', actions })
17 return {
18 config: { wide_screen_mode: true, update_multi: true },
19 header: { title: text(title), template },
20 elements,
21 }
22}
23
24const button = (label: string, type: string, value: Record<string, string>): Card => ({
25 tag: 'button',
26 text: text(label),
27 type,
28 value,
29})
30
31export type ApprovalChoice = 'once' | 'session' | 'deny'
32
33export function approvalCard(rid: string, tool: string, summary: string, reason?: string): Card {
34 // Answerable here or at the computer, whichever comes first.
35 const v = (choice: ApprovalChoice) => ({ rid, kind: 'approval', choice })
36 return card1(
37 `需要授权:${tool}`,
38 'orange',
39 [summary, reason ? `\n<font color='grey'>${reason}</font>` : ''].join(''),
40 [
41 button('✅ 允许一次', 'primary', v('once')),
42 button('✅ 本会话不再询问', 'default', v('session')),
43 button('❌ 拒绝', 'danger', v('deny')),
44 ],
45 )
46}
47
48export function resolvedCard(title: string, template: 'green' | 'red' | 'grey', markdown: string): Card {
49 return card1(title, template, markdown)
50}
51
52/** One form for up to four questions: a select (or multi-select) and an "other" box each. */
53export function questionCard(rid: string, questions: readonly AskQuestion[]): Card {
54 const elements: Card[] = []
55 questions.forEach((q, i) => {
56 const opts = (q.options ?? []).map((o, j) => ({ text: text(o.label), value: String(j) }))
57 const notes = (q.options ?? [])
58 .filter(o => o.description)
59 .map(o => `- **${o.label}**:${o.description}`)
60 .join('\n')
61 elements.push({ tag: 'markdown', content: `**${q.header ? `[${q.header}] ` : ''}${q.question}**${notes ? `\n${notes}` : ''}` })
62 if (opts.length) {
63 elements.push({
64 tag: q.multiSelect ? 'multi_select_static' : 'select_static',
65 name: `q${i}`,
66 placeholder: text(q.multiSelect ? '可多选' : '请选择'),
67 options: opts,
68 required: false,
69 width: 'fill',
70 })
71 }
72 elements.push({
73 tag: 'input',
74 name: `q${i}_other`,
75 placeholder: text(opts.length ? '或者直接写你的回答(可留空)' : '你的回答'),
76 required: false,
77 width: 'fill',
78 })
79 })
80 elements.push({
81 tag: 'button',
82 name: 'submit',
83 text: text('提交'),
84 type: 'primary_filled',
85 form_action_type: 'submit',
86 behaviors: [{ type: 'callback', value: { rid, kind: 'question' } }],
87 })
88 return {
89 schema: '2.0',
90 config: { update_multi: true, width_mode: 'fill' },
91 header: { title: text('Claude 想问你'), template: 'blue' },
92 body: { elements: [{ tag: 'form', name: 'ask', elements }] },
93 }
94}
95
96/** Maps a form submission back to AskUserQuestion's answers (question -> label(s)). */
97export function answersFromForm(
98 questions: readonly AskQuestion[],
99 form: Record<string, unknown>,
100): Record<string, string> {
101 const answers: Record<string, string> = {}
102 questions.forEach((q, i) => {
103 const labels = (q.options ?? []).map(o => o.label)
104 const raw = form[`q${i}`]
105 const picked = (Array.isArray(raw) ? raw : raw === undefined || raw === '' ? [] : [raw])
106 .map(v => labels[Number(v)])
107 .filter((l): l is string => typeof l === 'string')
108 const other = typeof form[`q${i}_other`] === 'string' ? (form[`q${i}_other`] as string).trim() : ''
109 const all = other ? [...picked, other] : picked
110 if (all.length) answers[q.question] = all.join(', ')
111 })
112 return answers
113}
114
115export function answersMarkdown(answers: Record<string, string>): string {
116 const lines = Object.entries(answers).map(([q, a]) => `- ${q}\n **${a}**`)
117 return lines.length ? lines.join('\n') : '(未作答)'
118}
119
120export type ConfigRowView = {
121 key: string
122 label: string
123 kind: 'boolean' | 'choice' | 'text' | 'number'
124 value: boolean | string | number | readonly string[]
125 options?: readonly string[]
126 isLocked: boolean
127}
128
129const show = (v: ConfigRowView['value']): string => (Array.isArray(v) ? v.join(', ') : String(v))
130
131/** A settings card: toggles as buttons, choices as selects; the rest read-only. `view` redraws it. */
132export function configCard(view: string, title: string, rows: readonly ConfigRowView[], note?: string): Card {
133 const elements: Card[] = []
134 if (note) elements.push({ tag: 'markdown', content: note })
135 for (const row of rows) {
136 const editable = !row.isLocked && (row.kind === 'boolean' || (row.kind === 'choice' && (row.options?.length ?? 0) > 0))
137 elements.push({ tag: 'markdown', content: `**${row.label}**:${show(row.value)}${row.isLocked ? '(已锁定)' : ''}` })
138 if (!editable) continue
139 if (row.kind === 'boolean') {
140 const next = row.value === true ? 'false' : 'true'
141 elements.push({
142 tag: 'action',
143 actions: [button(row.value === true ? '关闭' : '开启', row.value === true ? 'default' : 'primary', { kind: 'config', view, key: row.key, set: next })],
144 })
145 } else {
146 elements.push({
147 tag: 'action',
148 actions: [{
149 tag: 'select_static',
150 placeholder: text(`选择 ${row.label}`),
151 initial_option: typeof row.value === 'string' ? row.value : undefined,
152 options: (row.options ?? []).slice(0, 50).map(o => ({ text: text(o), value: o })),
153 value: { kind: 'config', view, key: row.key },
154 }],
155 })
156 }
157 }
158 if (!rows.length) elements.push({ tag: 'markdown', content: '没有可以在飞书里修改的设置。' })
159 return {
160 config: { wide_screen_mode: true, update_multi: true },
161 header: { title: text(title), template: 'blue' },
162 elements,
163 }
164}
165
166export type StatusView = {
167 title: string
168 subtitle?: string
169 costUsd?: number
170 contextPercent?: number
171 contextText: string
172 model?: string
173 limits: ReadonlyArray<{ name: string; percent: number; reset?: string }>
174 footnote?: string
175}
176
177const tone = (p: number) => (p >= 80 ? 'red' : p >= 50 ? 'orange' : 'green')
178const md = (content: string, align: 'left' | 'center' | 'right' = 'left'): Card => ({ tag: 'markdown', content, text_align: align })
179const column = (elements: Card[], weight = 1): Card => ({ tag: 'column', width: 'weighted', weight, vertical_align: 'center', elements })
180
181/** "claude-opus-5-5" -> "Opus 5.5"; anything else as given. */
182export function prettyModel(id: string): string {
183 const m = /^claude-([a-z]+)-(\d+)-(\d+)/.exec(id)
184 return m ? `${(m[1] ?? '').charAt(0).toUpperCase()}${(m[1] ?? '').slice(1)} ${m[2]}.${m[3]}` : id
185}
186
187/** /status, /cost, /usage as a small card: one line each, percentages colored. */
188export function statusCard(v: StatusView): Card {
189 const pct = (p: number) => `<font color='${tone(p)}'>**${Math.round(p)}%**</font>`
190 const lines: string[] = []
191 const head: string[] = []
192 if (v.costUsd !== undefined) head.push(`花费 **$${v.costUsd.toFixed(2)}**`)
193 head.push(`上下文 ${v.contextPercent === undefined ? v.contextText : pct(v.contextPercent)}`)
194 lines.push(head.join(' '))
195 for (const l of v.limits) lines.push(`${l.name} ${pct(l.percent)}${l.reset ? ` <font color='grey'>${l.reset}</font>` : ''}`)
196 if (v.footnote) lines.push(`<font color='grey'>${v.footnote}</font>`)
197 const title = [v.title, v.model ? prettyModel(v.model) : ''].filter(Boolean).join(' · ')
198 return {
199 config: { wide_screen_mode: true },
200 header: { title: text(title), template: 'blue' },
201 elements: [{ tag: 'markdown', content: lines.join('\n') }],
202 }
203}
204hooks/lib.ts 229 lines1// Pure helpers: no `$`, so the tests can call them directly.
2
3export type FeishuMessage = {
4 messageId: string
5 chatId: string
6 chatType: string
7 senderId: string
8 senderType: string
9 messageType: string
10 content: string
11}
12
13export type Resource = { key: string; type: 'image' | 'file'; name?: string }
14
15const MESSAGE_ID = /^om_[A-Za-z0-9_-]{1,64}$/
16const OPEN_ID = /^ou_[A-Za-z0-9_-]{1,64}$/
17const CHAT_ID = /^oc_[A-Za-z0-9_-]{1,64}$/
18const RESOURCE_KEY = /^(img|file)_[A-Za-z0-9_-]{1,128}$/
19const MARKER = /\[飞书消息 (om_[A-Za-z0-9_-]{1,64})\]/
20
21export const isMessageId = (id: string): boolean => MESSAGE_ID.test(id)
22export const isOpenId = (id: string): boolean => OPEN_ID.test(id)
23export const isChatId = (id: string): boolean => CHAT_ID.test(id)
24
25/** Message types whose files are worth fetching. */
26export const MEDIA_TYPES = new Set(['image', 'file', 'post', 'media', 'audio'])
27
28/** Splits streamed stdout into complete lines, keeping the unfinished tail. */
29export function splitLines(buffer: string, text: string): { lines: string[]; rest: string } {
30 const parts = (buffer + text).split('\n')
31 const rest = parts.pop() ?? ''
32 return { lines: parts.map(line => line.trim()).filter(Boolean), rest }
33}
34
35/** One NDJSON line of `lark-cli event consume im.message.receive_v1`, or null. */
36export function parseEvent(line: string): FeishuMessage | null {
37 const o = parseObject(line)
38 if (!o) return null
39 const str = (v: unknown): string => (typeof v === 'string' ? v : '')
40 const messageId = str(o.message_id) || str(o.id)
41 if (!isMessageId(messageId)) return null
42 return {
43 messageId,
44 chatId: str(o.chat_id),
45 chatType: str(o.chat_type),
46 senderId: str(o.sender_id),
47 senderType: str(o.sender_type),
48 messageType: str(o.message_type),
49 content: str(o.content),
50 }
51}
52
53export function parseObject(text: string): Record<string, unknown> | null {
54 try {
55 const v: unknown = JSON.parse(text)
56 return typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null
57 } catch {
58 return null
59 }
60}
61
62/** The prompt the session reads; the marker lets turn.start find the message again. */
63export function buildPrompt(m: FeishuMessage, files: readonly string[] = []): string {
64 const where = m.chatType === 'p2p' ? '私聊' : '群聊'
65 const lines = [`[飞书消息 ${m.messageId}] (${where})`, m.content]
66 if (files.length) {
67 lines.push('', '附件已下载到本地(图片可以直接用 Read 查看):', ...files.map(f => `- ${f}`))
68 }
69 return lines.join('\n')
70}
71
72export function markerOf(text: string): string | null {
73 return MARKER.exec(text)?.[1] ?? null
74}
75
76/** `/name args` typed in Feishu, or null for an ordinary message. */
77export function parseSlash(text: string): { command: string; args: string } | null {
78 const m = /^\/([A-Za-z][\w:.-]{0,63})(?:\s+([\s\S]*))?$/.exec(text.trim())
79 return m ? { command: m[1] ?? '', args: (m[2] ?? '').trim() } : null
80}
81
82/** Every image_key / file_key a raw message body holds, post bodies included. */
83export function findResources(body: unknown): Resource[] {
84 const out: Resource[] = []
85 const seen = new Set<string>()
86 const walk = (v: unknown): void => {
87 if (Array.isArray(v)) return v.forEach(walk)
88 if (typeof v !== 'object' || v === null) return
89 const o = v as Record<string, unknown>
90 const image = o.image_key
91 const file = o.file_key
92 if (typeof file === 'string' && RESOURCE_KEY.test(file) && !seen.has(file)) {
93 seen.add(file)
94 out.push({ key: file, type: 'file', name: typeof o.file_name === 'string' ? o.file_name : undefined })
95 } else if (typeof image === 'string' && RESOURCE_KEY.test(image) && !seen.has(image)) {
96 seen.add(image)
97 out.push({ key: image, type: 'image' })
98 }
99 Object.values(o).forEach(walk)
100 }
101 walk(body)
102 return out
103}
104
105/** A file name safe to write under the download folder. */
106export function safeName(r: Resource): string {
107 const base = (r.name ?? r.key).replace(/[^\w.\-一-鿿]+/g, '_').replace(/^\.+/, '').slice(0, 120)
108 return base || r.key
109}
110
111/** Absolute paths of local images an answer mentions, in order, without repeats. */
112export function localImages(answer: string): string[] {
113 const found = answer.match(/\/[^\s`'"()<>\[\]]+\.(?:png|jpe?g|gif|webp)\b/gi) ?? []
114 return [...new Set(found)].filter(p => !p.includes('..')).slice(0, 5)
115}
116
117/** The message_id a lark-cli send or reply printed, if any. */
118export function sentMessageId(stdout: string): string | null {
119 return /"message_id"\s*:\s*"(om_[A-Za-z0-9_-]{1,64})"/.exec(stdout)?.[1] ?? null
120}
121
122/** Cuts a reply into pieces Feishu accepts, preferring paragraph then line breaks. */
123export function chunkReply(text: string, max = 3500): string[] {
124 const out: string[] = []
125 let rest = text.trim()
126 while (rest.length > max) {
127 const window = rest.slice(0, max)
128 let cut = window.lastIndexOf('\n\n')
129 if (cut < max / 2) cut = window.lastIndexOf('\n')
130 if (cut < max / 2) cut = max
131 out.push(rest.slice(0, cut).trimEnd())
132 rest = rest.slice(cut).trimStart()
133 }
134 if (rest) out.push(rest)
135 return out
136}
137
138/** A short, readable summary of a tool call for an approval card. */
139export function describeToolInput(tool: string, input: unknown): string {
140 const o = (typeof input === 'object' && input !== null ? input : {}) as Record<string, unknown>
141 const pick = (k: string): string => (typeof o[k] === 'string' ? (o[k] as string) : '')
142 const clip = (s: string, n = 1500): string => (s.length > n ? `${s.slice(0, n)}…` : s)
143 if (tool === 'Bash') {
144 const desc = pick('description')
145 return `${desc ? `${desc}\n` : ''}\`\`\`bash\n${clip(pick('command'))}\n\`\`\``
146 }
147 const path = pick('file_path') || pick('notebook_path') || pick('path')
148 if (path) return `\`${path}\``
149 const url = pick('url')
150 if (url) return url
151 return `\`\`\`json\n${clip(JSON.stringify(o, null, 2))}\n\`\`\``
152}
153
154export const REPLY_GUIDE = [
155 '这条消息来自飞书机器人,你本轮的最终回答会被自动作为飞书回复发回给对方。',
156 '用简体中文,结论先行,简短;可以用简单的 Markdown(加粗、列表、代码块),不要用表格。',
157 '不要在回答里自己调用 lark-cli 发送回复,桥接会处理。要发图片给对方时,在回答里写出图片的本地绝对路径即可。',
158].join('\n')
159
160export type UsageView = {
161 version?: string
162 cwd?: string
163 home?: string
164 model?: string
165 costUsd?: number
166 context: { tokens?: number; window: number; percent?: number }
167 rateLimits: ReadonlyArray<{ kind: string; percentUsed: number; resetsAt?: string }>
168}
169
170export const LIMIT_NAMES: Record<string, string> = {
171 five_hour: '5 小时额度',
172 seven_day: '7 天额度',
173 seven_day_opus: '7 天额度(Opus)',
174 seven_day_sonnet: '7 天额度(Sonnet)',
175 spend_limit: '花费上限',
176}
177
178export const tokens = (n?: number): string =>
179 n === undefined ? '?' : n >= 1_000_000 ? `${+(n / 1_000_000).toFixed(2)}M` : n >= 1000 ? `${+(n / 1000).toFixed(1)}k` : String(n)
180
181export function bar(percent: number, width = 10): string {
182 const filled = Math.max(0, Math.min(width, Math.round((percent / 100) * width)))
183 return '▓'.repeat(filled) + '░'.repeat(width - filled)
184}
185
186/** "2 小时 59 分后" / "3 天 7 小时后", from now until `iso`. */
187export function untilText(iso: string, now: number): string {
188 const ms = Date.parse(iso) - now
189 if (!Number.isFinite(ms)) return ''
190 if (ms <= 0) return '即将'
191 const min = Math.round(ms / 60_000)
192 const d = Math.floor(min / 1440)
193 const h = Math.floor((min % 1440) / 60)
194 const m = min % 60
195 if (d) return `${d} 天${h ? ` ${h} 小时` : ''}后`
196 if (h) return `${h} 小时${m ? ` ${m} 分` : ''}后`
197 return `${m} 分钟后`
198}
199
200/** Local wall time of `iso`, "10/7 02:10", in the given offset (minutes east of UTC). */
201export function localTime(iso: string, offsetMin: number): string {
202 const t = Date.parse(iso)
203 if (!Number.isFinite(t)) return ''
204 const d = new Date(t + offsetMin * 60_000)
205 const pad = (n: number) => String(n).padStart(2, '0')
206 return `${d.getUTCMonth() + 1}/${d.getUTCDate()} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`
207}
208
209/** The usage / status reply, as Feishu markdown. `full` adds version, directory and model. */
210export function formatUsage(u: UsageView, now: number, offsetMin: number, full: boolean): string {
211 const lines: string[] = []
212 if (full && u.version) lines.push(`**Claude Code ${u.version}**`)
213 if (full && u.cwd) lines.push(`📁 ${u.home && u.cwd.startsWith(u.home) ? `~${u.cwd.slice(u.home.length)}` : u.cwd}`)
214 if (full && u.model) lines.push(`🧠 模型:${u.model}`)
215 if (u.costUsd !== undefined) lines.push(`💰 本会话花费:**$${u.costUsd.toFixed(2)}**`)
216 const pct = u.context.percent ?? (u.context.tokens !== undefined ? (u.context.tokens / u.context.window) * 100 : undefined)
217 lines.push(`📊 上下文:${tokens(u.context.tokens)} / ${tokens(u.context.window)}${pct === undefined ? '' : `(${Math.round(pct)}%)`}`)
218 if (pct !== undefined) lines.push(bar(pct))
219 if (u.rateLimits.length) lines.push('')
220 for (const r of u.rateLimits) {
221 const name = LIMIT_NAMES[r.kind] ?? r.kind
222 const warn = r.percentUsed >= 80 ? ' ⚠️' : ''
223 const reset = r.resetsAt ? `,${untilText(r.resetsAt, now)}重置(${localTime(r.resetsAt, offsetMin)})` : ''
224 lines.push(`⏱ ${name}:已用 **${Math.round(r.percentUsed)}%**${warn}${reset}`)
225 lines.push(bar(r.percentUsed))
226 }
227 return lines.join('\n')
228}
229types/index.d.ts 35 lines1export type FeishuModStatus = 'off' | 'starting' | 'listening' | 'error'
2
3/** A prompt typed at the computer, mirrored to Feishu and waiting for its turn. */
4export type FeishuMirrored = { text: string; messageId: string }
5
6/** A card waiting for a click: the sent card's message_id ('' while sending) and its tool. */
7export type FeishuPendingCard = { cardId: string; tool: string }
8
9/** A Feishu slash command's message, answered by the next turn it starts. */
10export type FeishuArmed = { messageId: string; until: number }
11
12declare module 'claude-code' {
13 interface PluginState {
14 'feishu-mod': {
15 /** Whether the bridge should be consuming events in this session. */
16 isOn: boolean
17 status: FeishuModStatus
18 /** turnId -> the Feishu message_id the turn's answer replies to. */
19 turns: Record<string, string>
20 /** turnId -> the visible text of each step so far, for a turn bound to Feishu. */
21 said: Record<string, string[]>
22 /** Recently handled message_ids, newest last. */
23 seen: string[]
24 mirrored: FeishuMirrored[]
25 armed: FeishuArmed | null
26 /** rid -> a card waiting for a click. */
27 pending: Record<string, FeishuPendingCard>
28 /** message_id -> the reaction_id of its Typing badge. */
29 typing: Record<string, string>
30 /** The model the last main-loop turn ran on. */
31 model: string
32 }
33 }
34}
35