@michengai/dsh-im-connect 1.0.47 → 1.0.49

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.
@@ -8,6 +8,7 @@ export interface ChannelField {
8
8
  secret?: boolean
9
9
  /** 仅用于已绑定账号的设置,不放进新增账号凭据表单。 */
10
10
  settingsOnly?: boolean
11
+ placeholder?: string
11
12
  }
12
13
 
13
14
  export interface ChannelMeta {
@@ -84,6 +85,7 @@ export const CHANNEL_META: Record<ChannelId, ChannelMeta> = {
84
85
  fields: [
85
86
  { key: 'botId', label: 'Bot ID' },
86
87
  { key: 'secret', label: 'Secret', secret: true },
88
+ { key: 'wsUrl', label: 'WebSocket URL', placeholder: '默认 wss://openws.work.weixin.qq.com' },
87
89
  ],
88
90
  },
89
91
 
@@ -21,9 +21,34 @@ async function downloadWecomImage(image: { url?: string; aeskey?: string }, addi
21
21
  return imageMedia(decryptFile(await requestChannelBytes(image.url, { additionalTrustedHosts: additionalImageHosts }), image.aeskey))
22
22
  }
23
23
 
24
+ export function validateWecomWsUrl(input?: unknown): string | undefined {
25
+ if (typeof input !== 'string' || !input.trim()) return undefined
26
+ const trimmed = input.trim()
27
+ let parsed: URL
28
+ try {
29
+ parsed = new URL(trimmed)
30
+ } catch {
31
+ throw new Error('WebSocket URL 无效:请填写合法的 WebSocket 地址')
32
+ }
33
+ if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
34
+ throw new Error('WebSocket URL 协议无效:仅支持 ws:// 或 wss:// 开头的地址')
35
+ }
36
+ if (parsed.username || parsed.password) {
37
+ throw new Error('WebSocket URL 无效:禁止在地址中携带用户名或密码凭据')
38
+ }
39
+ if (parsed.hash) {
40
+ throw new Error('WebSocket URL 无效:禁止在地址中携带 URL 片段(#fragment)')
41
+ }
42
+ if (parsed.pathname === '/' && !parsed.search) {
43
+ return parsed.origin
44
+ }
45
+ return parsed.href
46
+ }
47
+
24
48
  export interface WecomConfig {
25
49
  botId?: string
26
50
  secret?: string
51
+ wsUrl?: string
27
52
  additionalImageHosts?: readonly string[]
28
53
  host?: { get(name: string): unknown }
29
54
  }
