dsh-channel-feishu 0.9.1 → 0.9.3
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 +1 -1
- package/cordis.patch.yml +6 -2
- package/index.js +91 -6
- package/package.json +1 -1
- package/providers/feishu.js +65 -3
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.
|
|
85
|
+
dsh plugin add https://github.com/Poy-Coder/dsh-channel-feishu/releases/download/v0.9.3/dsh-channel-feishu-0.9.3.tgz
|
|
86
86
|
```
|
|
87
87
|
|
|
88
88
|
依赖必须用扁平结构装(非 ASCII 目录下 pnpm 的软链会把路径写坏):
|
package/cordis.patch.yml
CHANGED
|
@@ -13,9 +13,10 @@
|
|
|
13
13
|
# plugin, so "installs and starts receiving" is the expected behaviour.
|
|
14
14
|
# Set false when the bot should only send (feishu_send_message/file).
|
|
15
15
|
inboundEnabled: true
|
|
16
|
-
# Session inbound messages go to; `create` makes it when missing
|
|
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.
|
|
17
18
|
sessionId: ''
|
|
18
|
-
sessionMode:
|
|
19
|
+
sessionMode: create
|
|
19
20
|
# Sender allowlist (open_id); empty accepts anyone.
|
|
20
21
|
allowedUsers: []
|
|
21
22
|
# Workspace that owns channel sessions; '' uses <home>/dsh-feishu.
|
|
@@ -24,6 +25,9 @@
|
|
|
24
25
|
# back to the originating chat without the model calling a tool.
|
|
25
26
|
streamingCards: true
|
|
26
27
|
autoReply: true
|
|
28
|
+
# Messages typed on the desktop GUI are mirrored into the chat, so one
|
|
29
|
+
# conversation can be followed from either surface.
|
|
30
|
+
mirrorUserMessages: true
|
|
27
31
|
# Unattended turns have nobody to answer approvals, so sessions in the
|
|
28
32
|
# workspace switch to this preset (set applyPermissionPreset: false to
|
|
29
33
|
# keep each session's own policy).
|
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,
|
|
@@ -90,6 +92,7 @@ export const Config = z.object({
|
|
|
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.'),
|
|
92
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(true).description('Post messages typed outside Feishu (desktop GUI) into the owning chat, prefixed with 其他端.'),
|
|
93
96
|
logLevel: z.union([z.const('debug'), z.const('info'), z.const('warn'), z.const('error')])
|
|
94
97
|
.default('info')
|
|
95
98
|
.description('Minimum severity written to the diagnostics log.'),
|
|
@@ -1115,6 +1118,10 @@ function nextStepsOf(config, result, inbound) {
|
|
|
1115
1118
|
if (!String(result?.defaultChatId ?? '').trim()) {
|
|
1116
1119
|
steps.push('没有默认会话:把 defaultChatId(oc_ 开头)写进凭据文件,或在行 config 里设置')
|
|
1117
1120
|
}
|
|
1121
|
+
if (!String(currentSessionId(config ?? {}) ?? '').trim()
|
|
1122
|
+
&& String(config?.sessionMode ?? 'resume').toLowerCase() !== 'create') {
|
|
1123
|
+
steps.push('还没有会话:给 feishu-channel 行设 sessionMode: create,第一条飞书消息会自动开一个会话')
|
|
1124
|
+
}
|
|
1118
1125
|
return steps
|
|
1119
1126
|
}
|
|
1120
1127
|
|
|
@@ -1476,6 +1483,27 @@ const PLUGIN_VERSION = (() => {
|
|
|
1476
1483
|
|
|
1477
1484
|
let readyAnnounced = false
|
|
1478
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
|
+
|
|
1479
1507
|
/**
|
|
1480
1508
|
* One "channel ready" message per process.
|
|
1481
1509
|
*
|
|
@@ -2176,11 +2204,33 @@ export async function handleInboundEvent(ctx, config, data, seen) {
|
|
|
2176
2204
|
}
|
|
2177
2205
|
}
|
|
2178
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
|
+
|
|
2179
2230
|
if (!text) {
|
|
2180
2231
|
log({ event: 'inbound', result: 'dropped', reason: 'empty text', senderId, chatId })
|
|
2181
2232
|
return
|
|
2182
2233
|
}
|
|
2183
|
-
|
|
2184
2234
|
// Control phrases are consumed here, never delivered to the model.
|
|
2185
2235
|
// `/new` still starts a fresh conversation; `/help` lists the rest.
|
|
2186
2236
|
// Any accepted inbound counts as channel activity, commands included, so the
|
|
@@ -2196,10 +2246,22 @@ export async function handleInboundEvent(ctx, config, data, seen) {
|
|
|
2196
2246
|
// free-text answer settles the tool call instead of starting a new turn.
|
|
2197
2247
|
if (consumeQuestionTextAnswer(ctx, config, { chatId, senderId, text })) return
|
|
2198
2248
|
|
|
2199
|
-
|
|
2249
|
+
let sessionId = currentSessionId(config)
|
|
2200
2250
|
if (!sessionId) {
|
|
2201
|
-
|
|
2202
|
-
|
|
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 })
|
|
2203
2265
|
return
|
|
2204
2266
|
}
|
|
2205
2267
|
|
|
@@ -2221,9 +2283,12 @@ export async function handleInboundEvent(ctx, config, data, seen) {
|
|
|
2221
2283
|
// DSH only validates identity when reading the log, not when appending, so a
|
|
2222
2284
|
// raw `{ content, source }` followup corrupts the session silently.
|
|
2223
2285
|
lastInboundAt = Date.now()
|
|
2286
|
+
const promptId = randomUUID()
|
|
2287
|
+
channelPromptIds.add(promptId)
|
|
2288
|
+
if (channelPromptIds.size > 200) channelPromptIds.delete(channelPromptIds.values().next().value)
|
|
2224
2289
|
try {
|
|
2225
2290
|
await resolved.agent.followup({
|
|
2226
|
-
id:
|
|
2291
|
+
id: promptId,
|
|
2227
2292
|
role: 'user',
|
|
2228
2293
|
content: [{ type: 'text', text: inboundUserText(text) }],
|
|
2229
2294
|
source: { kind: 'user' },
|
|
@@ -3013,6 +3078,23 @@ function startInbound(ctx, config) {
|
|
|
3013
3078
|
observeSessionEvent(scoped, config, session, event)
|
|
3014
3079
|
})
|
|
3015
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
|
+
|
|
3016
3098
|
// Answer ask_user_question in Feishu: without this, a Feishu-only session
|
|
3017
3099
|
// fails the tool call with NO_PROVIDER (no browser page to answer it).
|
|
3018
3100
|
// Prepend so the chat wins over the GUI relay when the session is open in
|
|
@@ -3058,6 +3140,7 @@ function startInbound(ctx, config) {
|
|
|
3058
3140
|
disposed = true
|
|
3059
3141
|
clearInterval(releaseTimer)
|
|
3060
3142
|
try { offSessionEvent?.() } catch { /* ignore */ }
|
|
3143
|
+
try { offInbox?.() } catch { /* ignore */ }
|
|
3061
3144
|
try { offQuestion?.() } catch { /* ignore */ }
|
|
3062
3145
|
try { connectionCleanup() } catch { /* ignore */ }
|
|
3063
3146
|
disposeAgentStreams()
|
|
@@ -3073,7 +3156,9 @@ function startInbound(ctx, config) {
|
|
|
3073
3156
|
|
|
3074
3157
|
export function apply(ctx, config = {}) {
|
|
3075
3158
|
if (config.enabled === false) return
|
|
3076
|
-
|
|
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) }, {
|
|
3077
3162
|
log: (record) => logInbound(config, record),
|
|
3078
3163
|
credentials: typeof ctx.get === 'function' ? ctx.get('credentials') : undefined,
|
|
3079
3164
|
})
|
package/package.json
CHANGED
package/providers/feishu.js
CHANGED
|
@@ -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
|
-
/**
|
|
551
|
-
|
|
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()
|