@michengai/dsh-im-connect 0.1.39 → 0.1.41

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 (70) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/CHANGELOG.zh-CN.md +18 -0
  3. package/README.en.md +27 -7
  4. package/README.md +29 -9
  5. package/client.js +168 -100
  6. package/lib/channels/dingtalk.d.ts.map +1 -1
  7. package/lib/channels/dingtalk.js +4 -2
  8. package/lib/channels/dingtalk.js.map +1 -1
  9. package/lib/client.js +168 -100
  10. package/lib/engine/chat-commands.d.ts +30 -0
  11. package/lib/engine/chat-commands.d.ts.map +1 -0
  12. package/lib/engine/chat-commands.js +451 -0
  13. package/lib/engine/chat-commands.js.map +1 -0
  14. package/lib/engine/command-locale.d.ts +6 -0
  15. package/lib/engine/command-locale.d.ts.map +1 -0
  16. package/lib/engine/command-locale.js +21 -0
  17. package/lib/engine/command-locale.js.map +1 -0
  18. package/lib/engine/command-messages.d.ts +214 -0
  19. package/lib/engine/command-messages.d.ts.map +1 -0
  20. package/lib/engine/command-messages.js +214 -0
  21. package/lib/engine/command-messages.js.map +1 -0
  22. package/lib/engine/command-permissions.d.ts +15 -0
  23. package/lib/engine/command-permissions.d.ts.map +1 -0
  24. package/lib/engine/command-permissions.js +39 -0
  25. package/lib/engine/command-permissions.js.map +1 -0
  26. package/lib/engine/command-replies.d.ts +12 -0
  27. package/lib/engine/command-replies.d.ts.map +1 -0
  28. package/lib/engine/command-replies.js +36 -0
  29. package/lib/engine/command-replies.js.map +1 -0
  30. package/lib/engine/gateway.d.ts +6 -1
  31. package/lib/engine/gateway.d.ts.map +1 -1
  32. package/lib/engine/gateway.js +70 -33
  33. package/lib/engine/gateway.js.map +1 -1
  34. package/lib/engine/merge.d.ts +2 -0
  35. package/lib/engine/merge.d.ts.map +1 -1
  36. package/lib/engine/merge.js +2 -0
  37. package/lib/engine/merge.js.map +1 -1
  38. package/lib/engine/router.d.ts +19 -5
  39. package/lib/engine/router.d.ts.map +1 -1
  40. package/lib/engine/router.js +231 -61
  41. package/lib/engine/router.js.map +1 -1
  42. package/lib/engine/session-id.d.ts +7 -0
  43. package/lib/engine/session-id.d.ts.map +1 -1
  44. package/lib/engine/session-id.js.map +1 -1
  45. package/lib/engine/session-store.d.ts +6 -0
  46. package/lib/engine/session-store.d.ts.map +1 -1
  47. package/lib/engine/session-store.js +58 -1
  48. package/lib/engine/session-store.js.map +1 -1
  49. package/lib/engine/session-title.d.ts +8 -0
  50. package/lib/engine/session-title.d.ts.map +1 -0
  51. package/lib/engine/session-title.js +30 -0
  52. package/lib/engine/session-title.js.map +1 -0
  53. package/lib/manager.d.ts +7 -0
  54. package/lib/manager.d.ts.map +1 -1
  55. package/lib/manager.js +57 -9
  56. package/lib/manager.js.map +1 -1
  57. package/package.json +1 -1
  58. package/src/channels/dingtalk.ts +4 -2
  59. package/src/engine/chat-commands.ts +404 -0
  60. package/src/engine/command-locale.ts +20 -0
  61. package/src/engine/command-messages.ts +297 -0
  62. package/src/engine/command-permissions.ts +35 -0
  63. package/src/engine/command-replies.ts +37 -0
  64. package/src/engine/gateway.ts +59 -33
  65. package/src/engine/merge.ts +4 -0
  66. package/src/engine/router.ts +205 -60
  67. package/src/engine/session-id.ts +7 -0
  68. package/src/engine/session-store.ts +50 -1
  69. package/src/engine/session-title.ts +25 -0
  70. package/src/manager.ts +56 -10
@@ -1,11 +1,12 @@
1
1
  import type { Context } from '@deepseek-ai/cordis'
2
2
  import type { ChannelInstanceId, ChatKind, SessionRecord } from './session-id.js'
3
- import { createImSessionId, sessionKeyOf } from './session-id.js'
3
+ import { createImSessionId, parseImSessionId, sessionKeyOf } from './session-id.js'
4
4
  import { SessionMapStore } from './session-store.js'
5
5
  import { readHostDefaultModel, resolveImAgentOptions } from './agent-options.js'
6
6
  import type { EngineConfig } from './types.js'
7
7
  import { KeyedSerialQueue } from './keyed-queue.js'
8
8
  import { sameWorkspacePath } from './workspace-path.js'
