File size: 22,516 Bytes
73bc263
44e0492
73bc263
 
1caee20
 
44e0492
 
 
 
 
 
 
 
 
 
 
 
d6862e4
44e0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bc263
 
 
 
44e0492
 
73bc263
 
 
 
 
44e0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bc263
 
44e0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bc263
 
44e0492
73bc263
 
44e0492
 
 
 
 
 
73bc263
44e0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bc263
 
 
 
 
 
44e0492
 
 
 
 
73bc263
 
44e0492
 
73bc263
44e0492
 
 
 
73bc263
 
 
 
 
 
44e0492
 
 
73bc263
44e0492
73bc263
 
 
44e0492
 
 
 
 
 
 
 
 
96f34e3
44e0492
 
 
 
 
 
 
 
 
 
 
 
73bc263
 
44e0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bc263
44e0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bc263
 
44e0492
 
73bc263
 
44e0492
73bc263
44e0492
 
 
 
73bc263
 
44e0492
 
 
 
 
 
 
 
 
73bc263
 
44e0492
73bc263
 
44e0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bc263
 
44e0492
 
 
73bc263
 
 
 
 
 
 
 
 
 
 
 
44e0492
 
96f34e3
44e0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bc263
 
44e0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73bc263
44e0492
73bc263
44e0492
73bc263
 
 
 
44e0492
 
 
 
 
73bc263
 
 
1caee20
 
 
 
 
 
588f433
1caee20
 
 
 
 
 
 
 
 
 
 
588f433
1caee20
53e0f9f
1caee20
53e0f9f
 
588f433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96f34e3
588f433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53e0f9f
 
1caee20
588f433
 
 
 
53e0f9f
588f433
 
53e0f9f
588f433
 
53e0f9f
1caee20
53e0f9f
588f433
 
 
1caee20
588f433
 
 
 
 
 
 
 
 
 
 
 
1caee20
588f433
 
 
 
 
 
 
1caee20
 
 
 
53e0f9f
1caee20
 
 
 
 
 
588f433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44e0492
 
 
73bc263
 
44e0492
73bc263
44e0492
73bc263
 
 
 
 
44e0492
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
/**
 * FeishuService โ€” in-process Feishu bot using @larksuite/channel
 */

import * as path from 'node:path'
import * as os from 'node:os'
import {
  createLarkChannel,
  type LarkChannel,
  type NormalizedMessage,
  registerApp,
} from '@larksuite/channel'
import {
  getFeishuConfig,
  saveFeishuConfig,
  type FeishuRuntimeConfig,
} from './feishuConfig.js'

// Vendor modules (self-contained implementations)
import { log } from './vendor/core/logger.js'
import { PendingQueue } from './vendor/bot/pending-queue.js'
import { startKeepalive } from './vendor/bot/keepalive.js'

import { ChatModeCache } from './vendor/bot/chat-mode-cache.js'
import { createOwnerRefreshController } from './vendor/policy/owner.js'
import { fetchQuotedContext, renderQuotedBlock } from './vendor/bot/quote.js'

// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Minimal RuntimeControls interface (matches vendor/policy/access.ts)
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

interface RuntimeControls {
  botOwnerId?: string
  ownerRefreshState: 'ok' | 'failed' | 'unknown'
  ownerRefreshedAt?: number
  ownerRefreshError?: string
}

// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Types
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

type FeishuServiceState = {
  status: 'stopped' | 'starting' | 'running' | 'error'
  appId?: string
  botName?: string
  ownerId?: string
  lastError?: string
}

type Listener = () => void

/** Inbound event for bridge hook consumption */
type FeishuInboundEvent = {
  chatId: string
  text: string
  senderId: string
}

type InboundListener = (event: FeishuInboundEvent) => void

type AccessDecision = {
  ok: boolean
  reason: string
}

// Minimal RuntimeControls implementation for owner refresh
class FeishuRuntimeControls implements RuntimeControls {
  botOwnerId?: string
  ownerRefreshState: 'ok' | 'failed' | 'unknown' = 'unknown'
  ownerRefreshedAt?: number
  ownerRefreshError?: string
}

// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Access control helpers
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

function isOwner(controls: FeishuRuntimeControls, senderId: string): boolean {
  if (controls.ownerRefreshState === 'unknown') return false
  return Boolean(controls.botOwnerId) && controls.botOwnerId === senderId
}

function canUseDm(
  config: FeishuRuntimeConfig,
  controls: FeishuRuntimeControls,
  senderId: string,
): AccessDecision {
  if (isOwner(controls, senderId)) return { ok: true, reason: 'owner' }
  if (config.admins?.includes(senderId)) return { ok: true, reason: 'admin' }
  if (!config.allowedUsers || config.allowedUsers.length === 0) {
    return { ok: true, reason: 'open-dm' }
  }
  if (config.allowedUsers.includes(senderId)) return { ok: true, reason: 'allowed-user' }
  return { ok: false, reason: 'denied-user' }
}

function canUseGroup(
  config: FeishuRuntimeConfig,
  controls: FeishuRuntimeControls,
  chatId: string,
  senderId: string,
): AccessDecision {
  if (isOwner(controls, senderId)) return { ok: true, reason: 'owner' }
  if (config.admins?.includes(senderId)) return { ok: true, reason: 'admin' }
  if (config.allowedChats?.includes(chatId)) return { ok: true, reason: 'allowed-chat' }
  return { ok: false, reason: 'denied-chat' }
}

function canRunAdminCommand(
  config: FeishuRuntimeConfig,
  controls: FeishuRuntimeControls,
  senderId: string,
): AccessDecision {
  if (isOwner(controls, senderId)) return { ok: true, reason: 'owner' }
  if (config.admins?.includes(senderId)) return { ok: true, reason: 'admin' }
  return { ok: false, reason: 'denied-admin' }
}

// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Slash command handler type
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

type CommandHandler = (
  args: string,
  chatId: string,
  senderId: string,
  channel: LarkChannel,
) => Promise<boolean>

// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Main service
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class FeishuService {
  private listeners = new Set<Listener>()
  private inboundListeners = new Set<InboundListener>()
  private state: FeishuServiceState = { status: 'stopped' }
  private config?: FeishuRuntimeConfig
  private channel?: LarkChannel
  private pending?: PendingQueue
  private keepalive?: { stop(): void }
  private ownerRefresh?: { start(): Promise<void>; stop(): void }
  private chatModeCache?: ChatModeCache
  private controls = new FeishuRuntimeControls()
  private runId = 0
  private commandHandlers = new Map<string, CommandHandler>()

  constructor() {
    this.registerDefaultCommands()
  }

  // โ”€โ”€ Default slash commands โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  private registerDefaultCommands(): void {
    this.commandHandlers.set('/stop', async (_args, chatId, _senderId, channel) => {
      await channel.send(chatId, { text: 'โน ๅœๆญขๅ‘ฝไปคๅทฒๆ”ถๅˆฐใ€‚' })
      return true
    })

    this.commandHandlers.set('/reset', async (_args, chatId, _senderId, channel) => {
      await channel.send(chatId, { text: '๐Ÿ”„ ๅทฒ้‡็ฝฎไผš่ฏใ€‚' })
      return true
    })

    this.commandHandlers.set(
      '/status',
      async (_args, chatId, _senderId, channel) => {
        const cfg = this.config
        const lines = [
          `็Šถๆ€: ${this.state.status}`,
          `App ID: ${cfg?.appId ?? 'ๆœช้…็ฝฎ'}`,
          `Bot: ${this.state.botName ?? 'ๆœช็Ÿฅ'}`,
          `Owner: ${this.controls.botOwnerId ?? 'ๆœช็Ÿฅ'}`,
          `DM ็ญ–็•ฅ: ${
            !cfg?.allowedUsers || cfg.allowedUsers.length === 0
              ? 'ๆ‰€ๆœ‰ไบบ'
              : '็™ฝๅๅ•'
          }`,
          `็พค่Š็ญ–็•ฅ: ${
            cfg?.requireMentionInGroup !== false ? '้œ€ @bot' : 'ๆ‰€ๆœ‰ๆถˆๆฏ'
          }`,
          `้…็ฝฎ็พค็™ฝๅๅ•: ${cfg?.allowedChats?.length ?? 0} ไธช`,
        ]
        await channel.send(chatId, { text: lines.join('\n') })
        return true
      },
    )

    this.commandHandlers.set('/help', async (_args, chatId, _senderId, channel) => {
      const help = [
        '้ฃžไนฆ Bot ๅ‘ฝไปค:',
        '/stop โ€” ไธญๆ–ญๅฝ“ๅ‰ไปปๅŠก',
        '/reset โ€” ้‡็ฝฎไผš่ฏ',
        '/status โ€” ๆŸฅ็œ‹็Šถๆ€',
        '/help โ€” ๆ˜พ็คบๆญคๅธฎๅŠฉ',
      ]
      await channel.send(chatId, { text: help.join('\n') })
      return true
    })
  }

  // โ”€โ”€ React sync external store interface โ”€โ”€โ”€โ”€โ”€

  subscribe = (listener: Listener): (() => void) => {
    this.listeners.add(listener)
    return () => this.listeners.delete(listener)
  }

  subscribeToInbound = (listener: InboundListener): (() => void) => {
    this.inboundListeners.add(listener)
    return () => this.inboundListeners.delete(listener)
  }

  getStateSnapshot = (): FeishuServiceState => this.state

  // โ”€โ”€ Lifecycle โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  async start(config: FeishuRuntimeConfig): Promise<void> {
    if (
      this.state.status === 'running' &&
      this.config?.appId === config.appId
    ) {
      return
    }

    await this.stop()
    const runId = ++this.runId
    this.config = config

    this.setState({
      status: 'starting',
      appId: config.appId,
      lastError: undefined,
    })

    try {
      const domain =
        config.tenant === 'lark'
          ? 'https://open.larksuite.com'
          : 'https://open.feishu.cn'

      const channel = createLarkChannel({
        appId: config.appId!,
        appSecret: config.appSecret!,
        domain,
        source: 'codev',
        // Use default logger level (info)
        respectProxyEnv: true,
        wsConfig: { pingTimeout: 3 },
        handshakeTimeoutMs: 8000,
        httpTimeoutMs: 30000,
        policy: {
          dmMode: 'open',
          requireMention: false,
          respondToMentionAll: false,
        },
        safety: { chatQueue: { enabled: false } },
        includeRawEvent: true,
      })

      const chatModeCache = new ChatModeCache()
      const cfg = config // local ref for closure

      // Pending queue with block/unblock support
      const pending = new PendingQueue(600, async (scope, batch) => {
        const first = batch[0]
        if (!first) return

        const chatId = first.chatId
        const senderId = first.senderId
        const text = batch.map(m => m.content).join('\n---\n')

        log.info('flush', 'start', { scope, batchSize: batch.length })

        try {
          const mode = await chatModeCache.resolve(channel, chatId)
          const isGroup = mode !== 'p2p'

          // Access check
          if (isGroup) {
            const access = canUseGroup(cfg, this.controls, chatId, senderId)
            if (!access.ok) {
              if (first.mentionedBot) {
                await channel.send(chatId, {
                  text: 'ๅฝ“ๅ‰็พคๆœชๅŠ ๅ…ฅๅ“ๅบ”ๅˆ—่กจใ€‚่ฏท่”็ณป Bot owner ๆˆ–็ฎก็†ๅ‘˜ไฝฟ็”จ /invite group ๅŠ ๅ…ฅ็™ฝๅๅ•ใ€‚',
                })
              }
              log.info('intake', 'denied-group', {
                chatId,
                senderId,
                reason: access.reason,
              })
              return
            }
            // @mention policy โ€” default requires mention in groups
            if (cfg.requireMentionInGroup !== false && !first.mentionedBot) {
              log.info('intake', 'skip-no-mention', { chatId })
              return
            }
          } else {
            const access = canUseDm(cfg, this.controls, senderId)
            if (!access.ok) {
              log.info('intake', 'denied-dm', {
                chatId,
                senderId,
                reason: access.reason,
              })
              return
            }
          }

          // Slash command routing
          if (text.startsWith('/')) {
            const parts = text.split(/\s+/)
            const cmdName = parts[0] ?? ''
            const args = parts.slice(1).join(' ')
            const handler = this.commandHandlers.get(cmdName)
            if (handler) {
              await handler(args, chatId, senderId, channel)
              return // handled locally
            }
            // Unknown command โ€” let it pass through to the agent
          }

          // Build prompt with optional quoted context
          let fullText = text
          const replyToId = first.replyToMessageId
          if (replyToId) {
            const quote = await fetchQuotedContext(channel, replyToId)
            if (quote) {
              const quotedBlock = renderQuotedBlock([quote])
              if (quotedBlock) {
                fullText = `${quotedBlock}\n\n${text}`
              }
            }
          }

          // Notify inbound listeners (bridge hook uses this for chatId tracking)
          for (const listener of this.inboundListeners) {
            listener({ chatId, text: fullText, senderId })
          }

          // Enqueue to REPL
          const { enqueue } = await import(
            '../../utils/messageQueueManager.js'
          )
          enqueue({
            value: fullText,
            mode: 'prompt',
            skipSlashCommands: true,
            bridgeOrigin: true,
            origin: { kind: 'channel', server: 'feishu' },
          })
        } finally {
          log.info('flush', 'end')
        }
      })

      channel.on({
        message: async (msg: NormalizedMessage) => {
          if (runId !== this.runId) return
          try {
            pending.push(msg.chatId, msg)
          } catch (err) {
            log.fail('intake', err, {
              chatId: msg.chatId,
              msgId: msg.messageId,
            })
          }
        },
        error: (err: unknown) => {
          log.warn('ws', 'error', { err: String(err) })
        },
        reconnecting: () => {
          log.warn('ws', 'reconnecting')
        },
        reconnected: () => {
          log.info('ws', 'reconnected')
        },
      })

      await channel.connect()
      if (runId !== this.runId) return

      this.channel = channel
      this.pending = pending
      this.chatModeCache = chatModeCache

      // Keepalive โ€” defense-in-depth against silent WS issues
      this.keepalive = startKeepalive({
        channel,
        domain,
        forceReconnect: async () => {
          log.info('keepalive', 'reconnect-requested')
          await channel.disconnect()
          await channel.connect()
        },
      })

      // Owner refresh โ€” periodically fetches app owner from Feishu API
      this.ownerRefresh = createOwnerRefreshController({
        controls: this.controls,
        source: channel,
        appId: config.appId ?? '(unknown)',
      })
      await this.ownerRefresh.start()

      const botName = channel.botIdentity?.name ?? config.appId
      log.info('ws', 'connected', {
        bot: botName,
        openId: channel.botIdentity?.openId,
        appId: config.appId,
      })
      this.setState({
        status: 'running',
        appId: config.appId,
        botName,
        ownerId: this.controls.botOwnerId,
      })
    } catch (err) {
      if (runId !== this.runId) return
      const msg = err instanceof Error ? err.message : String(err)
      log.fail('start', err, { appId: config.appId })
      this.setState({ status: 'error', appId: config.appId, lastError: msg })
      throw err
    }
  }

  async startFromSavedConfig(): Promise<void> {
    const config = getFeishuConfig()
    if (!config.appId || !config.appSecret) {
      throw new Error('้ฃžไนฆ App ID ๆˆ– App Secret ๆœช้…็ฝฎใ€‚')
    }
    await this.start(config)
  }

  async runRegistrationWizard(): Promise<{ appId: string; appSecret: string }> {
    const result = await registerApp({
      source: 'codev',
      onQRCodeReady: info => {
        log.info('wizard', 'qr-ready', {
          url: info.url,
          expireIn: info.expireIn,
        })
      },
      onStatusChange: info => {
        log.info('wizard', 'status', { status: info.status })
      },
    })

    log.info('wizard', 'complete', { appId: result.client_id })

    saveFeishuConfig({
      appId: result.client_id,
      appSecret: result.client_secret,
    })

    return {
      appId: result.client_id,
      appSecret: result.client_secret,
    }
  }

  async stop(): Promise<void> {
    this.runId++
    if (this.ownerRefresh) {
      this.ownerRefresh.stop()
      this.ownerRefresh = undefined
    }
    if (this.keepalive) {
      this.keepalive.stop()
      this.keepalive = undefined
    }
    if (this.pending) {
      this.pending.cancelAll()
      this.pending = undefined
    }
    if (this.channel) {
      try {
        await this.channel.disconnect()
      } catch {}
      this.channel = undefined
    }
    this.chatModeCache = undefined
    this.config = undefined
    this.controls = new FeishuRuntimeControls()
    if (this.state.status !== 'stopped') {
      this.setState({ status: 'stopped' })
    }
  }

  async sendText(chatId: string, text: string): Promise<void> {
    if (!this.channel) return
    try {
      await this.channel.send(chatId, { text })
    } catch (err) {
      log.fail('send', err, { chatId, textLen: text.length })
    }
  }

  async sendMarkdown(chatId: string, markdown: string): Promise<void> {
    if (!this.channel) return
    try {
      const { optimizeMarkdownForFeishu } = await import(
        '../../utils/feishuMarkdown.js'
      )
      const optimized = optimizeMarkdownForFeishu(markdown).replace(/<br\s*\/?>/gi, '\n')
      await this.channel.send(chatId, { markdown: optimized })
    } catch (err) {
      log.fail('send', err, { chatId, markdownLen: markdown.length })
    }
  }

  async sendVoice(chatId: string, text: string): Promise<void> {
    if (!this.channel) return
    try {
      const config = getFeishuConfig()
      if (!config.ttsEnabled) return
      const { readFile, unlink, writeFile } = await import('node:fs/promises')
      const { spawn } = await import('node:child_process')
      const provider = config.ttsProvider || 'edge'

      if (provider === 'voxcpm') {
        const refAudio = config.ttsReferenceAudio
        if (!refAudio) return
        const chunks = this.splitTextForVoxCpm(text)
        console.log('[feishu][tts] voxcpm: splitting into', chunks.length, 'chunks')
        const timestamp = Date.now()
        const rawPaths: string[] = []
        const oggPaths: string[] = []

        // Generate each chunk
        for (let i = 0; i < chunks.length; i++) {
          const chunk = chunks[i]!.trim()
          if (!chunk) continue
          console.log('[feishu][tts] voxcpm: synthesizing chunk', i + 1, '/', chunks.length, 'len:', chunk.length)
          const rawPath = path.join(os.tmpdir(), `feishu_vc_${timestamp}_${i}.wav`)
          const oggPath = path.join(os.tmpdir(), `feishu_vc_${timestamp}_${i}.ogg`)
          rawPaths.push(rawPath)
          oggPaths.push(oggPath)
          try {
            await new Promise<void>((resolve, reject) => {
              const child = spawn(
                '/home/yuki/Code/Agent/Codev/.venv/bin/voxcpm',
                ['clone', '--text', chunk, '--reference-audio', refAudio, '--denoise', '--output', rawPath],
                { shell: false },
              )
              child.on('close', code => { code === 0 ? resolve() : reject(new Error(`voxcpm exit ${code}`)) })
              child.on('error', reject)
            })
            // Convert each chunk WAV โ†’ OGG (so concat can mix sample rates properly)
            await new Promise<void>((resolve, reject) => {
              const child = spawn('ffmpeg', ['-i', rawPath, '-c:a', 'libopus', '-b:a', '128k', '-y', oggPath])
              child.on('close', code => { code === 0 ? resolve() : reject(new Error(`ffmpeg exit ${code}`)) })
              child.on('error', reject)
            })
          } catch (err) {
            console.log('[feishu][tts] voxcpm: chunk', i + 1, 'failed, skipping:', err instanceof Error ? err.message : String(err))
            rawPaths.pop()
            oggPaths.pop()
          }
        }

        if (rawPaths.length === 0) {
          console.log('[feishu][tts] voxcpm: no chunks succeeded')
          return
        }

        // Write concat list for ffmpeg
        const listPath = path.join(os.tmpdir(), `feishu_vc_${timestamp}_list.txt`)
        const listContent = oggPaths.map(p => `file '${p}'`).join('\n')
        await writeFile(listPath, listContent)

        // Concat all OGG chunks into one
        const mergedOggPath = path.join(os.tmpdir(), `feishu_vc_${timestamp}_merged.ogg`)
        await new Promise<void>((resolve, reject) => {
          const child = spawn('ffmpeg', ['-f', 'concat', '-safe', '0', '-i', listPath, '-c', 'copy', '-y', mergedOggPath])
          child.on('close', code => { code === 0 ? resolve() : reject(new Error(`ffmpeg concat exit ${code}`)) })
          child.on('error', reject)
        })

        const buffer = await readFile(mergedOggPath)
        await this.channel.send(chatId, { audio: { source: buffer } })
        console.log('[feishu][tts] voxcpm: merged audio sent, size:', buffer.length)

        // Clean up
        for (const p of [...rawPaths, ...oggPaths, listPath, mergedOggPath]) {
          await unlink(p).catch(() => {})
        }
        return
      }

      // Edge TTS โ€” single shot
      const voice = config.ttsVoice || 'zh-CN-XiaoxiaoNeural'
      const timestamp = Date.now()
      const rawPath = path.join(os.tmpdir(), `feishu_tts_${timestamp}`)
      const oggPath = path.join(os.tmpdir(), `feishu_tts_${timestamp}.ogg`)
      await new Promise<void>((resolve, reject) => {
        const child = spawn('edge-tts', ['--voice', voice, '--text', text, '--write-media', rawPath])
        child.on('close', code => { code === 0 ? resolve() : reject(new Error(`edge-tts exit ${code}`)) })
        child.on('error', reject)
      })
      await new Promise<void>((resolve, reject) => {
        const child = spawn('ffmpeg', ['-i', rawPath, '-c:a', 'libopus', '-b:a', '128k', '-y', oggPath])
        child.on('close', code => { code === 0 ? resolve() : reject(new Error(`ffmpeg exit ${code}`)) })
        child.on('error', reject)
      })
      const buffer = await readFile(oggPath)
      await this.channel.send(chatId, { audio: { source: buffer } })
      await unlink(rawPath).catch(() => {})
      await unlink(oggPath).catch(() => {})
    } catch (err) {
      console.log('[feishu][tts] send-voice-failed:', err instanceof Error ? err.message : String(err))
    }
  }

  /**
   * Split text into VoxCPM-friendly chunks (max ~150 chars each).
   * Split at Chinese/English sentence boundaries to keep grammar intact.
   */
  private splitTextForVoxCpm(text: string): string[] {
    const sentences: string[] = []
    const parts = text.split(/(?<=[ใ€‚๏ผ๏ผŸโ€ฆ\n])/)
    let current = ''
    for (const p of parts) {
      const trimmed = p.trim()
      if (!trimmed) continue
      if (current.length + trimmed.length <= 150) {
        current += (current ? ' ' : '') + trimmed
      } else {
        if (current) sentences.push(current)
        current = trimmed
      }
    }
    if (current) sentences.push(current)
    return sentences
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  onMessagesChange(_messages: unknown[], _isLoading: boolean): void {
    // No-op
  }

  // โ”€โ”€ Internal โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  private setState(next: Partial<FeishuServiceState>): void {
    this.state = { ...this.state, ...next }
    for (const listener of this.listeners) listener()
  }
}

export const feishuService = new FeishuService()