@@ -236,6 +261,7 @@ export function createWecomChannel(config: WecomConfig, log: (line: string) => v
236
261
  const botId = config.botId?.trim()
237
262
  const secret = config.secret?.trim()
238
263
  if (!botId || !secret) return undefined
264
+ const wsUrl = validateWecomWsUrl(config.wsUrl)
239
265
  const additionalImageHosts = validateAdditionalImageHosts(config.additionalImageHosts)
240
266
 
241
267
  let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
@@ -254,7 +280,7 @@ export function createWecomChannel(config: WecomConfig, log: (line: string) => v
254
280
  async start() {
255
281
  const startedGeneration = ++generation
256
282
  let sdk: {
257
- WSClient: new (opts: { botId: string; secret: string; maxAuthFailureAttempts?: number; logger?: { debug: Function; info: Function; warn: Function; error: Function } }) => WecomSdkClient
283
+ WSClient: new (opts: { botId: string; secret: string; wsUrl?: string; maxAuthFailureAttempts?: number; logger?: { debug: Function; info: Function; warn: Function; error: Function } }) => WecomSdkClient
258
284
  generateReqId?: (prefix: string) => string
259
285
  }
260
286
  try {
@@ -262,7 +288,13 @@ export function createWecomChannel(config: WecomConfig, log: (line: string) => v
262
288
  } catch {
263
289
  throw new Error('缺少依赖 @wecom/aibot-node-sdk')
264
290
  }
265
- client = new sdk.WSClient({ botId, secret, maxAuthFailureAttempts: 1, logger: quietSdkLogger(log, 'wecom') })
291
+ client = new sdk.WSClient({
292
+ botId,
293
+ secret,
294
+ maxAuthFailureAttempts: 1,
295
+ logger: quietSdkLogger(log, 'wecom'),
296
+ ...(wsUrl ? { wsUrl } : {}),
297
+ })
266
298
  client.on('authenticated', () => { if (generation === startedGeneration) statusText = '长连接已建立' })
267
299
  client.on('disconnected', () => { if (generation === startedGeneration) statusText = '已断开' })
268
300
  client.on('reconnecting', () => { if (generation === startedGeneration) statusText = '重连中' })
package/src/manager.ts CHANGED
@@ -17,6 +17,7 @@ import { createFileVault, createServiceVault, credentialRef, type CredentialServ
17
17
  import { ImEngine } from './engine/gateway.js'
18
18
  import { SeenStore } from './engine/seen-store.js'
19
19
  import { clearWeixinLogin, persistWeixinLogin, readLegacyWeixinBotToken, readWeixinAllowedUserId } from './channels/weixin.js'
20
+ import { validateWecomWsUrl } from './channels/wecom.js'
20
21
  import { normalizeAssistantModel, normalizePermission, normalizeWorkspacePath, type AssistantModel, type PermissionPreset } from './engine/assistant-settings.js'
21
22
  import type { ChannelAdapter, EngineConfig, ImMessage, SendMode } from './engine/types.js'
22
23
  import { KeyedSerialQueue } from './engine/keyed-queue.js'
@@ -226,6 +227,7 @@ export interface AccountView {
226
227
  freeChatGroups?: string
227
228
  thinkingDisplay?: boolean
228
229
  threadSessions?: boolean
230
+ wsUrl?: string
229
231
  lastCheckedAt?: string
230
232
  }
231
233
 
@@ -251,6 +253,16 @@ export interface ChannelView {
251
253
  total: number
252
254
  }
253
255
 
256
+ export interface ChannelSessionGroup {
257
+ /** 兼容期平台标识(供旧客户端按平台聚合),多账号时平台内各账号实例共享;后续大版本迁移后将统一为 accountId */
258
+ id: string
259
+ /** 账号唯一实例 ID */
260
+ accountId: string
261
+ platform: ChannelId
262
+ label: string
263
+ sessions: SessionRecord[]
264
+ }
265
+
254
266
  interface PendingRequest {
255
267
  userId: string
256
268
  username?: string
@@ -460,20 +472,80 @@ export class ChannelManager {
460
472
  ...((platform === 'feishu' || platform === 'lark') ? {
461
473
  threadSessions: config.threadSessions === 'true',
462
474
  } : {}),
475
+ ...(platform === 'wecom' && config.wsUrl ? {
476
+ wsUrl: config.wsUrl,
477
+ } : {}),
463
478
  lastCheckedAt: state.lastCheckedAt,
464
479
  }
465
480
  }
466
481
 
467
- channelSessions() {
468
- const groups = new Map(CHANNEL_ORDER.map(id => [id, {
469
- id,
470
- label: CHANNEL_META[id].label,
471
- sessions: [] as SessionRecord[],
472
- }]))
482
+ accountGroupLabel(accountId: string, state: ChannelState | undefined, multiAccount: boolean): string {
483
+ const platform = this.platformOf(accountId, state)
484
+ const platformLabel = CHANNEL_META[platform]?.label ?? platform
485
+ if (!multiAccount) return platformLabel
486
+ if (state && typeof this.accountView === 'function') {
487
+ try {
488
+ const view = this.accountView(accountId, state)
489
+ if (!view.autoName && view.name) {
490
+ return `${platformLabel} · ${view.name}`
491
+ }
492
+ if (view.nameOrdinal) {
493
+ return `${platformLabel} · #${view.nameOrdinal}`
494
+ }
495
+ } catch {
496
+ // fallback below
497
+ }
498
+ }
499
+ const rawName = state?.name?.trim()
500
+ if (rawName) return `${platformLabel} · ${rawName}`
501
+ return `${platformLabel} · ${accountId}`
502
+ }
503
+
504
+ channelSessions(): ChannelSessionGroup[] {
505
+ const channelStore = this.store.channels
506
+ const platformAccounts = new Map<ChannelId, string[]>()
507
+ for (const [accountId, state] of Object.entries(channelStore)) {
508
+ const platform = this.platformOf(accountId, state)
509
+ const list = platformAccounts.get(platform) ?? []
510
+ list.push(accountId)
511
+ platformAccounts.set(platform, list)
512
+ }
513
+
514
+ const accountGroups = new Map<string, ChannelSessionGroup>()
515
+ for (const platform of CHANNEL_ORDER) {
516
+ const accounts = platformAccounts.get(platform) ?? []
517
+ const isMulti = accounts.length > 1
518
+ for (const accountId of accounts) {
519
+ const state = channelStore[accountId]
520
+ accountGroups.set(accountId, {
521
+ id: platform,
522
+ accountId,
523
+ platform,
524
+ label: this.accountGroupLabel(accountId, state, isMulti),
525
+ sessions: [],
526
+ })
527
+ }
528
+ }
529
+
473
530
  for (const item of this.sessions.list()) {
474
- groups.get(this.platformOf(item.channel, this.store.channels[item.channel]))?.sessions.push(item)
531
+ const accountId = item.channel
532
+ let group = accountGroups.get(accountId)
533
+ if (!group) {
534
+ const platform = this.platformOf(accountId, channelStore[accountId])
535
+ const platformLabel = CHANNEL_META[platform]?.label ?? platform
536
+ group = {
537
+ id: platform,
538
+ accountId,
539
+ platform,
540
+ label: platformLabel,
541
+ sessions: [],
542
+ }
543
+ accountGroups.set(accountId, group)
544
+ }
545
+ group.sessions.push(item)
475
546
  }
476
- return [...groups.values()].filter((group) => group.sessions.length > 0)
547
+
548
+ return [...accountGroups.values()].filter((group) => group.sessions.length > 0)
477
549
  }
478
550
 
479
551
  async connect(id: ChannelId, config?: Record<string, string>, settings?: Record<string, unknown>): Promise<{ ok: boolean; error?: string; accountId?: string; created?: boolean; newIdentity?: boolean }> {
@@ -496,6 +568,21 @@ export class ChannelManager {
496
568
  return { ok: false, error: '图片扩展主机配置无效:请填写精确域名,不要包含通配符、URL、端口或 IP 地址。' }
497
569
  }
498
570
  }
571
+ if (id === 'wecom' && Object.hasOwn(incoming, 'wsUrl')) {
572
+ const rawWsUrl = incoming.wsUrl
573
+ if (rawWsUrl !== undefined) {
574
+ const trimmed = typeof rawWsUrl === 'string' ? rawWsUrl.trim() : ''
575
+ if (trimmed) {
576
+ try {
577
+ incoming.wsUrl = validateWecomWsUrl(trimmed)!
578
+ } catch (error) {
579
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
580
+ }
581
+ } else {
582
+ delete incoming.wsUrl
583
+ }
584
+ }
585
+ }
499
586
  const normalized = await this.normalizeAccountSettings(id, settings, prev)
500
587
  if (!normalized.ok) return normalized
501
588
  if (id === 'weixin' && incoming.botToken) {
@@ -1100,9 +1187,27 @@ export class ChannelManager {
1100
1187
  else delete config.threadSessions
1101
1188
  state.config = config
1102
1189
  }
1190
+ const hasWecomWsUrlSetting = platform === 'wecom' && Object.hasOwn(input, 'wsUrl')
1191
+ let wecomWsUrlChanged = false
1192
+ if (hasWecomWsUrlSetting) {
1193
+ const previousWsUrl = state.config?.wsUrl
1194
+ let nextWsUrl: string | undefined
1195
+ if (typeof input.wsUrl === 'string' && input.wsUrl.trim()) {
1196
+ try {
1197
+ nextWsUrl = validateWecomWsUrl(input.wsUrl)
1198
+ } catch (error) {
1199
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
1200
+ }
1201
+ }
1202
+ wecomWsUrlChanged = nextWsUrl !== previousWsUrl
1203
+ const config = { ...(state.config ?? {}) }
1204
+ if (nextWsUrl) config.wsUrl = nextWsUrl
1205
+ else delete config.wsUrl
1206
+ state.config = config
1207
+ }
1103
1208
  this.flush()
1104
1209
  if (reloadSessions) await this.engine.reloadChannel(accountId, { resetSessions })
1105
- if ((proxyChanged || mentionPolicyChanged || threadSessionsChanged) && this.running.has(accountId)) await this.startOne(accountId)
1210
+ if ((proxyChanged || mentionPolicyChanged || threadSessionsChanged || wecomWsUrlChanged) && this.running.has(accountId)) await this.startOne(accountId)
1106
1211
  return { ok: true, account: this.accountView(accountId, state) }
1107
1212
  })
1108
1213
  }