@michengai/dsh-im-connect 0.1.0 → 0.1.2

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.
Files changed (103) hide show
  1. package/README.en.md +224 -0
  2. package/README.md +204 -19
  3. package/assets/branding/dsh-banner.png +0 -0
  4. package/assets/screenshots/dingtalk-chat.jpg +0 -0
  5. package/assets/screenshots/feishu-chat.jpg +0 -0
  6. package/assets/screenshots/qq-chat.jpg +0 -0
  7. package/assets/screenshots/settings-channels.png +0 -0
  8. package/assets/screenshots/telegram-chat.jpg +0 -0
  9. package/assets/screenshots/wecom-chat.jpg +0 -0
  10. package/assets/screenshots/wecom-qr.png +0 -0
  11. package/assets/screenshots/weixin-chat.jpg +0 -0
  12. package/assets/screenshots/workspace-channels.png +0 -0
  13. package/client.js +158 -82
  14. package/lib/channels/dingtalk-card.d.ts +2 -1
  15. package/lib/channels/dingtalk-card.d.ts.map +1 -1
  16. package/lib/channels/dingtalk-card.js +13 -5
  17. package/lib/channels/dingtalk-card.js.map +1 -1
  18. package/lib/channels/dingtalk.d.ts +19 -0
  19. package/lib/channels/dingtalk.d.ts.map +1 -1
  20. package/lib/channels/dingtalk.js +30 -16
  21. package/lib/channels/dingtalk.js.map +1 -1
  22. package/lib/channels/factory.d.ts.map +1 -1
  23. package/lib/channels/factory.js +3 -0
  24. package/lib/channels/factory.js.map +1 -1
  25. package/lib/channels/feishu.d.ts.map +1 -1
  26. package/lib/channels/feishu.js +5 -2
  27. package/lib/channels/feishu.js.map +1 -1
  28. package/lib/channels/meta.d.ts.map +1 -1
  29. package/lib/channels/meta.js +11 -0
  30. package/lib/channels/meta.js.map +1 -1
  31. package/lib/channels/qq.d.ts +9 -0
  32. package/lib/channels/qq.d.ts.map +1 -0
  33. package/lib/channels/qq.js +279 -0
  34. package/lib/channels/qq.js.map +1 -0
  35. package/lib/channels/qr/hub.d.ts +4 -1
  36. package/lib/channels/qr/hub.d.ts.map +1 -1
  37. package/lib/channels/qr/hub.js +27 -0
  38. package/lib/channels/qr/hub.js.map +1 -1
  39. package/lib/channels/qr/qq.d.ts +18 -0
  40. package/lib/channels/qr/qq.d.ts.map +1 -0
  41. package/lib/channels/qr/qq.js +86 -0
  42. package/lib/channels/qr/qq.js.map +1 -0
  43. package/lib/channels/qr/shared.d.ts +3 -0
  44. package/lib/channels/qr/shared.d.ts.map +1 -1
  45. package/lib/channels/qr/shared.js.map +1 -1
  46. package/lib/channels/telegram.d.ts.map +1 -1
  47. package/lib/channels/telegram.js +39 -8
  48. package/lib/channels/telegram.js.map +1 -1
  49. package/lib/channels/wecom.d.ts +1 -0
  50. package/lib/channels/wecom.d.ts.map +1 -1
  51. package/lib/channels/wecom.js +35 -15
  52. package/lib/channels/wecom.js.map +1 -1
  53. package/lib/channels/weixin.d.ts.map +1 -1
  54. package/lib/channels/weixin.js +9 -18
  55. package/lib/channels/weixin.js.map +1 -1
  56. package/lib/client.js +158 -82
  57. package/lib/engine/gateway.d.ts +3 -10
  58. package/lib/engine/gateway.d.ts.map +1 -1
  59. package/lib/engine/gateway.js +54 -65
  60. package/lib/engine/gateway.js.map +1 -1
  61. package/lib/engine/quiet-logger.d.ts +9 -0
  62. package/lib/engine/quiet-logger.d.ts.map +1 -0
  63. package/lib/engine/quiet-logger.js +26 -0
  64. package/lib/engine/quiet-logger.js.map +1 -0
  65. package/lib/engine/reply-stream.d.ts +25 -0
  66. package/lib/engine/reply-stream.d.ts.map +1 -0
  67. package/lib/engine/reply-stream.js +62 -0
  68. package/lib/engine/reply-stream.js.map +1 -0
  69. package/lib/engine/session-id.d.ts +1 -1
  70. package/lib/engine/session-id.d.ts.map +1 -1
  71. package/lib/engine/session-id.js +1 -1
  72. package/lib/engine/session-id.js.map +1 -1
  73. package/lib/engine/types.d.ts +0 -2
  74. package/lib/engine/types.d.ts.map +1 -1
  75. package/lib/index.d.ts +0 -1
  76. package/lib/index.d.ts.map +1 -1
  77. package/lib/index.js +0 -2
  78. package/lib/index.js.map +1 -1
  79. package/lib/manager.d.ts +1 -12
  80. package/lib/manager.d.ts.map +1 -1
  81. package/lib/manager.js +165 -167
  82. package/lib/manager.js.map +1 -1
  83. package/package.json +15 -4
  84. package/src/channels/dingtalk-card.ts +13 -6
  85. package/src/channels/dingtalk.ts +43 -18
  86. package/src/channels/factory.ts +8 -2
  87. package/src/channels/feishu.ts +6 -2
  88. package/src/channels/meta.ts +13 -0
  89. package/src/channels/qq.ts +302 -0
  90. package/src/channels/qr/hub.ts +27 -3
  91. package/src/channels/qr/qq.ts +91 -0
  92. package/src/channels/qr/shared.ts +4 -0
  93. package/src/channels/telegram.ts +39 -9
  94. package/src/channels/wecom.ts +37 -16
  95. package/src/channels/weixin.ts +44 -52
  96. package/src/engine/gateway.ts +316 -325
  97. package/src/engine/quiet-logger.ts +23 -0
  98. package/src/engine/reply-stream.ts +67 -0
  99. package/src/engine/session-id.ts +3 -2
  100. package/src/engine/types.ts +1 -3
  101. package/src/index.ts +2 -5
  102. package/src/manager.ts +542 -569
  103. package/src/engine/access.ts +0 -17
