dsh-channel-feishu 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -82,7 +82,7 @@ dsh plugin add dsh-channel-feishu
82
82
 
83
83
  ```bash
84
84
  dsh plugin add https://github.com/Poy-Coder/dsh-channel-feishu
85
- dsh plugin add https://github.com/Poy-Coder/dsh-channel-feishu/releases/download/v0.9.0/dsh-channel-feishu-0.9.0.tgz
85
+ dsh plugin add https://github.com/Poy-Coder/dsh-channel-feishu/releases/download/v0.9.2/dsh-channel-feishu-0.9.2.tgz
86
86
  ```
87
87
 
88
88
  依赖必须用扁平结构装(非 ASCII 目录下 pnpm 的软链会把路径写坏):
package/cordis.patch.yml CHANGED
@@ -9,12 +9,14 @@
9
9
  provider: feishu
10
10
  # Register the tools at all.
11
11
  enabled: true
12
- # Long connection + inbound delivery. Off by default: an unattended
13
- # channel should be an explicit choice.
14
- inboundEnabled: false
15
- # Session inbound messages go to; `create` makes it when missing.
12
+ # Long connection + inbound delivery. On by default: this is a channel
13
+ # plugin, so "installs and starts receiving" is the expected behaviour.
14
+ # Set false when the bot should only send (feishu_send_message/file).
15
+ inboundEnabled: true
16
+ # Session inbound messages go to; `create` makes it when missing, which
17
+ # is what a fresh install needs: the first message opens the session.
16
18
  sessionId: ''
17
- sessionMode: resume
19
+ sessionMode: create
18
20
  # Sender allowlist (open_id); empty accepts anyone.
19
21
  allowedUsers: []
20
22
  # Workspace that owns channel sessions; '' uses <home>/dsh-feishu.