9
+ import { readSessionTitle } from './session-title.js'
9
10
 
10
11
  const DEFAULT_DISPOSE_TIMEOUT_MS = 10_000
11
12
 
@@ -19,7 +20,7 @@ export interface ChatBinding {
19
20
  }
20
21
 
21
22
  type WorkspaceLookup = {
22
- list(): Array<{ path: string; attachSession(sessionId: string): Promise<void> }>
23
+ list(): Array<{ path: string; sessionIds?: readonly string[]; attachSession(sessionId: string): Promise<void> }>
23
24
  archivedSessionIds?: readonly string[]
24
25
  }
25
26
 
@@ -43,6 +44,7 @@ type AgentHost = Context & {
43
44
 
44
45
  export class SessionRouter {
45
46
  private readonly live = new Map<string, ChatBinding>()
47
+ private readonly historical = new Map<string, ChatBinding>()
46
48
  private readonly reloadDisposed = new Set<string>()
47
49
  private readonly channelOperations = new KeyedSerialQueue()
48
50
  private readonly disposeTimeoutMs: number
@@ -98,11 +100,11 @@ export class SessionRouter {
98
100
  ])]
99
101
  }
100
102
 
101
- async getOrCreate(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string, options?: { rebuildMissing?: boolean }): Promise<ChatBinding> {
102
- return this.channelOperations.run(channelId, () => this.getOrCreateNow(channelId, kind, chatId, title, options))
103
+ async getOrCreate(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string): Promise<ChatBinding> {
104
+ return this.channelOperations.run(channelId, () => this.getOrCreateNow(channelId, kind, chatId, title))
103
105
  }
104
106
 
105
- private async getOrCreateNow(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string, options?: { rebuildMissing?: boolean }): Promise<ChatBinding> {
107
+ private async getOrCreateNow(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string): Promise<ChatBinding> {
106
108
  const key = sessionKeyOf(channelId, kind, chatId)
107
109
  const live = this.live.get(key)
108
110
  if (live?.handle) {
@@ -123,13 +125,9 @@ export class SessionRouter {
123
125
  this.live.set(key, resumed)
124
126
  return resumed
125
127
  }
126
- if (options?.rebuildMissing) {
127
- try {
128
- return await this.create(channelId, kind, chatId, title, saved.sessionId)
129
- } catch (error) {
130
- if (!isIdCollision(error)) throw error
131
- this.log(`[router] 原 id 与磁盘日志冲突,改新建 ${saved.sessionId}`)
132
- }
128
+ const known = await this.knownSessionIds()
129
+ if (known === undefined || known.has(saved.sessionId)) {
130
+ throw new Error('当前会话暂时无法恢复,已保留原绑定,请稍后重试。')
133
131
  }
134
132
  this.log(`[router] 无法恢复会话,轮换 ${saved.sessionId}`)
135
133
  return this.rotateNow(channelId, kind, chatId, title)
@@ -137,25 +135,79 @@ export class SessionRouter {
137
135
  return this.create(channelId, kind, chatId, title)
138
136
  }
139
137
 
140
- async rotate(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string): Promise<ChatBinding> {
141
- return this.channelOperations.run(channelId, () => this.rotateNow(channelId, kind, chatId, title))
138
+ async rotate(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string, options?: { cwd?: string; signal?: AbortSignal }): Promise<ChatBinding> {
139
+ return this.channelOperations.run(channelId, () => this.rotateNow(channelId, kind, chatId, title, options))
142
140
  }
143
141
 
144
- private async rotateNow(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string): Promise<ChatBinding> {
142
+ private async rotateNow(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string, options?: { cwd?: string; signal?: AbortSignal }): Promise<ChatBinding> {
145
143
  const key = sessionKeyOf(channelId, kind, chatId)
146
144
  const old = this.live.get(key)
147
- if (old?.handle) await this.disposeHandle(old)
148
- this.live.delete(key)
149
- this.store.remove(key)
150
- return this.create(channelId, kind, chatId, title)
145
+ const record = this.store.get(key)
146
+ const cwd = options?.cwd || (record ? await this.sessionWorkspace(record) : undefined)
147
+ options?.signal?.throwIfAborted()
148
+ // 新会话准备成功后才替换当前映射,失败时旧句柄仍可继续使用。
149
+ const next = await this.create(channelId, kind, chatId, title, cwd, options?.signal)
150
+ // dispose 会触发宿主 api-session/removed,导致未刷新的网页拒绝打开历史。
151
+ // 轮换只转入历史,句柄在渠道停用或插件重载时统一释放。
152
+ if (old) this.historical.set(old.sessionId, old)
153
+ return next
154
+ }
155
+
156
+ private async sessionWorkspace(record: SessionRecord): Promise<string | undefined> {
157
+ if (record.cwd) return record.cwd
158
+ const registry = this.ctx.get?.('workspaceRegistry') as WorkspaceLookup | undefined
159
+ const workspace = registry?.list?.().find(item => item.sessionIds?.includes(record.sessionId))
160
+ if (workspace) return workspace.path
161
+ const controller = this.ctx.get?.('sessionController') as unknown as { list(request: object): Promise<{ items: Array<{ sessionId: string; cwd?: string }> }> } | undefined
162
+ if (controller?.list) {
163
+ const row = (await controller.list({})).items.find(item => item.sessionId === record.sessionId)
164
+ if (row?.cwd) return row.cwd
165
+ }
166
+ if (record.adopted) throw new Error('无法确定当前会话工作区,请使用 /workspace 重新选择。')
167
+ return undefined
151
168
  }
152
169
 
153
170
  rename(sessionId: string, title: string): boolean {
171
+ return this.setTitle(sessionId, title, 'user')
172
+ }
173
+
174
+ isAdopted(sessionId: string): boolean { return this.store.list().some(record => record.sessionId === sessionId && record.adopted) }
175
+
176
+ /** 只返回是否占用,不向列表暴露其他聊天身份。 */
177
+ isBoundElsewhere(sessionId: string, channelId: string, kind: ChatKind, chatId: string): boolean {
178
+ const key = sessionKeyOf(channelId, kind, chatId)
179
+ return this.store.list().some(item => item.sessionId === sessionId && sessionKeyOf(item.channel, item.kind, item.chatId) !== key)
180
+ }
181
+
182
+ /** 显式换绑保留旧历史与运行句柄,不改变 Host 会话的归属或默认配置。 */
183
+ async bind(channelId: string, kind: ChatKind, chatId: string, sessionId: string, title: string, agent: unknown, cwd?: string, signal?: AbortSignal): Promise<void> {
184
+ await this.channelOperations.run(channelId, async () => {
185
+ const key = sessionKeyOf(channelId, kind, chatId)
186
+ signal?.throwIfAborted()
187
+ const other = this.isBoundElsewhere(sessionId, channelId, kind, chatId)
188
+ if (other) throw Object.assign(new Error('该会话已关联其他聊天,不能重复绑定。'), { code: 'im/session-in-use' })
189
+ const old = this.live.get(key)
190
+ const previous = this.store.list().find(item => item.sessionId === sessionId)
191
+ this.store.upsert(key, { ...previous, channel: channelId, kind, chatId, sessionId, title: previous?.titleSource === 'user' ? previous.title : title, ...(cwd ? { cwd } : {}), adopted: true, updatedAt: new Date().toISOString() })
192
+ if (old && old.sessionId !== sessionId) this.historical.set(old.sessionId, old)
193
+ const binding = this.historical.get(sessionId) ?? { key, channelId, kind, chatId, sessionId, handle: { agent, dispose: async () => {} } }
194
+ this.historical.delete(sessionId)
195
+ this.live.set(key, binding)
196
+ })
197
+ }
198
+
199
+ setTitle(sessionId: string, title: string, source: 'message' | 'host' | 'user'): boolean {
154
200
  const rec = this.store.list().find((item) => item.sessionId === sessionId)
155
201
  if (!rec) return false
156
- this.store.upsert(sessionKeyOf(rec.channel, rec.kind, rec.chatId), {
202
+ const acceptsInitialMessage = rec.titleSource === 'pending' || (!rec.titleSource && !rec.title.trim())
203
+ if (!title.trim()
204
+ || (source === 'message' && !acceptsInitialMessage)
205
+ || (source === 'host' && rec.titleSource === 'user')) return false
206
+ if (rec.title === title && rec.titleSource === source) return true
207
+ this.store.updateSession({
157
208
  ...rec,
158
209
  title,
210
+ titleSource: source,
159
211
  updatedAt: new Date().toISOString(),
160
212
  })
161
213
  return true
@@ -167,7 +219,7 @@ export class SessionRouter {
167
219
  let removed = 0
168
220
  for (const rec of this.store.list()) {
169
221
  if (known.has(rec.sessionId)) continue
170
- await this.remove(rec.sessionId)
222
+ await this.channelOperations.run(rec.channel, () => this.removeFromChannel(rec.sessionId, false))
171
223
  removed += 1
172
224
  }
173
225
  if (removed > 0) this.log(`[router] 已清理 ${removed} 条宿主已删除的频道映射`)
@@ -181,7 +233,8 @@ export class SessionRouter {
181
233
  const persistence = this.ctx.get?.('sessionPersistence') as { list?: () => Promise<readonly { readonly id: string }[]> } | undefined
182
234
  const canListLive = typeof live?.list === "function"
183
235
  const canListStored = typeof persistence?.list === "function"
184
- if (!canListLive && !canListStored) return undefined
236
+ // 仅凭活会话列表不能判断已卸载的历史日志是否被删除。
237
+ if (!canListStored) return undefined
185
238
  const ids = new Set<string>()
186
239
  if (canListLive && live.list) {
187
240
  for (const session of live.list()) ids.add(String(session.id))
@@ -198,25 +251,46 @@ export class SessionRouter {
198
251
  async ensure(sessionId: string): Promise<boolean> {
199
252
  const rec = this.store.list().find((item) => item.sessionId === sessionId)
200
253
  if (!rec) return false
201
- await this.getOrCreate(rec.channel, rec.kind, rec.chatId, rec.title, { rebuildMissing: true })
202
- return true
254
+ return this.channelOperations.run(rec.channel, async () => {
255
+ if (this.isArchived(sessionId)) return false
256
+ const key = sessionKeyOf(rec.channel, rec.kind, rec.chatId)
257
+ const current = this.live.get(key)
258
+ if (this.historical.has(sessionId) || (current?.sessionId === sessionId && current.handle)) return true
259
+ const binding = await this.resume(rec)
260
+ if (!binding) return false
261
+ if (this.store.get(key)?.sessionId === sessionId) this.live.set(key, binding)
262
+ else this.historical.set(sessionId, binding)
263
+ return true
264
+ })
203
265
  }
204
266
 
205
267
  async disposeAll(): Promise<void> {
206
- const channels = [...new Set([...this.live.values()].map((item) => item.channelId))]
268
+ const channels = [...new Set([...this.live.values(), ...this.historical.values()].map((item) => item.channelId))]
207
269
  await Promise.all(channels.map((channelId) => this.disposeChannel(channelId)))
208
270
  this.live.clear()
271
+ this.historical.clear()
209
272
  }
210
273
 
211
- /** 配置重载触发的 dispose 只卸活句柄;归档/宿主删除才清映射。 */
274
+ /** 卸载不代表删除日志;只有可靠确认日志不存在才清除索引。 */
212
275
  async onHostDisposed(sessionId: string): Promise<boolean> {
213
276
  if (this.reloadDisposed.delete(sessionId)) {
277
+ this.historical.delete(sessionId)
278
+ for (const [key, item] of this.live) {
279
+ if (item.sessionId === sessionId) this.live.delete(key)
280
+ }
281
+ return false
282
+ }
283
+ const known = await this.knownSessionIds()
284
+ if (known === undefined || known.has(sessionId)) {
285
+ this.historical.delete(sessionId)
214
286
  for (const [key, item] of this.live) {
215
287
  if (item.sessionId === sessionId) this.live.delete(key)
216
288
  }
217
289
  return false
218
290
  }
219
- return this.remove(sessionId)
291
+ const record = this.store.list().find(item => item.sessionId === sessionId)
292
+ if (!record) return false
293
+ return this.channelOperations.run(record.channel, () => this.removeFromChannel(sessionId, false))
220
294
  }
221
295
 
222
296
  followup(binding: ChatBinding, message: unknown): void {
@@ -236,12 +310,18 @@ export class SessionRouter {
236
310
  // 工作区属于会话创建参数,不能拿旧 sessionId 在新目录恢复;仅解除映射,保留 Host 中的历史日志。
237
311
  for (const record of this.store.list()) {
238
312
  if (record.channel !== channelId) continue
239
- this.store.remove(sessionKeyOf(record.channel, record.kind, record.chatId))
313
+ this.store.retain(sessionKeyOf(record.channel, record.kind, record.chatId))
240
314
  }
241
315
  })
242
316
  }
243
317
 
244
318
  private async disposeChannelNow(channelId: string): Promise<void> {
319
+ for (const [id, item] of this.historical) {
320
+ if (item.channelId !== channelId) continue
321
+ this.reloadDisposed.add(id)
322
+ await this.disposeHandle(item)
323
+ this.historical.delete(id)
324
+ }
245
325
  const entries = [...this.live].filter(([, item]) => item.channelId === channelId)
246
326
  for (const [, item] of entries) this.reloadDisposed.add(item.sessionId)
247
327
  await Promise.all(entries.map(async ([key, item]) => {
@@ -269,14 +349,21 @@ export class SessionRouter {
269
349
  if (result === 'timed-out') this.log(`[router] 卸载会话超时 ${item.sessionId},已解除本地引用`)
270
350
  }
271
351
 
272
- private async removeFromChannel(sessionId: string): Promise<boolean> {
352
+ private async removeFromChannel(sessionId: string, retainArchived = true): Promise<boolean> {
273
353
  const rec = this.store.list().find((item) => item.sessionId === sessionId)
274
354
  if (!rec) return false
275
355
  const key = sessionKeyOf(rec.channel, rec.kind, rec.chatId)
276
- const live = this.live.get(key)
277
- if (live?.handle) await this.disposeHandle(live)
278
- this.live.delete(key)
279
- this.store.remove(key)
356
+ const current = this.live.get(key)
357
+ const live = current?.sessionId === sessionId ? current : this.historical.get(sessionId)
358
+ if (live?.handle) {
359
+ this.reloadDisposed.add(sessionId)
360
+ await this.disposeHandle(live)
361
+ }
362
+ if (current?.sessionId === sessionId) this.live.delete(key)
363
+ this.historical.delete(sessionId)
364
+ if (retainArchived && this.isArchived(sessionId)) {
365
+ if (this.store.get(key)?.sessionId === sessionId) this.store.retain(key)
366
+ } else this.store.removeSession(sessionId)
280
367
  return true
281
368
  }
282
369
 
@@ -286,20 +373,36 @@ export class SessionRouter {
286
373
  return this.channelOperations.run(rec.channel, () => this.removeFromChannel(sessionId))
287
374
  }
288
375
 
376
+ /** 归档失败后,仅在可靠确认日志缺失时清理残留索引。 */
377
+ async cleanupMissing(sessionId: string): Promise<boolean> {
378
+ const rec = this.store.list().find(item => item.sessionId === sessionId)
379
+ if (!rec) return true
380
+ return this.channelOperations.run(rec.channel, async () => {
381
+ const persistence = this.ctx.get?.('sessionPersistence') as { list?: () => Promise<readonly { id: string }[]> } | undefined
382
+ if (!persistence?.list) return false
383
+ try {
384
+ if ((await persistence.list()).some(item => item.id === sessionId)) return false
385
+ } catch { return false }
386
+ return this.removeFromChannel(sessionId, false)
387
+ })
388
+ }
389
+
289
390
  private samePath(left: string, right: string): boolean {
290
391
  return sameWorkspacePath(left, right)
291
392
  }
292
393
 
293
- private async create(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string, preferredSessionId?: string): Promise<ChatBinding> {
394
+ private async create(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string, cwd?: string, signal?: AbortSignal): Promise<ChatBinding> {
294
395
  const key = sessionKeyOf(channelId, kind, chatId)
295
- const sessionId = preferredSessionId || createImSessionId(channelId, kind, chatId)
296
- let handle: Awaited<ReturnType<SessionRouter['createHandle']>>
396
+ const sessionId = createImSessionId(channelId, kind, chatId)
397
+ const config = { ...this.resolveConfig(channelId), ...(cwd ? { cwd } : {}) }
398
+ const handle = await this.createHandle(sessionId, channelId, config)
297
399
  try {
298
- handle = await this.createHandle(sessionId, channelId)
400
+ signal?.throwIfAborted()
401
+ await this.attachWorkspace(sessionId, channelId, config.cwd, true)
402
+ signal?.throwIfAborted()
299
403
  } catch (error) {
300
- if (!preferredSessionId || !isIdCollision(error)) throw error
301
- this.log(`[router] 创建冲突,改用新 id ${sessionId}`)
302
- return this.create(channelId, kind, chatId, title)
404
+ await this.disposeHandle({ key, channelId, kind, chatId, sessionId, handle })
405
+ throw error
303
406
  }
304
407
  const record: SessionRecord = {
305
408
  sessionId,
@@ -307,19 +410,35 @@ export class SessionRouter {
307
410
  kind,
308
411
  chatId,
309
412
  title,
413
+ titleSource: 'pending',
414
+ agentPreset: config.agentPreset || 'standard',
415
+ cwd: config.cwd || process.cwd(),
310
416
  updatedAt: new Date().toISOString(),
311
417
  }
312
- this.store.upsert(key, record)
418
+ try {
419
+ this.store.upsert(key, record)
420
+ } catch (error) {
421
+ await this.disposeHandle({ key, channelId, kind, chatId, sessionId, handle })
422
+ throw error
423
+ }
313
424
  const binding: ChatBinding = { key, channelId, kind, chatId, sessionId, handle }
314
425
  this.live.set(key, binding)
315
- await this.attachWorkspace(sessionId, channelId)
316
426
  this.log(`[router] 新建 IM 会话 ${sessionId}`)
317
427
  return binding
318
428
  }
319
429
 
320
430
  private async resume(record: SessionRecord): Promise<ChatBinding | undefined> {
431
+ if (record.adopted) {
432
+ const controller = this.ctx.get?.('sessionController') as unknown as { resolveAgent(id: string): Promise<{ agent?: unknown }> } | undefined
433
+ if (!controller?.resolveAgent) return undefined
434
+ const result = await controller.resolveAgent(record.sessionId)
435
+ if (!result.agent) return undefined
436
+ return { key: sessionKeyOf(record.channel, record.kind, record.chatId), channelId: record.channel, kind: record.kind, chatId: record.chatId,
437
+ sessionId: record.sessionId, handle: { agent: result.agent, dispose: async () => {} } }
438
+ }
321
439
  const liveAgent = this.ctx.agents?.get?.(record.sessionId)
322
440
  if (liveAgent) {
441
+ this.syncStoredTitle(record.sessionId, liveAgent)
323
442
  const binding: ChatBinding = {
324
443
  key: sessionKeyOf(record.channel, record.kind, record.chatId),
325
444
  channelId: record.channel,
@@ -327,7 +446,7 @@ export class SessionRouter {
327
446
  chatId: record.chatId,
328
447
  sessionId: record.sessionId,
329
448
  }
330
- await this.attachWorkspace(record.sessionId, record.channel)
449
+ await this.attachWorkspace(record.sessionId, record.channel, record.cwd)
331
450
  return binding
332
451
  }
333
452
  if (!this.ctx.agents?.resume) return undefined
@@ -338,9 +457,10 @@ export class SessionRouter {
338
457
  ...this.resolveAgentOptions(record.channel),
339
458
  ...(this.resolveConfig(record.channel).reasoningEffort ? { reasoningEffort: this.resolveConfig(record.channel).reasoningEffort } : {}),
340
459
  },
341
- setup: this.presetSetup(record.channel),
460
+ setup: this.presetSetup(record.channel, record.agentPreset, true),
342
461
  })
343
- await this.attachWorkspace(record.sessionId, record.channel)
462
+ this.syncStoredTitle(record.sessionId, handle.agent)
463
+ await this.attachWorkspace(record.sessionId, record.channel, record.cwd)
344
464
  return {
345
465
  key: sessionKeyOf(record.channel, record.kind, record.chatId),
346
466
  channelId: record.channel,
@@ -355,13 +475,12 @@ export class SessionRouter {
355
475
  }
356
476
  }
357
477
 
358
- private async createHandle(sessionId: string, channelId: string) {
478
+ private async createHandle(sessionId: string, channelId: string, config: EngineConfig = this.resolveConfig(channelId)) {
359
479
  const agents = this.ctx.agents
360
480
  if (!agents?.create) throw new Error('当前 Host 没有 agents 服务,无法创建 IM 会话')
361
481
  // IM 保持普通会话(不设置 subagent origin);Chat prompt 会拒绝子代理所有权。
362
482
  // IM 与任务的区分靠 sessionId 的 im: 前缀。
363
483
  // 必须带上当前默认模型,否则 deployment:persona 的 {{model}} 组装会失败。
364
- const config = this.resolveConfig(channelId)
365
484
  const agentOptions = this.resolveAgentOptions(channelId)
366
485
  this.log(`[router] ${channelId} 使用模型 ${agentOptions.provider}/${agentOptions.model}${config.reasoningEffort ? ` ${config.reasoningEffort}` : ''}`)
367
486
  const create = () => agents.create({
@@ -398,13 +517,40 @@ export class SessionRouter {
398
517
 
399
518
  async attachMappedSessions(): Promise<void> {
400
519
  const started = Date.now()
520
+ await this.recoverHistory()
401
521
  await this.pruneMissingSessions()
402
522
  for (const record of this.store.list()) {
403
- await this.attachWorkspace(record.sessionId, record.channel)
523
+ if (record.adopted || this.isArchived(record.sessionId)) continue
524
+ await this.attachWorkspace(record.sessionId, record.channel, record.cwd)
404
525
  }
405
526
  this.log(`[boot] attachMappedSessions ${Date.now() - started}ms`)
406
527
  }
407
528
 
529
+ private syncStoredTitle(sessionId: string, agent: unknown): void {
530
+ const session = (agent as { session?: { snapshotEvents?: () => readonly { type: string; data?: unknown }[]; events?: readonly { type: string; data?: unknown }[] } } | undefined)?.session
531
+ const events = session?.snapshotEvents?.() ?? session?.events ?? []
532
+ const latest = readSessionTitle(events.findLast(event => event.type === 'session/title')?.data)
533
+ if (latest) this.setTitle(sessionId, latest.title, latest.source)
534
+ }
535
+
536
+ private async recoverHistory(): Promise<void> {
537
+ try {
538
+ const persistence = this.ctx.get?.('sessionPersistence') as { list?: () => Promise<readonly { id: string; createdAt?: number; cwd?: string }[]> } | undefined
539
+ if (!persistence?.list) return
540
+ for (const header of await persistence.list()) {
541
+ const parsed = parseImSessionId(header.id)
542
+ if (!parsed) continue
543
+ this.store.saveHistory({
544
+ sessionId: header.id, ...parsed,
545
+ title: parsed.chatId, ...(header.cwd ? { cwd: header.cwd } : {}),
546
+ updatedAt: new Date(Number.isFinite(header.createdAt) ? header.createdAt! : 0).toISOString(),
547
+ })
548
+ }
549
+ } catch (error) {
550
+ this.log(`[router] 恢复历史索引失败: ${error instanceof Error ? error.message : String(error)}`)
551
+ }
552
+ }
553
+
408
554
  private isArchived(sessionId: string): boolean {
409
555
  try {
410
556
  const ids = this.ctx.get?.('workspaceRegistry')?.archivedSessionIds
@@ -415,7 +561,7 @@ export class SessionRouter {
415
561
  }
416
562
  }
417
563
 
418
- private async attachWorkspace(sessionId: string, channelId: string): Promise<void> {
564
+ private async attachWorkspace(sessionId: string, channelId: string, cwd?: string, strict = false): Promise<void> {
419
565
  let workspaces: Array<{ path: string; attachSession(sessionId: string): Promise<void> }> = []
420
566
  try {
421
567
  workspaces = this.ctx.get?.('workspaceRegistry')?.list?.() ?? []
@@ -426,14 +572,14 @@ export class SessionRouter {
426
572
  this.log(`[router] 当前没有工作区,网页点不开会话 ${sessionId}`)
427
573
  return
428
574
  }
429
- const preferred = this.resolveConfig(channelId).cwd || process.cwd()
575
+ const preferred = cwd || this.resolveConfig(channelId).cwd || process.cwd()
430
576
  const ordered = [...workspaces].sort((left, right) => {
431
577
  const leftHit = this.samePath(left.path, preferred) ? 0 : 1
432
578
  const rightHit = this.samePath(right.path, preferred) ? 0 : 1
433
579
  return leftHit - rightHit
434
580
  })
435
581
  let lastError = ''
436
- for (const workspace of ordered) {
582
+ for (const workspace of ordered.filter(item => !cwd || this.samePath(item.path, preferred))) {
437
583
  try {
438
584
  await workspace.attachSession(sessionId)
439
585
  this.log(`[router] 已把 ${sessionId} 挂到工作区 ${workspace.path}`)
@@ -442,6 +588,7 @@ export class SessionRouter {
442
588
  lastError = error instanceof Error ? error.message : String(error)
443
589
  }
444
590
  }
591
+ if (strict) throw new Error(`挂载会话失败 ${sessionId}: ${lastError || '目标工作区不可用'}`)
445
592
  this.log(`[router] 挂载会话失败 ${sessionId}: ${lastError}`)
446
593
  }
447
594
 
@@ -454,18 +601,22 @@ export class SessionRouter {
454
601
  })
455
602
  }
456
603
 
457
- private presetSetup(channelId: string) {
604
+ private presetSetup(channelId: string, savedPreset?: string, restoring = false) {
458
605
  const ctx = this.ctx
459
606
  const config = this.resolveConfig(channelId)
460
- const preset = config.agentPreset || 'standard'
607
+ const preset = savedPreset || config.agentPreset || 'standard'
461
608
  const permission = config.permissionPreset
462
609
  return async (agentCtx: unknown) => {
610
+ const session = (agentCtx as { agent?: { session?: { snapshotEvents?: () => readonly { type: string }[]; events?: readonly { type: string }[] } } }).agent?.session
611
+ const events = session?.snapshotEvents?.() ?? session?.events
612
+ // 在挂载前读取历史;来源不可读取时也不冒险覆盖已有权限。
613
+ const preservePermission = restoring && (!events || events.some(event => ['permission/preset', 'sandbox/mode', 'approval/policy'].includes(event.type)))
463
614
  if (ctx.agentPresets?.mount) await ctx.agentPresets.mount(agentCtx, preset)
464
615
  // Account defaults belong in agentOptions (including on legacy Hosts),
465
616
  // not a second installModelSelection middleware. Its outer after-next
466
617
  // override would defeat Chat's session selection and image admission.
467
618
  // New sessions also persist their initial selection in createHandle().
468
- if (permission) {
619
+ if (permission && !preservePermission) {
469
620
  try {
470
621
  const agent = (agentCtx as { agent?: { session?: unknown } }).agent
471
622
  const permissionPresets = ctx.permissionPresets
@@ -478,9 +629,3 @@ export class SessionRouter {
478
629
  }
479
630
  }
480
631
  }
481
-
482
-
483
- function isIdCollision(error: unknown): boolean {
484
- const message = error instanceof Error ? error.message : String(error)
485
- return message.includes('id collision') || message.includes('already has a persisted log')
486
- }
@@ -8,11 +8,18 @@ export type ChannelInstanceId = string
8
8
  export type ChatKind = 'dm' | 'group'
9
9
 
10
10
  export interface SessionRecord {
11
+ /** 已通过 Host 接入的会话;恢复时不能套用机器人默认配置。 */
12
+ adopted?: boolean
13
+ agentPreset?: string
14
+ /** 创建或接续时的工作区,轮换不跟随账号默认值漂移。 */
15
+ cwd?: string
11
16
  sessionId: string
12
17
  channel: ChannelInstanceId
13
18
  kind: ChatKind
14
19
  chatId: string
15
20
  title: string
21
+ /** pending 仅用于新会话占位名称;缺省表示旧数据来源未知。 */
22
+ titleSource?: 'pending' | 'message' | 'host' | 'user'
16
23
  updatedAt: string
17
24
  }
18
25
 
@@ -1,10 +1,11 @@
1
- import { readFileSync } from 'node:fs'
1
+ import { constants, copyFileSync, readFileSync } from 'node:fs'
2
2
  import type { SessionRecord } from './session-id.js'
3
3
  import { backupCorruptFileSync, writeFileAtomicSync } from './atomic-file.js'
4
4
 
5
5
  export class SessionMapStore {
6
6
  private readonly file: string
7
7
  private records: Record<string, SessionRecord> = {}
8
+ private historyBackupTaken = false
8
9
 
9
10
  constructor(file: string) {
10
11
  this.file = file
@@ -20,7 +21,44 @@ export class SessionMapStore {
20
21
  }
21
22
 
22
23
  upsert(key: string, record: SessionRecord): void {
24
+ const before = { ...this.records }
25
+ const old = this.records[key]
26
+ if (old && old.sessionId !== record.sessionId) {
27
+ this.backupBeforeHistory()
28
+ this.records[`history:${old.sessionId}`] = old
29
+ }
23
30
  this.records[key] = record
31
+ if (key !== `history:${record.sessionId}`) delete this.records[`history:${record.sessionId}`]
32
+ try { this.flush() }
33
+ catch (error) { this.records = before; throw error }
34
+ }
35
+
36
+ retain(key: string): void {
37
+ const record = this.records[key]
38
+ if (!record) return
39
+ this.backupBeforeHistory()
40
+ this.records[`history:${record.sessionId}`] = record
41
+ delete this.records[key]
42
+ this.flush()
43
+ }
44
+
45
+ saveHistory(record: SessionRecord): void {
46
+ if (this.list().some(item => item.sessionId === record.sessionId)) return
47
+ this.backupBeforeHistory()
48
+ this.upsert(`history:${record.sessionId}`, record)
49
+ }
50
+
51
+ updateSession(record: SessionRecord): void {
52
+ for (const key of Object.keys(this.records)) {
53
+ if (this.records[key]?.sessionId === record.sessionId) this.records[key] = record
54
+ }
55
+ this.flush()
56
+ }
57
+
58
+ removeSession(sessionId: string): void {
59
+ for (const key of Object.keys(this.records)) {
60
+ if (this.records[key]?.sessionId === sessionId) delete this.records[key]
61
+ }
24
62
  this.flush()
25
63
  }
26
64
 
@@ -43,4 +81,15 @@ export class SessionMapStore {
43
81
  private flush(): void {
44
82
  writeFileAtomicSync(this.file, `${JSON.stringify(this.records, null, 2)}\n`)
45
83
  }
84
+
85
+ private backupBeforeHistory(): void {
86
+ if (this.historyBackupTaken) return
87
+ try {
88
+ copyFileSync(this.file, `${this.file}.before-history.json`, constants.COPYFILE_EXCL)
89
+ } catch (error) {
90
+ const code = (error as NodeJS.ErrnoException).code
91
+ if (code !== 'ENOENT' && code !== 'EEXIST') throw error
92
+ }
93
+ this.historyBackupTaken = true
94
+ }
46
95
  }
@@ -0,0 +1,25 @@
1
+ import { stripVTControlCharacters } from 'node:util'
2
+
3
+ /** 仅接受已知宿主标题来源;未知事件不能覆盖迁移前的名称。 */
4
+ export function readSessionTitle(data: unknown): { title: string; source: 'host' | 'user' } | undefined {
5
+ if (!data || typeof data !== 'object') return undefined
6
+ const value = data as { title?: unknown; source?: { kind?: unknown } }
7
+ if (typeof value.title !== 'string' || !value.title.trim()) return undefined
8
+ const kind = value.source?.kind
9
+ if (kind !== 'user' && kind !== 'provider' && kind !== 'fallback') return undefined
10
+ return { title: value.title, source: kind === 'user' ? 'user' : 'host' }
11
+ }
12
+
13
+ /** 首条原始消息的本地兜底标题;不调用重命名接口,以免锁住宿主自动命名。 */
14
+ export function initialSessionTitle(text: string): string | undefined {
15
+ const clean = stripVTControlCharacters(text).replace(/[\u0000-\u001f\u007f-\u009f\u200b\u200e\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/gu, ' ')
16
+ .replace(/\s+/gu, ' ').trim()
17
+ if (!clean) return undefined
18
+ if (Buffer.byteLength(clean, 'utf8') <= 60) return clean
19
+ let title = ''
20
+ for (const { segment } of new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(clean)) {
21
+ if (Buffer.byteLength(title + segment, 'utf8') > 57) break
22
+ title += segment
23
+ }
24
+ return `${title.trimEnd()}…`
25
+ }