package/src/manager.ts CHANGED
@@ -1,571 +1,544 @@
1
- import type { Context } from '@deepseek-ai/cordis'
2
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
3
- import { join } from 'node:path'
4
- import { createChannelAdapter } from './channels/factory.js'
5
- import { CHANNEL_META, CHANNEL_ORDER, supportsQr } from './channels/meta.js'
6
- import { PairingHub } from './channels/qr/hub.js'
7
- import type { ChannelId } from './engine/session-id.js'
8
- import { SessionMapStore } from './engine/session-store.js'
9
- import { createFileVault, createServiceVault, credentialRef, type CredentialService, type CredentialVault } from './engine/credentials.js'
10
- import { ImEngine } from './engine/gateway.js'
11
- import { SeenStore } from './engine/seen-store.js'
12
- import { clearWeixinLogin, persistWeixinLogin } from './channels/weixin.js'
13
- import { normalizeAssistantModel, normalizePermission, normalizeWorkspacePath, type AssistantModel, type PermissionPreset } from './engine/assistant-settings.js'
14
- import type { ChannelAdapter, EngineConfig, ImMessage } from './engine/types.js'
15
-
16
- export interface ChannelState {
17
- enabled?: boolean
18
- receiveEnabled?: boolean
19
- lastError?: string
20
- config?: Record<string, string>
21
- }
22
-
23
- export interface ChannelView {
24
- id: ChannelId
25
- label: string
26
- description: string
27
- kind: string
28
- fields: Array<{ key: string; label: string; secret?: boolean }>
29
- connected: boolean
30
- receiveEnabled: boolean
31
- configuredKeys: string[]
32
- status: string
33
- accessMode?: string
34
- }
35
-
36
- interface Persisted {
37
- channels: Record<string, ChannelState>
38
- allowlist: Record<string, string[]>
39
- pending: Record<string, Array<{ userId: string; username?: string; chatId?: string; time: number }>>
40
- assistant?: AssistantModel
41
- cwd?: string
42
- permission?: PermissionPreset
43
- }
44
-
45
- export class ChannelManager {
46
- private readonly file: string
47
- private readonly stateDir: string
48
- private readonly sessions: SessionMapStore
49
- private readonly engine: ImEngine
50
- private readonly vault: CredentialVault
51
- private readonly pairing: PairingHub
52
- private readonly log: (line: string) => void
53
- private readonly ctx: Context
54
- private readonly engineConfig: EngineConfig
55
- private store: Persisted = { channels: {}, allowlist: {}, pending: {} }
56
- private readonly running = new Map<string, ChannelAdapter>()
57
- private apiDisposers: Array<() => void> = []
58
-
59
- constructor(options: { ctx: Context; stateDir: string; log: (line: string) => void; engineConfig: EngineConfig }) {
60
- this.ctx = options.ctx
61
- this.engineConfig = options.engineConfig
62
- this.stateDir = options.stateDir
63
- this.file = join(options.stateDir, 'channels.json')
64
- this.sessions = new SessionMapStore(join(options.stateDir, 'sessions.json'))
65
- this.log = options.log
66
- this.load()
67
- this.applyAssistant(this.store.assistant)
68
- this.applyWorkspace(this.store.cwd)
69
- this.applyPermission(this.store.permission)
70
- const seen = new SeenStore(join(options.stateDir, 'seen.json'))
71
- const credentials = (options.ctx as Context & { credentials?: CredentialService }).credentials
72
- this.vault = credentials
73
- ? createServiceVault(credentials)
74
- : createFileVault(join(options.stateDir, 'secrets.json'))
75
- this.engine = new ImEngine(options.ctx, this.sessions, seen, options.engineConfig, options.log, (channelId, msg) => {
76
- this.requestAuthorization(channelId, msg)
77
- return '未授权:请管理员在设置 → IM助理 中批准你的访问。'
78
- })
79
- this.pairing = new PairingHub({
80
- log: options.log,
81
- onSuccess: async (id, creds) => {
82
- const result = await this.connect(id, creds)
83
- if (!result.ok) throw new Error(result.error ?? '保存失败')
84
- },
85
- })
86
- for (const [channelId, users] of Object.entries(this.store.allowlist)) {
87
- for (const userId of users) this.engine.addAllowed(channelId, userId)
88
- }
89
- }
90
-
91
- list(): ChannelView[] {
92
- return CHANNEL_ORDER.map((id) => {
93
- const meta = CHANNEL_META[id]
94
- const state = this.store.channels[id] ?? {}
95
- const config = state.config ?? {}
96
- const configuredKeys = Object.keys(config).filter((key) => Boolean(config[key]) && !key.endsWith('Ref'))
97
- const adapter = this.running.get(id)
98
- const status = adapter?.status() ?? state.lastError ?? '未连接'
99
- const connected = adapter !== undefined && !status.includes('失败') && status !== '未连接' && status !== '已停止'
100
- return {
101
- id,
102
- label: meta.label,
103
- description: meta.description,
104
- kind: meta.kind,
105
- fields: meta.fields,
106
- connected,
107
- receiveEnabled: connected && state.receiveEnabled !== false,
108
- configuredKeys,
109
- status,
110
- accessMode: config.accessMode,
111
- }
112
- })
113
- }
114
-
115
- channelSessions() {
116
- const connected = new Set(this.list().filter((item) => item.connected).map((item) => item.id))
117
- return CHANNEL_ORDER.map((id) => ({
118
- id,
119
- label: CHANNEL_META[id].label,
120
- sessions: this.sessions.list().filter((item) => item.channel === id),
121
- })).filter((group) => group.sessions.length > 0 || connected.has(group.id))
122
- }
123
-
124
- pendingRequests() {
125
- return Object.entries(this.store.pending).flatMap(([channelId, list]) =>
126
- list.map((item) => ({ channelId, ...item })),
127
- )
128
- }
129
-
130
- async connect(id: ChannelId, config?: Record<string, string>): Promise<{ ok: boolean; error?: string }> {
131
- if (!CHANNEL_META[id]) return { ok: false, error: '未知渠道' }
132
- const incoming = { ...(config ?? {}) }
133
- if (id === 'weixin' && incoming.botToken) {
134
- persistWeixinLogin(join(this.stateDir, 'weixin'), {
135
- botToken: incoming.botToken,
136
- allowedUserId: incoming.allowedUserId,
137
- baseUrl: incoming.baseUrl,
138
- })
139
- delete incoming.botToken
140
- incoming.bound = '1'
141
- }
142
- const prev = this.store.channels[id] ?? {}
143
- const nextConfig = await this.persistSecrets(id, { ...(prev.config ?? {}), ...incoming })
144
- this.store.channels[id] = { ...prev, enabled: true, receiveEnabled: true, config: nextConfig }
145
- this.flush()
146
- this.applyAccessMode(id, nextConfig.accessMode)
147
- try {
148
- await this.startOne(id)
149
- return { ok: true }
150
- } catch (error) {
151
- return { ok: false, error: error instanceof Error ? error.message : String(error) }
152
- }
153
- }
154
-
155
- async setReceive(id: ChannelId, receiveEnabled: boolean): Promise<{ ok: boolean; error?: string }> {
156
- const state = this.store.channels[id]
157
- if (!state?.enabled) return { ok: false, error: '渠道未配置' }
158
- state.receiveEnabled = receiveEnabled
159
- this.flush()
160
- if (!receiveEnabled) await this.stopOne(id)
161
- else if (!this.running.has(id)) await this.startOne(id)
162
- return { ok: true }
163
- }
164
-
165
- async disconnect(id: ChannelId): Promise<void> {
166
- const state = this.store.channels[id]
167
- if (state) {
168
- state.enabled = false
169
- state.receiveEnabled = false
170
- this.flush()
171
- }
172
- this.pairing.cancel(id)
173
- await this.stopOne(id)
174
- }
175
-
176
- async remove(id: ChannelId): Promise<void> {
177
- await this.stopOne(id)
178
- this.pairing.cancel(id)
179
- delete this.store.channels[id]
180
- this.flush()
181
- if (id === 'weixin') clearWeixinLogin(join(this.stateDir, 'weixin'))
182
- for (const field of CHANNEL_META[id].fields.filter((item) => item.secret)) {
183
- await this.vault.unset(credentialRef(id, field.key)).catch(() => undefined)
184
- }
185
- }
186
-
187
- approve(id: string, userId: string): void {
188
- const list = this.store.allowlist[id] ?? []
189
- if (!list.includes(userId)) list.push(userId)
190
- this.store.allowlist[id] = list
191
- this.store.pending[id] = (this.store.pending[id] ?? []).filter((item) => item.userId !== userId)
192
- this.engine.addAllowed(id, userId)
193
- this.flush()
194
- }
195
-
196
- deny(id: string, userId: string): void {
197
- this.store.pending[id] = (this.store.pending[id] ?? []).filter((item) => item.userId !== userId)
198
- this.flush()
199
- }
200
-
201
- attachMappedSessions(): Promise<void> {
202
- return this.engine.attachMappedSessions()
203
- }
204
-
205
- async initEnabled(): Promise<void> {
206
- const started = Date.now()
207
- for (const id of CHANNEL_ORDER) {
208
- const state = this.store.channels[id]
209
- if (state?.enabled && state.receiveEnabled !== false) {
210
- this.applyAccessMode(id, state.config?.accessMode)
211
- const one = Date.now()
212
- await this.startOne(id).catch((error) => {
213
- this.log(`[manager] 启动 ${id} 失败: ${error instanceof Error ? error.message : String(error)}`)
214
- })
215
- this.log(`[boot] 渠道 ${id} 启动 ${Date.now() - one}ms`)
216
- }
217
- }
218
- this.log(`[boot] initEnabled ${Date.now() - started}ms`)
219
- }
220
-
221
- registerApi(ctx: Context): void {
222
- const webServer = (ctx as Context & {
223
- webServer?: {
224
- register(route: {
225
- kind: string
226
- path: string
227
- handler: (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => void
228
- }): (() => void) | void
229
- }
230
- }).webServer
231
- if (!webServer) return
232
- const send = (res: import('node:http').ServerResponse, status: number, body: unknown) => {
233
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
234
- res.end(JSON.stringify(body))
235
- }
236
- const readBody = (req: import('node:http').IncomingMessage): Promise<Record<string, unknown>> =>
237
- new Promise((resolve) => {
238
- let raw = ''
239
- req.on('data', (chunk) => { raw += chunk })
240
- req.on('end', () => {
241
- try { resolve(raw ? JSON.parse(raw) as Record<string, unknown> : {}) } catch { resolve({}) }
242
- })
243
- })
244
- const payload = () => ({
245
- ok: true,
246
- channels: this.list(),
247
- groups: this.channelSessions(),
248
- pending: this.pendingRequests(),
249
- assistant: this.currentAssistant(),
250
- })
251
- const dispose = webServer.register({
252
- kind: 'prefix',
253
- path: '/dsh-im-connect/api',
254
- handler: async (req, res) => {
255
- const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`)
256
- const parts = url.pathname.split('/').filter(Boolean)
257
- if (parts[2] === 'assistant' && parts.length === 3) {
258
- if (req.method === 'GET') {
259
- send(res, 200, { ok: true, assistant: this.currentAssistant(), cwd: this.currentWorkspace(), permission: this.currentPermission(), providers: await this.listModelCatalog() })
260
- return
261
- }
262
- if (req.method === 'POST') {
263
- const body = await readBody(req)
264
- const result = this.setAssistant(body)
265
- send(res, result.ok ? 200 : 400, result)
266
- return
267
- }
268
- send(res, 405, { ok: false, error: 'method not allowed' })
269
- return
270
- }
271
- if (parts[2] === 'sessions' && parts.length === 4 && req.method === 'POST') {
272
- const action = parts[3]
273
- const body = await readBody(req)
274
- const sessionId = String(body.sessionId ?? '')
275
- if (!sessionId) { send(res, 400, { ok: false, error: '缺少 sessionId' }); return }
276
- if (action === 'rename') {
277
- const title = String(body.title ?? '').trim()
278
- if (!title) { send(res, 400, { ok: false, error: '缺少标题' }); return }
279
- const ok = this.engine.renameSession(sessionId, title)
280
- send(res, ok ? 200 : 404, ok ? { ok: true, groups: this.channelSessions() } : { ok: false, error: '会话不存在' })
281
- return
282
- }
283
- if (action === 'remove') {
284
- const ok = await this.engine.removeSession(sessionId)
285
- send(res, ok ? 200 : 404, ok ? { ok: true, groups: this.channelSessions() } : { ok: false, error: '会话不存在' })
286
- return
287
- }
288
- if (action === 'ensure') {
289
- const ok = await this.engine.ensureSession(sessionId)
290
- send(res, ok ? 200 : 404, ok ? { ok: true, sessionId } : { ok: false, error: '会话不存在' })
291
- return
292
- }
293
- send(res, 404, { ok: false, error: `未知会话操作 ${action}` })
294
- return
295
- }
296
- if (parts[2] === 'channels' && parts.length === 3 && req.method === 'GET') {
297
- send(res, 200, payload())
298
- return
299
- }
300
- if (parts[2] === 'channels' && parts.length === 6 && parts[4] === 'qr') {
301
- const id = parts[3] as ChannelId
302
- const action = parts[5]
303
- if (!CHANNEL_META[id]) { send(res, 404, { ok: false, error: '未知渠道' }); return }
304
- if (!supportsQr(id)) { send(res, 400, { ok: false, error: '该渠道不支持扫码绑定' }); return }
305
- if (action === 'status' && req.method === 'GET') {
306
- send(res, 200, { ok: true, pairing: this.pairing.view(id), channel: this.list().find((item) => item.id === id) })
307
- return
308
- }
309
- if (req.method !== 'POST') { send(res, 405, { ok: false, error: 'method not allowed' }); return }
310
- const body = await readBody(req)
311
- if (action === 'start') {
312
- const extra: Record<string, string> = {}
313
- if (id === 'dingtalk' && (body.accessMode === 'pair' || body.accessMode === 'open')) {
314
- extra.accessMode = String(body.accessMode)
315
- }
316
- const pairing = await this.pairing.start(id, extra)
317
- send(res, pairing.status === 'failed' ? 400 : 200, { ok: pairing.status !== 'failed', pairing, error: pairing.error })
318
- return
319
- }
320
- if (action === 'refresh') {
321
- const pairing = await this.pairing.refresh(id)
322
- send(res, pairing.status === 'failed' ? 400 : 200, { ok: pairing.status !== 'failed', pairing, error: pairing.error })
323
- return
324
- }
325
- if (action === 'cancel') {
326
- send(res, 200, { ok: true, pairing: this.pairing.cancel(id) })
327
- return
328
- }
329
- send(res, 404, { ok: false, error: `未知扫码操作 ${action}` })
330
- return
331
- }
332
- if (parts[2] === 'channels' && parts.length === 5 && req.method === 'POST') {
333
- const id = parts[3] as ChannelId
334
- const action = parts[4]
335
- const body = await readBody(req)
336
- if (action === 'connect') {
337
- const result = await this.connect(id, body.config as Record<string, string> | undefined)
338
- send(res, result.ok ? 200 : 400, result.ok ? { ok: true, channel: this.list().find((item) => item.id === id) } : result)
339
- return
340
- }
341
- if (action === 'receive') {
342
- const result = await this.setReceive(id, body.receiveEnabled !== false)
343
- send(res, result.ok ? 200 : 400, result.ok ? { ok: true, channel: this.list().find((item) => item.id === id) } : result)
344
- return
345
- }
346
- if (action === 'disconnect') {
347
- await this.disconnect(id)
348
- send(res, 200, { ok: true, channel: this.list().find((item) => item.id === id) })
349
- return
350
- }
351
- if (action === 'remove') {
352
- await this.remove(id)
353
- send(res, 200, { ok: true, channel: this.list().find((item) => item.id === id) })
354
- return
355
- }
356
- if (action === 'approve' || action === 'deny') {
357
- const userId = String(body.userId ?? '')
358
- if (!userId) { send(res, 400, { ok: false, error: '缺少 userId' }); return }
359
- if (action === 'approve') this.approve(id, userId)
360
- else this.deny(id, userId)
361
- send(res, 200, { ok: true, pending: this.pendingRequests() })
362
- return
363
- }
364
- send(res, 404, { ok: false, error: `未知操作 ${action}` })
365
- return
366
- }
367
- send(res, 404, { ok: false, error: 'not found' })
368
- },
369
- })
370
- if (typeof dispose === 'function') this.apiDisposers.push(dispose)
371
- this.log('[manager] API 已注册 /dsh-im-connect/api')
372
- }
373
-
374
- disposeApi(): void {
375
- for (const dispose of this.apiDisposers) dispose()
376
- this.apiDisposers = []
377
- this.pairing.dispose()
378
- for (const id of [...this.running.keys()]) void this.stopOne(id as ChannelId)
379
- this.engine.dispose()
380
- }
381
-
382
-
383
- currentAssistant(): AssistantModel | undefined {
384
- return normalizeAssistantModel(this.store.assistant ?? this.engineConfig)
385
- }
386
-
387
- setAssistant(input: { provider?: unknown; model?: unknown; cwd?: unknown; permission?: unknown }): { ok: boolean; error?: string; assistant?: AssistantModel; cwd?: string; permission?: PermissionPreset } {
388
- const hasModel = input.provider !== undefined || input.model !== undefined
389
- const hasWorkspace = input.cwd !== undefined
390
- const hasPermission = input.permission !== undefined
391
- if (!hasModel && !hasWorkspace && !hasPermission) return { ok: false, error: '请选择提供商、模型、工作区或权限' }
392
- if (hasModel) {
393
- const next = normalizeAssistantModel(input)
394
- if (!next) return { ok: false, error: '请选择提供商和模型' }
395
- this.store.assistant = next
396
- this.applyAssistant(next)
397
- this.engine.setModel(next.provider, next.model, next.reasoningEffort)
398
- this.log(`[manager] 助手模型已设为 ${next.provider}/${next.model}`)
399
- }
400
- if (hasWorkspace) {
401
- const cwd = normalizeWorkspacePath(input.cwd)
402
- if (!cwd) return { ok: false, error: '请选择工作区' }
403
- this.store.cwd = cwd
404
- this.applyWorkspace(cwd)
405
- this.log(`[manager] 工作区已设为 ${cwd}`)
406
- }
407
- if (hasPermission) {
408
- const permission = normalizePermission(input.permission)
409
- if (!permission) return { ok: false, error: '请选择权限' }
410
- this.store.permission = permission
411
- this.applyPermission(permission)
412
- this.log(`[manager] 权限已设为 ${permission}`)
413
- }
414
- this.flush()
415
- return { ok: true, assistant: this.currentAssistant(), cwd: this.currentWorkspace(), permission: this.currentPermission() }
416
- }
417
-
418
- private applyAssistant(assistant?: AssistantModel): void {
419
- const next = normalizeAssistantModel(assistant ?? {})
420
- if (!next) return
421
- this.engineConfig.provider = next.provider
422
- this.engineConfig.model = next.model
423
- this.engineConfig.reasoningEffort = next.reasoningEffort
424
- }
425
-
426
- currentWorkspace(): string {
427
- return this.store.cwd || this.engineConfig.cwd
428
- }
429
-
430
- private applyWorkspace(cwd?: string): void {
431
- const next = normalizeWorkspacePath(cwd)
432
- if (!next) return
433
- this.engineConfig.cwd = next
434
- // 构造阶段 engine 还没建好,先只写配置;ImEngine 会读同一份 engineConfig。
435
- this.engine?.setCwd(next)
436
- }
437
-
438
- currentPermission(): PermissionPreset {
439
- return this.store.permission || this.engineConfig.permissionPreset || 'full-access'
440
- }
441
-
442
- private applyPermission(permission?: PermissionPreset): void {
443
- const next = normalizePermission(permission)
444
- if (!next) return
445
- this.engineConfig.permissionPreset = next
446
- this.engine?.setPermission(next)
447
- }
448
-
449
- private async listModelCatalog(): Promise<Array<{ id: string; name: string; models: Array<{ id: string; name: string }> }>> {
450
- const llm = (this.ctx as Context & {
451
- get?(name: string): {
452
- listProviders?: () => Array<{ id: string; name?: string }>
453
- listModels?: (provider: string) => Promise<Array<{ id: string; name?: string }>>
454
- } | undefined
455
- }).get?.('llm')
456
- const providers = llm?.listProviders?.() ?? []
457
- const out: Array<{ id: string; name: string; models: Array<{ id: string; name: string }> }> = []
458
- for (const item of providers) {
459
- const models = llm?.listModels ? await llm.listModels(item.id).catch(() => []) : []
460
- out.push({
461
- id: item.id,
462
- name: item.name || item.id,
463
- models: models.map((model: { id: string; name?: string; reasoning?: { defaultEffort?: string; efforts?: Array<{ id: string; name?: string }> } }) => ({
464
- id: model.id,
465
- name: model.name || model.id,
466
- reasoning: model.reasoning,
467
- })),
468
- })
469
- }
470
- return out
471
- }
472
-
473
- private requestAuthorization(channelId: string, msg: ImMessage): void {
474
- const userId = msg.userId ?? '(匿名)'
475
- const list = this.store.pending[channelId] ?? []
476
- if (!list.some((item) => item.userId === userId)) {
477
- list.push({ userId, username: msg.username, chatId: msg.chatId, time: Date.now() })
478
- this.store.pending[channelId] = list
479
- this.flush()
480
- }
481
- }
482
-
483
- private applyAccessMode(id: ChannelId, mode?: string): void {
484
- if (id !== 'dingtalk') return
485
- this.engine.setAccessMode(id, mode === 'open' ? 'open' : 'pair')
486
- }
487
-
488
- private async startOne(id: ChannelId): Promise<void> {
489
- await this.stopOne(id)
490
- const state = this.store.channels[id]
491
- const resolved = await this.resolveSecrets(id, state?.config ?? {})
492
- const adapter = createChannelAdapter(id, resolved, this.log, join(this.stateDir, id))
493
- if (!adapter) throw new Error('凭据不足,无法启动渠道')
494
- this.applyAccessMode(id, resolved.accessMode)
495
- this.engine.register(adapter)
496
- this.running.set(id, adapter)
497
- try {
498
- await adapter.start()
499
- } catch (error) {
500
- this.engine.unregister(id)
501
- this.running.delete(id)
502
- await Promise.resolve(adapter.stop()).catch(() => undefined)
503
- const message = error instanceof Error ? error.message : String(error)
504
- if (state) {
505
- state.lastError = message
506
- this.flush()
507
- }
508
- throw error
509
- }
510
- if (state) {
511
- state.lastError = undefined
512
- this.flush()
513
- }
514
- this.log(`[manager] ${id} 已启动:${adapter.status()}`)
515
- }
516
-
517
- private async stopOne(id: ChannelId): Promise<void> {
518
- const adapter = this.running.get(id)
519
- if (!adapter) return
520
- this.engine.unregister(id)
521
- this.running.delete(id)
522
- await Promise.resolve(adapter.stop()).catch(() => undefined)
523
- }
524
-
525
- private async persistSecrets(id: ChannelId, config: Record<string, string>): Promise<Record<string, string>> {
526
- const secrets = new Set((CHANNEL_META[id].fields.filter((field) => field.secret)).map((field) => field.key))
527
- const out = { ...config }
528
- for (const key of secrets) {
529
- const value = out[key]
530
- if (!value) continue
531
- const ref = credentialRef(id, key)
532
- await this.vault.set(ref, value)
533
- out[key] = ''
534
- out[`${key}Ref`] = ref
535
- }
536
- return out
537
- }
538
-
539
- private async resolveSecrets(id: ChannelId, config: Record<string, string>): Promise<Record<string, string>> {
540
- const secrets = new Set((CHANNEL_META[id].fields.filter((field) => field.secret)).map((field) => field.key))
541
- const out = { ...config }
542
- for (const key of secrets) {
543
- const ref = out[`${key}Ref`] || credentialRef(id, key)
544
- const value = await this.vault.resolve(ref)
545
- if (value) out[key] = value
546
- }
547
- return out
548
- }
549
-
550
- private load(): void {
551
- try {
552
- const parsed = JSON.parse(readFileSync(this.file, 'utf8')) as Partial<Persisted>
553
- this.store = {
554
- channels: parsed.channels ?? {},
555
- allowlist: parsed.allowlist ?? {},
556
- pending: parsed.pending ?? {},
557
- assistant: normalizeAssistantModel(parsed.assistant ?? {}),
558
- cwd: normalizeWorkspacePath(parsed.cwd),
559
- permission: normalizePermission(parsed.permission),
560
- }
561
- } catch {
562
- this.store = { channels: {}, allowlist: {}, pending: {} }
563
- }
564
- }
565
-
566
- private flush(): void {
567
- mkdirSync(this.stateDir, { recursive: true })
568
- writeFileSync(this.file, `${JSON.stringify(this.store, null, 2)}\n`, 'utf8')
569
- }
1
+ import type { Context } from '@deepseek-ai/cordis'
2
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { createChannelAdapter } from './channels/factory.js'
5
+ import { CHANNEL_META, CHANNEL_ORDER, supportsQr } from './channels/meta.js'
6
+ import { PairingHub } from './channels/qr/hub.js'
7
+ import type { ChannelId } from './engine/session-id.js'
8
+ import { SessionMapStore } from './engine/session-store.js'
9
+ import { createFileVault, createServiceVault, credentialRef, type CredentialService, type CredentialVault } from './engine/credentials.js'
10
+ import { ImEngine } from './engine/gateway.js'
11
+ import { SeenStore } from './engine/seen-store.js'
12
+ import { clearWeixinLogin, persistWeixinLogin } from './channels/weixin.js'
13
+ import { normalizeAssistantModel, normalizePermission, normalizeWorkspacePath, type AssistantModel, type PermissionPreset } from './engine/assistant-settings.js'
14
+ import type { ChannelAdapter, EngineConfig } from './engine/types.js'
15
+
16
+ export interface ChannelState {
17
+ enabled?: boolean
18
+ receiveEnabled?: boolean
19
+ lastError?: string
20
+ config?: Record<string, string>
21
+ }
22
+
23
+ export interface ChannelView {
24
+ id: ChannelId
25
+ label: string
26
+ description: string
27
+ kind: string
28
+ fields: Array<{ key: string; label: string; secret?: boolean }>
29
+ connected: boolean
30
+ receiveEnabled: boolean
31
+ configuredKeys: string[]
32
+ status: string
33
+ }
34
+
35
+ interface Persisted {
36
+ channels: Record<string, ChannelState>
37
+ assistant?: AssistantModel
38
+ cwd?: string
39
+ permission?: PermissionPreset
40
+ }
41
+
42
+ export class ChannelManager {
43
+ private readonly file: string
44
+ private readonly stateDir: string
45
+ private readonly sessions: SessionMapStore
46
+ private readonly engine: ImEngine
47
+ private readonly vault: CredentialVault
48
+ private readonly pairing: PairingHub
49
+ private readonly log: (line: string) => void
50
+ private readonly ctx: Context
51
+ private readonly engineConfig: EngineConfig
52
+ private store: Persisted = { channels: {} }
53
+ private readonly running = new Map<string, ChannelAdapter>()
54
+ private apiDisposers: Array<() => void> = []
55
+ // dispose 后阻止 initEnabled/startOne 再拉起渠道,避免插件重载时新旧双实例并存
56
+ private disposed = false
57
+
58
+ constructor(options: { ctx: Context; stateDir: string; log: (line: string) => void; engineConfig: EngineConfig }) {
59
+ this.ctx = options.ctx
60
+ this.engineConfig = options.engineConfig
61
+ this.stateDir = options.stateDir
62
+ this.file = join(options.stateDir, 'channels.json')
63
+ this.sessions = new SessionMapStore(join(options.stateDir, 'sessions.json'))
64
+ this.log = options.log
65
+ this.load()
66
+ this.applyAssistant(this.store.assistant)
67
+ this.applyWorkspace(this.store.cwd)
68
+ this.applyPermission(this.store.permission)
69
+ const seen = new SeenStore(join(options.stateDir, 'seen.json'))
70
+ const credentials = (options.ctx as Context & { credentials?: CredentialService }).credentials
71
+ this.vault = credentials
72
+ ? createServiceVault(credentials)
73
+ : createFileVault(join(options.stateDir, 'secrets.json'))
74
+ this.engine = new ImEngine(options.ctx, this.sessions, seen, options.engineConfig, options.log)
75
+ this.pairing = new PairingHub({
76
+ log: options.log,
77
+ onSuccess: async (id, creds) => {
78
+ const result = await this.connect(id, creds)
79
+ if (!result.ok) throw new Error(result.error ?? '保存失败')
80
+ },
81
+ })
82
+ }
83
+
84
+ list(): ChannelView[] {
85
+ return CHANNEL_ORDER.map((id) => {
86
+ const meta = CHANNEL_META[id]
87
+ const state = this.store.channels[id] ?? {}
88
+ const config = state.config ?? {}
89
+ const configuredKeys = Object.keys(config).filter((key) => Boolean(config[key]) && !key.endsWith('Ref'))
90
+ const adapter = this.running.get(id)
91
+ const status = adapter?.status() ?? state.lastError ?? '未连接'
92
+ const connected = adapter !== undefined && !status.includes('失败') && status !== '未连接' && status !== '已停止'
93
+ return {
94
+ id,
95
+ label: meta.label,
96
+ description: meta.description,
97
+ kind: meta.kind,
98
+ fields: meta.fields,
99
+ connected,
100
+ receiveEnabled: connected && state.receiveEnabled !== false,
101
+ configuredKeys,
102
+ status,
103
+ }
104
+ })
105
+ }
106
+
107
+ channelSessions() {
108
+ const connected = new Set(this.list().filter((item) => item.connected).map((item) => item.id))
109
+ return CHANNEL_ORDER.map((id) => ({
110
+ id,
111
+ label: CHANNEL_META[id].label,
112
+ sessions: this.sessions.list().filter((item) => item.channel === id),
113
+ })).filter((group) => group.sessions.length > 0 || connected.has(group.id))
114
+ }
115
+
116
+ async connect(id: ChannelId, config?: Record<string, string>): Promise<{ ok: boolean; error?: string }> {
117
+ if (!CHANNEL_META[id]) return { ok: false, error: '未知渠道' }
118
+ const incoming = { ...(config ?? {}) }
119
+ if (id === 'weixin' && incoming.botToken) {
120
+ persistWeixinLogin(join(this.stateDir, 'weixin'), {
121
+ botToken: incoming.botToken,
122
+ allowedUserId: incoming.allowedUserId,
123
+ baseUrl: incoming.baseUrl,
124
+ })
125
+ delete incoming.botToken
126
+ incoming.bound = '1'
127
+ }
128
+ const prev = this.store.channels[id] ?? {}
129
+ const nextConfig = await this.persistSecrets(id, { ...(prev.config ?? {}), ...incoming })
130
+ this.store.channels[id] = { ...prev, enabled: true, receiveEnabled: true, config: nextConfig }
131
+ this.flush()
132
+ try {
133
+ await this.startOne(id)
134
+ return { ok: true }
135
+ } catch (error) {
136
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
137
+ }
138
+ }
139
+
140
+ async setReceive(id: ChannelId, receiveEnabled: boolean): Promise<{ ok: boolean; error?: string }> {
141
+ const state = this.store.channels[id]
142
+ if (!state?.enabled) return { ok: false, error: '渠道未配置' }
143
+ state.receiveEnabled = receiveEnabled
144
+ this.flush()
145
+ if (!receiveEnabled) await this.stopOne(id)
146
+ else if (!this.running.has(id)) await this.startOne(id)
147
+ return { ok: true }
148
+ }
149
+
150
+ async disconnect(id: ChannelId): Promise<void> {
151
+ const state = this.store.channels[id]
152
+ if (state) {
153
+ state.enabled = false
154
+ state.receiveEnabled = false
155
+ this.flush()
156
+ }
157
+ this.pairing.cancel(id)
158
+ await this.stopOne(id)
159
+ }
160
+
161
+ async remove(id: ChannelId): Promise<void> {
162
+ if (!CHANNEL_META[id]) return
163
+ await this.stopOne(id)
164
+ this.pairing.cancel(id)
165
+ delete this.store.channels[id]
166
+ this.flush()
167
+ if (id === 'weixin') clearWeixinLogin(join(this.stateDir, 'weixin'))
168
+ for (const field of CHANNEL_META[id].fields.filter((item) => item.secret)) {
169
+ await this.vault.unset(credentialRef(id, field.key)).catch(() => undefined)
170
+ }
171
+ }
172
+
173
+ attachMappedSessions(): Promise<void> {
174
+ return this.engine.attachMappedSessions()
175
+ }
176
+
177
+ async initEnabled(): Promise<void> {
178
+ const started = Date.now()
179
+ for (const id of CHANNEL_ORDER) {
180
+ if (this.disposed) return
181
+ const state = this.store.channels[id]
182
+ if (state?.enabled && state.receiveEnabled !== false) {
183
+ const one = Date.now()
184
+ await this.startOne(id).catch((error) => {
185
+ this.log(`[manager] 启动 ${id} 失败: ${error instanceof Error ? error.message : String(error)}`)
186
+ })
187
+ this.log(`[boot] 渠道 ${id} 启动 ${Date.now() - one}ms`)
188
+ }
189
+ }
190
+ this.log(`[boot] initEnabled ${Date.now() - started}ms`)
191
+ }
192
+
193
+ registerApi(ctx: Context): void {
194
+ const webServer = (ctx as Context & {
195
+ webServer?: {
196
+ register(route: {
197
+ kind: string
198
+ path: string
199
+ handler: (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => void
200
+ }): (() => void) | void
201
+ }
202
+ }).webServer
203
+ if (!webServer) return
204
+ const send = (res: import('node:http').ServerResponse, status: number, body: unknown) => {
205
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
206
+ res.end(JSON.stringify(body))
207
+ }
208
+ const MAX_BODY_CHARS = 1024 * 1024
209
+ const readBody = (req: import('node:http').IncomingMessage): Promise<{ body: Record<string, unknown>; oversized: boolean }> =>
210
+ new Promise((resolve) => {
211
+ let raw = ''
212
+ let oversized = false
213
+ // 超限后停止累计但不掐断连接,等 end 后统一按 413 拒绝,防止内存被撑爆
214
+ req.on('data', (chunk) => {
215
+ if (oversized) return
216
+ raw += chunk
217
+ if (raw.length > MAX_BODY_CHARS) oversized = true
218
+ })
219
+ req.on('error', () => resolve({ body: {}, oversized }))
220
+ req.on('end', () => {
221
+ if (oversized) { resolve({ body: {}, oversized }); return }
222
+ try { resolve({ body: raw ? JSON.parse(raw) as Record<string, unknown> : {}, oversized: false }) } catch { resolve({ body: {}, oversized: false }) }
223
+ })
224
+ })
225
+ const payload = () => ({
226
+ ok: true,
227
+ channels: this.list(),
228
+ groups: this.channelSessions(),
229
+ assistant: this.currentAssistant(),
230
+ })
231
+ const dispose = webServer.register({
232
+ kind: 'prefix',
233
+ path: '/dsh-im-connect/api',
234
+ handler: async (req, res) => {
235
+ try {
236
+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`)
237
+ const parts = url.pathname.split('/').filter(Boolean)
238
+ if (parts[2] === 'assistant' && parts.length === 3) {
239
+ if (req.method === 'GET') {
240
+ send(res, 200, { ok: true, assistant: this.currentAssistant(), cwd: this.currentWorkspace(), permission: this.currentPermission(), providers: await this.listModelCatalog() })
241
+ return
242
+ }
243
+ if (req.method === 'POST') {
244
+ const { body, oversized } = await readBody(req)
245
+ if (oversized) { send(res, 413, { ok: false, error: '请求体超过 1MB 上限' }); return }
246
+ const result = this.setAssistant(body)
247
+ send(res, result.ok ? 200 : 400, result)
248
+ return
249
+ }
250
+ send(res, 405, { ok: false, error: 'method not allowed' })
251
+ return
252
+ }
253
+ if (parts[2] === 'sessions' && parts.length === 4 && req.method === 'POST') {
254
+ const action = parts[3]
255
+ const { body, oversized } = await readBody(req)
256
+ if (oversized) { send(res, 413, { ok: false, error: '请求体超过 1MB 上限' }); return }
257
+ const sessionId = String(body.sessionId ?? '')
258
+ if (!sessionId) { send(res, 400, { ok: false, error: '缺少 sessionId' }); return }
259
+ if (action === 'rename') {
260
+ const title = String(body.title ?? '').trim()
261
+ if (!title) { send(res, 400, { ok: false, error: '缺少标题' }); return }
262
+ const ok = this.engine.renameSession(sessionId, title)
263
+ send(res, ok ? 200 : 404, ok ? { ok: true, groups: this.channelSessions() } : { ok: false, error: '会话不存在' })
264
+ return
265
+ }
266
+ if (action === 'remove') {
267
+ const ok = await this.engine.removeSession(sessionId)
268
+ send(res, ok ? 200 : 404, ok ? { ok: true, groups: this.channelSessions() } : { ok: false, error: '会话不存在' })
269
+ return
270
+ }
271
+ if (action === 'ensure') {
272
+ const ok = await this.engine.ensureSession(sessionId)
273
+ send(res, ok ? 200 : 404, ok ? { ok: true, sessionId } : { ok: false, error: '会话不存在' })
274
+ return
275
+ }
276
+ send(res, 404, { ok: false, error: `未知会话操作 ${action}` })
277
+ return
278
+ }
279
+ if (parts[2] === 'channels' && parts.length === 3 && req.method === 'GET') {
280
+ send(res, 200, payload())
281
+ return
282
+ }
283
+ if (parts[2] === 'channels' && parts.length === 6 && parts[4] === 'qr') {
284
+ const id = parts[3] as ChannelId
285
+ const action = parts[5]
286
+ if (!CHANNEL_META[id]) { send(res, 404, { ok: false, error: '未知渠道' }); return }
287
+ if (!supportsQr(id)) { send(res, 400, { ok: false, error: '该渠道不支持扫码绑定' }); return }
288
+ if (action === 'status' && req.method === 'GET') {
289
+ send(res, 200, { ok: true, pairing: this.pairing.view(id), channel: this.list().find((item) => item.id === id) })
290
+ return
291
+ }
292
+ if (req.method !== 'POST') { send(res, 405, { ok: false, error: 'method not allowed' }); return }
293
+ const { oversized } = await readBody(req)
294
+ if (oversized) { send(res, 413, { ok: false, error: '请求体超过 1MB 上限' }); return }
295
+ if (action === 'start') {
296
+ const pairing = await this.pairing.start(id)
297
+ send(res, pairing.status === 'failed' ? 400 : 200, { ok: pairing.status !== 'failed', pairing, error: pairing.error })
298
+ return
299
+ }
300
+ if (action === 'refresh') {
301
+ const pairing = await this.pairing.refresh(id)
302
+ send(res, pairing.status === 'failed' ? 400 : 200, { ok: pairing.status !== 'failed', pairing, error: pairing.error })
303
+ return
304
+ }
305
+ if (action === 'cancel') {
306
+ send(res, 200, { ok: true, pairing: this.pairing.cancel(id) })
307
+ return
308
+ }
309
+ send(res, 404, { ok: false, error: `未知扫码操作 ${action}` })
310
+ return
311
+ }
312
+ if (parts[2] === 'channels' && parts.length === 5 && req.method === 'POST') {
313
+ const id = parts[3] as ChannelId
314
+ const action = parts[4]
315
+ const { body, oversized } = await readBody(req)
316
+ if (oversized) { send(res, 413, { ok: false, error: '请求体超过 1MB 上限' }); return }
317
+ if (action === 'connect') {
318
+ const result = await this.connect(id, body.config as Record<string, string> | undefined)
319
+ send(res, result.ok ? 200 : 400, result.ok ? { ok: true, channel: this.list().find((item) => item.id === id) } : result)
320
+ return
321
+ }
322
+ if (action === 'receive') {
323
+ const result = await this.setReceive(id, body.receiveEnabled !== false)
324
+ send(res, result.ok ? 200 : 400, result.ok ? { ok: true, channel: this.list().find((item) => item.id === id) } : result)
325
+ return
326
+ }
327
+ if (action === 'disconnect') {
328
+ await this.disconnect(id)
329
+ send(res, 200, { ok: true, channel: this.list().find((item) => item.id === id) })
330
+ return
331
+ }
332
+ if (action === 'remove') {
333
+ await this.remove(id)
334
+ send(res, 200, { ok: true, channel: this.list().find((item) => item.id === id) })
335
+ return
336
+ }
337
+ send(res, 404, { ok: false, error: `未知操作 ${action}` })
338
+ return
339
+ }
340
+ send(res, 404, { ok: false, error: 'not found' })
341
+ } catch (error) {
342
+ // 单个路由异常不能让 HTTP 连接悬死,统一回 500 并落日志
343
+ const detail = error instanceof Error ? error.message : String(error)
344
+ this.log(`[manager] API 处理失败: ${detail}`)
345
+ send(res, 500, { ok: false, error: detail })
346
+ }
347
+ },
348
+ })
349
+ if (typeof dispose === 'function') this.apiDisposers.push(dispose)
350
+ this.log('[manager] API 已注册 /dsh-im-connect/api')
351
+ }
352
+
353
+ disposeApi(): void {
354
+ this.disposed = true
355
+ for (const dispose of this.apiDisposers) dispose()
356
+ this.apiDisposers = []
357
+ this.pairing.dispose()
358
+ for (const id of [...this.running.keys()]) void this.stopOne(id as ChannelId)
359
+ this.engine.dispose()
360
+ }
361
+
362
+
363
+ currentAssistant(): AssistantModel | undefined {
364
+ return normalizeAssistantModel(this.store.assistant ?? this.engineConfig)
365
+ }
366
+
367
+ setAssistant(input: { provider?: unknown; model?: unknown; cwd?: unknown; permission?: unknown }): { ok: boolean; error?: string; assistant?: AssistantModel; cwd?: string; permission?: PermissionPreset } {
368
+ const hasModel = input.provider !== undefined || input.model !== undefined
369
+ const hasWorkspace = input.cwd !== undefined
370
+ const hasPermission = input.permission !== undefined
371
+ if (!hasModel && !hasWorkspace && !hasPermission) return { ok: false, error: '请选择提供商、模型、工作区或权限' }
372
+ if (hasModel) {
373
+ const next = normalizeAssistantModel(input)
374
+ if (!next) return { ok: false, error: '请选择提供商和模型' }
375
+ this.store.assistant = next
376
+ this.applyAssistant(next)
377
+ this.engine.setModel(next.provider, next.model, next.reasoningEffort)
378
+ this.log(`[manager] 助手模型已设为 ${next.provider}/${next.model}`)
379
+ }
380
+ if (hasWorkspace) {
381
+ const cwd = normalizeWorkspacePath(input.cwd)
382
+ if (!cwd) return { ok: false, error: '请选择工作区' }
383
+ this.store.cwd = cwd
384
+ this.applyWorkspace(cwd)
385
+ this.log(`[manager] 工作区已设为 ${cwd}`)
386
+ }
387
+ if (hasPermission) {
388
+ const permission = normalizePermission(input.permission)
389
+ if (!permission) return { ok: false, error: '请选择权限' }
390
+ this.store.permission = permission
391
+ this.applyPermission(permission)
392
+ this.log(`[manager] 权限已设为 ${permission}`)
393
+ }
394
+ this.flush()
395
+ return { ok: true, assistant: this.currentAssistant(), cwd: this.currentWorkspace(), permission: this.currentPermission() }
396
+ }
397
+
398
+ private applyAssistant(assistant?: AssistantModel): void {
399
+ const next = normalizeAssistantModel(assistant ?? {})
400
+ if (!next) return
401
+ this.engineConfig.provider = next.provider
402
+ this.engineConfig.model = next.model
403
+ this.engineConfig.reasoningEffort = next.reasoningEffort
404
+ }
405
+
406
+ currentWorkspace(): string {
407
+ return this.store.cwd || this.engineConfig.cwd
408
+ }
409
+
410
+ private applyWorkspace(cwd?: string): void {
411
+ const next = normalizeWorkspacePath(cwd)
412
+ if (!next) return
413
+ this.engineConfig.cwd = next
414
+ // 构造阶段 engine 还没建好,先只写配置;ImEngine 会读同一份 engineConfig。
415
+ this.engine?.setCwd(next)
416
+ }
417
+
418
+ currentPermission(): PermissionPreset {
419
+ return this.store.permission || this.engineConfig.permissionPreset || 'full-access'
420
+ }
421
+
422
+ private applyPermission(permission?: PermissionPreset): void {
423
+ const next = normalizePermission(permission)
424
+ if (!next) return
425
+ this.engineConfig.permissionPreset = next
426
+ this.engine?.setPermission(next)
427
+ }
428
+
429
+ private async listModelCatalog(): Promise<Array<{ id: string; name: string; models: Array<{ id: string; name: string }> }>> {
430
+ const llm = (this.ctx as Context & {
431
+ get?(name: string): {
432
+ listProviders?: () => Array<{ id: string; name?: string }>
433
+ listModels?: (provider: string) => Promise<Array<{ id: string; name?: string }>>
434
+ } | undefined
435
+ }).get?.('llm')
436
+ const providers = llm?.listProviders?.() ?? []
437
+ const out: Array<{ id: string; name: string; models: Array<{ id: string; name: string }> }> = []
438
+ for (const item of providers) {
439
+ const models = llm?.listModels ? await llm.listModels(item.id).catch(() => []) : []
440
+ out.push({
441
+ id: item.id,
442
+ name: item.name || item.id,
443
+ models: models.map((model: { id: string; name?: string; reasoning?: { defaultEffort?: string; efforts?: Array<{ id: string; name?: string }> } }) => ({
444
+ id: model.id,
445
+ name: model.name || model.id,
446
+ reasoning: model.reasoning,
447
+ })),
448
+ })
449
+ }
450
+ return out
451
+ }
452
+
453
+ private async startOne(id: ChannelId): Promise<void> {
454
+ await this.stopOne(id)
455
+ if (this.disposed) return
456
+ const state = this.store.channels[id]
457
+ const resolved = await this.resolveSecrets(id, state?.config ?? {})
458
+ const adapter = createChannelAdapter(id, resolved, this.log, join(this.stateDir, id))
459
+ if (!adapter) throw new Error('凭据不足,无法启动渠道')
460
+ this.engine.register(adapter)
461
+ this.running.set(id, adapter)
462
+ // 渠道网络异常时 start 可能永久挂起,超时按启动失败处理(catch 会顺带 stop)
463
+ const START_TIMEOUT_MS = 30_000
464
+ let startTimer: ReturnType<typeof setTimeout> | undefined
465
+ try {
466
+ await Promise.race([
467
+ adapter.start(),
468
+ new Promise<never>((_, reject) => {
469
+ startTimer = setTimeout(() => reject(new Error('渠道启动超时')), START_TIMEOUT_MS)
470
+ }),
471
+ ])
472
+ } catch (error) {
473
+ this.engine.unregister(id)
474
+ this.running.delete(id)
475
+ await Promise.resolve(adapter.stop()).catch(() => undefined)
476
+ const message = error instanceof Error ? error.message : String(error)
477
+ if (state) {
478
+ state.lastError = message
479
+ this.flush()
480
+ }
481
+ throw error
482
+ } finally {
483
+ if (startTimer) clearTimeout(startTimer)
484
+ }
485
+ if (state) {
486
+ state.lastError = undefined
487
+ this.flush()
488
+ }
489
+ this.log(`[manager] ${id} 已启动:${adapter.status()}`)
490
+ }
491
+
492
+ private async stopOne(id: ChannelId): Promise<void> {
493
+ const adapter = this.running.get(id)
494
+ if (!adapter) return
495
+ this.engine.unregister(id)
496
+ this.running.delete(id)
497
+ await Promise.resolve(adapter.stop()).catch(() => undefined)
498
+ }
499
+
500
+ private async persistSecrets(id: ChannelId, config: Record<string, string>): Promise<Record<string, string>> {
501
+ const secrets = new Set((CHANNEL_META[id].fields.filter((field) => field.secret)).map((field) => field.key))
502
+ const out = { ...config }
503
+ for (const key of secrets) {
504
+ const value = out[key]
505
+ if (!value) continue
506
+ const ref = credentialRef(id, key)
507
+ await this.vault.set(ref, value)
508
+ out[key] = ''
509
+ out[`${key}Ref`] = ref
510
+ }
511
+ return out
512
+ }
513
+
514
+ private async resolveSecrets(id: ChannelId, config: Record<string, string>): Promise<Record<string, string>> {
515
+ const secrets = new Set((CHANNEL_META[id].fields.filter((field) => field.secret)).map((field) => field.key))
516
+ const out = { ...config }
517
+ for (const key of secrets) {
518
+ const ref = out[`${key}Ref`] || credentialRef(id, key)
519
+ const value = await this.vault.resolve(ref)
520
+ if (value) out[key] = value
521
+ }
522
+ return out
523
+ }
524
+
525
+ private load(): void {
526
+ try {
527
+ const parsed = JSON.parse(readFileSync(this.file, 'utf8')) as Partial<Persisted>
528
+ this.store = {
529
+ channels: parsed.channels ?? {},
530
+ assistant: normalizeAssistantModel(parsed.assistant ?? {}),
531
+ cwd: normalizeWorkspacePath(parsed.cwd),
532
+ permission: normalizePermission(parsed.permission),
533
+ }
534
+ } catch {
535
+ this.store = { channels: {} }
536
+ }
537
+ }
538
+
539
+ private flush(): void {
540
+ mkdirSync(this.stateDir, { recursive: true })
541
+ writeFileSync(this.file, `${JSON.stringify(this.store, null, 2)}\n`, 'utf8')
542
+ }
570
543
  }
571
544