package/index.js CHANGED
@@ -35,9 +35,11 @@ export {
35
35
  attachmentKind,
36
36
  closeCard,
37
37
  createCard,
38
+ downloadMessageFile,
38
39
  downloadMessageImage,
39
40
  imageExtension,
40
41
  inboundFilesDir,
42
+ parseFileContent,
41
43
  parseImageContent,
42
44
  parseInboundEvent,
43
45
  parsePostContent,
@@ -89,6 +91,8 @@ export const Config = z.object({
89
91
  appSecret: z.string().default('').description('Optional app secret; prefer the credentials store or credentials file.'),
90
92
  defaultChatId: z.string().default('').description('Destination used when a tool call omits receiveId.'),
91
93
  logFile: z.string().default('').description('Inbound diagnostics log path.'),
94
+ readyNotice: z.boolean().default(true).description('Send one "channel ready" message to the default chat after the inbound long connection comes up.'),
95
+ mirrorUserMessages: z.boolean().default(false).description('Post messages typed outside Feishu (desktop GUI) into the owning chat, prefixed with 其他端.'),
92
96
  logLevel: z.union([z.const('debug'), z.const('info'), z.const('warn'), z.const('error')])
93
97
  .default('info')
94
98
  .description('Minimum severity written to the diagnostics log.'),
@@ -1090,6 +1094,37 @@ const sendFileTool = (config) => ({
1090
1094
  },
1091
1095
  })
1092
1096
 
1097
+ /**
1098
+ * What the operator (or another agent) should do next, derived from live state.
1099
+ * Installing used to be trial and error; the tool now names the missing step.
1100
+ */
1101
+ function nextStepsOf(config, result, inbound) {
1102
+ const steps = []
1103
+ if (!result?.configured) {
1104
+ steps.push(
1105
+ `写凭据:把 appId / appSecret 放进 ${credentialsFilePath()}(UTF-8 无 BOM),`
1106
+ + '或设环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET',
1107
+ )
1108
+ }
1109
+ if (result?.configured && !result?.tokenOk) {
1110
+ steps.push('取 token 失败:核对 appId / appSecret、region(国际版用 lark),确认应用已发布并开通机器人能力')
1111
+ }
1112
+ if (config?.enabled !== false && config?.inboundEnabled !== true) {
1113
+ steps.push('入站未开启:在 profile 的 cordis.patch.yml 给 feishu-channel 行设 inboundEnabled: true,然后重启 DSH')
1114
+ }
1115
+ if (config?.inboundEnabled === true && !inbound?.ready) {
1116
+ steps.push('入站长连接未就绪:确认没有另一个飞书插件用同一个 App 在连接(会互相抢事件),然后重启 DSH')
1117
+ }
1118
+ if (!String(result?.defaultChatId ?? '').trim()) {
1119
+ steps.push('没有默认会话:把 defaultChatId(oc_ 开头)写进凭据文件,或在行 config 里设置')
1120
+ }
1121
+ if (!String(currentSessionId(config ?? {}) ?? '').trim()
1122
+ && String(config?.sessionMode ?? 'resume').toLowerCase() !== 'create') {
1123
+ steps.push('还没有会话:给 feishu-channel 行设 sessionMode: create,第一条飞书消息会自动开一个会话')
1124
+ }
1125
+ return steps
1126
+ }
1127
+
1093
1128
  const statusTool = (config) => ({
1094
1129
  name: 'feishu_channel_status',
1095
1130
  description:
@@ -1124,13 +1159,18 @@ const statusTool = (config) => ({
1124
1159
  flushRan: { type: 'number' },
1125
1160
  streamShape: { type: 'string' },
1126
1161
  error: { type: 'string' },
1162
+ version: { type: 'string' },
1163
+ nextSteps: { type: 'array', items: { type: 'string' } },
1127
1164
  },
1128
1165
  required: ['configured', 'tokenOk'],
1129
1166
  additionalProperties: true,
1130
1167
  },
1131
1168
  render(_args, value) {
1169
+ const steps = Array.isArray(value?.nextSteps) && value.nextSteps.length > 0
1170
+ ? `\n下一步:\n${value.nextSteps.map((step, index) => `${index + 1}. ${step}`).join('\n')}`
1171
+ : ''
1132
1172
  if (!value?.configured) {
1133
- return [{ type: 'text', text: `飞书通道未配置。${value?.error ?? ''}`.trim() }]
1173
+ return [{ type: 'text', text: `飞书通道未配置。${value?.error ?? ''}`.trim() + steps }]
1134
1174
  }
1135
1175
  const head = value.tokenOk
1136
1176
  ? '飞书通道已配置,tenant_access_token 获取成功。'
@@ -1154,14 +1194,18 @@ const statusTool = (config) => ({
1154
1194
  + (value.streamShape ? `\n首帧结构=${value.streamShape}` : '')
1155
1195
  + `\n观察:不符=${value.observeMismatch ?? 0} 无帧=${value.observeNoFrame ?? 0}`
1156
1196
  + ` start=${value.observeStart ?? 0} end=${value.observeEnd ?? 0} chunk=${value.observeChunk ?? 0}`
1157
- + (value.lastObserve ? `\n最近=${value.lastObserve}` : ''),
1197
+ + (value.lastObserve ? `\n最近=${value.lastObserve}` : '')
1198
+ + `\n版本=${value.version || '(unknown)'}`
1199
+ + (Array.isArray(value.nextSteps) && value.nextSteps.length > 0
1200
+ ? `\n下一步:\n${value.nextSteps.map((step, index) => `${index + 1}. ${step}`).join('\n')}`
1201
+ : ''),
1158
1202
  }]
1159
1203
  },
1160
1204
  },
1161
1205
  async execute(_args, exec) {
1162
1206
  const inbound = inboundSnapshot()
1163
1207
  const result = await provider().checkStatus(exec?.signal)
1164
- return {
1208
+ const state = {
1165
1209
  ...result,
1166
1210
  autoReply: config.autoReply !== false,
1167
1211
  streamingCards: config.streamingCards !== false,
@@ -1189,7 +1233,9 @@ const statusTool = (config) => ({
1189
1233
  observeStart: observeStats.start,
1190
1234
  observeEnd: observeStats.end,
1191
1235
  observeChunk: observeStats.chunk,
1236
+ version: PLUGIN_VERSION,
1192
1237
  }
1238
+ return { ...state, nextSteps: nextStepsOf(config, state, inbound) }
1193
1239
  },
1194
1240
  })
1195
1241
 
@@ -1426,6 +1472,63 @@ function setInboundState(config, next) {
1426
1472
  logInbound(config, { event: 'channel', ...next })
1427
1473
  }
1428
1474
 
1475
+ /** Version of the running package, shown in the status tool and the ready notice. */
1476
+ const PLUGIN_VERSION = (() => {
1477
+ try {
1478
+ return String(JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version ?? '')
1479
+ } catch {
1480
+ return ''
1481
+ }
1482
+ })()
1483
+
1484
+ let readyAnnounced = false
1485
+
1486
+ /** Ids of the user messages this channel injected, so they are not mirrored back. */
1487
+ const channelPromptIds = new Set()
1488
+
1489
+ /**
1490
+ * Mirror a message typed outside Feishu (desktop GUI) into the owning chat, so
1491
+ * one conversation can be followed from either surface.
1492
+ */
1493
+ async function mirrorUserMessage(config, sessionId, text) {
1494
+ const chatId = replyTargetOf(config, sessionId)
1495
+ if (!chatId) return
1496
+ const body = String(text ?? '').trim()
1497
+ if (!body) return
1498
+ const clipped = body.length > 2000 ? `${body.slice(0, 2000)}…` : body
1499
+ try {
1500
+ await provider().sendText({ chatId, text: `👤 其他端:${clipped}` })
1501
+ logInbound(config, { event: 'mirror', result: 'sent', sessionId, chatId })
1502
+ } catch (error) {
1503
+ logInbound(config, { event: 'mirror', result: 'failed', sessionId, reason: errorText(error) })
1504
+ }
1505
+ }
1506
+
1507
+ /**
1508
+ * One "channel ready" message per process.
1509
+ *
1510
+ * Installing the plugin used to end with a manual test round trip; this hands the
1511
+ * first proof of life straight to the chat that configured `defaultChatId`.
1512
+ */
1513
+ async function announceReady(config) {
1514
+ if (readyAnnounced) return
1515
+ readyAnnounced = true
1516
+ if (config?.readyNotice === false) return
1517
+ try {
1518
+ const chatId = String(provider().settings().defaultChatId ?? '').trim()
1519
+ if (!chatId) return
1520
+ const session = String(config?.sessionId ?? '').trim()
1521
+ await provider().sendText({
1522
+ chatId,
1523
+ text: `✅ 飞书通道已就绪\n插件 dsh-channel-feishu v${PLUGIN_VERSION || '(unknown)'}\n`
1524
+ + `入站长连接正常,接收会话=${session || '按消息新建'}`,
1525
+ })
1526
+ logInbound(config, { event: 'channel', result: 'ready-notice', chatId })
1527
+ } catch (error) {
1528
+ logInbound(config, { event: 'channel', result: 'ready-notice-failed', reason: errorText(error) })
1529
+ }
1530
+ }
1531
+
1429
1532
  const errorText = (error) => (error instanceof Error ? error.message : String(error))
1430
1533
 
1431
1534
  /** Inbound diagnostics land next to the credentials unless `logFile` says otherwise. */
@@ -2101,11 +2204,33 @@ export async function handleInboundEvent(ctx, config, data, seen) {
2101
2204
  }
2102
2205
  }
2103
2206
 
2207
+ const inboundFiles = Array.isArray(inbound.files) ? inbound.files : []
2208
+ if (inboundFiles.length > 0) {
2209
+ const messageId = inbound.messageId
2210
+ if (!messageId) {
2211
+ log({ event: 'inbound', result: 'file-error', reason: 'message_id missing', senderId, chatId })
2212
+ } else {
2213
+ const savedFiles = []
2214
+ for (const file of inboundFiles.slice(0, 4)) {
2215
+ try {
2216
+ savedFiles.push(await provider().downloadFile({
2217
+ messageId, fileKey: file.fileKey, fileName: file.fileName,
2218
+ }))
2219
+ } catch (error) {
2220
+ log({ event: 'inbound', result: 'file-error', reason: errorText(error), senderId, chatId })
2221
+ }
2222
+ }
2223
+ if (savedFiles.length > 0) {
2224
+ text = [text, ...savedFiles.map((path) => `[文件] ${path}`)].filter(Boolean).join('\n')
2225
+ log({ event: 'inbound', result: 'files', count: savedFiles.length, senderId, chatId })
2226
+ }
2227
+ }
2228
+ }
2229
+
2104
2230
  if (!text) {
2105
2231
  log({ event: 'inbound', result: 'dropped', reason: 'empty text', senderId, chatId })
2106
2232
  return
2107
2233
  }
2108
-
2109
2234
  // Control phrases are consumed here, never delivered to the model.
2110
2235
  // `/new` still starts a fresh conversation; `/help` lists the rest.
2111
2236
  // Any accepted inbound counts as channel activity, commands included, so the
@@ -2121,10 +2246,22 @@ export async function handleInboundEvent(ctx, config, data, seen) {
2121
2246
  // free-text answer settles the tool call instead of starting a new turn.
2122
2247
  if (consumeQuestionTextAnswer(ctx, config, { chatId, senderId, text })) return
2123
2248
 
2124
- const sessionId = currentSessionId(config)
2249
+ let sessionId = currentSessionId(config)
2125
2250
  if (!sessionId) {
2126
- warnTo(ctx, 'inbound message dropped: no sessionId configured')
2127
- log({ event: 'inbound', result: 'dropped', reason: 'no sessionId configured', senderId, chatId })
2251
+ const mode = String(config.sessionMode ?? 'resume').toLowerCase()
2252
+ if (mode !== 'create') {
2253
+ warnTo(ctx, 'inbound message dropped: no sessionId configured')
2254
+ log({
2255
+ event: 'inbound', result: 'dropped',
2256
+ reason: 'no sessionId configured (set sessionMode: create to bootstrap one)', senderId, chatId,
2257
+ })
2258
+ return
2259
+ }
2260
+ // Fresh install: the bundle row carries no sessionId. Create the channel's
2261
+ // session (and, below, its Feishu workspace) from the first inbound message
2262
+ // instead of dropping it — otherwise a new install looks connected but deaf.
2263
+ log({ event: 'inbound', result: 'bootstrap', reason: 'no session yet; creating one', senderId, chatId })
2264
+ await switchToNewSession(ctx, config, { chatId, senderId, firstMessage: text })
2128
2265
  return
2129
2266
  }
2130
2267
 
@@ -2146,9 +2283,12 @@ export async function handleInboundEvent(ctx, config, data, seen) {
2146
2283
  // DSH only validates identity when reading the log, not when appending, so a
2147
2284
  // raw `{ content, source }` followup corrupts the session silently.
2148
2285
  lastInboundAt = Date.now()
2286
+ const promptId = randomUUID()
2287
+ channelPromptIds.add(promptId)
2288
+ if (channelPromptIds.size > 200) channelPromptIds.delete(channelPromptIds.values().next().value)
2149
2289
  try {
2150
2290
  await resolved.agent.followup({
2151
- id: randomUUID(),
2291
+ id: promptId,
2152
2292
  role: 'user',
2153
2293
  content: [{ type: 'text', text: inboundUserText(text) }],
2154
2294
  source: { kind: 'user' },
@@ -2938,6 +3078,23 @@ function startInbound(ctx, config) {
2938
3078
  observeSessionEvent(scoped, config, session, event)
2939
3079
  })
2940
3080
 
3081
+ // Messages typed elsewhere (desktop GUI) are not visible in Feishu unless
3082
+ // the channel mirrors them: user messages enter the live inbox, and the
3083
+ // ones this channel injected itself are recognised by id and skipped.
3084
+ const offInbox = scoped.on?.('agent/inbox/inserted', (payload) => {
3085
+ if (config.mirrorUserMessages !== true) return
3086
+ const agent = payload?.agent
3087
+ const sessionId = agent?.session?.id ?? agent?.id
3088
+ if (!sessionId || sessionId !== activeSessionId(config)) return
3089
+ const message = payload?.message
3090
+ if (!message?.id || channelPromptIds.has(message.id)) return
3091
+ const text = textOfMessage(message)
3092
+ if (!text.trim()) return
3093
+ // Scheduled reminders are injected as user messages; they are not typed.
3094
+ if (/^\[SCHEDULE REMINDER/i.test(text.trim())) return
3095
+ void mirrorUserMessage(config, sessionId, text)
3096
+ })
3097
+
2941
3098
  // Answer ask_user_question in Feishu: without this, a Feishu-only session
2942
3099
  // fails the tool call with NO_PROVIDER (no browser page to answer it).
2943
3100
  // Prepend so the chat wins over the GUI relay when the session is open in
@@ -2966,8 +3123,10 @@ function startInbound(ctx, config) {
2966
3123
  onCardAction: async (data) => await handleQuestionCardAction(scoped, config, data),
2967
3124
  onState: ({ ready, error }) => {
2968
3125
  setInboundState(config, { ready: Boolean(ready), transport: 'websocket', error: String(error ?? '') })
2969
- if (ready) warnTo(scoped, 'inbound long connection ready')
2970
- else if (error && error !== 'closed') warnTo(scoped, `inbound connection problem: ${error}`)
3126
+ if (ready) {
3127
+ warnTo(scoped, 'inbound long connection ready')
3128
+ void announceReady(config)
3129
+ } else if (error && error !== 'closed') warnTo(scoped, `inbound connection problem: ${error}`)
2971
3130
  },
2972
3131
  })
2973
3132
  if (disposed) {
@@ -2981,6 +3140,7 @@ function startInbound(ctx, config) {
2981
3140
  disposed = true
2982
3141
  clearInterval(releaseTimer)
2983
3142
  try { offSessionEvent?.() } catch { /* ignore */ }
3143
+ try { offInbox?.() } catch { /* ignore */ }
2984
3144
  try { offQuestion?.() } catch { /* ignore */ }
2985
3145
  try { connectionCleanup() } catch { /* ignore */ }
2986
3146
  disposeAgentStreams()
@@ -2996,7 +3156,9 @@ function startInbound(ctx, config) {
2996
3156
 
2997
3157
  export function apply(ctx, config = {}) {
2998
3158
  if (config.enabled === false) return
2999
- activeProvider = resolveProvider(config, {
3159
+ // Hand the provider the effective workspace so inbound attachments land in
3160
+ // <workspace>/attachments even when the row leaves workspacePath empty.
3161
+ activeProvider = resolveProvider({ ...config, workspacePath: workspacePathFor(config) }, {
3000
3162
  log: (record) => logInbound(config, record),
3001
3163
  credentials: typeof ctx.get === 'function' ? ctx.get('credentials') : undefined,
3002
3164
  })
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-channel-feishu",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "type": "module",
5
- "description": "Feishu/Lark (飞书) channel for DeepSeek Harness: a chat bound to a DSH session, with streaming cards and attachments.",
5
+ "description": "Feishu/Lark (椋炰功) channel for DeepSeek Harness: a chat bound to a DSH session, with streaming cards and attachments.",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -41,6 +41,7 @@
41
41
  "AGENTS.md",
42
42
  "locale",
43
43
  "docs",
44
+ "scripts",
44
45
  "icon.svg",
45
46
  "LICENSE"
46
47
  ],
@@ -24,7 +24,7 @@
24
24
  * 3. the credentials file <DSH_HOME>/feishu-channel.json
25
25
  */
26
26
 
27
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
27
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
28
28
  import { homedir } from 'node:os'
29
29
  import { basename, dirname, join } from 'node:path'
30
30
 
@@ -512,6 +512,10 @@ export function parseImageContent(content) {
512
512
  export function inboundFilesDir(config) {
513
513
  const configured = String(config?.inboundFilesDir ?? '').trim()
514
514
  if (configured) return configured
515
+ // Attachments belong with the work they feed: put them inside the channel
516
+ // workspace so the agent can open them by a workspace-relative path.
517
+ const workspace = String(config?.workspacePath ?? '').trim()
518
+ if (workspace) return join(workspace, 'attachments')
515
519
  return join(dirname(credentialsFilePath()), 'feishu-inbound-files')
516
520
  }
517
521
 
@@ -547,8 +551,40 @@ export async function downloadMessageImage(base, token, messageId, imageKey, con
547
551
  return path
548
552
  }
549
553
 
550
- /** Normalize one `im.message.receive_v1` payload; null means "nothing usable". */
551
- export function parseInboundEvent(event) {
554
+ /** Keep an attachment name usable as a Windows path segment. */
555
+ function safeFileName(fileName, fileKey) {
556
+ const base = String(fileName ?? '').split(/[\\/]/).pop() ?? ''
557
+ const cleaned = base.replace(/[<>:"|?*\u0000-\u001f]/g, '').trim()
558
+ if (cleaned) return cleaned.slice(0, 120)
559
+ return `${String(fileKey ?? 'file').slice(-12) || 'file'}.bin`
560
+ }
561
+
562
+ /**
563
+ * Download one message file (document, archive, audio…) through the
564
+ * message-resource endpoint and land it in the inbound attachment directory.
565
+ */
566
+ export async function downloadMessageFile(base, token, messageId, fileKey, fileName, config, signal) {
567
+ const resource = `${base}/open-apis/im/v1/messages/${encodeURIComponent(messageId)}`
568
+ + `/resources/${encodeURIComponent(fileKey)}?type=file`
569
+ const response = await fetch(resource, { headers: { authorization: `Bearer ${token}` }, signal })
570
+ if (!response.ok) throw new Error(`Feishu file download failed (HTTP ${response.status})`)
571
+ const buffer = Buffer.from(await response.arrayBuffer())
572
+ const dir = inboundFilesDir(config)
573
+ mkdirSync(dir, { recursive: true })
574
+ let name = safeFileName(fileName, fileKey)
575
+ let path = join(dir, name)
576
+ if (existsSync(path)) {
577
+ const at = name.lastIndexOf('.')
578
+ const stem = at > 0 ? name.slice(0, at) : name
579
+ const ext = at > 0 ? name.slice(at) : ''
580
+ name = `${stem}-${String(fileKey ?? '').slice(-6)}${ext}`
581
+ path = join(dir, name)
582
+ }
583
+ writeFileSync(path, buffer)
584
+ return path
585
+ }
586
+
587
+ /** Normalize one `im.message.receive_v1` payload; null means "nothing usable". */export function parseInboundEvent(event) {
552
588
  const message = event?.message
553
589
  const sender = event?.sender
554
590
  if (!message || !sender) return null
@@ -556,6 +592,7 @@ export function parseInboundEvent(event) {
556
592
  const mentions = message.mentions
557
593
  let text = ''
558
594
  let imageKeys = []
595
+ let files = []
559
596
  if (messageType === 'text') {
560
597
  text = stripMentions(parseTextContent(message.content), mentions)
561
598
  } else if (messageType === 'post') {
@@ -565,6 +602,9 @@ export function parseInboundEvent(event) {
565
602
  } else if (messageType === 'image') {
566
603
  const key = parseImageContent(message.content)
567
604
  if (key) imageKeys = [key]
605
+ } else if (messageType === 'file') {
606
+ const file = parseFileContent(message.content)
607
+ if (file.fileKey) files = [file]
568
608
  } else {
569
609
  return {
570
610
  dedupeKey: String(event?.header?.event_id ?? ''),
@@ -574,6 +614,7 @@ export function parseInboundEvent(event) {
574
614
  messageId: String(message.message_id ?? ''),
575
615
  text: '',
576
616
  imageKeys: [],
617
+ files: [],
577
618
  unsupported: messageType,
578
619
  }
579
620
  }
@@ -585,10 +626,24 @@ export function parseInboundEvent(event) {
585
626
  messageId: String(message.message_id ?? ''),
586
627
  text,
587
628
  imageKeys,
629
+ files,
588
630
  unsupported: '',
589
631
  }
590
632
  }
591
633
 
634
+ /** One `file` message body: `{ file_key, file_name }`. */
635
+ export function parseFileContent(content) {
636
+ try {
637
+ const parsed = JSON.parse(content ?? '{}')
638
+ return {
639
+ fileKey: typeof parsed?.file_key === 'string' ? parsed.file_key : '',
640
+ fileName: typeof parsed?.file_name === 'string' ? parsed.file_name : '',
641
+ }
642
+ } catch {
643
+ return { fileKey: '', fileName: '' }
644
+ }
645
+ }
646
+
592
647
  /**
593
648
  * Normalize one `card.action.trigger` payload.
594
649
  *
@@ -684,6 +739,13 @@ export function createFeishuProvider(config = {}, deps = {}) {
684
739
  )
685
740
  },
686
741
 
742
+ async downloadFile({ messageId, fileKey, fileName }, signal) {
743
+ const resolved = await settingsAsync()
744
+ return await downloadMessageFile(
745
+ resolved.baseUrl, await token(signal), messageId, fileKey, fileName, config, signal,
746
+ )
747
+ },
748
+
687
749
  card: {
688
750
  async create({ text, summary }, signal) {
689
751
  const resolved = await settingsAsync()
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * One-command credential setup for dsh-channel-feishu.
4
+ *
5
+ * The only manual step left after `dsh plugin add` is teaching the plugin the
6
+ * Feishu app credentials. Doing that by hand invites two mistakes: a UTF-8 BOM
7
+ * in the JSON file (the plugin then fails to load) and a wrong region. This
8
+ * script finds the credentials that another Feishu channel already uses, writes
9
+ * the file correctly, and verifies them against the Feishu API.
10
+ *
11
+ * Usage:
12
+ * node scripts/setup.mjs # scan, write, verify
13
+ * node scripts/setup.mjs --dry-run # scan and verify only
14
+ * node scripts/setup.mjs --region lark # international tenant
15
+ * node scripts/setup.mjs --app-id X --app-secret Y
16
+ */
17
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
+ import { dirname, join } from 'node:path'
20
+
21
+ const argv = process.argv.slice(2)
22
+ const has = (flag) => argv.includes(flag)
23
+ const valueOf = (flag) => {
24
+ const at = argv.indexOf(flag)
25
+ return at >= 0 ? String(argv[at + 1] ?? '') : ''
26
+ }
27
+
28
+ const dryRun = has('--dry-run')
29
+ const HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
30
+ const target = join(HOME, 'feishu-channel.json')
31
+ const say = (...args) => console.log(...args)
32
+
33
+ const mask = (value) => {
34
+ const text = String(value ?? '')
35
+ if (text.length <= 8) return text ? '****' : ''
36
+ return `${text.slice(0, 6)}…${text.slice(-4)}(${text.length} 字符)`
37
+ }
38
+
39
+ /** Read every small text file under the DSH home, skipping noise. */
40
+ function candidateFiles() {
41
+ const skip = new Set(['sessions', 'node_modules', 'attachments', 'feishu-inbound-files', '.git'])
42
+ const found = []
43
+ const walk = (dir, depth) => {
44
+ if (depth > 3) return
45
+ let entries
46
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
47
+ for (const entry of entries) {
48
+ const path = join(dir, entry.name)
49
+ if (entry.isDirectory()) {
50
+ if (skip.has(entry.name)) continue
51
+ walk(path, depth + 1)
52
+ continue
53
+ }
54
+ if (!/\.(json|ya?ml|env)$/i.test(entry.name)) continue
55
+ try {
56
+ if (statSync(path).size > 512 * 1024) continue
57
+ } catch { continue }
58
+ found.push(path)
59
+ }
60
+ }
61
+ walk(HOME, 0)
62
+ return found
63
+ }
64
+
65
+ const pick = (text, key) => {
66
+ const match = text.match(new RegExp(`["']?${key}["']?\\s*[:=]\\s*["']?([A-Za-z0-9_-]{6,})`, 'i'))
67
+ return match ? match[1] : ''
68
+ }
69
+
70
+ function scan() {
71
+ const fromEnv = {
72
+ appId: String(process.env.FEISHU_APP_ID ?? '').trim(),
73
+ appSecret: String(process.env.FEISHU_APP_SECRET ?? '').trim(),
74
+ source: 'environment',
75
+ }
76
+ if (fromEnv.appId && fromEnv.appSecret) return fromEnv
77
+
78
+ if (existsSync(target)) {
79
+ try {
80
+ const existing = JSON.parse(readFileSync(target, 'utf8'))
81
+ if (existing.appId && existing.appSecret) {
82
+ return { ...existing, source: target }
83
+ }
84
+ } catch { /* unreadable: fall through to the scan */ }
85
+ }
86
+
87
+ for (const path of candidateFiles()) {
88
+ let text
89
+ try { text = readFileSync(path, 'utf8') } catch { continue }
90
+ const appId = pick(text, 'appId') || pick(text, 'FEISHU_APP_ID') || pick(text, 'app_id')
91
+ const appSecret = pick(text, 'appSecret') || pick(text, 'FEISHU_APP_SECRET') || pick(text, 'app_secret')
92
+ if (!appId || !appSecret) continue
93
+ const region = /(?:region|lark)/i.test(text) && /lark/i.test(text) ? 'lark' : 'feishu'
94
+ const chat = pick(text, 'defaultChatId') || pick(text, 'chat_id')
95
+ return { appId, appSecret, region, defaultChatId: chat, source: path }
96
+ }
97
+ return undefined
98
+ }
99
+
100
+ async function verify({ appId, appSecret, region }) {
101
+ const base = region === 'lark' ? 'https://open.larksuite.com' : 'https://open.feishu.cn'
102
+ try {
103
+ const response = await fetch(`${base}/open-apis/auth/v3/tenant_access_token/internal`, {
104
+ method: 'POST',
105
+ headers: { 'content-type': 'application/json; charset=utf-8' },
106
+ body: JSON.stringify({ app_id: appId, app_secret: appSecret }),
107
+ })
108
+ const payload = await response.json().catch(() => undefined)
109
+ if (payload?.code === 0 && payload?.tenant_access_token) return { ok: true }
110
+ return { ok: false, reason: `code=${payload?.code ?? '?'} msg=${payload?.msg ?? response.status}` }
111
+ } catch (error) {
112
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) }
113
+ }
114
+ }
115
+
116
+ const explicitId = valueOf('--app-id')
117
+ const explicitSecret = valueOf('--app-secret')
118
+ const found = explicitId && explicitSecret
119
+ ? { appId: explicitId, appSecret: explicitSecret, source: 'command line' }
120
+ : scan()
121
+
122
+ if (!found) {
123
+ say('没找到飞书应用凭据。请二选一:')
124
+ say(` 1. 写 ${target}:{"appId":"…","appSecret":"…","region":"feishu","defaultChatId":"oc_…"}`)
125
+ say(' 2. 设置环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET')
126
+ say('提示:Windows 上用 PowerShell 5.1 的 Set-Content -Encoding UTF8 会写入 BOM,插件会加载失败。')
127
+ process.exit(1)
128
+ }
129
+
130
+ const region = valueOf('--region') || String(found.region ?? '').trim() || 'feishu'
131
+ say(`来源: ${found.source}`)
132
+ say(`appId: ${mask(found.appId)}`)
133
+ say(`appSecret: ${mask(found.appSecret)}`)
134
+ say(`region: ${region}`)
135
+
136
+ const check = await verify({ appId: found.appId, appSecret: found.appSecret, region })
137
+ say(`凭据校验: ${check.ok ? '通过(tenant_access_token 获取成功)' : `失败(${check.reason})`}`)
138
+
139
+ if (dryRun) {
140
+ say('dry run:未写入任何文件。')
141
+ process.exit(check.ok ? 0 : 1)
142
+ }
143
+ if (!check.ok) {
144
+ say('凭据未通过校验,不写入。核对 appId / appSecret / region 后重试。')
145
+ process.exit(1)
146
+ }
147
+
148
+ const payload = {
149
+ appId: found.appId,
150
+ appSecret: found.appSecret,
151
+ region,
152
+ ...(String(found.defaultChatId ?? '').trim() ? { defaultChatId: String(found.defaultChatId).trim() } : {}),
153
+ }
154
+ mkdirSync(dirname(target), { recursive: true })
155
+ // UTF-8 without BOM: a BOM makes the plugin's JSON.parse fail at load time.
156
+ writeFileSync(target, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
157
+ say(`已写入 ${target}(UTF-8 无 BOM,仅当前用户可读)`)
158
+ say('')
159
+ say('下一步:')
160
+ say(' 1. 如有别的飞书插件用同一个 App,先在 profile 的 cordis.patch.yml 里给它加 disabled: true')
161
+ say(' 2. 完全退出 DSH 再打开(关窗口只是隐藏)')
162
+ say(' 3. 打开后机器人会发一条「飞书通道已就绪」,也可以调 feishu_channel_status 确认')