dsh-channel-feishu 0.8.4 → 0.9.1
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 +4 -3
- package/index.js +281 -12
- package/package.json +3 -2
- package/providers/feishu.js +3 -1
- package/scripts/setup.mjs +162 -0
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.
|
|
85
|
+
dsh plugin add https://github.com/Poy-Coder/dsh-channel-feishu/releases/download/v0.9.1/dsh-channel-feishu-0.9.1.tgz
|
|
86
86
|
```
|
|
87
87
|
|
|
88
88
|
依赖必须用扁平结构装(非 ASCII 目录下 pnpm 的软链会把路径写坏):
|
package/cordis.patch.yml
CHANGED
|
@@ -9,9 +9,10 @@
|
|
|
9
9
|
provider: feishu
|
|
10
10
|
# Register the tools at all.
|
|
11
11
|
enabled: true
|
|
12
|
-
# Long connection + inbound delivery.
|
|
13
|
-
#
|
|
14
|
-
|
|
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
|
|
15
16
|
# Session inbound messages go to; `create` makes it when missing.
|
|
16
17
|
sessionId: ''
|
|
17
18
|
sessionMode: resume
|
package/index.js
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
21
|
import { randomUUID } from 'node:crypto'
|
|
22
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
22
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
|
|
23
23
|
import { homedir } from 'node:os'
|
|
24
24
|
import { dirname, join, parse } from 'node:path'
|
|
25
25
|
import { fileURLToPath } from 'node:url'
|
|
@@ -89,6 +89,10 @@ export const Config = z.object({
|
|
|
89
89
|
appSecret: z.string().default('').description('Optional app secret; prefer the credentials store or credentials file.'),
|
|
90
90
|
defaultChatId: z.string().default('').description('Destination used when a tool call omits receiveId.'),
|
|
91
91
|
logFile: z.string().default('').description('Inbound diagnostics log path.'),
|
|
92
|
+
readyNotice: z.boolean().default(true).description('Send one "channel ready" message to the default chat after the inbound long connection comes up.'),
|
|
93
|
+
logLevel: z.union([z.const('debug'), z.const('info'), z.const('warn'), z.const('error')])
|
|
94
|
+
.default('info')
|
|
95
|
+
.description('Minimum severity written to the diagnostics log.'),
|
|
92
96
|
stateFile: z.string().default('').description('Channel state path (current session, chat memory).'),
|
|
93
97
|
inboundFilesDir: z.string().default('').description('Where inbound images are saved.'),
|
|
94
98
|
})
|
|
@@ -301,6 +305,7 @@ function turnRecord(sessionId, turn) {
|
|
|
301
305
|
committed: '', stepStream: '', stepBlocks: new Set(),
|
|
302
306
|
card: undefined, cardFailed: false, sentByTool: false, lastCardText: '', updates: 0,
|
|
303
307
|
backoffUntil: 0, cardCreating: undefined, timer: undefined, lastSentAt: 0, phase: 'thinking',
|
|
308
|
+
activity: '', toolSteps: 0, startedAt: Date.now(), heartbeat: undefined, footerText: '等待回答',
|
|
304
309
|
}
|
|
305
310
|
turns.set(key, record)
|
|
306
311
|
if (turns.size > 64) {
|
|
@@ -321,12 +326,41 @@ function textOfMessage(message) {
|
|
|
321
326
|
/** Shown from turn start until the first answer token arrives. */
|
|
322
327
|
const THINKING_TEXT = '思考中…'
|
|
323
328
|
|
|
324
|
-
/**
|
|
325
|
-
|
|
329
|
+
/** Footer once the answer text starts streaming (the card opens on 等待回答). */
|
|
330
|
+
const FOOTER_STREAMING = '流式输出中'
|
|
331
|
+
|
|
332
|
+
/** How often the placeholder card refreshes its elapsed time while thinking. */
|
|
333
|
+
const PROGRESS_HEARTBEAT_MS = 10_000
|
|
334
|
+
|
|
335
|
+
/** The answer text committed so far, without any placeholder. */
|
|
336
|
+
function answerTextOf(record) {
|
|
326
337
|
const head = String(record.committed ?? '').trimEnd()
|
|
327
338
|
const tail = String(record.stepStream ?? '')
|
|
328
|
-
|
|
329
|
-
|
|
339
|
+
return [head, tail].filter(Boolean).join(head && tail ? '\n\n' : '')
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Placeholder body for a turn that has no answer yet.
|
|
344
|
+
*
|
|
345
|
+
* A tool-heavy turn can spend minutes before the first token, and a card that
|
|
346
|
+
* only says 思考中… looks frozen. The placeholder therefore names the tool that
|
|
347
|
+
* is running, counts the calls, and ticks the elapsed time.
|
|
348
|
+
*/
|
|
349
|
+
export function progressText(record, now = Date.now()) {
|
|
350
|
+
const lines = [THINKING_TEXT]
|
|
351
|
+
const seconds = Math.max(0, Math.round((now - (record?.startedAt ?? now)) / 1000))
|
|
352
|
+
const meta = []
|
|
353
|
+
if (record?.activity) meta.push(`正在执行 ${record.activity}`)
|
|
354
|
+
if ((record?.toolSteps ?? 0) > 0) meta.push(`已调用 ${record.toolSteps} 个工具`)
|
|
355
|
+
if (seconds >= 5) meta.push(`已用时 ${seconds}s`)
|
|
356
|
+
if (meta.length > 0) lines.push('', `<font color="grey">${meta.join(' · ')}</font>`)
|
|
357
|
+
return lines.join('\n')
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** The text a card/text reply should carry right now: committed steps + live deltas. */
|
|
361
|
+
function replyText(record) {
|
|
362
|
+
const joined = answerTextOf(record)
|
|
363
|
+
if (!joined) return record.phase === 'answering' ? '' : progressText(record)
|
|
330
364
|
if (joined.length <= MAX_REPLY_CHARS) return joined
|
|
331
365
|
return `${joined.slice(0, MAX_REPLY_CHARS)}\n\n…(内容过长,已截断)`
|
|
332
366
|
}
|
|
@@ -386,6 +420,18 @@ async function ensureCard(record, ctx, config) {
|
|
|
386
420
|
return await record.cardCreating
|
|
387
421
|
}
|
|
388
422
|
|
|
423
|
+
/** Keep the placeholder card's elapsed time moving while the turn has no text. */
|
|
424
|
+
function startProgressHeartbeat(record, ctx, config) {
|
|
425
|
+
if (record.heartbeat) return
|
|
426
|
+
const timer = setInterval(() => {
|
|
427
|
+
if (!turns.has(record.key)) return
|
|
428
|
+
if (record.phase !== 'thinking' || !record.card) return
|
|
429
|
+
scheduleCardFlush(record, ctx, config)
|
|
430
|
+
}, PROGRESS_HEARTBEAT_MS)
|
|
431
|
+
timer.unref?.()
|
|
432
|
+
record.heartbeat = timer
|
|
433
|
+
}
|
|
434
|
+
|
|
389
435
|
/** Coalesce stream deltas: one Feishu write per CARD_FLUSH_MS at most. */
|
|
390
436
|
function scheduleCardFlush(record, ctx, config) {
|
|
391
437
|
if (record.timer) return
|
|
@@ -428,6 +474,20 @@ async function flushCard(record, ctx, config) {
|
|
|
428
474
|
record.lastCardText = text
|
|
429
475
|
record.updates = (record.updates ?? 0) + 1
|
|
430
476
|
record.lastSentAt = Date.now()
|
|
477
|
+
// The footer opens on 等待回答 (nothing has streamed yet) and switches here
|
|
478
|
+
// the first time real answer text lands.
|
|
479
|
+
if (record.phase === 'answering' && record.footerText !== FOOTER_STREAMING) {
|
|
480
|
+
try {
|
|
481
|
+
card.sequence += 1
|
|
482
|
+
await provider().card.update({
|
|
483
|
+
cardId: card.cardId,
|
|
484
|
+
content: `<font color="grey">${FOOTER_STREAMING}</font>`,
|
|
485
|
+
sequence: card.sequence,
|
|
486
|
+
elementId: 'note_1',
|
|
487
|
+
})
|
|
488
|
+
record.footerText = FOOTER_STREAMING
|
|
489
|
+
} catch { /* footer is cosmetic */ }
|
|
490
|
+
}
|
|
431
491
|
} catch (error) {
|
|
432
492
|
if (isRateLimited(error)) {
|
|
433
493
|
// Keep the card: slow down instead of dropping to text, which would need
|
|
@@ -452,6 +512,42 @@ async function flushCard(record, ctx, config) {
|
|
|
452
512
|
}
|
|
453
513
|
}
|
|
454
514
|
|
|
515
|
+
/**
|
|
516
|
+
* Post a finished answer as its own card so it lands below the question cards,
|
|
517
|
+
* and turn the original turn card into a pointer to it.
|
|
518
|
+
*/
|
|
519
|
+
async function postAnswerBelow(ctx, config, chatId, record, text) {
|
|
520
|
+
try {
|
|
521
|
+
const cardId = await provider().card.create({ text, summary: summaryOf(text) })
|
|
522
|
+
await provider().card.attach({ chatId, cardId })
|
|
523
|
+
// This card is born complete, so its footer never claims to be waiting.
|
|
524
|
+
try {
|
|
525
|
+
await provider().card.update({
|
|
526
|
+
cardId, content: '<font color="grey">完成</font>', sequence: 1, elementId: 'note_1',
|
|
527
|
+
})
|
|
528
|
+
} catch { /* footer is cosmetic */ }
|
|
529
|
+
await provider().card.close({ cardId, sequence: 2, summary: summaryOf(text) })
|
|
530
|
+
if (record.card) {
|
|
531
|
+
try {
|
|
532
|
+
record.card.sequence += 1
|
|
533
|
+
await provider().card.update({
|
|
534
|
+
cardId: record.card.cardId,
|
|
535
|
+
content: '<font color="grey">本轮回答见下方 ↓</font>',
|
|
536
|
+
sequence: record.card.sequence,
|
|
537
|
+
})
|
|
538
|
+
record.card.sequence += 1
|
|
539
|
+
await provider().card.close({
|
|
540
|
+
cardId: record.card.cardId, sequence: record.card.sequence, summary: '回答见下方',
|
|
541
|
+
})
|
|
542
|
+
} catch { /* the new card already carries the answer */ }
|
|
543
|
+
}
|
|
544
|
+
return cardId
|
|
545
|
+
} catch (error) {
|
|
546
|
+
warnTo(ctx, `posting the answer below the questions failed: ${errorText(error)}`)
|
|
547
|
+
return ''
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
455
551
|
/**
|
|
456
552
|
* Close one turn: finish the card that already carries the answer, or send the
|
|
457
553
|
* answer as a plain text message when cards are off or unavailable.
|
|
@@ -465,6 +561,10 @@ export async function finalizeTurn(ctx, config, sessionId, turn, reason) {
|
|
|
465
561
|
clearTimeout(record.timer)
|
|
466
562
|
record.timer = undefined
|
|
467
563
|
}
|
|
564
|
+
if (record.heartbeat) {
|
|
565
|
+
clearInterval(record.heartbeat)
|
|
566
|
+
record.heartbeat = undefined
|
|
567
|
+
}
|
|
468
568
|
// Drop the acknowledgement reaction now that the turn is over.
|
|
469
569
|
const ack = ackReactions.get(sessionId)
|
|
470
570
|
if (ack) {
|
|
@@ -477,7 +577,7 @@ export async function finalizeTurn(ctx, config, sessionId, turn, reason) {
|
|
|
477
577
|
|
|
478
578
|
// Nothing but the placeholder: finish the card with a clear note instead of
|
|
479
579
|
// leaving a "thinking" card open forever.
|
|
480
|
-
if (!
|
|
580
|
+
if (!answerTextOf(record).trim()) {
|
|
481
581
|
if (cardsOn && record.card) {
|
|
482
582
|
const note = reason?.kind === 'error' ? '(这一轮出错了,没有产生回复)' : '(没有产生文字回答)'
|
|
483
583
|
try {
|
|
@@ -506,6 +606,20 @@ export async function finalizeTurn(ctx, config, sessionId, turn, reason) {
|
|
|
506
606
|
return
|
|
507
607
|
}
|
|
508
608
|
|
|
609
|
+
// A turn that asked a question posted its question cards *below* the turn
|
|
610
|
+
// card, so updating the turn card would land the answer above them and read as
|
|
611
|
+
// silence. Post the answer as a fresh card underneath instead.
|
|
612
|
+
if (cardsOn && record.askedQuestion && chatId) {
|
|
613
|
+
const posted = await postAnswerBelow(ctx, config, chatId, record, text)
|
|
614
|
+
if (posted) {
|
|
615
|
+
logInbound(config, {
|
|
616
|
+
event: 'card', result: 'answered-below', sessionId, turn, cardId: posted,
|
|
617
|
+
chars: text.length, turnCard: record.card?.cardId ?? '',
|
|
618
|
+
})
|
|
619
|
+
return
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
509
623
|
if (cardsOn) {
|
|
510
624
|
const card = await ensureCard(record, ctx, config)
|
|
511
625
|
if (card) {
|
|
@@ -606,10 +720,17 @@ export function observeSessionEvent(ctx, config, session, event) {
|
|
|
606
720
|
// first token), then the card placeholder.
|
|
607
721
|
ensureCotRun(ctx, config, target, data.turn)
|
|
608
722
|
void ensureCard(record, ctx, config).catch(() => {})
|
|
723
|
+
startProgressHeartbeat(record, ctx, config)
|
|
609
724
|
return
|
|
610
725
|
}
|
|
611
726
|
if (event.type === 'tool/call') {
|
|
612
727
|
if (data.name === 'feishu_send_message') turnRecord(target, data.turn).sentByTool = true
|
|
728
|
+
const record = turnRecord(target, data.turn)
|
|
729
|
+
// The card placeholder names the running tool, so a long tool phase still
|
|
730
|
+
// shows progress instead of a frozen 思考中….
|
|
731
|
+
record.activity = String(data.name ?? '')
|
|
732
|
+
record.toolSteps = (record.toolSteps ?? 0) + 1
|
|
733
|
+
scheduleCardFlush(record, ctx, config)
|
|
613
734
|
const run = cotRuns.get(`${target}|${data.turn}`)
|
|
614
735
|
if (run) {
|
|
615
736
|
if (run.reasoningOpen) {
|
|
@@ -626,6 +747,11 @@ export function observeSessionEvent(ctx, config, session, event) {
|
|
|
626
747
|
return
|
|
627
748
|
}
|
|
628
749
|
if (event.type === 'tool/result') {
|
|
750
|
+
const record = turnRecord(target, data.turn)
|
|
751
|
+
if (record.activity) {
|
|
752
|
+
record.activity = ''
|
|
753
|
+
scheduleCardFlush(record, ctx, config)
|
|
754
|
+
}
|
|
629
755
|
const run = cotRuns.get(`${target}|${data.turn}`)
|
|
630
756
|
if (run) {
|
|
631
757
|
const text = textOfMessage(data.message)
|
|
@@ -644,6 +770,10 @@ export function observeSessionEvent(ctx, config, session, event) {
|
|
|
644
770
|
const text = textOfMessage(data.message)
|
|
645
771
|
if (!text) return
|
|
646
772
|
record.phase = 'answering'
|
|
773
|
+
if (record.heartbeat) {
|
|
774
|
+
clearInterval(record.heartbeat)
|
|
775
|
+
record.heartbeat = undefined
|
|
776
|
+
}
|
|
647
777
|
record.committed = record.committed ? `${record.committed}\n\n${text}` : text
|
|
648
778
|
record.stepStream = ''
|
|
649
779
|
record.stepBlocks = new Set()
|
|
@@ -961,6 +1091,33 @@ const sendFileTool = (config) => ({
|
|
|
961
1091
|
},
|
|
962
1092
|
})
|
|
963
1093
|
|
|
1094
|
+
/**
|
|
1095
|
+
* What the operator (or another agent) should do next, derived from live state.
|
|
1096
|
+
* Installing used to be trial and error; the tool now names the missing step.
|
|
1097
|
+
*/
|
|
1098
|
+
function nextStepsOf(config, result, inbound) {
|
|
1099
|
+
const steps = []
|
|
1100
|
+
if (!result?.configured) {
|
|
1101
|
+
steps.push(
|
|
1102
|
+
`写凭据:把 appId / appSecret 放进 ${credentialsFilePath()}(UTF-8 无 BOM),`
|
|
1103
|
+
+ '或设环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET',
|
|
1104
|
+
)
|
|
1105
|
+
}
|
|
1106
|
+
if (result?.configured && !result?.tokenOk) {
|
|
1107
|
+
steps.push('取 token 失败:核对 appId / appSecret、region(国际版用 lark),确认应用已发布并开通机器人能力')
|
|
1108
|
+
}
|
|
1109
|
+
if (config?.enabled !== false && config?.inboundEnabled !== true) {
|
|
1110
|
+
steps.push('入站未开启:在 profile 的 cordis.patch.yml 给 feishu-channel 行设 inboundEnabled: true,然后重启 DSH')
|
|
1111
|
+
}
|
|
1112
|
+
if (config?.inboundEnabled === true && !inbound?.ready) {
|
|
1113
|
+
steps.push('入站长连接未就绪:确认没有另一个飞书插件用同一个 App 在连接(会互相抢事件),然后重启 DSH')
|
|
1114
|
+
}
|
|
1115
|
+
if (!String(result?.defaultChatId ?? '').trim()) {
|
|
1116
|
+
steps.push('没有默认会话:把 defaultChatId(oc_ 开头)写进凭据文件,或在行 config 里设置')
|
|
1117
|
+
}
|
|
1118
|
+
return steps
|
|
1119
|
+
}
|
|
1120
|
+
|
|
964
1121
|
const statusTool = (config) => ({
|
|
965
1122
|
name: 'feishu_channel_status',
|
|
966
1123
|
description:
|
|
@@ -995,13 +1152,18 @@ const statusTool = (config) => ({
|
|
|
995
1152
|
flushRan: { type: 'number' },
|
|
996
1153
|
streamShape: { type: 'string' },
|
|
997
1154
|
error: { type: 'string' },
|
|
1155
|
+
version: { type: 'string' },
|
|
1156
|
+
nextSteps: { type: 'array', items: { type: 'string' } },
|
|
998
1157
|
},
|
|
999
1158
|
required: ['configured', 'tokenOk'],
|
|
1000
1159
|
additionalProperties: true,
|
|
1001
1160
|
},
|
|
1002
1161
|
render(_args, value) {
|
|
1162
|
+
const steps = Array.isArray(value?.nextSteps) && value.nextSteps.length > 0
|
|
1163
|
+
? `\n下一步:\n${value.nextSteps.map((step, index) => `${index + 1}. ${step}`).join('\n')}`
|
|
1164
|
+
: ''
|
|
1003
1165
|
if (!value?.configured) {
|
|
1004
|
-
return [{ type: 'text', text: `飞书通道未配置。${value?.error ?? ''}`.trim() }]
|
|
1166
|
+
return [{ type: 'text', text: `飞书通道未配置。${value?.error ?? ''}`.trim() + steps }]
|
|
1005
1167
|
}
|
|
1006
1168
|
const head = value.tokenOk
|
|
1007
1169
|
? '飞书通道已配置,tenant_access_token 获取成功。'
|
|
@@ -1025,14 +1187,18 @@ const statusTool = (config) => ({
|
|
|
1025
1187
|
+ (value.streamShape ? `\n首帧结构=${value.streamShape}` : '')
|
|
1026
1188
|
+ `\n观察:不符=${value.observeMismatch ?? 0} 无帧=${value.observeNoFrame ?? 0}`
|
|
1027
1189
|
+ ` start=${value.observeStart ?? 0} end=${value.observeEnd ?? 0} chunk=${value.observeChunk ?? 0}`
|
|
1028
|
-
+ (value.lastObserve ? `\n最近=${value.lastObserve}` : '')
|
|
1190
|
+
+ (value.lastObserve ? `\n最近=${value.lastObserve}` : '')
|
|
1191
|
+
+ `\n版本=${value.version || '(unknown)'}`
|
|
1192
|
+
+ (Array.isArray(value.nextSteps) && value.nextSteps.length > 0
|
|
1193
|
+
? `\n下一步:\n${value.nextSteps.map((step, index) => `${index + 1}. ${step}`).join('\n')}`
|
|
1194
|
+
: ''),
|
|
1029
1195
|
}]
|
|
1030
1196
|
},
|
|
1031
1197
|
},
|
|
1032
1198
|
async execute(_args, exec) {
|
|
1033
1199
|
const inbound = inboundSnapshot()
|
|
1034
1200
|
const result = await provider().checkStatus(exec?.signal)
|
|
1035
|
-
|
|
1201
|
+
const state = {
|
|
1036
1202
|
...result,
|
|
1037
1203
|
autoReply: config.autoReply !== false,
|
|
1038
1204
|
streamingCards: config.streamingCards !== false,
|
|
@@ -1060,7 +1226,9 @@ const statusTool = (config) => ({
|
|
|
1060
1226
|
observeStart: observeStats.start,
|
|
1061
1227
|
observeEnd: observeStats.end,
|
|
1062
1228
|
observeChunk: observeStats.chunk,
|
|
1229
|
+
version: PLUGIN_VERSION,
|
|
1063
1230
|
}
|
|
1231
|
+
return { ...state, nextSteps: nextStepsOf(config, state, inbound) }
|
|
1064
1232
|
},
|
|
1065
1233
|
})
|
|
1066
1234
|
|
|
@@ -1297,6 +1465,42 @@ function setInboundState(config, next) {
|
|
|
1297
1465
|
logInbound(config, { event: 'channel', ...next })
|
|
1298
1466
|
}
|
|
1299
1467
|
|
|
1468
|
+
/** Version of the running package, shown in the status tool and the ready notice. */
|
|
1469
|
+
const PLUGIN_VERSION = (() => {
|
|
1470
|
+
try {
|
|
1471
|
+
return String(JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version ?? '')
|
|
1472
|
+
} catch {
|
|
1473
|
+
return ''
|
|
1474
|
+
}
|
|
1475
|
+
})()
|
|
1476
|
+
|
|
1477
|
+
let readyAnnounced = false
|
|
1478
|
+
|
|
1479
|
+
/**
|
|
1480
|
+
* One "channel ready" message per process.
|
|
1481
|
+
*
|
|
1482
|
+
* Installing the plugin used to end with a manual test round trip; this hands the
|
|
1483
|
+
* first proof of life straight to the chat that configured `defaultChatId`.
|
|
1484
|
+
*/
|
|
1485
|
+
async function announceReady(config) {
|
|
1486
|
+
if (readyAnnounced) return
|
|
1487
|
+
readyAnnounced = true
|
|
1488
|
+
if (config?.readyNotice === false) return
|
|
1489
|
+
try {
|
|
1490
|
+
const chatId = String(provider().settings().defaultChatId ?? '').trim()
|
|
1491
|
+
if (!chatId) return
|
|
1492
|
+
const session = String(config?.sessionId ?? '').trim()
|
|
1493
|
+
await provider().sendText({
|
|
1494
|
+
chatId,
|
|
1495
|
+
text: `✅ 飞书通道已就绪\n插件 dsh-channel-feishu v${PLUGIN_VERSION || '(unknown)'}\n`
|
|
1496
|
+
+ `入站长连接正常,接收会话=${session || '按消息新建'}`,
|
|
1497
|
+
})
|
|
1498
|
+
logInbound(config, { event: 'channel', result: 'ready-notice', chatId })
|
|
1499
|
+
} catch (error) {
|
|
1500
|
+
logInbound(config, { event: 'channel', result: 'ready-notice-failed', reason: errorText(error) })
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1300
1504
|
const errorText = (error) => (error instanceof Error ? error.message : String(error))
|
|
1301
1505
|
|
|
1302
1506
|
/** Inbound diagnostics land next to the credentials unless `logFile` says otherwise. */
|
|
@@ -1304,15 +1508,64 @@ function inboundLogPath(config) {
|
|
|
1304
1508
|
return String(config.logFile ?? '').trim() || join(dirname(credentialsFilePath()), 'feishu-inbound.log')
|
|
1305
1509
|
}
|
|
1306
1510
|
|
|
1511
|
+
const LOG_RANK = { debug: 10, info: 20, warn: 30, error: 40 }
|
|
1512
|
+
const LOG_ROTATE_BYTES = 4 * 1024 * 1024
|
|
1513
|
+
|
|
1514
|
+
/**
|
|
1515
|
+
* Severity of one diagnostic record.
|
|
1516
|
+
*
|
|
1517
|
+
* Callers may pass `level` explicitly; otherwise it is inferred from the event,
|
|
1518
|
+
* result and reason, so the existing call sites gain levels without a rewrite.
|
|
1519
|
+
*/
|
|
1520
|
+
export function logLevelOf(record) {
|
|
1521
|
+
const declared = String(record?.level ?? '')
|
|
1522
|
+
if (Object.prototype.hasOwnProperty.call(LOG_RANK, declared)) return declared
|
|
1523
|
+
const text = `${record?.event ?? ''} ${record?.result ?? ''} ${record?.reason ?? ''}`.toLowerCase()
|
|
1524
|
+
if (/fail|error|denied|refused|invalid/.test(text)) return 'error'
|
|
1525
|
+
if (record?.event === 'debug') return 'debug'
|
|
1526
|
+
if (/drop|skip|timeout|abort|rate-limited|closed|bad-value|empty|stale|missing/.test(text)) return 'warn'
|
|
1527
|
+
return 'info'
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
// One writer owns the file. Writes stay synchronous on purpose: a record must be
|
|
1531
|
+
// readable the moment the caller returns (the smoke test and `tail` both assume
|
|
1532
|
+
// it), and a ~100-byte append costs far less than the Feishu round trip it
|
|
1533
|
+
// describes. Rotation keeps the file bounded.
|
|
1534
|
+
const logBytes = new Map()
|
|
1535
|
+
|
|
1307
1536
|
/** Append one JSONL diagnostic record. Must never throw into the delivery path. */
|
|
1308
1537
|
function logInbound(config, record) {
|
|
1309
1538
|
try {
|
|
1310
|
-
|
|
1539
|
+
const level = logLevelOf(record)
|
|
1540
|
+
const floor = LOG_RANK[config?.logLevel] ?? LOG_RANK.info
|
|
1541
|
+
if ((LOG_RANK[level] ?? LOG_RANK.info) < floor) return
|
|
1542
|
+
const path = inboundLogPath(config)
|
|
1543
|
+
const line = `${JSON.stringify({ time: Date.now(), level, ...record })}\n`
|
|
1544
|
+
let size = logBytes.get(path)
|
|
1545
|
+
if (size === undefined) {
|
|
1546
|
+
try { size = statSync(path).size } catch { size = 0 }
|
|
1547
|
+
}
|
|
1548
|
+
if (size > LOG_ROTATE_BYTES) {
|
|
1549
|
+
// Keep exactly one previous file: diagnostics are for the last failure,
|
|
1550
|
+
// not for an unbounded archive.
|
|
1551
|
+
try { renameSync(path, `${path}.1`) } catch { /* keep appending */ }
|
|
1552
|
+
size = 0
|
|
1553
|
+
}
|
|
1554
|
+
appendFileSync(path, line)
|
|
1555
|
+
logBytes.set(path, size + Buffer.byteLength(line))
|
|
1311
1556
|
} catch {
|
|
1312
1557
|
// a broken log path must not break message delivery
|
|
1313
1558
|
}
|
|
1314
1559
|
}
|
|
1315
1560
|
|
|
1561
|
+
/** Leveled facade for new call sites, so they do not pass `level` by hand. */
|
|
1562
|
+
export const channelLog = {
|
|
1563
|
+
debug: (config, record) => logInbound(config, { ...record, level: 'debug' }),
|
|
1564
|
+
info: (config, record) => logInbound(config, { ...record, level: 'info' }),
|
|
1565
|
+
warn: (config, record) => logInbound(config, { ...record, level: 'warn' }),
|
|
1566
|
+
error: (config, record) => logInbound(config, { ...record, level: 'error' }),
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1316
1569
|
/** Default provider/model route, when the profile exposes the default-model service. */
|
|
1317
1570
|
function agentOptionsFor(ctx) {
|
|
1318
1571
|
try {
|
|
@@ -2523,6 +2776,19 @@ function finishQuestion(config, pending, status, explicitAnswers) {
|
|
|
2523
2776
|
return true
|
|
2524
2777
|
}
|
|
2525
2778
|
|
|
2779
|
+
/**
|
|
2780
|
+
* Flag the newest live turn of a session, so that turn's answer is posted below
|
|
2781
|
+
* the question cards instead of into the card opened at turn start.
|
|
2782
|
+
*/
|
|
2783
|
+
function markQuestionAsked(sessionId) {
|
|
2784
|
+
let latest
|
|
2785
|
+
for (const record of turns.values()) {
|
|
2786
|
+
if (record.sessionId !== sessionId) continue
|
|
2787
|
+
if (!latest || record.turn > latest.turn) latest = record
|
|
2788
|
+
}
|
|
2789
|
+
if (latest) latest.askedQuestion = true
|
|
2790
|
+
}
|
|
2791
|
+
|
|
2526
2792
|
/** Send the question as a card; fall back to plain text if card creation fails. */
|
|
2527
2793
|
async function sendQuestionCard(ctx, config, pending) {
|
|
2528
2794
|
const step = pending.step ?? 0
|
|
@@ -2541,6 +2807,7 @@ async function sendQuestionCard(ctx, config, pending) {
|
|
|
2541
2807
|
const messageId = await provider().card.attach({ chatId: pending.chatId, cardId })
|
|
2542
2808
|
pending.cardId = cardId
|
|
2543
2809
|
pending.messageId = messageId
|
|
2810
|
+
markQuestionAsked(pending.sessionId)
|
|
2544
2811
|
logInbound(config, {
|
|
2545
2812
|
event: 'question', result: 'card-sent', sessionId: pending.sessionId,
|
|
2546
2813
|
callId: pending.callId, chatId: pending.chatId, cardId, messageId,
|
|
@@ -2774,8 +3041,10 @@ function startInbound(ctx, config) {
|
|
|
2774
3041
|
onCardAction: async (data) => await handleQuestionCardAction(scoped, config, data),
|
|
2775
3042
|
onState: ({ ready, error }) => {
|
|
2776
3043
|
setInboundState(config, { ready: Boolean(ready), transport: 'websocket', error: String(error ?? '') })
|
|
2777
|
-
if (ready)
|
|
2778
|
-
|
|
3044
|
+
if (ready) {
|
|
3045
|
+
warnTo(scoped, 'inbound long connection ready')
|
|
3046
|
+
void announceReady(config)
|
|
3047
|
+
} else if (error && error !== 'closed') warnTo(scoped, `inbound connection problem: ${error}`)
|
|
2779
3048
|
},
|
|
2780
3049
|
})
|
|
2781
3050
|
if (disposed) {
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-channel-feishu",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "Feishu/Lark (
|
|
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
|
],
|
package/providers/feishu.js
CHANGED
|
@@ -321,7 +321,9 @@ function cardJson(text, summary) {
|
|
|
321
321
|
{
|
|
322
322
|
tag: 'markdown',
|
|
323
323
|
element_id: 'note_1',
|
|
324
|
-
|
|
324
|
+
// The card opens before the model has produced anything, so the footer
|
|
325
|
+
// starts as a wait notice; flushCard flips it once the answer streams.
|
|
326
|
+
content: '<font color="grey">等待回答</font>',
|
|
325
327
|
text_size: 'notation',
|
|
326
328
|
},
|
|
327
329
|
],
|
|
@@ -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 确认')
|