@samuelchung2010/dshift 0.0.0-stage → 0.3.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 (46) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +116 -0
  4. package/README.md +116 -3
  5. package/assets/dshift-readme.gif +0 -0
  6. package/client.js +18831 -0
  7. package/cordis.patch.yml +58 -0
  8. package/docs/architecture.md +203 -0
  9. package/docs/configuration.md +103 -0
  10. package/docs/development.md +125 -0
  11. package/docs/limitations.md +74 -0
  12. package/docs/math-boxed-qquad.png +0 -0
  13. package/docs/math-boxed-single.png +0 -0
  14. package/docs/memory-integration.md +111 -0
  15. package/docs/perf/baseline-before.json +4872 -0
  16. package/docs/perf/baseline-before.summary.json +659 -0
  17. package/docs/perf/fixed-after.json +2927 -0
  18. package/docs/perf/fixed-after.summary.json +583 -0
  19. package/docs/perf/long-chat-performance.md +340 -0
  20. package/docs/perf/merged-after.json +1953 -0
  21. package/docs/perf/merged-after.summary.json +382 -0
  22. package/docs/perf/mount-after.json +82 -0
  23. package/docs/perf/mount-baseline.json +82 -0
  24. package/docs/user-guide.md +202 -0
  25. package/icon.svg +13 -0
  26. package/index.js +16 -0
  27. package/lib/api.js +336 -0
  28. package/lib/artifact/approval-bus.js +94 -0
  29. package/lib/artifact/prompt.js +99 -0
  30. package/lib/artifact/service.js +602 -0
  31. package/lib/artifact/workspace.js +260 -0
  32. package/lib/import/convert.js +343 -0
  33. package/lib/import/format.js +262 -0
  34. package/lib/import/index.js +585 -0
  35. package/lib/import/media.js +101 -0
  36. package/lib/import/zip.js +296 -0
  37. package/lib/memory-store.js +629 -0
  38. package/lib/memory-text.js +162 -0
  39. package/lib/memory.js +871 -0
  40. package/lib/model-config.js +280 -0
  41. package/lib/protocol.js +593 -0
  42. package/lib/service.js +2102 -0
  43. package/lib/store.js +1011 -0
  44. package/locale/en.json +6 -0
  45. package/locale/zh.json +6 -0
  46. package/package.json +49 -6
