@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
@@ -0,0 +1,333 @@
1
+ import type { Context } from '@deepseek-ai/cordis'
2
+ import type { ChannelId, ChatKind, SessionRecord } from './session-id.js'
3
+ import { createImSessionId, sessionKeyOf } from './session-id.js'
4
+ import { SessionMapStore } from './session-store.js'
5
+ import { readHostDefaultModel, resolveImAgentOptions } from './agent-options.js'
6
+ import type { EngineConfig } from './types.js'
7
+
8
+ export interface ChatBinding {
9
+ key: string
10
+ channelId: ChannelId
11
+ kind: ChatKind
12
+ chatId: string
13
+ sessionId: string
14
+ handle?: { agent?: unknown; dispose(): Promise<void> }
15
+ }
16
+
17
+ type WorkspaceLookup = {
18
+ list(): Array<{ path: string; attachSession(sessionId: string): Promise<void> }>
19
+ archivedSessionIds?: readonly string[]
20
+ }
21
+
22
+ type AgentHost = Context & {
23
+ agents?: {
24
+ create(opts: Record<string, unknown>): Promise<{ agent?: { followup(message: unknown): void; session?: { id?: string } }; dispose(): Promise<void> }>
25
+ get?(id: string): { followup(message: unknown): void; session?: { id?: string } } | undefined
26
+ resume?(opts: Record<string, unknown>): Promise<{ agent?: { followup(message: unknown): void }; dispose(): Promise<void> }>
27
+ withoutInitiator?<T>(operation: () => T): T
28
+ }
29
+ get?(name: string): WorkspaceLookup | undefined
30
+ agentPresets?: { mount(agentCtx: unknown, presetId: string): Promise<void> }
31
+ agentDefaultModel?: { currentSelection(): { provider?: string; model?: string } }
32
+ }
33
+
34
+ export class SessionRouter {
35
+ private readonly live = new Map<string, ChatBinding>()
36
+
37
+ constructor(
38
+ private readonly ctx: AgentHost,
39
+ private readonly store: SessionMapStore,
40
+ private readonly config: EngineConfig,
41
+ private readonly log: (line: string) => void,
42
+ ) {}
43
+
44
+ get(channelId: ChannelId, kind: ChatKind, chatId: string): ChatBinding | undefined {
45
+ return this.live.get(sessionKeyOf(channelId, kind, chatId))
46
+ }
47
+
48
+ bindingForSession(sessionId: string): ChatBinding | undefined {
49
+ for (const item of this.live.values()) {
50
+ if (item.sessionId === sessionId) return item
51
+ }
52
+ const rec = this.store.list().find((item) => item.sessionId === sessionId)
53
+ if (!rec) return undefined
54
+ return {
55
+ key: sessionKeyOf(rec.channel, rec.kind, rec.chatId),
56
+ channelId: rec.channel,
57
+ kind: rec.kind,
58
+ chatId: rec.chatId,
59
+ sessionId: rec.sessionId,
60
+ }
61
+ }
62
+
63
+ async getOrCreate(channelId: ChannelId, kind: ChatKind, chatId: string, title: string, options?: { rebuildMissing?: boolean }): Promise<ChatBinding> {
64
+ const key = sessionKeyOf(channelId, kind, chatId)
65
+ const live = this.live.get(key)
66
+ if (live?.handle) {
67
+ if (this.isArchived(live.sessionId)) {
68
+ this.log(`[router] 当前会话已归档,轮换 ${live.sessionId}`)
69
+ return this.rotate(channelId, kind, chatId, title)
70
+ }
71
+ return live
72
+ }
73
+ const saved = this.store.get(key)
74
+ if (saved) {
75
+ if (this.isArchived(saved.sessionId)) {
76
+ this.log(`[router] 映射会话已归档,轮换 ${saved.sessionId}`)
77
+ return this.rotate(channelId, kind, chatId, title)
78
+ }
79
+ const resumed = await this.resume(saved)
80
+ if (resumed) {
81
+ this.live.set(key, resumed)
82
+ return resumed
83
+ }
84
+ if (options?.rebuildMissing) {
85
+ try {
86
+ return await this.create(channelId, kind, chatId, title, saved.sessionId)
87
+ } catch (error) {
88
+ if (!isIdCollision(error)) throw error
89
+ this.log(`[router] 原 id 与磁盘日志冲突,改新建 ${saved.sessionId}`)
90
+ }
91
+ }
92
+ this.log(`[router] 无法恢复会话,轮换 ${saved.sessionId}`)
93
+ return this.rotate(channelId, kind, chatId, title)
94
+ }
95
+ return this.create(channelId, kind, chatId, title)
96
+ }
97
+
98
+ async rotate(channelId: ChannelId, kind: ChatKind, chatId: string, title: string): Promise<ChatBinding> {
99
+ const key = sessionKeyOf(channelId, kind, chatId)
100
+ const old = this.live.get(key)
101
+ if (old?.handle) await old.handle.dispose().catch(() => undefined)
102
+ this.live.delete(key)
103
+ this.store.remove(key)
104
+ return this.create(channelId, kind, chatId, title)
105
+ }
106
+
107
+ rename(sessionId: string, title: string): boolean {
108
+ const rec = this.store.list().find((item) => item.sessionId === sessionId)
109
+ if (!rec) return false
110
+ this.store.upsert(sessionKeyOf(rec.channel, rec.kind, rec.chatId), {
111
+ ...rec,
112
+ title,
113
+ updatedAt: new Date().toISOString(),
114
+ })
115
+ return true
116
+ }
117
+
118
+ async remove(sessionId: string): Promise<boolean> {
119
+ const rec = this.store.list().find((item) => item.sessionId === sessionId)
120
+ if (!rec) return false
121
+ const key = sessionKeyOf(rec.channel, rec.kind, rec.chatId)
122
+ const live = this.live.get(key)
123
+ if (live?.handle) await live.handle.dispose().catch(() => undefined)
124
+ this.live.delete(key)
125
+ this.store.remove(key)
126
+ return true
127
+ }
128
+
129
+ async ensure(sessionId: string): Promise<boolean> {
130
+ const rec = this.store.list().find((item) => item.sessionId === sessionId)
131
+ if (!rec) return false
132
+ await this.getOrCreate(rec.channel, rec.kind, rec.chatId, rec.title, { rebuildMissing: true })
133
+ return true
134
+ }
135
+
136
+ async disposeAll(): Promise<void> {
137
+ for (const item of this.live.values()) {
138
+ await item.handle?.dispose().catch(() => undefined)
139
+ }
140
+ this.live.clear()
141
+ }
142
+
143
+ followup(binding: ChatBinding, message: unknown): void {
144
+ const raw = binding.handle?.agent ?? this.ctx.agents?.get?.(binding.sessionId)
145
+ const agent = raw as { followup?: (message: unknown) => void } | undefined
146
+ if (!agent?.followup) throw new Error(`会话 ${binding.sessionId} 当前没有运行中的 agent`)
147
+ agent.followup(message)
148
+ }
149
+
150
+ private async create(channelId: ChannelId, kind: ChatKind, chatId: string, title: string, preferredSessionId?: string): Promise<ChatBinding> {
151
+ const key = sessionKeyOf(channelId, kind, chatId)
152
+ const sessionId = preferredSessionId || createImSessionId(channelId, kind, chatId)
153
+ let handle: Awaited<ReturnType<SessionRouter['createHandle']>>
154
+ try {
155
+ handle = await this.createHandle(sessionId)
156
+ } catch (error) {
157
+ if (!preferredSessionId || !isIdCollision(error)) throw error
158
+ this.log(`[router] 创建冲突,改用新 id ${sessionId}`)
159
+ return this.create(channelId, kind, chatId, title)
160
+ }
161
+ const record: SessionRecord = {
162
+ sessionId,
163
+ channel: channelId,
164
+ kind,
165
+ chatId,
166
+ title,
167
+ updatedAt: new Date().toISOString(),
168
+ }
169
+ this.store.upsert(key, record)
170
+ const binding: ChatBinding = { key, channelId, kind, chatId, sessionId, handle }
171
+ this.live.set(key, binding)
172
+ await this.attachWorkspace(sessionId)
173
+ this.log(`[router] 新建 IM 会话 ${sessionId}`)
174
+ return binding
175
+ }
176
+
177
+ private async resume(record: SessionRecord): Promise<ChatBinding | undefined> {
178
+ const liveAgent = this.ctx.agents?.get?.(record.sessionId)
179
+ if (liveAgent) {
180
+ const binding: ChatBinding = {
181
+ key: sessionKeyOf(record.channel, record.kind, record.chatId),
182
+ channelId: record.channel,
183
+ kind: record.kind,
184
+ chatId: record.chatId,
185
+ sessionId: record.sessionId,
186
+ }
187
+ await this.attachWorkspace(record.sessionId)
188
+ return binding
189
+ }
190
+ if (!this.ctx.agents?.resume) return undefined
191
+ try {
192
+ const handle = await this.ctx.agents.resume({
193
+ resumeSessionId: record.sessionId,
194
+ agentOptions: this.resolveAgentOptions(),
195
+ setup: this.presetSetup(),
196
+ })
197
+ await this.attachWorkspace(record.sessionId)
198
+ return {
199
+ key: sessionKeyOf(record.channel, record.kind, record.chatId),
200
+ channelId: record.channel,
201
+ kind: record.kind,
202
+ chatId: record.chatId,
203
+ sessionId: record.sessionId,
204
+ handle,
205
+ }
206
+ } catch (error) {
207
+ this.log(`[router] 恢复会话失败 ${record.sessionId}: ${error instanceof Error ? error.message : String(error)}`)
208
+ return undefined
209
+ }
210
+ }
211
+
212
+ private async createHandle(sessionId: string) {
213
+ const agents = this.ctx.agents
214
+ if (!agents?.create) throw new Error('当前 Host 没有 agents 服务,无法创建 IM 会话')
215
+ // DSH 会话头的 origin 只能是 subagent;IM 与任务的区分靠 sessionId 的 im: 前缀。
216
+ // 必须带上当前默认模型,否则 deployment:persona 的 {{model}} 组装会失败。
217
+ const agentOptions = this.resolveAgentOptions()
218
+ this.log(`[router] 使用模型 ${agentOptions.provider}/${agentOptions.model}${this.config.reasoningEffort ? ` ${this.config.reasoningEffort}` : ''}`)
219
+ const create = () => agents.create({
220
+ sessionId,
221
+ meta: {
222
+ cwd: this.config.cwd || process.cwd(),
223
+ ...(this.config.agentPreset ? { agentPreset: this.config.agentPreset } : {}),
224
+ },
225
+ agentOptions: {
226
+ ...agentOptions,
227
+ ...(this.config.reasoningEffort ? { reasoningEffort: this.config.reasoningEffort } : {}),
228
+ },
229
+ setup: this.presetSetup(),
230
+ })
231
+ return agents.withoutInitiator ? agents.withoutInitiator(create) : create()
232
+ }
233
+
234
+ async attachMappedSessions(): Promise<void> {
235
+ const started = Date.now()
236
+ for (const record of this.store.list()) {
237
+ await this.attachWorkspace(record.sessionId)
238
+ }
239
+ this.log(`[boot] attachMappedSessions ${Date.now() - started}ms`)
240
+ }
241
+
242
+ private isArchived(sessionId: string): boolean {
243
+ try {
244
+ const ids = this.ctx.get?.('workspaceRegistry')?.archivedSessionIds
245
+ if (!ids) return false
246
+ return ids.some((id: unknown) => String(id) === sessionId)
247
+ } catch {
248
+ return false
249
+ }
250
+ }
251
+
252
+ private samePath(left: string, right: string): boolean {
253
+ const norm = (value: string) => value.replace(/[\\/]+/g, '/').replace(/\/+$/, '').toLowerCase()
254
+ return norm(left) === norm(right)
255
+ }
256
+
257
+ private async attachWorkspace(sessionId: string): Promise<void> {
258
+ let workspaces: Array<{ path: string; attachSession(sessionId: string): Promise<void> }> = []
259
+ try {
260
+ workspaces = this.ctx.get?.('workspaceRegistry')?.list?.() ?? []
261
+ } catch {
262
+ workspaces = []
263
+ }
264
+ if (workspaces.length === 0) {
265
+ this.log(`[router] 当前没有工作区,网页点不开会话 ${sessionId}`)
266
+ return
267
+ }
268
+ const preferred = this.config.cwd || process.cwd()
269
+ const ordered = [...workspaces].sort((left, right) => {
270
+ const leftHit = this.samePath(left.path, preferred) ? 0 : 1
271
+ const rightHit = this.samePath(right.path, preferred) ? 0 : 1
272
+ return leftHit - rightHit
273
+ })
274
+ let lastError = ''
275
+ for (const workspace of ordered) {
276
+ try {
277
+ await workspace.attachSession(sessionId)
278
+ this.log(`[router] 已把 ${sessionId} 挂到工作区 ${workspace.path}`)
279
+ return
280
+ } catch (error) {
281
+ lastError = error instanceof Error ? error.message : String(error)
282
+ }
283
+ }
284
+ this.log(`[router] 挂载会话失败 ${sessionId}: ${lastError}`)
285
+ }
286
+
287
+ private resolveAgentOptions(): { provider: string; model: string } {
288
+ return resolveImAgentOptions({
289
+ provider: this.config.provider,
290
+ model: this.config.model,
291
+ fallback: readHostDefaultModel(this.ctx),
292
+ })
293
+ }
294
+
295
+ private presetSetup() {
296
+ const ctx = this.ctx
297
+ const preset = this.config.agentPreset || 'standard'
298
+ const permission = this.config.permissionPreset
299
+ return async (agentCtx: unknown) => {
300
+ if (ctx.agentPresets?.mount) await ctx.agentPresets.mount(agentCtx, preset)
301
+ if (this.config.provider && this.config.model) {
302
+ try {
303
+ const { installModelSelection } = await import('@deepseek-ai/dsh-agent')
304
+ installModelSelection(agentCtx, {
305
+ current: {
306
+ provider: this.config.provider,
307
+ model: this.config.model,
308
+ ...(this.config.reasoningEffort ? { reasoningEffort: this.config.reasoningEffort } : {}),
309
+ },
310
+ assembled: undefined,
311
+ })
312
+ } catch {
313
+ // Host 未暴露该接口时,仍把 reasoningEffort 放在 agentOptions 里。
314
+ }
315
+ }
316
+ if (permission && permission !== 'full-access') {
317
+ try {
318
+ const { setSandboxMode } = await import('@deepseek-ai/dsh-sandbox-policy')
319
+ const agent = (agentCtx as { agent?: { session?: unknown } }).agent
320
+ if (agent?.session) setSandboxMode(agent.session, permission)
321
+ } catch (error) {
322
+ this.log(`[router] 无法应用权限 ${permission}: ${error instanceof Error ? error.message : String(error)}`)
323
+ }
324
+ }
325
+ }
326
+ }
327
+ }
328
+
329
+
330
+ function isIdCollision(error: unknown): boolean {
331
+ const message = error instanceof Error ? error.message : String(error)
332
+ return message.includes('id collision') || message.includes('already has a persisted log')
333
+ }
@@ -0,0 +1,36 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { dirname } from 'node:path'
3
+
4
+ /** 去重最近见过的消息 id,避免重启或重复投递打两次。 */
5
+ export class SeenStore {
6
+ private ids: string[] = []
7
+
8
+ constructor(private readonly file: string, private readonly limit = 2000) {
9
+ this.load()
10
+ }
11
+
12
+ has(id: string): boolean {
13
+ return this.ids.includes(id)
14
+ }
15
+
16
+ add(id: string): void {
17
+ if (!id || this.has(id)) return
18
+ this.ids.push(id)
19
+ if (this.ids.length > this.limit) this.ids = this.ids.slice(-this.limit)
20
+ this.flush()
21
+ }
22
+
23
+ private load(): void {
24
+ try {
25
+ const parsed = JSON.parse(readFileSync(this.file, 'utf8')) as { ids?: string[] }
26
+ this.ids = Array.isArray(parsed.ids) ? parsed.ids.filter((item) => typeof item === 'string') : []
27
+ } catch {
28
+ this.ids = []
29
+ }
30
+ }
31
+
32
+ private flush(): void {
33
+ mkdirSync(dirname(this.file), { recursive: true })
34
+ writeFileSync(this.file, `${JSON.stringify({ ids: this.ids }, null, 2)}\n`, 'utf8')
35
+ }
36
+ }
@@ -0,0 +1,65 @@
1
+ /** IM 会话标识:与网页任务分列。DSH 会话头不能写 origin=im,只靠 id 前缀。 */
2
+ export const IM_ORIGIN = 'im'
3
+ export const IM_SESSION_PREFIX = 'im:'
4
+
5
+ export type ChannelId = 'dingtalk' | 'feishu' | 'lark' | 'weixin' | 'wecom' | 'telegram'
6
+ export type ChatKind = 'dm' | 'group'
7
+
8
+ export interface SessionRecord {
9
+ sessionId: string
10
+ channel: ChannelId
11
+ kind: ChatKind
12
+ chatId: string
13
+ title: string
14
+ updatedAt: string
15
+ }
16
+
17
+ export function sessionKeyOf(channel: ChannelId, kind: ChatKind, chatId: string): string {
18
+ return `${channel}:${kind}:${chatId}`
19
+ }
20
+
21
+ let lastStamp = 0
22
+
23
+ /** 新建会话用带时间戳的唯一 id;同一毫秒连续创建会递增,避免撞上已归档记录。 */
24
+ export function createImSessionId(channel: ChannelId, kind: ChatKind, chatId: string, now = Date.now()): string {
25
+ const stamp = now <= lastStamp ? lastStamp + 1 : now
26
+ lastStamp = stamp
27
+ return `${IM_SESSION_PREFIX}${channel}:${kind}:${stamp}:${chatId}`
28
+ }
29
+
30
+ export function isImSessionId(sessionId: string): boolean {
31
+ return sessionId.startsWith(IM_SESSION_PREFIX)
32
+ }
33
+
34
+ const CHANNEL_IDS: readonly ChannelId[] = ['dingtalk', 'feishu', 'lark', 'weixin', 'wecom', 'telegram']
35
+ const STAMP_RE = /^\d{13,}$/
36
+
37
+ export function parseImSessionId(sessionId: string): { channel: ChannelId; kind: ChatKind; chatId: string } | undefined {
38
+ if (!isImSessionId(sessionId)) return undefined
39
+ const rest = sessionId.slice(IM_SESSION_PREFIX.length)
40
+ const first = rest.indexOf(':')
41
+ const second = rest.indexOf(':', first + 1)
42
+ if (first <= 0 || second <= first) return undefined
43
+ const channel = rest.slice(0, first)
44
+ const kind = rest.slice(first + 1, second)
45
+ let chatId = rest.slice(second + 1)
46
+ const third = chatId.indexOf(':')
47
+ if (third > 0 && STAMP_RE.test(chatId.slice(0, third))) {
48
+ chatId = chatId.slice(third + 1)
49
+ }
50
+ if (!CHANNEL_IDS.includes(channel as ChannelId) || (kind !== 'dm' && kind !== 'group') || chatId === '') return undefined
51
+ return { channel: channel as ChannelId, kind, chatId }
52
+ }
53
+
54
+ export function isImOrigin(origin: string | undefined): boolean {
55
+ return origin === IM_ORIGIN
56
+ }
57
+
58
+ /** 任务列表可见:排除 IM 与子 agent。 */
59
+ export function isTaskSession(input: { id?: string; origin?: string; blank?: boolean }): boolean {
60
+ if (input.blank === true) return false
61
+ if (isImOrigin(input.origin)) return false
62
+ if (typeof input.id === 'string' && isImSessionId(input.id)) return false
63
+ if (input.origin === 'subagent') return false
64
+ return true
65
+ }
@@ -0,0 +1,45 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { dirname } from 'node:path'
3
+ import type { SessionRecord } from './session-id.js'
4
+
5
+ export class SessionMapStore {
6
+ private readonly file: string
7
+ private records: Record<string, SessionRecord> = {}
8
+
9
+ constructor(file: string) {
10
+ this.file = file
11
+ this.load()
12
+ }
13
+
14
+ list(): SessionRecord[] {
15
+ return Object.values(this.records).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
16
+ }
17
+
18
+ get(key: string): SessionRecord | undefined {
19
+ return this.records[key]
20
+ }
21
+
22
+ upsert(key: string, record: SessionRecord): void {
23
+ this.records[key] = record
24
+ this.flush()
25
+ }
26
+
27
+ remove(key: string): void {
28
+ delete this.records[key]
29
+ this.flush()
30
+ }
31
+
32
+ private load(): void {
33
+ try {
34
+ const parsed = JSON.parse(readFileSync(this.file, 'utf8')) as Record<string, SessionRecord>
35
+ this.records = parsed && typeof parsed === 'object' ? parsed : {}
36
+ } catch {
37
+ this.records = {}
38
+ }
39
+ }
40
+
41
+ private flush(): void {
42
+ mkdirSync(dirname(this.file), { recursive: true })
43
+ writeFileSync(this.file, `${JSON.stringify(this.records, null, 2)}\n`, 'utf8')
44
+ }
45
+ }
@@ -0,0 +1,29 @@
1
+ export function splitText(text: string, max: number): string[] {
2
+ if (max <= 0) return text === '' ? [] : [text]
3
+ const chars = [...text]
4
+ if (chars.length === 0) return []
5
+ if (chars.length <= max) return [text]
6
+ const parts: string[] = []
7
+ let rest = chars
8
+ while (rest.length > 0) {
9
+ if (rest.length <= max) {
10
+ parts.push(rest.join(''))
11
+ break
12
+ }
13
+ const window = rest.slice(0, max)
14
+ let cut = 0
15
+ for (let i = window.length - 1; i >= 0; i -= 1) {
16
+ if (window[i] === '\n') { cut = i + 1; break }
17
+ }
18
+ if (cut === 0) {
19
+ for (let i = window.length - 1; i >= 0; i -= 1) {
20
+ if ('。!?…;'.includes(window[i] ?? '')) { cut = i + 1; break }
21
+ }
22
+ }
23
+ if (cut === 0) cut = max
24
+ parts.push(rest.slice(0, cut).join(''))
25
+ rest = rest.slice(cut)
26
+ }
27
+ if (parts.length <= 1) return parts
28
+ return parts.map((part, index) => `(${index + 1}/${parts.length})${part}`)
29
+ }
@@ -0,0 +1,55 @@
1
+ /** 统一渠道契约。 */
2
+ export interface ImMedia {
3
+ kind: 'image' | 'voice-text' | 'file' | 'video'
4
+ data?: Uint8Array
5
+ mediaType?: string
6
+ name?: string
7
+ text?: string
8
+ path?: string
9
+ }
10
+
11
+ export interface ImMessage {
12
+ chatId: string
13
+ userId?: string
14
+ username?: string
15
+ text: string
16
+ kind?: 'dm' | 'group'
17
+ addressed?: boolean
18
+ messageId?: string
19
+ context?: Record<string, unknown>
20
+ media?: ImMedia[]
21
+ }
22
+
23
+ export interface ReplyStream {
24
+ update(text: string): Promise<void>
25
+ finish(text: string): Promise<void>
26
+ }
27
+
28
+ export interface ChannelAdapter {
29
+ readonly id: string
30
+ readonly label: string
31
+ readonly maxMessageLength: number
32
+ start(): void | Promise<void>
33
+ stop(): void | Promise<void>
34
+ send(chatId: string, text: string): Promise<void>
35
+ setMessageHandler(handler: (msg: ImMessage) => void | Promise<void>): void
36
+ status(): string
37
+ loginUrl?(): string | undefined
38
+ sendAction?(chatId: string, action: 'typing'): Promise<void>
39
+ sendMedia?(chatId: string, filePath: string, caption?: string): Promise<void>
40
+ authorizes?(userId: string): boolean | undefined
41
+ beginReply?(chatId: string): Promise<ReplyStream>
42
+ /** 企业微信等回调通道不能等合并窗口,必须立刻处理。 */
43
+ skipMerge?: boolean
44
+ }
45
+
46
+ export interface EngineConfig {
47
+ cwd: string
48
+ provider: string
49
+ model: string
50
+ agentPreset: string
51
+ allowAllUsers: boolean
52
+ mergeTimeoutSecs: number
53
+ permissionPreset: 'read-only' | 'workspace-write' | 'full-access'
54
+ reasoningEffort?: string
55
+ }
package/src/index.ts ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * dsh-im-connect Host:IM 助理。
3
+ */
4
+ import type { Context } from '@deepseek-ai/cordis'
5
+ import Schema from '@deepseek-ai/schemastery'
6
+ import { homedir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import { mkdirSync, writeFileSync } from 'node:fs'
9
+ import { ChannelManager } from './manager.js'
10
+ import type { EngineConfig } from './engine/types.js'
11
+
12
+ export const name = 'dsh-im-connect'
13
+ export const inject = ['webServer', 'credentials', 'agents', 'agentPresets', 'agentDefaultModel', 'llm']
14
+
15
+ export interface PluginConfig {
16
+ stateDir: string
17
+ cwd: string
18
+ provider: string
19
+ model: string
20
+ agentPreset: string
21
+ allowAllUsers: boolean
22
+ mergeTimeoutSecs: number
23
+ }
24
+
25
+ export const Config: Schema<PluginConfig> = Schema.object({
26
+ stateDir: Schema.string().default(''),
27
+ cwd: Schema.string().default(process.cwd()),
28
+ provider: Schema.string().default(''),
29
+ model: Schema.string().default(''),
30
+ agentPreset: Schema.string().default('standard'),
31
+ allowAllUsers: Schema.boolean().default(true),
32
+ mergeTimeoutSecs: Schema.number().default(5),
33
+ })
34
+
35
+ export function apply(ctx: Context, config: PluginConfig): void {
36
+ const stateDir = config.stateDir !== ''
37
+ ? config.stateDir
38
+ : join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'dsh-im-connect')
39
+ mkdirSync(stateDir, { recursive: true })
40
+ const logFile = join(stateDir, 'gateway.log')
41
+ const log = (line: string) => {
42
+ const stamped = `${new Date().toISOString()} ${line}`
43
+ ctx.logger(name).info(line)
44
+ try { writeFileSync(logFile, `${stamped}\n`, { flag: 'a' }) } catch { /* 忽略 */ }
45
+ }
46
+
47
+ const engineConfig: EngineConfig = {
48
+ cwd: config.cwd || process.cwd(),
49
+ provider: config.provider,
50
+ model: config.model,
51
+ agentPreset: config.agentPreset || 'standard',
52
+ allowAllUsers: config.allowAllUsers,
53
+ mergeTimeoutSecs: config.mergeTimeoutSecs || 5,
54
+ permissionPreset: 'full-access',
55
+ }
56
+
57
+ const applyStarted = Date.now()
58
+ const manager = new ChannelManager({ ctx, stateDir, log, engineConfig })
59
+ log(`[boot] ChannelManager 构造 ${Date.now() - applyStarted}ms`)
60
+ ctx.effect(() => {
61
+ manager.registerApi(ctx)
62
+ void manager.initEnabled().finally(() => { void manager.attachMappedSessions() })
63
+ log(`[boot] apply 完成 ${Date.now() - applyStarted}ms`)
64
+ return () => { manager.disposeApi() }
65
+ }, 'im-connect.serve')
66
+ }
67
+
68
+ export { CHANNEL_META, CHANNEL_ORDER, listChannelMeta } from './channels/meta.js'
69
+ export {
70
+ IM_ORIGIN,
71
+ IM_SESSION_PREFIX,
72
+ createImSessionId,
73
+ isImOrigin,
74
+ isImSessionId,
75
+ isTaskSession,
76
+ sessionKeyOf,
77
+ } from './engine/session-id.js'
78
+ export { splitText } from './engine/split.js'
79
+
80
+
81
+