@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
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Document workspaces for Chat.
3
+ *
4
+ * Every document task lives under one shared `Documents` workspace, so the
5
+ * Agent UI shows a single group and the user finds every file in one place.
6
+ * Each Chat conversation still gets its own subfolder inside it (readable title
7
+ * plus a short id suffix); the task prompt confines the Agent to that subfolder.
8
+ * `uploads/` holds read-only copies of what the user attached; `files/` holds the
9
+ * documents the Agent produces. Every request path goes through `resolveInside`,
10
+ * so a request can never escape the conversation folder.
11
+ */
12
+
13
+ import path from 'node:path'
14
+ import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises'
15
+
16
+ /** The document formats the Chat half may send into a workspace. */
17
+ export const DOCUMENT_EXTENSIONS = new Set([
18
+ 'doc', 'docx', 'odt', 'xls', 'xlsx', 'ods', 'csv', 'ppt', 'pptx', 'odp',
19
+ 'pdf', 'txt', 'md', 'markdown',
20
+ ])
21
+
22
+ /** Formats the Host can turn into a PNG preview through Office Kit. */
23
+ export const PREVIEW_EXTENSIONS = new Set(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'])
24
+
25
+ const MIME_TYPES = {
26
+ doc: 'application/msword',
27
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
28
+ odt: 'application/vnd.oasis.opendocument.text',
29
+ xls: 'application/vnd.ms-excel',
30
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
31
+ ods: 'application/vnd.oasis.opendocument.spreadsheet',
32
+ csv: 'text/csv',
33
+ ppt: 'application/vnd.ms-powerpoint',
34
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
35
+ odp: 'application/vnd.oasis.opendocument.presentation',
36
+ pdf: 'application/pdf',
37
+ txt: 'text/plain',
38
+ md: 'text/markdown',
39
+ markdown: 'text/markdown',
40
+ }
41
+
42
+ /** Strip anything that could steer a path or a shell, and bound the name. */
43
+ export function safeFileName(input) {
44
+ const raw = typeof input === 'string' ? input : ''
45
+ const base = path.basename(raw.replace(/\\/g, '/'))
46
+ const cleaned = base
47
+ .replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_')
48
+ .replace(/^\.+/, '')
49
+ .trim()
50
+ if (cleaned === '') return 'document'
51
+ if (cleaned.length <= 120) return cleaned
52
+ const ext = path.extname(cleaned).slice(0, 12)
53
+ return `${cleaned.slice(0, Math.max(1, 120 - ext.length))}${ext}`
54
+ }
55
+
56
+ export function fileKind(name) {
57
+ const ext = path.extname(String(name)).slice(1).toLowerCase()
58
+ if (ext === 'doc' || ext === 'docx' || ext === 'odt') return 'word'
59
+ if (ext === 'xls' || ext === 'xlsx' || ext === 'ods' || ext === 'csv') return 'excel'
60
+ if (ext === 'ppt' || ext === 'pptx' || ext === 'odp') return 'slides'
61
+ if (ext === 'pdf') return 'pdf'
62
+ if (ext === 'md' || ext === 'markdown' || ext === 'txt') return 'text'
63
+ return 'file'
64
+ }
65
+
66
+ export function fileMime(name) {
67
+ return MIME_TYPES[path.extname(String(name)).slice(1).toLowerCase()] ?? 'application/octet-stream'
68
+ }
69
+
70
+ export function fileExtension(name) {
71
+ return path.extname(String(name)).slice(1).toLowerCase()
72
+ }
73
+
74
+ /** The one Documents workspace shared by every Chat document task. */
75
+ export function documentsRoot(baseDir) {
76
+ return path.join(baseDir, 'Documents')
77
+ }
78
+
79
+ /** A readable, stable subfolder name inside Documents for one conversation. */
80
+ export function conversationFolderName(conversationId, title) {
81
+ const compact = String(conversationId).replace(/[^a-zA-Z0-9]/g, '')
82
+ if (compact === '') throw new Error('invalid conversation id')
83
+ return `${folderSlug(title)}-${compact.slice(0, 8).toLowerCase()}`
84
+ }
85
+
86
+ function folderSlug(title) {
87
+ const cleaned = String(title ?? '')
88
+ .replace(/[<>:"/\\|?*\u0000-\u001f]/g, ' ')
89
+ .replace(/\s+/g, '-')
90
+ .replace(/^[.\-\s]+|[.\-\s]+$/g, '')
91
+ .slice(0, 40)
92
+ return cleaned === '' ? 'documents' : cleaned
93
+ }
94
+
95
+ /** Find the conversation's existing subfolder by its id suffix. */
96
+ export async function findConversationRoot(sharedRoot, conversationId) {
97
+ const compact = String(conversationId).replace(/[^a-zA-Z0-9]/g, '')
98
+ if (compact === '') throw new Error('invalid conversation id')
99
+ const suffix = `-${compact.slice(0, 8).toLowerCase()}`
100
+ let entries
101
+ try {
102
+ entries = await readdir(sharedRoot, { withFileTypes: true })
103
+ } catch {
104
+ return undefined
105
+ }
106
+ const found = entries.find(entry => entry.isDirectory() && entry.name.toLowerCase().endsWith(suffix))
107
+ return found === undefined ? undefined : path.join(sharedRoot, found.name)
108
+ }
109
+
110
+ /**
111
+ * Ensure the conversation's subfolder exists and return it.
112
+ * @returns the folder and whether this call created it.
113
+ */
114
+ export async function ensureConversationRoot(sharedRoot, conversationId, title) {
115
+ await mkdir(sharedRoot, { recursive: true })
116
+ const existing = await findConversationRoot(sharedRoot, conversationId)
117
+ if (existing !== undefined) return { root: existing, created: false }
118
+ const root = path.join(sharedRoot, conversationFolderName(conversationId, title))
119
+ await mkdir(root, { recursive: true })
120
+ return { root, created: true }
121
+ }
122
+
123
+ /** Resolve one workspace-relative path, refusing escapes and absolute input. */
124
+ export function resolveInside(root, relPath) {
125
+ if (typeof relPath !== 'string' || relPath === '') throw new Error('empty path')
126
+ if (path.isAbsolute(relPath)) throw new Error('absolute paths are not accepted')
127
+ const normalized = path.normalize(relPath.replace(/\\/g, '/'))
128
+ if (normalized === '.' || normalized.startsWith('..')) throw new Error('path escapes the workspace')
129
+ const absolute = path.resolve(root, normalized)
130
+ const relative = path.relative(root, absolute)
131
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
132
+ throw new Error('path escapes the workspace')
133
+ }
134
+ return { absolute, relPath: relative.split(path.sep).join('/') }
135
+ }
136
+
137
+ export async function ensureWorkspace(root) {
138
+ await mkdir(path.join(root, 'files'), { recursive: true })
139
+ await mkdir(path.join(root, 'uploads'), { recursive: true })
140
+ }
141
+
142
+ /** Store one uploaded file as a read-only copy and return its metadata. */
143
+ export async function saveUpload(root, name, bytes) {
144
+ const safe = safeFileName(name)
145
+ const uploads = path.join(root, 'uploads')
146
+ await mkdir(uploads, { recursive: true })
147
+ const stored = await uniquePath(uploads, safe)
148
+ await writeFile(stored.absolute, bytes)
149
+ return {
150
+ name: path.basename(stored.absolute),
151
+ relPath: `uploads/${path.basename(stored.absolute)}`,
152
+ bytes: bytes.length,
153
+ kind: fileKind(safe),
154
+ mime: fileMime(safe),
155
+ }
156
+ }
157
+
158
+ /** Add " (2)" before the extension until the name is free. */
159
+ async function uniquePath(dir, name) {
160
+ const ext = path.extname(name)
161
+ const stem = name.slice(0, name.length - ext.length)
162
+ for (let index = 1; index < 200; index += 1) {
163
+ const candidate = index === 1 ? name : `${stem} (${index})${ext}`
164
+ const absolute = path.join(dir, candidate)
165
+ try {
166
+ await stat(absolute)
167
+ } catch {
168
+ return { absolute, name: candidate }
169
+ }
170
+ }
171
+ return { absolute: path.join(dir, `${stem} (${Date.now()})${ext}`), name }
172
+ }
173
+
174
+ /**
175
+ * Every document currently in the workspace. `files/` is scanned recursively;
176
+ * a file the Agent dropped at the root is included too, but uploads and control
177
+ * files never are.
178
+ */
179
+ export async function listDocuments(root) {
180
+ const found = []
181
+ await collect(path.join(root, 'files'), 'files', found, 0)
182
+ await collectRoot(path.join(root), found)
183
+ found.sort((left, right) => right.updatedAt - left.updatedAt)
184
+ return found
185
+ }
186
+
187
+ /** The user's uploaded read-only copies, for the task prompt. */
188
+ export async function listUploads(root) {
189
+ const found = []
190
+ await collect(path.join(root, 'uploads'), 'uploads', found, 0)
191
+ found.sort((left, right) => left.name.localeCompare(right.name))
192
+ return found
193
+ }
194
+
195
+ async function collectRoot(root, found) {
196
+ let entries
197
+ try {
198
+ entries = await readdir(root, { withFileTypes: true })
199
+ } catch {
200
+ return
201
+ }
202
+ for (const entry of entries) {
203
+ if (!entry.isFile()) continue
204
+ if (entry.name.startsWith('.') || entry.name === 'meta.json') continue
205
+ await pushFile(path.join(root, entry.name), entry.name, found)
206
+ }
207
+ }
208
+
209
+ async function collect(dir, prefix, found, depth) {
210
+ if (depth > 2) return
211
+ let entries
212
+ try {
213
+ entries = await readdir(dir, { withFileTypes: true })
214
+ } catch {
215
+ return
216
+ }
217
+ for (const entry of entries) {
218
+ const relPath = `${prefix}/${entry.name}`
219
+ if (entry.isDirectory()) {
220
+ if (entry.name.startsWith('.')) continue
221
+ await collect(path.join(dir, entry.name), relPath, found, depth + 1)
222
+ continue
223
+ }
224
+ if (!entry.isFile() || entry.name.startsWith('.')) continue
225
+ await pushFile(path.join(dir, entry.name), relPath, found)
226
+ }
227
+ }
228
+
229
+ async function pushFile(absolute, relPath, found) {
230
+ let info
231
+ try {
232
+ info = await stat(absolute)
233
+ } catch {
234
+ return
235
+ }
236
+ if (!info.isFile() || info.size === 0) return
237
+ const name = path.basename(absolute)
238
+ found.push({
239
+ name,
240
+ relPath: relPath.split(path.sep).join('/'),
241
+ kind: fileKind(name),
242
+ mime: fileMime(name),
243
+ bytes: info.size,
244
+ updatedAt: Math.floor(info.mtimeMs),
245
+ })
246
+ }
247
+
248
+ export async function readMeta(root) {
249
+ try {
250
+ const value = JSON.parse(await readFile(path.join(root, 'meta.json'), 'utf8'))
251
+ return value !== null && typeof value === 'object' ? value : {}
252
+ } catch {
253
+ return {}
254
+ }
255
+ }
256
+
257
+ export async function writeMeta(root, meta) {
258
+ await mkdir(root, { recursive: true })
259
+ await writeFile(path.join(root, 'meta.json'), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
260
+ }
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Conversion of one exported DeepSeek conversation into a dsh-chat conversation.
3
+ *
4
+ * The result is a plain draft in the shape the chat store already persists, so
5
+ * the import reuses the native history: no parallel storage, and every existing
6
+ * feature (reading, search, rename, pin, archive, folders, branch switching,
7
+ * continuing, handing off to Agent) works on an imported chat unchanged.
8
+ *
9
+ * What is preserved:
10
+ * - the whole message tree, so edited questions and regenerated answers stay
11
+ * switchable as sibling versions, with `current_message_id` as the active leaf;
12
+ * - the original title, creation and update time, and pin state;
13
+ * - question text, answers, reasoning (with its reported duration), web-search
14
+ * steps and their results, opened pages, and attachment metadata with locally
15
+ * recovered image bytes;
16
+ * - the server's content-warning notice, as a non-answer notice block.
17
+ *
18
+ * What is not invented: an answer that the export records as unfinished stays
19
+ * unfinished, a filtered or timed-out reply keeps the server's template text,
20
+ * and no citation markers are placed inside an answer the export does not
21
+ * position.
22
+ */
23
+
24
+ import { randomUUID } from 'node:crypto'
25
+ import { selectActiveBranch, ExportFormatError } from './format.js'
26
+
27
+ /** Marker stored on every imported conversation so re-imports are recognised. */
28
+ export const SOURCE_KIND = 'deepseek-export'
29
+
30
+ /** Model id recorded on imported replies: the export never names the model. */
31
+ const IMPORTED_MODEL = 'deepseek-flash'
32
+
33
+ /** Media types restored for attachments; anything else stays metadata only. */
34
+ const MIME_BY_EXTENSION = new Map([
35
+ ['png', 'image/png'],
36
+ ['jpg', 'image/jpeg'],
37
+ ['jpeg', 'image/jpeg'],
38
+ ['webp', 'image/webp'],
39
+ ['gif', 'image/gif'],
40
+ ['bmp', 'image/bmp'],
41
+ ['tif', 'image/tiff'],
42
+ ['tiff', 'image/tiff'],
43
+ ['svg', 'image/svg+xml'],
44
+ ['avif', 'image/avif'],
45
+ ['pdf', 'application/pdf'],
46
+ ])
47
+
48
+ const MAX_TITLE = 80
49
+
50
+ function extensionOf(name) {
51
+ const value = typeof name === 'string' ? name : ''
52
+ const dot = value.lastIndexOf('.')
53
+ return dot > 0 && dot < value.length - 1 ? value.slice(dot + 1).toLowerCase() : ''
54
+ }
55
+
56
+ function mimeTypeOf(name) {
57
+ return MIME_BY_EXTENSION.get(extensionOf(name)) ?? 'application/octet-stream'
58
+ }
59
+
60
+ /** The display name of an exported file: its leaf name, without control characters. */
61
+ function displayName(name) {
62
+ const value = typeof name === 'string' ? name : ''
63
+ const leaf = value.slice(Math.max(value.lastIndexOf('/'), value.lastIndexOf('\\')) + 1)
64
+ const clean = leaf.replace(/[\u0000-\u001f\u007f]/gu, '').trim()
65
+ return clean === '' ? 'file' : clean.slice(0, 200)
66
+ }
67
+
68
+ /** One display title candidate, normalized the way the store normalizes titles. */
69
+ function normalizeTitle(value) {
70
+ return typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE) : ''
71
+ }
72
+
73
+ /**
74
+ * Convert the fragments of one reply into stored display blocks.
75
+ *
76
+ * Reasoning becomes `thinking` blocks, whose reported duration is laid out from
77
+ * the reply's own start time. Answers become `text` blocks. A web search and an
78
+ * opened page each become the pair the chat already renders as one process step.
79
+ * The content-warning notice becomes a `notice` block, so it never becomes part
80
+ * of the answer text, the copied text, or the model context.
81
+ *
82
+ * @param message - one export message.
83
+ * @param startedAt - epoch ms the reply started, used for reasoning durations.
84
+ * @returns `{ blocks, elapsedMs, thinking, search }`.
85
+ */
86
+ function replyBlocks(message, startedAt) {
87
+ const blocks = []
88
+ let cursor = startedAt
89
+ let toolIndex = 0
90
+ let thinking = false
91
+ let search = false
92
+ const nextToolId = () => {
93
+ toolIndex += 1
94
+ return `t${message.id}-${toolIndex}`
95
+ }
96
+ for (const fragment of message.fragments) {
97
+ if (fragment === undefined || fragment.ignored === true) continue
98
+ switch (fragment.type) {
99
+ case 'THINK': {
100
+ const end = cursor + fragment.elapsedMs
101
+ if (fragment.content.trim() !== '') {
102
+ thinking = true
103
+ blocks.push({
104
+ type: 'thinking',
105
+ thinking: fragment.content,
106
+ signature: '',
107
+ startedAt: cursor,
108
+ endedAt: end,
109
+ })
110
+ }
111
+ cursor = end
112
+ break
113
+ }
114
+ case 'RESPONSE':
115
+ if (fragment.content !== '') blocks.push({ type: 'text', text: fragment.content, citations: [] })
116
+ break
117
+ case 'TEMPLATE_RESPONSE':
118
+ // The server's own wording for a filtered or timed-out reply is what the
119
+ // website showed, so it stays the visible answer.
120
+ if (fragment.content !== '') blocks.push({ type: 'text', text: fragment.content, citations: [] })
121
+ break
122
+ case 'CONTENT_RISK':
123
+ blocks.push({ type: 'notice', kind: 'content_risk', style: fragment.style, text: fragment.content })
124
+ break
125
+ case 'TOOL_SEARCH': {
126
+ if (fragment.status === 'WIP') break
127
+ search = true
128
+ const id = nextToolId()
129
+ blocks.push({
130
+ type: 'server_tool_use',
131
+ id,
132
+ name: 'deepseek_web_search',
133
+ kind: 'search',
134
+ input: { action: 'search', queries: fragment.queries },
135
+ })
136
+ const failed = fragment.status === 'FAILED'
137
+ blocks.push({
138
+ type: 'web_search_tool_result',
139
+ tool_use_id: id,
140
+ kind: 'search',
141
+ content: failed
142
+ ? [{ type: 'web_search_tool_result_error', error_code: 'unavailable' }]
143
+ : fragment.results.map(result => ({
144
+ type: 'web_search_result',
145
+ title: result.title,
146
+ url: result.url,
147
+ snippet: result.snippet,
148
+ site_name: result.siteName === '' ? null : result.siteName,
149
+ site_icon: result.siteIcon === '' ? null : result.siteIcon,
150
+ page_age: result.publishedAt ?? null,
151
+ })),
152
+ })
153
+ break
154
+ }
155
+ case 'TOOL_OPEN': {
156
+ if (fragment.status === 'WIP' || fragment.url === undefined) break
157
+ const id = nextToolId()
158
+ const failed = fragment.status === 'FAILED'
159
+ blocks.push({
160
+ type: 'server_tool_use',
161
+ id,
162
+ name: 'deepseek_read_url',
163
+ kind: 'read_link',
164
+ input: { url: fragment.url },
165
+ })
166
+ blocks.push({
167
+ type: 'web_fetch_tool_result',
168
+ tool_use_id: id,
169
+ kind: 'read_link',
170
+ content: failed
171
+ ? { type: 'web_fetch_tool_result_error', error_code: 'unavailable' }
172
+ : {
173
+ type: 'web_fetch_result',
174
+ url: fragment.url,
175
+ title: fragment.title ?? null,
176
+ published_at: fragment.publishedAt ?? null,
177
+ // The export carries the page address and title only; the body is
178
+ // never part of it, so no body is stored.
179
+ content: {
180
+ type: 'document',
181
+ source: { type: 'text', media_type: 'text/plain', data: '' },
182
+ title: fragment.title ?? null,
183
+ },
184
+ },
185
+ })
186
+ break
187
+ }
188
+ default:
189
+ break
190
+ }
191
+ }
192
+ return { blocks, elapsedMs: cursor - startedAt, thinking, search }
193
+ }
194
+
195
+ /** Stored status of one reply, from the export status. */
196
+ function replyStatus(status) {
197
+ // An unfinished reply stays visibly unfinished; the chat shows a muted note and
198
+ // offers to continue it instead of pretending the answer completed.
199
+ if (status === 'INCOMPLETE' || status === 'TIMEOUT') return 'stopped'
200
+ return 'done'
201
+ }
202
+
203
+ /**
204
+ * Convert one exported conversation tree.
205
+ *
206
+ * @param file - validated conversation file from the archive.
207
+ * @param row - the conversation's index row (title, times, pin, message count).
208
+ * @param options - `importedAt` timestamp and `resolveMedia(exportPath)`.
209
+ * @returns `{ draft, stats }`; `draft` is ready for `store.adoptConversations`.
210
+ * @throws {ExportFormatError} when the tree is unusable.
211
+ */
212
+ export function convertConversation(file, row, options = {}) {
213
+ const importedAt = typeof options.importedAt === 'number' ? options.importedAt : Date.now()
214
+ const resolveMedia = typeof options.resolveMedia === 'function' ? options.resolveMedia : () => undefined
215
+ const branch = selectActiveBranch(file.messages, file.currentMessageId)
216
+ const lastMessage = branch[branch.length - 1]
217
+ const firstMessage = branch[0]
218
+ const stats = { messages: file.messages.length, files: 0, images: 0, restoredImages: 0, notices: 0 }
219
+
220
+ const nodes = {}
221
+ const ordered = [...file.messages].sort((left, right) => left.id - right.id)
222
+ let fallbackTime = file.insertedAt ?? row.insertedAt ?? Date.now()
223
+ for (const message of ordered) {
224
+ const createdAt = message.createdAt ?? fallbackTime
225
+ if (message.createdAt !== undefined) fallbackTime = message.createdAt
226
+ const nodeId = `m${message.id}`
227
+ const parentId = message.parentId === null ? null : `m${message.parentId}`
228
+ if (message.role === 'USER') {
229
+ const parts = []
230
+ const files = []
231
+ for (const fragment of message.fragments) {
232
+ if (fragment === undefined || fragment.ignored === true) continue
233
+ if (fragment.type === 'REQUEST') parts.push(fragment.content)
234
+ if (fragment.type !== 'FILE') continue
235
+ for (const entry of fragment.files) {
236
+ stats.files += 1
237
+ if (entry.isImage) stats.images += 1
238
+ const recovered = entry.exportPath === undefined ? undefined : resolveMedia(entry.exportPath)
239
+ if (recovered !== undefined && entry.isImage) stats.restoredImages += 1
240
+ const name = displayName(entry.name)
241
+ files.push({
242
+ id: entry.id ?? randomUUID(),
243
+ // Imported attachments are not on DeepSeek's file service, so the id
244
+ // is a local marker: it names the stored bytes and is never sent to
245
+ // the API (protocol.js skips local files when building a request).
246
+ fileId: recovered === undefined ? `export:${entry.id ?? name}` : `local:${recovered.media}`,
247
+ name,
248
+ size: recovered?.size ?? entry.size,
249
+ mimeType: mimeTypeOf(name),
250
+ isImage: entry.isImage,
251
+ local: true,
252
+ ...(recovered === undefined ? {} : { media: recovered.media }),
253
+ })
254
+ }
255
+ }
256
+ nodes[nodeId] = {
257
+ parentId,
258
+ message: {
259
+ id: nodeId,
260
+ role: 'user',
261
+ content: parts.join('\n'),
262
+ files,
263
+ createdAt,
264
+ },
265
+ }
266
+ continue
267
+ }
268
+ const built = replyBlocks(message, createdAt)
269
+ for (const block of built.blocks) {
270
+ if (block.type === 'notice') stats.notices += 1
271
+ }
272
+ nodes[nodeId] = {
273
+ parentId,
274
+ message: {
275
+ id: nodeId,
276
+ role: 'assistant',
277
+ createdAt,
278
+ updatedAt: createdAt + built.elapsedMs,
279
+ model: IMPORTED_MODEL,
280
+ thinking: built.thinking,
281
+ search: built.search,
282
+ status: replyStatus(message.status),
283
+ blocks: built.blocks,
284
+ prefix: true,
285
+ },
286
+ }
287
+ }
288
+ if (Object.keys(nodes).length === 0) {
289
+ throw new ExportFormatError('NO_MESSAGES', 'the conversation has no usable message')
290
+ }
291
+
292
+ // The active leaf is the message the export says the user last saw; the branch
293
+ // selection already rejected a missing or looped tree, so the node exists.
294
+ const leafId = `m${lastMessage.id}`
295
+ const title = normalizeTitle(file.title) || normalizeTitle(row.title) || titleFromBranch(branch)
296
+ const createdAt = row.insertedAt ?? file.insertedAt ?? firstMessage.createdAt ?? importedAt
297
+ const updatedAt = Math.max(
298
+ createdAt,
299
+ row.updatedAt ?? file.updatedAt ?? lastMessage.createdAt ?? createdAt,
300
+ )
301
+ const pinned = row.pinned === true
302
+ return {
303
+ draft: {
304
+ id: randomUUID(),
305
+ title,
306
+ // A title the export supplied is the user's own title and must not be
307
+ // replaced by the automatic first-line title.
308
+ titleAuto: normalizeTitle(file.title) === '' && normalizeTitle(row.title) === '',
309
+ createdAt,
310
+ updatedAt,
311
+ pinned,
312
+ pinnedAt: pinned ? updatedAt : null,
313
+ archived: false,
314
+ archivedAt: null,
315
+ folderId: null,
316
+ leafId,
317
+ nodes,
318
+ source: { kind: SOURCE_KIND, id: file.id, importedAt },
319
+ },
320
+ stats: {
321
+ ...stats,
322
+ activeMessages: branch.length,
323
+ },
324
+ }
325
+ }
326
+
327
+ /** First line of the first question on the active branch, used when no title exists. */
328
+ function titleFromBranch(branch) {
329
+ for (const message of branch) {
330
+ if (message.role !== 'USER') continue
331
+ for (const fragment of message.fragments) {
332
+ if (fragment?.type !== 'REQUEST') continue
333
+ const line = fragment.content.split('\n').map(value => value.trim()).find(Boolean)
334
+ if (line !== undefined) return normalizeTitle(line)
335
+ }
336
+ for (const fragment of message.fragments) {
337
+ if (fragment?.type !== 'FILE' || fragment.files.length === 0) continue
338
+ const name = displayName(fragment.files[0].name)
339
+ if (name !== '') return normalizeTitle(name)
340
+ }
341
+ }
342
+ return ''
343
+ }