package/lib/store.js ADDED
@@ -0,0 +1,1011 @@
1
+ /**
2
+ * Durable chat history for Chat mode. One JSON document under
3
+ * `$DSH_HOME/deepseek-chat`, written atomically and serialized per process.
4
+ *
5
+ * History is a small tree per conversation: every message is a node with a
6
+ * parent, so editing a question or regenerating an answer adds a sibling branch
7
+ * instead of overwriting history. The active branch is a path from the virtual
8
+ * root to `leafId`; `conversation.messages` is that path and is what every
9
+ * request and renderer uses, so a model only ever sees the messages the user
10
+ * currently has on screen. Sibling branches are kept for version switching.
11
+ */
12
+
13
+ import { promises as fs } from 'node:fs'
14
+ import path from 'node:path'
15
+ import { randomUUID } from 'node:crypto'
16
+
17
+ export const STORE_VERSION = 2
18
+ export const MAX_SYSTEM_PROMPT = 8000
19
+ export const MAX_TITLE = 80
20
+ export const MAX_FOLDER_NAME = 60
21
+ export const MAX_SEARCH_QUERY = 200
22
+ export const SEARCH_LIMIT = 40
23
+
24
+ const AUTH_MODES = new Set(['auto', 'account', 'api-key'])
25
+
26
+ /**
27
+ * Where an imported conversation came from. `kind` names the source system and
28
+ * `id` is that system's own stable conversation id, which is what makes a
29
+ * re-import of the same export a no-op instead of a duplicate. `importedAt` is
30
+ * the epoch millisecond of the import that created it. `memoryExtractedAt`
31
+ * records the last long-term-memory analysis of this conversation, so the same
32
+ * imported history is not sent to the model twice by accident.
33
+ */
34
+ const SOURCE_KIND_LIMIT = 40
35
+ const SOURCE_ID_LIMIT = 200
36
+ const LOCAL_FILE_MEDIA = /^[a-f0-9]{64}\.[a-z0-9]{2,5}$/u
37
+
38
+ function normalizeSource(source) {
39
+ if (source === null || typeof source !== 'object') return null
40
+ const kind = typeof source.kind === 'string' ? source.kind.trim().slice(0, SOURCE_KIND_LIMIT) : ''
41
+ const id = typeof source.id === 'string' ? source.id.trim().slice(0, SOURCE_ID_LIMIT) : ''
42
+ if (kind === '' || id === '') return null
43
+ return {
44
+ kind,
45
+ id,
46
+ importedAt: typeof source.importedAt === 'number' && Number.isFinite(source.importedAt) ? source.importedAt : null,
47
+ memoryExtractedAt: typeof source.memoryExtractedAt === 'number' && Number.isFinite(source.memoryExtractedAt)
48
+ ? source.memoryExtractedAt
49
+ : null,
50
+ }
51
+ }
52
+
53
+ export function defaultSettings() {
54
+ return {
55
+ authMode: 'auto',
56
+ thinking: false,
57
+ search: false,
58
+ systemPrompt: '',
59
+ }
60
+ }
61
+
62
+ function normalizeSettings(input) {
63
+ const base = defaultSettings()
64
+ if (input === null || typeof input !== 'object') return base
65
+ if (AUTH_MODES.has(input.authMode)) base.authMode = input.authMode
66
+ if (typeof input.thinking === 'boolean') base.thinking = input.thinking
67
+ if (typeof input.search === 'boolean') base.search = input.search
68
+ if (typeof input.systemPrompt === 'string') base.systemPrompt = input.systemPrompt.slice(0, MAX_SYSTEM_PROMPT)
69
+ return base
70
+ }
71
+
72
+ function normalizeFolderName(value) {
73
+ if (typeof value !== 'string') return ''
74
+ return value.replace(/\s+/g, ' ').trim().slice(0, MAX_FOLDER_NAME)
75
+ }
76
+
77
+ function normalizeFile(file) {
78
+ if (file === null || typeof file !== 'object') return null
79
+ if (typeof file.fileId !== 'string' || file.fileId === '') return null
80
+ // An imported attachment is not on DeepSeek's file service. `local` marks it so
81
+ // a request never sends its marker as a file id, and `media` names the stored
82
+ // bytes when the import could recover them.
83
+ const local = file.local === true
84
+ const media = typeof file.media === 'string' && LOCAL_FILE_MEDIA.test(file.media) ? file.media : undefined
85
+ return {
86
+ id: typeof file.id === 'string' ? file.id : randomUUID(),
87
+ fileId: file.fileId,
88
+ name: typeof file.name === 'string' ? file.name.slice(0, 200) : 'file',
89
+ size: typeof file.size === 'number' && Number.isFinite(file.size) ? file.size : 0,
90
+ mimeType: typeof file.mimeType === 'string' ? file.mimeType : '',
91
+ isImage: file.isImage === true,
92
+ ...(local ? { local: true } : {}),
93
+ ...(media === undefined ? {} : { media }),
94
+ }
95
+ }
96
+
97
+ function normalizeMessage(message) {
98
+ if (message === null || typeof message !== 'object') return null
99
+ if (message.role !== 'user' && message.role !== 'assistant') return null
100
+ if (message.role === 'user') {
101
+ return {
102
+ id: typeof message.id === 'string' && message.id !== '' ? message.id : randomUUID(),
103
+ role: 'user',
104
+ content: typeof message.content === 'string' ? message.content.slice(0, 100_000) : '',
105
+ files: Array.isArray(message.files) ? message.files.map(normalizeFile).filter(Boolean) : [],
106
+ createdAt: typeof message.createdAt === 'number' ? message.createdAt : Date.now(),
107
+ }
108
+ }
109
+ const status = ['streaming', 'done', 'stopped', 'error'].includes(message.status) ? message.status : 'done'
110
+ const now = Date.now()
111
+ const sourceBlocks = Array.isArray(message.blocks) ? message.blocks : []
112
+ // A reply left streaming by a crash or an abrupt shutdown is presented as
113
+ // stopped. Its open thinking block is closed against the reply's own last
114
+ // write, never against load time: the reasoning duration must stay the same
115
+ // across reloads instead of growing with the wall clock.
116
+ const lastWrite = typeof message.updatedAt === 'number'
117
+ ? message.updatedAt
118
+ : typeof message.createdAt === 'number' ? message.createdAt : now
119
+ const blocks = status === 'streaming'
120
+ ? sourceBlocks.map((block) => {
121
+ if (block?.type !== 'thinking' || typeof block.endedAt === 'number') return block
122
+ const startedAt = typeof block.startedAt === 'number' ? block.startedAt : lastWrite
123
+ return { ...block, endedAt: Math.max(startedAt, lastWrite) }
124
+ })
125
+ : sourceBlocks
126
+ return {
127
+ id: typeof message.id === 'string' && message.id !== '' ? message.id : randomUUID(),
128
+ role: 'assistant',
129
+ createdAt: typeof message.createdAt === 'number' ? message.createdAt : now,
130
+ updatedAt: typeof message.updatedAt === 'number' ? message.updatedAt : now,
131
+ model: typeof message.model === 'string' ? message.model : 'deepseek-flash',
132
+ thinking: message.thinking === true,
133
+ search: message.search === true,
134
+ status: status === 'streaming' ? 'stopped' : status,
135
+ blocks,
136
+ usage: message.usage !== null && typeof message.usage === 'object' ? message.usage : undefined,
137
+ stopReason: typeof message.stopReason === 'string' ? message.stopReason : undefined,
138
+ stopDetails: message.stopDetails !== null && typeof message.stopDetails === 'object' ? message.stopDetails : undefined,
139
+ error: message.error !== null && typeof message.error === 'object' ? message.error : undefined,
140
+ prefix: message.prefix !== false,
141
+ ...(typeof message.continueCount === 'number' && Number.isFinite(message.continueCount) && message.continueCount > 0
142
+ ? { continueCount: Math.floor(message.continueCount) }
143
+ : {}),
144
+ }
145
+ }
146
+
147
+ /** Normalize one stored folder record; an unnamed folder is dropped. */
148
+ function normalizeFolder(folder) {
149
+ if (folder === null || typeof folder !== 'object') return null
150
+ const name = normalizeFolderName(folder.name)
151
+ if (name === '') return null
152
+ const createdAt = typeof folder.createdAt === 'number' ? folder.createdAt : Date.now()
153
+ return {
154
+ id: typeof folder.id === 'string' && folder.id !== '' ? folder.id : randomUUID(),
155
+ name,
156
+ collapsed: folder.collapsed === true,
157
+ createdAt,
158
+ updatedAt: typeof folder.updatedAt === 'number' ? folder.updatedAt : createdAt,
159
+ }
160
+ }
161
+
162
+ /** Whether a parent chain is safe to walk (no missing node, no cycle). */
163
+ function parentChainIsSound(nodes, id) {
164
+ const seen = new Set([id])
165
+ let current = nodes[id].parentId
166
+ while (current !== null) {
167
+ if (seen.has(current)) return false
168
+ const parent = nodes[current]
169
+ if (parent === undefined) return false
170
+ seen.add(current)
171
+ current = parent.parentId
172
+ }
173
+ return true
174
+ }
175
+
176
+ /** Rebuild children/roots and the active path from the nodes map. */
177
+ function rebuildLinks(conversation) {
178
+ const ids = Object.keys(conversation.nodes)
179
+ for (const node of Object.values(conversation.nodes)) node.children = []
180
+ conversation.roots = []
181
+ for (const id of ids) {
182
+ const node = conversation.nodes[id]
183
+ if (node.parentId === null) {
184
+ conversation.roots.push(id)
185
+ continue
186
+ }
187
+ const parent = conversation.nodes[node.parentId]
188
+ if (parent === undefined) {
189
+ node.parentId = null
190
+ conversation.roots.push(id)
191
+ } else {
192
+ parent.children.push(id)
193
+ }
194
+ }
195
+ }
196
+
197
+ /** Follow the most recent child chain to a leaf, used when switching branches. */
198
+ function deepestLeafId(conversation, nodeId) {
199
+ let current = nodeId
200
+ const seen = new Set()
201
+ for (;;) {
202
+ if (seen.has(current) || conversation.nodes[current] === undefined) return nodeId
203
+ seen.add(current)
204
+ const node = conversation.nodes[current]
205
+ if (node.children.length === 0) return current
206
+ current = node.children[node.children.length - 1]
207
+ }
208
+ }
209
+
210
+ /** Recompute the active path from `leafId`, walking up to the virtual root. */
211
+ function rebuildPath(conversation) {
212
+ const messages = []
213
+ const seen = new Set()
214
+ let current = conversation.leafId
215
+ while (typeof current === 'string' && conversation.nodes[current] !== undefined && !seen.has(current)) {
216
+ seen.add(current)
217
+ const node = conversation.nodes[current]
218
+ messages.push(node.message)
219
+ current = node.parentId
220
+ }
221
+ messages.reverse()
222
+ conversation.messages = messages
223
+ }
224
+
225
+ function makeNode(id, parentId, message) {
226
+ return { id, parentId, children: [], message }
227
+ }
228
+
229
+ /** Convert the pre-tree `messages` array into a single linear branch. */
230
+ function nodesFromMessages(messages) {
231
+ const nodes = {}
232
+ let parentId = null
233
+ for (const raw of Array.isArray(messages) ? messages : []) {
234
+ const normalized = normalizeMessage(raw)
235
+ if (normalized === null) continue
236
+ let id = normalized.id
237
+ if (nodes[id] !== undefined) {
238
+ id = randomUUID()
239
+ normalized.id = id
240
+ }
241
+ nodes[id] = makeNode(id, parentId, normalized)
242
+ parentId = id
243
+ }
244
+ return nodes
245
+ }
246
+
247
+ function normalizeConversation(input) {
248
+ if (input === null || typeof input !== 'object') return null
249
+ const now = Date.now()
250
+ const conversation = {
251
+ id: typeof input.id === 'string' && input.id !== '' ? input.id : randomUUID(),
252
+ title: typeof input.title === 'string' ? input.title.slice(0, MAX_TITLE) : '',
253
+ titleAuto: input.titleAuto === true,
254
+ createdAt: typeof input.createdAt === 'number' ? input.createdAt : now,
255
+ updatedAt: typeof input.updatedAt === 'number' ? input.updatedAt : now,
256
+ pinned: input.pinned === true,
257
+ pinnedAt: typeof input.pinnedAt === 'number' ? input.pinnedAt : null,
258
+ archived: input.archived === true,
259
+ archivedAt: typeof input.archivedAt === 'number' ? input.archivedAt : null,
260
+ folderId: typeof input.folderId === 'string' && input.folderId !== '' ? input.folderId : null,
261
+ source: normalizeSource(input.source),
262
+ nodes: {},
263
+ roots: [],
264
+ leafId: null,
265
+ messages: [],
266
+ }
267
+ if (conversation.pinned && conversation.pinnedAt === null) conversation.pinnedAt = conversation.updatedAt
268
+ if (conversation.archived && conversation.archivedAt === null) conversation.archivedAt = conversation.updatedAt
269
+
270
+ let nodes = {}
271
+ if (input.nodes !== null && typeof input.nodes === 'object' && !Array.isArray(input.nodes)) {
272
+ for (const [key, raw] of Object.entries(input.nodes)) {
273
+ if (raw === null || typeof raw !== 'object') continue
274
+ const source = raw.message !== null && typeof raw.message === 'object' ? raw.message : raw
275
+ const normalized = normalizeMessage(
276
+ typeof source.id === 'string' && source.id !== '' ? source : { ...source, id: key },
277
+ )
278
+ if (normalized === null) continue
279
+ const id = typeof key === 'string' && key !== '' ? key : normalized.id
280
+ // The map key is the branch identity; keep the message id in step with it
281
+ // so sibling lookups always line up.
282
+ normalized.id = id
283
+ if (nodes[id] !== undefined) continue
284
+ nodes[id] = {
285
+ id,
286
+ parentId: typeof raw.parentId === 'string' && raw.parentId !== '' ? raw.parentId : null,
287
+ children: [],
288
+ message: normalized,
289
+ }
290
+ }
291
+ } else if (Array.isArray(input.messages)) {
292
+ nodes = nodesFromMessages(input.messages)
293
+ }
294
+ // A half-written tree (empty nodes map) still recovers from the legacy array.
295
+ if (Object.keys(nodes).length === 0 && Array.isArray(input.messages)) {
296
+ nodes = nodesFromMessages(input.messages)
297
+ }
298
+
299
+ // A saved parent pointer is only trusted when it resolves inside this
300
+ // conversation and its chain does not loop; otherwise the node becomes a root.
301
+ for (const [id, node] of Object.entries(nodes)) {
302
+ if (node.parentId !== null && (nodes[node.parentId] === undefined || !parentChainIsSound(nodes, id))) {
303
+ node.parentId = null
304
+ }
305
+ }
306
+ conversation.nodes = nodes
307
+ rebuildLinks(conversation)
308
+
309
+ if (Object.keys(nodes).length === 0) {
310
+ conversation.leafId = null
311
+ conversation.messages = []
312
+ return conversation
313
+ }
314
+ const storedLeaf = typeof input.leafId === 'string' && nodes[input.leafId] !== undefined
315
+ ? input.leafId
316
+ : null
317
+ conversation.leafId = storedLeaf ?? deepestLeafId(conversation, conversation.roots[conversation.roots.length - 1])
318
+ rebuildPath(conversation)
319
+ return conversation
320
+ }
321
+
322
+ function normalizeState(parsed) {
323
+ const folders = []
324
+ const seenFolders = new Set()
325
+ for (const raw of Array.isArray(parsed?.folders) ? parsed.folders : []) {
326
+ const folder = normalizeFolder(raw)
327
+ if (folder === null || seenFolders.has(folder.id)) continue
328
+ seenFolders.add(folder.id)
329
+ folders.push(folder)
330
+ }
331
+ const folderIds = new Set(folders.map(folder => folder.id))
332
+ const conversations = []
333
+ const seenConversations = new Set()
334
+ for (const raw of Array.isArray(parsed?.conversations) ? parsed.conversations : []) {
335
+ const conversation = normalizeConversation(raw)
336
+ if (conversation === null || seenConversations.has(conversation.id)) continue
337
+ seenConversations.add(conversation.id)
338
+ if (conversation.folderId !== null && !folderIds.has(conversation.folderId)) conversation.folderId = null
339
+ conversations.push(conversation)
340
+ }
341
+ return { folders, conversations }
342
+ }
343
+
344
+ /** Visible answer text of an assistant message, used by history search. */
345
+ function messageSearchText(message) {
346
+ if (message.role === 'user') return typeof message.content === 'string' ? message.content : ''
347
+ if (!Array.isArray(message.blocks)) return ''
348
+ return message.blocks
349
+ .filter(block => block?.type === 'text' && typeof block.text === 'string')
350
+ .map(block => block.text)
351
+ .join('')
352
+ }
353
+
354
+ /** One-line excerpt around the first match, with ellipses where trimmed. */
355
+ function excerptOf(text, needle) {
356
+ const plain = text.replace(/\s+/g, ' ').trim()
357
+ const index = plain.toLowerCase().indexOf(needle)
358
+ if (index < 0) return ''
359
+ const start = Math.max(0, index - 34)
360
+ const end = Math.min(plain.length, index + needle.length + 76)
361
+ return `${start > 0 ? '…' : ''}${plain.slice(start, end)}${end < plain.length ? '…' : ''}`
362
+ }
363
+
364
+ export class ChatStore {
365
+ constructor(directory, { logger = console } = {}) {
366
+ this.directory = directory
367
+ this.file = path.join(directory, 'state.json')
368
+ this.logger = logger
369
+ this.state = {
370
+ version: STORE_VERSION,
371
+ settings: defaultSettings(),
372
+ folders: [],
373
+ conversations: [],
374
+ }
375
+ this.loaded = false
376
+ this.writeChain = Promise.resolve()
377
+ }
378
+
379
+ async load() {
380
+ if (this.loaded) return this
381
+ await fs.mkdir(this.directory, { recursive: true })
382
+ let raw
383
+ try {
384
+ raw = await fs.readFile(this.file, 'utf8')
385
+ } catch (error) {
386
+ if (error?.code !== 'ENOENT') throw error
387
+ this.loaded = true
388
+ return this
389
+ }
390
+ let parsed
391
+ try {
392
+ parsed = JSON.parse(raw)
393
+ } catch (error) {
394
+ // A genuinely unreadable document is quarantined and the plugin starts
395
+ // empty; a failed migration write is handled separately below and never
396
+ // reaches this path.
397
+ const backup = `${this.file}.corrupt-${Date.now()}`
398
+ try {
399
+ await fs.rename(this.file, backup)
400
+ } catch {
401
+ // Leave the unreadable file if it cannot be moved; the next save replaces it.
402
+ }
403
+ this.logger.warn?.('deepseek-chat: unreadable state.json; starting with empty history', error)
404
+ this.state = {
405
+ version: STORE_VERSION,
406
+ settings: defaultSettings(),
407
+ folders: [],
408
+ conversations: [],
409
+ }
410
+ this.loaded = true
411
+ return this
412
+ }
413
+
414
+ const sourceVersion = typeof parsed?.version === 'number' ? parsed.version : 1
415
+ let normalized
416
+ try {
417
+ normalized = normalizeState(parsed)
418
+ } catch (error) {
419
+ this.logger.warn?.('deepseek-chat: could not normalize state.json; keeping settings only', error)
420
+ normalized = { folders: [], conversations: [] }
421
+ }
422
+ if (sourceVersion < STORE_VERSION && (normalized.conversations.length > 0 || normalized.folders.length > 0)) {
423
+ // Keep the exact pre-upgrade document next to the state file. The copy is
424
+ // never read by the plugin; it exists so a failed upgrade can be undone by
425
+ // hand without losing a single conversation.
426
+ const backup = `${this.file}.v${sourceVersion}-backup-${Date.now()}`
427
+ try {
428
+ await fs.copyFile(this.file, backup)
429
+ this.logger.info?.(`deepseek-chat: backed up state.json to ${path.basename(backup)} before migrating`)
430
+ } catch (error) {
431
+ this.logger.warn?.('deepseek-chat: could not back up state.json before migrating', error)
432
+ }
433
+ }
434
+ this.state = {
435
+ version: STORE_VERSION,
436
+ settings: normalizeSettings(parsed?.settings),
437
+ folders: normalized.folders,
438
+ conversations: normalized.conversations,
439
+ }
440
+ this.loaded = true
441
+ if (sourceVersion < STORE_VERSION) {
442
+ // Persist the migrated shape, but a failed write must not discard the
443
+ // in-memory history that was just read successfully.
444
+ try {
445
+ await this.save()
446
+ } catch (error) {
447
+ this.logger.warn?.('deepseek-chat: could not persist the migrated state.json', error)
448
+ }
449
+ }
450
+ return this
451
+ }
452
+
453
+ getSettings() {
454
+ return { ...this.state.settings }
455
+ }
456
+
457
+ async updateSettings(patch) {
458
+ this.state.settings = normalizeSettings({ ...this.state.settings, ...(patch ?? {}) })
459
+ await this.save()
460
+ return this.getSettings()
461
+ }
462
+
463
+ summary(conversation) {
464
+ return {
465
+ id: conversation.id,
466
+ title: conversation.title,
467
+ titleAuto: conversation.titleAuto === true,
468
+ createdAt: conversation.createdAt,
469
+ updatedAt: conversation.updatedAt,
470
+ pinned: conversation.pinned === true,
471
+ pinnedAt: conversation.pinnedAt ?? null,
472
+ archived: conversation.archived === true,
473
+ archivedAt: conversation.archivedAt ?? null,
474
+ folderId: conversation.folderId ?? null,
475
+ messageCount: conversation.messages.length,
476
+ // Present only on an imported conversation; the browser uses it to mark
477
+ // imported chats and a future extractor uses it to find them by source.
478
+ source: conversation.source ?? null,
479
+ }
480
+ }
481
+
482
+ listSummaries() {
483
+ return this.state.conversations
484
+ .map(conversation => this.summary(conversation))
485
+ .sort((left, right) => right.updatedAt - left.updatedAt)
486
+ }
487
+
488
+ listFolders() {
489
+ return [...this.state.folders]
490
+ .sort((left, right) => left.createdAt - right.createdAt)
491
+ .map(folder => ({ ...folder }))
492
+ }
493
+
494
+ getConversation(id) {
495
+ return this.state.conversations.find(conversation => conversation.id === id)
496
+ }
497
+
498
+ /** The conversation one source system already contributed, if any. */
499
+ findBySource(kind, id) {
500
+ if (typeof kind !== 'string' || typeof id !== 'string' || kind === '' || id === '') return undefined
501
+ return this.state.conversations.find(conversation => (
502
+ conversation.source?.kind === kind && conversation.source?.id === id
503
+ ))
504
+ }
505
+
506
+ /** Every source id already imported from one source system. */
507
+ importedSourceIds(kind) {
508
+ const ids = new Set()
509
+ if (typeof kind !== 'string' || kind === '') return ids
510
+ for (const conversation of this.state.conversations) {
511
+ if (conversation.source?.kind === kind) ids.add(conversation.source.id)
512
+ }
513
+ return ids
514
+ }
515
+
516
+ /**
517
+ * Record that long-term memory was extracted from these imported
518
+ * conversations. The marker lives next to the import source so a later run
519
+ * (and a restart) can skip the same history unless it is explicitly redone.
520
+ * Chat messages and ordering are untouched.
521
+ * @returns the conversation ids that were actually marked.
522
+ */
523
+ async markMemoryExtracted(ids, at = Date.now()) {
524
+ const pending = new Set(Array.isArray(ids) ? ids.filter(id => typeof id === 'string' && id !== '') : [])
525
+ if (pending.size === 0) return []
526
+ const marked = []
527
+ for (const conversation of this.state.conversations) {
528
+ if (!pending.has(conversation.id)) continue
529
+ if (conversation.source === null || typeof conversation.source !== 'object') continue
530
+ conversation.source.memoryExtractedAt = at
531
+ marked.push(conversation.id)
532
+ }
533
+ if (marked.length === 0) return []
534
+ await this.save()
535
+ return marked
536
+ }
537
+
538
+ /**
539
+ * Copy the current state document next to itself before a bulk change.
540
+ * @param label - short marker placed in the file name.
541
+ * @returns the backup path, or undefined when no document exists yet.
542
+ */
543
+ async backup(label) {
544
+ try {
545
+ await fs.access(this.file)
546
+ } catch {
547
+ return undefined
548
+ }
549
+ const target = `${this.file}.${label}-${Date.now()}`
550
+ await fs.copyFile(this.file, target)
551
+ return target
552
+ }
553
+
554
+ /**
555
+ * Merge complete conversation drafts into the history.
556
+ *
557
+ * This is the one entry point an importer uses, so an import never writes a
558
+ * second store: drafts go through the same normalization as a loaded
559
+ * document, an id or source already present is refused instead of replaced,
560
+ * and the whole batch is persisted in one write. When that write fails the
561
+ * added conversations are removed again, so the in-memory history keeps
562
+ * matching the document on disk.
563
+ *
564
+ * @param drafts - conversations in the stored shape.
565
+ * @returns `{ added, rejected }`; `added` holds the new conversation ids.
566
+ */
567
+ async adoptConversations(drafts) {
568
+ const added = []
569
+ const rejected = []
570
+ const folderIds = new Set(this.state.folders.map(folder => folder.id))
571
+ for (const draft of Array.isArray(drafts) ? drafts : []) {
572
+ const source = normalizeSource(draft?.source)
573
+ const conversation = normalizeConversation(draft)
574
+ if (conversation === null || conversation.messages.length === 0) {
575
+ rejected.push({ sourceId: source?.id ?? '', reason: 'empty' })
576
+ continue
577
+ }
578
+ if (conversation.folderId !== null && !folderIds.has(conversation.folderId)) conversation.folderId = null
579
+ if (this.state.conversations.some(item => item.id === conversation.id)) {
580
+ rejected.push({ sourceId: source?.id ?? '', reason: 'duplicate-id' })
581
+ continue
582
+ }
583
+ if (conversation.source !== null && this.findBySource(conversation.source.kind, conversation.source.id) !== undefined) {
584
+ rejected.push({ sourceId: conversation.source.id, reason: 'duplicate-source' })
585
+ continue
586
+ }
587
+ this.state.conversations.push(conversation)
588
+ added.push(conversation)
589
+ }
590
+ if (added.length === 0) return { added: [], rejected }
591
+ try {
592
+ await this.save()
593
+ } catch (error) {
594
+ const ids = new Set(added.map(conversation => conversation.id))
595
+ this.state.conversations = this.state.conversations.filter(conversation => !ids.has(conversation.id))
596
+ throw error
597
+ }
598
+ return { added: added.map(conversation => conversation.id), rejected }
599
+ }
600
+
601
+ /** Version metadata for the message's sibling group, when it has one. */
602
+ versionInfo(conversation, messageId) {
603
+ const node = conversation.nodes[messageId]
604
+ if (node === undefined) return null
605
+ const siblings = node.parentId === null
606
+ ? conversation.roots
607
+ : (conversation.nodes[node.parentId]?.children ?? [])
608
+ if (siblings.length < 2) return null
609
+ const index = siblings.indexOf(messageId)
610
+ if (index < 0) return null
611
+ return { index: index + 1, count: siblings.length }
612
+ }
613
+
614
+ presentMessage(conversation, message) {
615
+ const version = this.versionInfo(conversation, message.id)
616
+ return version === null ? message : { ...message, version }
617
+ }
618
+
619
+ /** The active branch with each message's version position attached. */
620
+ presentPath(conversation) {
621
+ return conversation.messages.map(message => this.presentMessage(conversation, message))
622
+ }
623
+
624
+ presentConversation(conversation) {
625
+ return { ...this.summary(conversation), messages: this.presentPath(conversation) }
626
+ }
627
+
628
+ async createConversation() {
629
+ const now = Date.now()
630
+ const conversation = {
631
+ id: randomUUID(),
632
+ title: '',
633
+ titleAuto: true,
634
+ createdAt: now,
635
+ updatedAt: now,
636
+ pinned: false,
637
+ pinnedAt: null,
638
+ archived: false,
639
+ archivedAt: null,
640
+ folderId: null,
641
+ nodes: {},
642
+ roots: [],
643
+ leafId: null,
644
+ messages: [],
645
+ }
646
+ this.state.conversations.push(conversation)
647
+ await this.save()
648
+ return conversation
649
+ }
650
+
651
+ async renameConversation(id, title) {
652
+ const conversation = this.getConversation(id)
653
+ if (conversation === undefined) return undefined
654
+ const next = typeof title === 'string' ? title.replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE) : ''
655
+ conversation.title = next
656
+ conversation.titleAuto = false
657
+ conversation.updatedAt = Date.now()
658
+ await this.save()
659
+ return conversation
660
+ }
661
+
662
+ async deleteConversation(id) {
663
+ const index = this.state.conversations.findIndex(conversation => conversation.id === id)
664
+ if (index < 0) return false
665
+ this.state.conversations.splice(index, 1)
666
+ await this.save()
667
+ return true
668
+ }
669
+
670
+ /**
671
+ * Pin or unpin one conversation. Pinning does not count as activity: the
672
+ * pinned section is ordered by `updatedAt` first and `pinnedAt` second, so a
673
+ * pin never reorders the normal history list.
674
+ */
675
+ async setPinned(id, pinned) {
676
+ const conversation = this.getConversation(id)
677
+ if (conversation === undefined) return undefined
678
+ const next = pinned === true
679
+ if (conversation.pinned !== next) {
680
+ conversation.pinned = next
681
+ conversation.pinnedAt = next ? Date.now() : null
682
+ await this.save()
683
+ }
684
+ return conversation
685
+ }
686
+
687
+ /** Archive or restore a conversation without touching its messages. */
688
+ async setArchived(id, archived) {
689
+ const conversation = this.getConversation(id)
690
+ if (conversation === undefined) return undefined
691
+ const next = archived === true
692
+ if (conversation.archived !== next) {
693
+ conversation.archived = next
694
+ conversation.archivedAt = next ? Date.now() : null
695
+ await this.save()
696
+ }
697
+ return conversation
698
+ }
699
+
700
+ async createFolder(name) {
701
+ const normalized = normalizeFolderName(name)
702
+ if (normalized === '') return undefined
703
+ const now = Date.now()
704
+ const folder = { id: randomUUID(), name: normalized, collapsed: false, createdAt: now, updatedAt: now }
705
+ this.state.folders.push(folder)
706
+ await this.save()
707
+ return folder
708
+ }
709
+
710
+ async renameFolder(id, name) {
711
+ const folder = this.state.folders.find(item => item.id === id)
712
+ if (folder === undefined) return undefined
713
+ const normalized = normalizeFolderName(name)
714
+ if (normalized === '') return undefined
715
+ folder.name = normalized
716
+ folder.updatedAt = Date.now()
717
+ await this.save()
718
+ return folder
719
+ }
720
+
721
+ /**
722
+ * Delete a folder. Chats inside are moved back to the unfiled area; no
723
+ * history is deleted as a side effect of removing the folder itself.
724
+ */
725
+ async deleteFolder(id) {
726
+ const index = this.state.folders.findIndex(folder => folder.id === id)
727
+ if (index < 0) return undefined
728
+ this.state.folders.splice(index, 1)
729
+ let moved = 0
730
+ for (const conversation of this.state.conversations) {
731
+ if (conversation.folderId !== id) continue
732
+ conversation.folderId = null
733
+ moved += 1
734
+ }
735
+ await this.save()
736
+ return { removed: true, moved }
737
+ }
738
+
739
+ async setFolderCollapsed(id, collapsed) {
740
+ const folder = this.state.folders.find(item => item.id === id)
741
+ if (folder === undefined) return undefined
742
+ const next = collapsed === true
743
+ if (folder.collapsed !== next) {
744
+ folder.collapsed = next
745
+ folder.updatedAt = Date.now()
746
+ await this.save()
747
+ }
748
+ return folder
749
+ }
750
+
751
+ /** Move one or more conversations into a folder (`null` means unfiled). */
752
+ async moveConversations(ids, folderId) {
753
+ const target = typeof folderId === 'string' && folderId !== '' ? folderId : null
754
+ if (target !== null && !this.state.folders.some(folder => folder.id === target)) return undefined
755
+ let moved = 0
756
+ for (const id of new Set(Array.isArray(ids) ? ids : [])) {
757
+ const conversation = this.getConversation(id)
758
+ if (conversation === undefined) continue
759
+ if (conversation.folderId === target) continue
760
+ conversation.folderId = target
761
+ moved += 1
762
+ }
763
+ if (moved > 0) await this.save()
764
+ return moved
765
+ }
766
+
767
+ /** Add one message as a child of `parentId` and make it the active leaf. */
768
+ attachNode(conversation, parentId, message) {
769
+ if (message === null || typeof message !== 'object') return null
770
+ let id = typeof message.id === 'string' && message.id !== '' ? message.id : randomUUID()
771
+ if (conversation.nodes[id] !== undefined) id = randomUUID()
772
+ const stored = message.id === id ? message : { ...message, id }
773
+ const parent = typeof parentId === 'string' ? conversation.nodes[parentId] : undefined
774
+ const node = makeNode(id, parent === undefined ? null : parentId, stored)
775
+ conversation.nodes[id] = node
776
+ if (node.parentId === null) conversation.roots.push(id)
777
+ else parent.children.push(id)
778
+ conversation.leafId = id
779
+ rebuildPath(conversation)
780
+ return node
781
+ }
782
+
783
+ applyFirstUserTitle(conversation, message) {
784
+ if (message.role !== 'user') return
785
+ if (conversation.title !== '' || conversation.titleAuto === false) return
786
+ const firstLine = (message.content ?? '').split('\n').map(line => line.trim()).find(Boolean) ?? ''
787
+ const fallback = firstLine || message.files?.[0]?.name || '新对话'
788
+ conversation.title = fallback.replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE)
789
+ conversation.titleAuto = true
790
+ }
791
+
792
+ /** Append one message to the active branch (legacy-friendly entry point). */
793
+ async appendMessage(conversationId, message) {
794
+ const conversation = this.getConversation(conversationId)
795
+ if (conversation === undefined) return undefined
796
+ const node = this.attachNode(conversation, conversation.leafId, message)
797
+ if (node === null) return undefined
798
+ conversation.updatedAt = Math.max(conversation.updatedAt, message.createdAt ?? Date.now())
799
+ this.applyFirstUserTitle(conversation, node.message)
800
+ await this.save()
801
+ return conversation
802
+ }
803
+
804
+ /** Append a complete user/assistant turn to the active branch. */
805
+ async appendTurn(conversationId, userMessage, assistantMessage) {
806
+ const conversation = this.getConversation(conversationId)
807
+ if (conversation === undefined) return undefined
808
+ const userNode = this.attachNode(conversation, conversation.leafId, userMessage)
809
+ if (userNode === null) return undefined
810
+ const replyNode = this.attachNode(conversation, userNode.id, assistantMessage)
811
+ if (replyNode === null) return undefined
812
+ conversation.updatedAt = Math.max(
813
+ conversation.updatedAt,
814
+ userNode.message.createdAt ?? Date.now(),
815
+ replyNode.message.createdAt ?? Date.now(),
816
+ )
817
+ // Sending a new turn in an archived chat brings it back to the history list;
818
+ // the user is clearly using it again.
819
+ if (conversation.archived === true) {
820
+ conversation.archived = false
821
+ conversation.archivedAt = null
822
+ }
823
+ this.applyFirstUserTitle(conversation, userNode.message)
824
+ await this.save()
825
+ return { conversation, userMessage: userNode.message, assistantMessage: replyNode.message }
826
+ }
827
+
828
+ /**
829
+ * Start a new user branch under `parentId` (an edit of a former question);
830
+ * `parentId` is null when the edited message was the first in the chat.
831
+ */
832
+ async createUserBranch(conversationId, message, parentId) {
833
+ const conversation = this.getConversation(conversationId)
834
+ if (conversation === undefined) return undefined
835
+ const node = this.attachNode(conversation, parentId ?? null, message)
836
+ if (node === null) return undefined
837
+ conversation.updatedAt = Math.max(conversation.updatedAt, node.message.createdAt ?? Date.now())
838
+ this.applyFirstUserTitle(conversation, node.message)
839
+ await this.save()
840
+ return { conversation, message: node.message }
841
+ }
842
+
843
+ /** Start a new answer branch under a user message (a regeneration). */
844
+ async createAssistantBranch(conversationId, message, parentUserId) {
845
+ const conversation = this.getConversation(conversationId)
846
+ if (conversation === undefined) return undefined
847
+ const node = this.attachNode(conversation, parentUserId, message)
848
+ if (node === null) return undefined
849
+ conversation.updatedAt = Math.max(conversation.updatedAt, node.message.createdAt ?? Date.now())
850
+ await this.save()
851
+ return { conversation, message: node.message }
852
+ }
853
+
854
+ async replaceMessage(conversationId, message) {
855
+ const conversation = this.getConversation(conversationId)
856
+ if (conversation === undefined) return undefined
857
+ const node = conversation.nodes[message.id]
858
+ if (node === undefined) return undefined
859
+ node.message = message
860
+ conversation.updatedAt = Math.max(conversation.updatedAt, message.updatedAt ?? message.createdAt ?? Date.now())
861
+ rebuildPath(conversation)
862
+ await this.save()
863
+ return conversation
864
+ }
865
+
866
+ /** Apply a server-generated title only while the current title is automatic. */
867
+ async applyAutoTitle(conversationId, title) {
868
+ const conversation = this.getConversation(conversationId)
869
+ if (conversation === undefined) return false
870
+ const normalized = typeof title === 'string' ? title.replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE) : ''
871
+ if (normalized === '' || conversation.titleAuto === false) return false
872
+ conversation.title = normalized
873
+ conversation.titleAuto = false
874
+ conversation.updatedAt = Date.now()
875
+ await this.save()
876
+ return true
877
+ }
878
+
879
+ /**
880
+ * Switch to the neighbouring sibling of `messageId` and reopen the deepest
881
+ * branch below it, so the previous edits and answers remain reachable.
882
+ */
883
+ async selectVersion(conversationId, messageId, direction) {
884
+ const conversation = this.getConversation(conversationId)
885
+ if (conversation === undefined) return undefined
886
+ const node = conversation.nodes[messageId]
887
+ if (node === undefined) return undefined
888
+ const siblings = node.parentId === null
889
+ ? conversation.roots
890
+ : (conversation.nodes[node.parentId]?.children ?? [])
891
+ if (siblings.length < 2) return undefined
892
+ const index = siblings.indexOf(messageId)
893
+ if (index < 0) return undefined
894
+ const step = direction < 0 ? -1 : 1
895
+ const selectedId = siblings[(index + step + siblings.length) % siblings.length]
896
+ conversation.leafId = deepestLeafId(conversation, selectedId)
897
+ rebuildPath(conversation)
898
+ await this.save()
899
+ return { conversation, selectedId }
900
+ }
901
+
902
+ /** Reopen the branch that contains `messageId` (history-search jump). */
903
+ async focusMessage(conversationId, messageId) {
904
+ const conversation = this.getConversation(conversationId)
905
+ if (conversation === undefined) return undefined
906
+ if (conversation.nodes[messageId] === undefined) return undefined
907
+ conversation.leafId = deepestLeafId(conversation, messageId)
908
+ rebuildPath(conversation)
909
+ await this.save()
910
+ return conversation
911
+ }
912
+
913
+ /**
914
+ * Search titles and message bodies across every folder, pinned and archived
915
+ * conversation. The active branch wins ties, so the most useful match is the
916
+ * one the user can jump to directly.
917
+ */
918
+ search(query, { limit = SEARCH_LIMIT } = {}) {
919
+ const raw = typeof query === 'string' ? query.replace(/\s+/g, ' ').trim().slice(0, MAX_SEARCH_QUERY) : ''
920
+ if (raw === '') return { query: '', results: [], total: 0 }
921
+ const needle = raw.toLowerCase()
922
+ const results = []
923
+ for (const conversation of this.state.conversations) {
924
+ const titleMatch = conversation.title.toLowerCase().includes(needle)
925
+ const activeIds = new Set(conversation.messages.map(message => message.id))
926
+ let best = null
927
+ for (const node of Object.values(conversation.nodes)) {
928
+ const text = messageSearchText(node.message)
929
+ if (text === '') continue
930
+ const snippet = excerptOf(text, needle)
931
+ if (snippet === '') continue
932
+ const active = activeIds.has(node.message.id)
933
+ const candidate = {
934
+ messageId: node.message.id,
935
+ role: node.message.role,
936
+ snippet,
937
+ onActivePath: active,
938
+ }
939
+ if (
940
+ best === null
941
+ || (candidate.onActivePath && !best.onActivePath)
942
+ || (candidate.onActivePath === best.onActivePath && candidate.role === 'user' && best.role !== 'user')
943
+ ) {
944
+ best = candidate
945
+ }
946
+ }
947
+ if (!titleMatch && best === null) continue
948
+ results.push({ ...this.summary(conversation), titleMatch, ...(best ?? {}) })
949
+ }
950
+ results.sort((left, right) => (
951
+ Number(right.titleMatch) - Number(left.titleMatch)
952
+ || Number(right.onActivePath === true) - Number(left.onActivePath === true)
953
+ || right.updatedAt - left.updatedAt
954
+ ))
955
+ return { query: raw, results: results.slice(0, limit), total: results.length }
956
+ }
957
+
958
+ async save() {
959
+ const write = () => this.writeNow()
960
+ this.writeChain = this.writeChain.then(write, write)
961
+ return this.writeChain
962
+ }
963
+
964
+ /** Persist the tree without the derived links and active path. */
965
+ serializable() {
966
+ return {
967
+ version: STORE_VERSION,
968
+ settings: this.state.settings,
969
+ folders: this.state.folders,
970
+ conversations: this.state.conversations.map(conversation => ({
971
+ id: conversation.id,
972
+ title: conversation.title,
973
+ titleAuto: conversation.titleAuto,
974
+ createdAt: conversation.createdAt,
975
+ updatedAt: conversation.updatedAt,
976
+ pinned: conversation.pinned === true,
977
+ pinnedAt: conversation.pinnedAt ?? null,
978
+ archived: conversation.archived === true,
979
+ archivedAt: conversation.archivedAt ?? null,
980
+ folderId: conversation.folderId ?? null,
981
+ ...(conversation.source === null || conversation.source === undefined ? {} : { source: conversation.source }),
982
+ leafId: conversation.leafId,
983
+ nodes: Object.fromEntries(
984
+ Object.entries(conversation.nodes).map(([id, node]) => [id, { parentId: node.parentId, message: node.message }]),
985
+ ),
986
+ })),
987
+ }
988
+ }
989
+
990
+ async writeNow() {
991
+ const temporary = `${this.file}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`
992
+ const data = `${JSON.stringify(this.serializable())}\n`
993
+ await fs.mkdir(this.directory, { recursive: true })
994
+ await fs.writeFile(temporary, data, 'utf8')
995
+ try {
996
+ await fs.rename(temporary, this.file)
997
+ } catch (error) {
998
+ if (error?.code === 'EEXIST' || error?.code === 'EPERM' || error?.code === 'EACCES') {
999
+ await fs.copyFile(temporary, this.file)
1000
+ await fs.rm(temporary, { force: true })
1001
+ } else {
1002
+ await fs.rm(temporary, { force: true }).catch(() => {})
1003
+ throw error
1004
+ }
1005
+ }
1006
+ }
1007
+
1008
+ async flush() {
1009
+ await this.writeChain
1010
+ }
1011
+ }