@michengai/dsh-im-connect 0.1.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.
Files changed (162) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +39 -0
  3. package/client.js +1479 -0
  4. package/cordis.patch.yml +4 -0
  5. package/lib/channels/dingtalk-card.d.ts +24 -0
  6. package/lib/channels/dingtalk-card.d.ts.map +1 -0
  7. package/lib/channels/dingtalk-card.js +182 -0
  8. package/lib/channels/dingtalk-card.js.map +1 -0
  9. package/lib/channels/dingtalk.d.ts +7 -0
  10. package/lib/channels/dingtalk.d.ts.map +1 -0
  11. package/lib/channels/dingtalk.js +107 -0
  12. package/lib/channels/dingtalk.js.map +1 -0
  13. package/lib/channels/factory.d.ts +4 -0
  14. package/lib/channels/factory.d.ts.map +1 -0
  15. package/lib/channels/factory.js +24 -0
  16. package/lib/channels/factory.js.map +1 -0
  17. package/lib/channels/feishu.d.ts +8 -0
  18. package/lib/channels/feishu.d.ts.map +1 -0
  19. package/lib/channels/feishu.js +73 -0
  20. package/lib/channels/feishu.js.map +1 -0
  21. package/lib/channels/meta.d.ts +20 -0
  22. package/lib/channels/meta.d.ts.map +1 -0
  23. package/lib/channels/meta.js +69 -0
  24. package/lib/channels/meta.js.map +1 -0
  25. package/lib/channels/qr/dingtalk.d.ts +12 -0
  26. package/lib/channels/qr/dingtalk.d.ts.map +1 -0
  27. package/lib/channels/qr/dingtalk.js +69 -0
  28. package/lib/channels/qr/dingtalk.js.map +1 -0
  29. package/lib/channels/qr/feishu.d.ts +14 -0
  30. package/lib/channels/qr/feishu.d.ts.map +1 -0
  31. package/lib/channels/qr/feishu.js +87 -0
  32. package/lib/channels/qr/feishu.js.map +1 -0
  33. package/lib/channels/qr/hub.d.ts +22 -0
  34. package/lib/channels/qr/hub.d.ts.map +1 -0
  35. package/lib/channels/qr/hub.js +193 -0
  36. package/lib/channels/qr/hub.js.map +1 -0
  37. package/lib/channels/qr/render.d.ts +3 -0
  38. package/lib/channels/qr/render.d.ts.map +1 -0
  39. package/lib/channels/qr/render.js +9 -0
  40. package/lib/channels/qr/render.js.map +1 -0
  41. package/lib/channels/qr/shared.d.ts +39 -0
  42. package/lib/channels/qr/shared.d.ts.map +1 -0
  43. package/lib/channels/qr/shared.js +51 -0
  44. package/lib/channels/qr/shared.js.map +1 -0
  45. package/lib/channels/qr/wecom.d.ts +10 -0
  46. package/lib/channels/qr/wecom.d.ts.map +1 -0
  47. package/lib/channels/qr/wecom.js +81 -0
  48. package/lib/channels/qr/wecom.js.map +1 -0
  49. package/lib/channels/qr/weixin.d.ts +10 -0
  50. package/lib/channels/qr/weixin.d.ts.map +1 -0
  51. package/lib/channels/qr/weixin.js +77 -0
  52. package/lib/channels/qr/weixin.js.map +1 -0
  53. package/lib/channels/telegram.d.ts +7 -0
  54. package/lib/channels/telegram.d.ts.map +1 -0
  55. package/lib/channels/telegram.js +133 -0
  56. package/lib/channels/telegram.js.map +1 -0
  57. package/lib/channels/wecom.d.ts +28 -0
  58. package/lib/channels/wecom.d.ts.map +1 -0
  59. package/lib/channels/wecom.js +168 -0
  60. package/lib/channels/wecom.js.map +1 -0
  61. package/lib/channels/weixin.d.ts +41 -0
  62. package/lib/channels/weixin.d.ts.map +1 -0
  63. package/lib/channels/weixin.js +678 -0
  64. package/lib/channels/weixin.js.map +1 -0
  65. package/lib/client.js +1479 -0
  66. package/lib/engine/access.d.ts +11 -0
  67. package/lib/engine/access.d.ts.map +1 -0
  68. package/lib/engine/access.js +11 -0
  69. package/lib/engine/access.js.map +1 -0
  70. package/lib/engine/agent-options.d.ts +25 -0
  71. package/lib/engine/agent-options.d.ts.map +1 -0
  72. package/lib/engine/agent-options.js +19 -0
  73. package/lib/engine/agent-options.js.map +1 -0
  74. package/lib/engine/approval.d.ts +9 -0
  75. package/lib/engine/approval.d.ts.map +1 -0
  76. package/lib/engine/approval.js +38 -0
  77. package/lib/engine/approval.js.map +1 -0
  78. package/lib/engine/assistant-settings.d.ts +17 -0
  79. package/lib/engine/assistant-settings.d.ts.map +1 -0
  80. package/lib/engine/assistant-settings.js +35 -0
  81. package/lib/engine/assistant-settings.js.map +1 -0
  82. package/lib/engine/credentials.d.ts +17 -0
  83. package/lib/engine/credentials.d.ts.map +1 -0
  84. package/lib/engine/credentials.js +51 -0
  85. package/lib/engine/credentials.js.map +1 -0
  86. package/lib/engine/gateway.d.ts +46 -0
  87. package/lib/engine/gateway.d.ts.map +1 -0
  88. package/lib/engine/gateway.js +333 -0
  89. package/lib/engine/gateway.js.map +1 -0
  90. package/lib/engine/json-state.d.ts +8 -0
  91. package/lib/engine/json-state.d.ts.map +1 -0
  92. package/lib/engine/json-state.js +24 -0
  93. package/lib/engine/json-state.js.map +1 -0
  94. package/lib/engine/merge.d.ts +21 -0
  95. package/lib/engine/merge.d.ts.map +1 -0
  96. package/lib/engine/merge.js +55 -0
  97. package/lib/engine/merge.js.map +1 -0
  98. package/lib/engine/router.d.ts +88 -0
  99. package/lib/engine/router.d.ts.map +1 -0
  100. package/lib/engine/router.js +309 -0
  101. package/lib/engine/router.js.map +1 -0
  102. package/lib/engine/seen-store.d.ts +12 -0
  103. package/lib/engine/seen-store.d.ts.map +1 -0
  104. package/lib/engine/seen-store.js +38 -0
  105. package/lib/engine/seen-store.js.map +1 -0
  106. package/lib/engine/session-id.d.ts +30 -0
  107. package/lib/engine/session-id.d.ts.map +1 -0
  108. package/lib/engine/session-id.js +53 -0
  109. package/lib/engine/session-id.js.map +1 -0
  110. package/lib/engine/session-store.d.ts +13 -0
  111. package/lib/engine/session-store.d.ts.map +1 -0
  112. package/lib/engine/session-store.js +38 -0
  113. package/lib/engine/session-store.js.map +1 -0
  114. package/lib/engine/split.d.ts +2 -0
  115. package/lib/engine/split.d.ts.map +1 -0
  116. package/lib/engine/split.js +41 -0
  117. package/lib/engine/split.js.map +1 -0
  118. package/lib/engine/types.d.ts +52 -0
  119. package/lib/engine/types.d.ts.map +1 -0
  120. package/lib/engine/types.js +2 -0
  121. package/lib/engine/types.js.map +1 -0
  122. package/lib/index.d.ts +22 -0
  123. package/lib/index.d.ts.map +1 -0
  124. package/lib/index.js +53 -0
  125. package/lib/index.js.map +1 -0
  126. package/lib/manager.d.ts +103 -0
  127. package/lib/manager.d.ts.map +1 -0
  128. package/lib/manager.js +543 -0
  129. package/lib/manager.js.map +1 -0
  130. package/package.json +63 -0
  131. package/src/channels/dingtalk-card.ts +191 -0
  132. package/src/channels/dingtalk.ts +113 -0
  133. package/src/channels/factory.ts +32 -0
  134. package/src/channels/feishu.ts +77 -0
  135. package/src/channels/meta.ts +89 -0
  136. package/src/channels/qr/dingtalk.ts +71 -0
  137. package/src/channels/qr/feishu.ts +90 -0
  138. package/src/channels/qr/hub.ts +206 -0
  139. package/src/channels/qr/render.ts +7 -0
  140. package/src/channels/qr/shared.ts +80 -0
  141. package/src/channels/qr/wecom.ts +78 -0
  142. package/src/channels/qr/weixin.ts +78 -0
  143. package/src/channels/telegram.ts +145 -0
  144. package/src/channels/wecom.ts +182 -0
  145. package/src/channels/weixin.ts +712 -0
  146. package/src/engine/access.ts +17 -0
  147. package/src/engine/agent-options.ts +24 -0
  148. package/src/engine/approval.ts +45 -0
  149. package/src/engine/assistant-settings.ts +41 -0
  150. package/src/engine/credentials.ts +64 -0
  151. package/src/engine/gateway.ts +330 -0
  152. package/src/engine/json-state.ts +20 -0
  153. package/src/engine/merge.ts +60 -0
  154. package/src/engine/router.ts +333 -0
  155. package/src/engine/seen-store.ts +36 -0
  156. package/src/engine/session-id.ts +65 -0
  157. package/src/engine/session-store.ts +45 -0
  158. package/src/engine/split.ts +29 -0
  159. package/src/engine/types.ts +55 -0
  160. package/src/index.ts +81 -0
  161. package/src/manager.ts +571 -0
  162. package/src/optional-modules.d.ts +13 -0
package/src/manager.ts ADDED
@@ -0,0 +1,571 @@
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
+ }
570
+ }
571
+
@@ -0,0 +1,13 @@
1
+ declare module '@larksuiteoapi/node-sdk'
2
+ declare module '@wecom/aibot-node-sdk'
3
+ declare module 'dingtalk-stream'
4
+ declare module 'qrcode'
5
+ declare module '@deepseek-ai/dsh-sandbox-policy' {
6
+ export function setSandboxMode(session: unknown, mode: 'read-only' | 'workspace-write'): void
7
+ }
8
+ declare module '@deepseek-ai/dsh-agent' {
9
+ export function installModelSelection(agentCtx: unknown, selection: {
10
+ current: { provider: string; model: string; reasoningEffort?: string }
11
+ assembled: undefined
12
+ }): void
13
+ }