@michengai/dsh-im-connect 0.1.39 → 0.1.40

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.
@@ -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
 
@@ -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
@@ -144,18 +146,31 @@ export class SessionRouter {
144
146
  private async rotateNow(channelId: ChannelInstanceId, kind: ChatKind, chatId: string, title: string): Promise<ChatBinding> {
145
147
  const key = sessionKeyOf(channelId, kind, chatId)
146
148
  const old = this.live.get(key)
147
- if (old?.handle) await this.disposeHandle(old)
149
+ if (old?.handle) {
150
+ this.reloadDisposed.add(old.sessionId)
151
+ await this.disposeHandle(old)
152
+ }
148
153
  this.live.delete(key)
149
- this.store.remove(key)
154
+ this.store.retain(key)
150
155
  return this.create(channelId, kind, chatId, title)
151
156
  }
152
157
 
153
158
  rename(sessionId: string, title: string): boolean {
159
+ return this.setTitle(sessionId, title, 'user')
160
+ }
161
+
162
+ setTitle(sessionId: string, title: string, source: 'message' | 'host' | 'user'): boolean {
154
163
  const rec = this.store.list().find((item) => item.sessionId === sessionId)
155
164
  if (!rec) return false
156
- this.store.upsert(sessionKeyOf(rec.channel, rec.kind, rec.chatId), {
165
+ const acceptsInitialMessage = rec.titleSource === 'pending' || (!rec.titleSource && !rec.title.trim())
166
+ if (!title.trim()
167
+ || (source === 'message' && !acceptsInitialMessage)
168
+ || (source === 'host' && rec.titleSource === 'user')) return false
169
+ if (rec.title === title && rec.titleSource === source) return true
170
+ this.store.updateSession({
157
171
  ...rec,
158
172
  title,
173
+ titleSource: source,
159
174
  updatedAt: new Date().toISOString(),
160
175
  })
161
176
  return true
@@ -167,7 +182,7 @@ export class SessionRouter {
167
182
  let removed = 0
168
183
  for (const rec of this.store.list()) {
169
184
  if (known.has(rec.sessionId)) continue
170
- await this.remove(rec.sessionId)
185
+ await this.channelOperations.run(rec.channel, () => this.removeFromChannel(rec.sessionId, false))
171
186
  removed += 1
172
187
  }
173
188
  if (removed > 0) this.log(`[router] 已清理 ${removed} 条宿主已删除的频道映射`)
@@ -181,7 +196,8 @@ export class SessionRouter {
181
196
  const persistence = this.ctx.get?.('sessionPersistence') as { list?: () => Promise<readonly { readonly id: string }[]> } | undefined
182
197
  const canListLive = typeof live?.list === "function"
183
198
  const canListStored = typeof persistence?.list === "function"
184
- if (!canListLive && !canListStored) return undefined
199
+ // 仅凭活会话列表不能判断已卸载的历史日志是否被删除。
200
+ if (!canListStored) return undefined
185
201
  const ids = new Set<string>()
186
202
  if (canListLive && live.list) {
187
203
  for (const session of live.list()) ids.add(String(session.id))
@@ -198,25 +214,46 @@ export class SessionRouter {
198
214
  async ensure(sessionId: string): Promise<boolean> {
199
215
  const rec = this.store.list().find((item) => item.sessionId === sessionId)
200
216
  if (!rec) return false
201
- await this.getOrCreate(rec.channel, rec.kind, rec.chatId, rec.title, { rebuildMissing: true })
202
- return true
217
+ return this.channelOperations.run(rec.channel, async () => {
218
+ if (this.isArchived(sessionId)) return false
219
+ const key = sessionKeyOf(rec.channel, rec.kind, rec.chatId)
220
+ const current = this.live.get(key)
221
+ if (this.historical.has(sessionId) || (current?.sessionId === sessionId && current.handle)) return true
222
+ const binding = await this.resume(rec)
223
+ if (!binding) return false
224
+ if (this.store.get(key)?.sessionId === sessionId) this.live.set(key, binding)
225
+ else this.historical.set(sessionId, binding)
226
+ return true
227
+ })
203
228
  }
204
229
 
205
230
  async disposeAll(): Promise<void> {
206
- const channels = [...new Set([...this.live.values()].map((item) => item.channelId))]
231
+ const channels = [...new Set([...this.live.values(), ...this.historical.values()].map((item) => item.channelId))]
207
232
  await Promise.all(channels.map((channelId) => this.disposeChannel(channelId)))
208
233
  this.live.clear()
234
+ this.historical.clear()
209
235
  }
210
236
 
211
- /** 配置重载触发的 dispose 只卸活句柄;归档/宿主删除才清映射。 */
237
+ /** 卸载不代表删除日志;只有可靠确认日志不存在才清除索引。 */
212
238
  async onHostDisposed(sessionId: string): Promise<boolean> {
213
239
  if (this.reloadDisposed.delete(sessionId)) {
240
+ this.historical.delete(sessionId)
214
241
  for (const [key, item] of this.live) {
215
242
  if (item.sessionId === sessionId) this.live.delete(key)
216
243
  }
217
244
  return false
218
245
  }
219
- return this.remove(sessionId)
246
+ const known = await this.knownSessionIds()
247
+ if (known === undefined || known.has(sessionId)) {
248
+ this.historical.delete(sessionId)
249
+ for (const [key, item] of this.live) {
250
+ if (item.sessionId === sessionId) this.live.delete(key)
251
+ }
252
+ return false
253
+ }
254
+ const record = this.store.list().find(item => item.sessionId === sessionId)
255
+ if (!record) return false
256
+ return this.channelOperations.run(record.channel, () => this.removeFromChannel(sessionId, false))
220
257
  }
221
258
 
222
259
  followup(binding: ChatBinding, message: unknown): void {
@@ -236,12 +273,18 @@ export class SessionRouter {
236
273
  // 工作区属于会话创建参数,不能拿旧 sessionId 在新目录恢复;仅解除映射,保留 Host 中的历史日志。
237
274
  for (const record of this.store.list()) {
238
275
  if (record.channel !== channelId) continue
239
- this.store.remove(sessionKeyOf(record.channel, record.kind, record.chatId))
276
+ this.store.retain(sessionKeyOf(record.channel, record.kind, record.chatId))
240
277
  }
241
278
  })
242
279
  }
243
280
 
244
281
  private async disposeChannelNow(channelId: string): Promise<void> {
282
+ for (const [id, item] of this.historical) {
283
+ if (item.channelId !== channelId) continue
284
+ this.reloadDisposed.add(id)
285
+ await this.disposeHandle(item)
286
+ this.historical.delete(id)
287
+ }
245
288
  const entries = [...this.live].filter(([, item]) => item.channelId === channelId)
246
289
  for (const [, item] of entries) this.reloadDisposed.add(item.sessionId)
247
290
  await Promise.all(entries.map(async ([key, item]) => {
@@ -269,14 +312,21 @@ export class SessionRouter {
269
312
  if (result === 'timed-out') this.log(`[router] 卸载会话超时 ${item.sessionId},已解除本地引用`)
270
313
  }
271
314
 
272
- private async removeFromChannel(sessionId: string): Promise<boolean> {
315
+ private async removeFromChannel(sessionId: string, retainArchived = true): Promise<boolean> {
273
316
  const rec = this.store.list().find((item) => item.sessionId === sessionId)
274
317
  if (!rec) return false
275
318
  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)
319
+ const current = this.live.get(key)
320
+ const live = current?.sessionId === sessionId ? current : this.historical.get(sessionId)
321
+ if (live?.handle) {
322
+ this.reloadDisposed.add(sessionId)
323
+ await this.disposeHandle(live)
324
+ }
325
+ if (current?.sessionId === sessionId) this.live.delete(key)
326
+ this.historical.delete(sessionId)
327
+ if (retainArchived && this.isArchived(sessionId)) {
328
+ if (this.store.get(key)?.sessionId === sessionId) this.store.retain(key)
329
+ } else this.store.removeSession(sessionId)
280
330
  return true
281
331
  }
282
332
 
@@ -307,6 +357,7 @@ export class SessionRouter {
307
357
  kind,
308
358
  chatId,
309
359
  title,
360
+ titleSource: 'pending',
310
361
  updatedAt: new Date().toISOString(),
311
362
  }
312
363
  this.store.upsert(key, record)
@@ -320,6 +371,7 @@ export class SessionRouter {
320
371
  private async resume(record: SessionRecord): Promise<ChatBinding | undefined> {
321
372
  const liveAgent = this.ctx.agents?.get?.(record.sessionId)
322
373
  if (liveAgent) {
374
+ this.syncStoredTitle(record.sessionId, liveAgent)
323
375
  const binding: ChatBinding = {
324
376
  key: sessionKeyOf(record.channel, record.kind, record.chatId),
325
377
  channelId: record.channel,
@@ -340,6 +392,7 @@ export class SessionRouter {
340
392
  },
341
393
  setup: this.presetSetup(record.channel),
342
394
  })
395
+ this.syncStoredTitle(record.sessionId, handle.agent)
343
396
  await this.attachWorkspace(record.sessionId, record.channel)
344
397
  return {
345
398
  key: sessionKeyOf(record.channel, record.kind, record.chatId),
@@ -398,13 +451,40 @@ export class SessionRouter {
398
451
 
399
452
  async attachMappedSessions(): Promise<void> {
400
453
  const started = Date.now()
454
+ await this.recoverHistory()
401
455
  await this.pruneMissingSessions()
402
456
  for (const record of this.store.list()) {
457
+ if (this.isArchived(record.sessionId)) continue
403
458
  await this.attachWorkspace(record.sessionId, record.channel)
404
459
  }
405
460
  this.log(`[boot] attachMappedSessions ${Date.now() - started}ms`)
406
461
  }
407
462
 
463
+ private syncStoredTitle(sessionId: string, agent: unknown): void {
464
+ const session = (agent as { session?: { snapshotEvents?: () => readonly { type: string; data?: unknown }[]; events?: readonly { type: string; data?: unknown }[] } } | undefined)?.session
465
+ const events = session?.snapshotEvents?.() ?? session?.events ?? []
466
+ const latest = readSessionTitle(events.findLast(event => event.type === 'session/title')?.data)
467
+ if (latest) this.setTitle(sessionId, latest.title, latest.source)
468
+ }
469
+
470
+ private async recoverHistory(): Promise<void> {
471
+ try {
472
+ const persistence = this.ctx.get?.('sessionPersistence') as { list?: () => Promise<readonly { id: string; createdAt?: number }[]> } | undefined
473
+ if (!persistence?.list) return
474
+ for (const header of await persistence.list()) {
475
+ const parsed = parseImSessionId(header.id)
476
+ if (!parsed) continue
477
+ this.store.saveHistory({
478
+ sessionId: header.id, ...parsed,
479
+ title: parsed.chatId,
480
+ updatedAt: new Date(Number.isFinite(header.createdAt) ? header.createdAt! : 0).toISOString(),
481
+ })
482
+ }
483
+ } catch (error) {
484
+ this.log(`[router] 恢复历史索引失败: ${error instanceof Error ? error.message : String(error)}`)
485
+ }
486
+ }
487
+
408
488
  private isArchived(sessionId: string): boolean {
409
489
  try {
410
490
  const ids = this.ctx.get?.('workspaceRegistry')?.archivedSessionIds
@@ -13,6 +13,8 @@ export interface SessionRecord {
13
13
  kind: ChatKind
14
14
  chatId: string
15
15
  title: string
16
+ /** pending 仅用于新会话占位名称;缺省表示旧数据来源未知。 */
17
+ titleSource?: 'pending' | 'message' | 'host' | 'user'
16
18
  updatedAt: string
17
19
  }
18
20
 
@@ -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,10 +21,44 @@ export class SessionMapStore {
20
21
  }
21
22
 
22
23
  upsert(key: string, record: SessionRecord): void {
24
+ const old = this.records[key]
25
+ if (old && old.sessionId !== record.sessionId) {
26
+ this.backupBeforeHistory()
27
+ this.records[`history:${old.sessionId}`] = old
28
+ }
23
29
  this.records[key] = record
24
30
  this.flush()
25
31
  }
26
32
 
33
+ retain(key: string): void {
34
+ const record = this.records[key]
35
+ if (!record) return
36
+ this.backupBeforeHistory()
37
+ this.records[`history:${record.sessionId}`] = record
38
+ delete this.records[key]
39
+ this.flush()
40
+ }
41
+
42
+ saveHistory(record: SessionRecord): void {
43
+ if (this.list().some(item => item.sessionId === record.sessionId)) return
44
+ this.backupBeforeHistory()
45
+ this.upsert(`history:${record.sessionId}`, record)
46
+ }
47
+
48
+ updateSession(record: SessionRecord): void {
49
+ for (const key of Object.keys(this.records)) {
50
+ if (this.records[key]?.sessionId === record.sessionId) this.records[key] = record
51
+ }
52
+ this.flush()
53
+ }
54
+
55
+ removeSession(sessionId: string): void {
56
+ for (const key of Object.keys(this.records)) {
57
+ if (this.records[key]?.sessionId === sessionId) delete this.records[key]
58
+ }
59
+ this.flush()
60
+ }
61
+
27
62
  remove(key: string): void {
28
63
  delete this.records[key]
29
64
  this.flush()
@@ -43,4 +78,15 @@ export class SessionMapStore {
43
78
  private flush(): void {
44
79
  writeFileAtomicSync(this.file, `${JSON.stringify(this.records, null, 2)}\n`)
45
80
  }
81
+
82
+ private backupBeforeHistory(): void {
83
+ if (this.historyBackupTaken) return
84
+ try {
85
+ copyFileSync(this.file, `${this.file}.before-history.json`, constants.COPYFILE_EXCL)
86
+ } catch (error) {
87
+ const code = (error as NodeJS.ErrnoException).code
88
+ if (code !== 'ENOENT' && code !== 'EEXIST') throw error
89
+ }
90
+ this.historyBackupTaken = true
91
+ }
46
92
  }
@@ -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
+ }