dsh-channel-feishu 0.8.4 → 0.9.0

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.8.3/dsh-channel-feishu-0.8.3.tgz
85
+ dsh plugin add https://github.com/Poy-Coder/dsh-channel-feishu/releases/download/v0.9.0/dsh-channel-feishu-0.9.0.tgz
86
86
  ```
87
87
 
88
88
  依赖必须用扁平结构装(非 ASCII 目录下 pnpm 的软链会把路径写坏):
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,9 @@ 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
+ logLevel: z.union([z.const('debug'), z.const('info'), z.const('warn'), z.const('error')])
93
+ .default('info')
94
+ .description('Minimum severity written to the diagnostics log.'),
92
95
  stateFile: z.string().default('').description('Channel state path (current session, chat memory).'),
93
96
  inboundFilesDir: z.string().default('').description('Where inbound images are saved.'),
94
97
  })
@@ -301,6 +304,7 @@ function turnRecord(sessionId, turn) {
301
304
  committed: '', stepStream: '', stepBlocks: new Set(),
302
305
  card: undefined, cardFailed: false, sentByTool: false, lastCardText: '', updates: 0,
303
306
  backoffUntil: 0, cardCreating: undefined, timer: undefined, lastSentAt: 0, phase: 'thinking',
307
+ activity: '', toolSteps: 0, startedAt: Date.now(), heartbeat: undefined, footerText: '等待回答',
304
308
  }
305
309
  turns.set(key, record)
306
310
  if (turns.size > 64) {
@@ -321,12 +325,41 @@ function textOfMessage(message) {
321
325
  /** Shown from turn start until the first answer token arrives. */
322
326
  const THINKING_TEXT = '思考中…'
323
327
 
324
- /** The text a card/text reply should carry right now: committed steps + live deltas. */
325
- function replyText(record) {
328
+ /** Footer once the answer text starts streaming (the card opens on 等待回答). */
329
+ const FOOTER_STREAMING = '流式输出中'
330
+
331
+ /** How often the placeholder card refreshes its elapsed time while thinking. */
332
+ const PROGRESS_HEARTBEAT_MS = 10_000
333
+
334
+ /** The answer text committed so far, without any placeholder. */
335
+ function answerTextOf(record) {
326
336
  const head = String(record.committed ?? '').trimEnd()
327
337
  const tail = String(record.stepStream ?? '')
328
- const joined = [head, tail].filter(Boolean).join(head && tail ? '\n\n' : '')
329
- if (!joined) return record.phase === 'answering' ? '' : THINKING_TEXT
338
+ return [head, tail].filter(Boolean).join(head && tail ? '\n\n' : '')
339
+ }
340
+
341
+ /**
342
+ * Placeholder body for a turn that has no answer yet.
343
+ *
344
+ * A tool-heavy turn can spend minutes before the first token, and a card that
345
+ * only says 思考中… looks frozen. The placeholder therefore names the tool that
346
+ * is running, counts the calls, and ticks the elapsed time.
347
+ */
348
+ export function progressText(record, now = Date.now()) {
349
+ const lines = [THINKING_TEXT]
350
+ const seconds = Math.max(0, Math.round((now - (record?.startedAt ?? now)) / 1000))
351
+ const meta = []
352
+ if (record?.activity) meta.push(`正在执行 ${record.activity}`)
353
+ if ((record?.toolSteps ?? 0) > 0) meta.push(`已调用 ${record.toolSteps} 个工具`)
354
+ if (seconds >= 5) meta.push(`已用时 ${seconds}s`)
355
+ if (meta.length > 0) lines.push('', `<font color="grey">${meta.join(' · ')}</font>`)
356
+ return lines.join('\n')
357
+ }
358
+
359
+ /** The text a card/text reply should carry right now: committed steps + live deltas. */
360
+ function replyText(record) {
361
+ const joined = answerTextOf(record)
362
+ if (!joined) return record.phase === 'answering' ? '' : progressText(record)
330
363
  if (joined.length <= MAX_REPLY_CHARS) return joined
331
364
  return `${joined.slice(0, MAX_REPLY_CHARS)}\n\n…(内容过长,已截断)`
332
365
  }
@@ -386,6 +419,18 @@ async function ensureCard(record, ctx, config) {
386
419
  return await record.cardCreating
387
420
  }
388
421
 
422
+ /** Keep the placeholder card's elapsed time moving while the turn has no text. */
423
+ function startProgressHeartbeat(record, ctx, config) {
424
+ if (record.heartbeat) return
425
+ const timer = setInterval(() => {
426
+ if (!turns.has(record.key)) return
427
+ if (record.phase !== 'thinking' || !record.card) return
428
+ scheduleCardFlush(record, ctx, config)
429
+ }, PROGRESS_HEARTBEAT_MS)
430
+ timer.unref?.()
431
+ record.heartbeat = timer
432
+ }
433
+
389
434
  /** Coalesce stream deltas: one Feishu write per CARD_FLUSH_MS at most. */
390
435
  function scheduleCardFlush(record, ctx, config) {
391
436
  if (record.timer) return
@@ -428,6 +473,20 @@ async function flushCard(record, ctx, config) {
428
473
  record.lastCardText = text
429
474
  record.updates = (record.updates ?? 0) + 1
430
475
  record.lastSentAt = Date.now()
476
+ // The footer opens on 等待回答 (nothing has streamed yet) and switches here
477
+ // the first time real answer text lands.
478
+ if (record.phase === 'answering' && record.footerText !== FOOTER_STREAMING) {
479
+ try {
480
+ card.sequence += 1
481
+ await provider().card.update({
482
+ cardId: card.cardId,
483
+ content: `<font color="grey">${FOOTER_STREAMING}</font>`,
484
+ sequence: card.sequence,
485
+ elementId: 'note_1',
486
+ })
487
+ record.footerText = FOOTER_STREAMING
488
+ } catch { /* footer is cosmetic */ }
489
+ }
431
490
  } catch (error) {
432
491
  if (isRateLimited(error)) {
433
492
  // Keep the card: slow down instead of dropping to text, which would need
@@ -452,6 +511,42 @@ async function flushCard(record, ctx, config) {
452
511
  }
453
512
  }
454
513
 
514
+ /**
515
+ * Post a finished answer as its own card so it lands below the question cards,
516
+ * and turn the original turn card into a pointer to it.
517
+ */
518
+ async function postAnswerBelow(ctx, config, chatId, record, text) {
519
+ try {
520
+ const cardId = await provider().card.create({ text, summary: summaryOf(text) })
521
+ await provider().card.attach({ chatId, cardId })
522
+ // This card is born complete, so its footer never claims to be waiting.
523
+ try {
524
+ await provider().card.update({
525
+ cardId, content: '<font color="grey">完成</font>', sequence: 1, elementId: 'note_1',
526
+ })
527
+ } catch { /* footer is cosmetic */ }
528
+ await provider().card.close({ cardId, sequence: 2, summary: summaryOf(text) })
529
+ if (record.card) {
530
+ try {
531
+ record.card.sequence += 1
532
+ await provider().card.update({
533
+ cardId: record.card.cardId,
534
+ content: '<font color="grey">本轮回答见下方 ↓</font>',
535
+ sequence: record.card.sequence,
536
+ })
537
+ record.card.sequence += 1
538
+ await provider().card.close({
539
+ cardId: record.card.cardId, sequence: record.card.sequence, summary: '回答见下方',
540
+ })
541
+ } catch { /* the new card already carries the answer */ }
542
+ }
543
+ return cardId
544
+ } catch (error) {
545
+ warnTo(ctx, `posting the answer below the questions failed: ${errorText(error)}`)
546
+ return ''
547
+ }
548
+ }
549
+
455
550
  /**
456
551
  * Close one turn: finish the card that already carries the answer, or send the
457
552
  * answer as a plain text message when cards are off or unavailable.
@@ -465,6 +560,10 @@ export async function finalizeTurn(ctx, config, sessionId, turn, reason) {
465
560
  clearTimeout(record.timer)
466
561
  record.timer = undefined
467
562
  }
563
+ if (record.heartbeat) {
564
+ clearInterval(record.heartbeat)
565
+ record.heartbeat = undefined
566
+ }
468
567
  // Drop the acknowledgement reaction now that the turn is over.
469
568
  const ack = ackReactions.get(sessionId)
470
569
  if (ack) {
@@ -477,7 +576,7 @@ export async function finalizeTurn(ctx, config, sessionId, turn, reason) {
477
576
 
478
577
  // Nothing but the placeholder: finish the card with a clear note instead of
479
578
  // leaving a "thinking" card open forever.
480
- if (!text || text === THINKING_TEXT) {
579
+ if (!answerTextOf(record).trim()) {
481
580
  if (cardsOn && record.card) {
482
581
  const note = reason?.kind === 'error' ? '(这一轮出错了,没有产生回复)' : '(没有产生文字回答)'
483
582
  try {
@@ -506,6 +605,20 @@ export async function finalizeTurn(ctx, config, sessionId, turn, reason) {
506
605
  return
507
606
  }
508
607
 
608
+ // A turn that asked a question posted its question cards *below* the turn
609
+ // card, so updating the turn card would land the answer above them and read as
610
+ // silence. Post the answer as a fresh card underneath instead.
611
+ if (cardsOn && record.askedQuestion && chatId) {
612
+ const posted = await postAnswerBelow(ctx, config, chatId, record, text)
613
+ if (posted) {
614
+ logInbound(config, {
615
+ event: 'card', result: 'answered-below', sessionId, turn, cardId: posted,
616
+ chars: text.length, turnCard: record.card?.cardId ?? '',
617
+ })
618
+ return
619
+ }
620
+ }
621
+
509
622
  if (cardsOn) {
510
623
  const card = await ensureCard(record, ctx, config)
511
624
  if (card) {
@@ -606,10 +719,17 @@ export function observeSessionEvent(ctx, config, session, event) {
606
719
  // first token), then the card placeholder.
607
720
  ensureCotRun(ctx, config, target, data.turn)
608
721
  void ensureCard(record, ctx, config).catch(() => {})
722
+ startProgressHeartbeat(record, ctx, config)
609
723
  return
610
724
  }
611
725
  if (event.type === 'tool/call') {
612
726
  if (data.name === 'feishu_send_message') turnRecord(target, data.turn).sentByTool = true
727
+ const record = turnRecord(target, data.turn)
728
+ // The card placeholder names the running tool, so a long tool phase still
729
+ // shows progress instead of a frozen 思考中….
730
+ record.activity = String(data.name ?? '')
731
+ record.toolSteps = (record.toolSteps ?? 0) + 1
732
+ scheduleCardFlush(record, ctx, config)
613
733
  const run = cotRuns.get(`${target}|${data.turn}`)
614
734
  if (run) {
615
735
  if (run.reasoningOpen) {
@@ -626,6 +746,11 @@ export function observeSessionEvent(ctx, config, session, event) {
626
746
  return
627
747
  }
628
748
  if (event.type === 'tool/result') {
749
+ const record = turnRecord(target, data.turn)
750
+ if (record.activity) {
751
+ record.activity = ''
752
+ scheduleCardFlush(record, ctx, config)
753
+ }
629
754
  const run = cotRuns.get(`${target}|${data.turn}`)
630
755
  if (run) {
631
756
  const text = textOfMessage(data.message)
@@ -644,6 +769,10 @@ export function observeSessionEvent(ctx, config, session, event) {
644
769
  const text = textOfMessage(data.message)
645
770
  if (!text) return
646
771
  record.phase = 'answering'
772
+ if (record.heartbeat) {
773
+ clearInterval(record.heartbeat)
774
+ record.heartbeat = undefined
775
+ }
647
776
  record.committed = record.committed ? `${record.committed}\n\n${text}` : text
648
777
  record.stepStream = ''
649
778
  record.stepBlocks = new Set()
@@ -1304,15 +1433,64 @@ function inboundLogPath(config) {
1304
1433
  return String(config.logFile ?? '').trim() || join(dirname(credentialsFilePath()), 'feishu-inbound.log')
1305
1434
  }
1306
1435
 
1436
+ const LOG_RANK = { debug: 10, info: 20, warn: 30, error: 40 }
1437
+ const LOG_ROTATE_BYTES = 4 * 1024 * 1024
1438
+
1439
+ /**
1440
+ * Severity of one diagnostic record.
1441
+ *
1442
+ * Callers may pass `level` explicitly; otherwise it is inferred from the event,
1443
+ * result and reason, so the existing call sites gain levels without a rewrite.
1444
+ */
1445
+ export function logLevelOf(record) {
1446
+ const declared = String(record?.level ?? '')
1447
+ if (Object.prototype.hasOwnProperty.call(LOG_RANK, declared)) return declared
1448
+ const text = `${record?.event ?? ''} ${record?.result ?? ''} ${record?.reason ?? ''}`.toLowerCase()
1449
+ if (/fail|error|denied|refused|invalid/.test(text)) return 'error'
1450
+ if (record?.event === 'debug') return 'debug'
1451
+ if (/drop|skip|timeout|abort|rate-limited|closed|bad-value|empty|stale|missing/.test(text)) return 'warn'
1452
+ return 'info'
1453
+ }
1454
+
1455
+ // One writer owns the file. Writes stay synchronous on purpose: a record must be
1456
+ // readable the moment the caller returns (the smoke test and `tail` both assume
1457
+ // it), and a ~100-byte append costs far less than the Feishu round trip it
1458
+ // describes. Rotation keeps the file bounded.
1459
+ const logBytes = new Map()
1460
+
1307
1461
  /** Append one JSONL diagnostic record. Must never throw into the delivery path. */
1308
1462
  function logInbound(config, record) {
1309
1463
  try {
1310
- appendFileSync(inboundLogPath(config), `${JSON.stringify({ time: Date.now(), ...record })}\n`)
1464
+ const level = logLevelOf(record)
1465
+ const floor = LOG_RANK[config?.logLevel] ?? LOG_RANK.info
1466
+ if ((LOG_RANK[level] ?? LOG_RANK.info) < floor) return
1467
+ const path = inboundLogPath(config)
1468
+ const line = `${JSON.stringify({ time: Date.now(), level, ...record })}\n`
1469
+ let size = logBytes.get(path)
1470
+ if (size === undefined) {
1471
+ try { size = statSync(path).size } catch { size = 0 }
1472
+ }
1473
+ if (size > LOG_ROTATE_BYTES) {
1474
+ // Keep exactly one previous file: diagnostics are for the last failure,
1475
+ // not for an unbounded archive.
1476
+ try { renameSync(path, `${path}.1`) } catch { /* keep appending */ }
1477
+ size = 0
1478
+ }
1479
+ appendFileSync(path, line)
1480
+ logBytes.set(path, size + Buffer.byteLength(line))
1311
1481
  } catch {
1312
1482
  // a broken log path must not break message delivery
1313
1483
  }
1314
1484
  }
1315
1485
 
1486
+ /** Leveled facade for new call sites, so they do not pass `level` by hand. */
1487
+ export const channelLog = {
1488
+ debug: (config, record) => logInbound(config, { ...record, level: 'debug' }),
1489
+ info: (config, record) => logInbound(config, { ...record, level: 'info' }),
1490
+ warn: (config, record) => logInbound(config, { ...record, level: 'warn' }),
1491
+ error: (config, record) => logInbound(config, { ...record, level: 'error' }),
1492
+ }
1493
+
1316
1494
  /** Default provider/model route, when the profile exposes the default-model service. */
1317
1495
  function agentOptionsFor(ctx) {
1318
1496
  try {
@@ -2523,6 +2701,19 @@ function finishQuestion(config, pending, status, explicitAnswers) {
2523
2701
  return true
2524
2702
  }
2525
2703
 
2704
+ /**
2705
+ * Flag the newest live turn of a session, so that turn's answer is posted below
2706
+ * the question cards instead of into the card opened at turn start.
2707
+ */
2708
+ function markQuestionAsked(sessionId) {
2709
+ let latest
2710
+ for (const record of turns.values()) {
2711
+ if (record.sessionId !== sessionId) continue
2712
+ if (!latest || record.turn > latest.turn) latest = record
2713
+ }
2714
+ if (latest) latest.askedQuestion = true
2715
+ }
2716
+
2526
2717
  /** Send the question as a card; fall back to plain text if card creation fails. */
2527
2718
  async function sendQuestionCard(ctx, config, pending) {
2528
2719
  const step = pending.step ?? 0
@@ -2541,6 +2732,7 @@ async function sendQuestionCard(ctx, config, pending) {
2541
2732
  const messageId = await provider().card.attach({ chatId: pending.chatId, cardId })
2542
2733
  pending.cardId = cardId
2543
2734
  pending.messageId = messageId
2735
+ markQuestionAsked(pending.sessionId)
2544
2736
  logInbound(config, {
2545
2737
  event: 'question', result: 'card-sent', sessionId: pending.sessionId,
2546
2738
  callId: pending.callId, chatId: pending.chatId, cardId, messageId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-channel-feishu",
3
- "version": "0.8.4",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "Feishu/Lark (飞书) channel for DeepSeek Harness: a chat bound to a DSH session, with streaming cards and attachments.",
6
6
  "license": "MIT",
@@ -321,7 +321,9 @@ function cardJson(text, summary) {
321
321
  {
322
322
  tag: 'markdown',
323
323
  element_id: 'note_1',
324
- content: '<font color="grey">流式输出中</font>',
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
  ],