@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,593 @@
1
+ /**
2
+ * Pure protocol helpers for the DeepSeek Chat mode.
3
+ *
4
+ * The chat speaks DeepSeek's Anthropic-compatible Messages API. The complete
5
+ * conversation is reconstructed from this plugin's own persisted history; the
6
+ * helpers below fold streamed events into display/persisted blocks and rebuild
7
+ * a request body from completed turn pairs.
8
+ */
9
+
10
+ /** Official identity line used by the web/app assistant. */
11
+ export const DEFAULT_SYSTEM_PROMPT = '该助手为DeepSeek,由深度求索公司创造。'
12
+
13
+ /** Model used when the caller does not choose one. */
14
+ export const CHAT_MODEL = 'deepseek-flash'
15
+
16
+ /** Human-facing label of the default model. */
17
+ export const CHAT_MODEL_NAME = 'DeepSeek V4.1 Flash'
18
+
19
+ /** Roles this plugin writes to its own store. */
20
+ export const MESSAGE_ROLE = Object.freeze({ user: 'user', assistant: 'assistant' })
21
+
22
+ /**
23
+ * Thinking parameters for one Messages request.
24
+ *
25
+ * The API separates the switch (`thinking.type`) from the intensity
26
+ * (`output_config.effort`). An explicit type wins over effort, so the effort is
27
+ * only meaningful while thinking is on; sending it with thinking disabled would
28
+ * be ignored but noisy, therefore it is omitted.
29
+ * @param thinking - whether the reply should reason first.
30
+ * @param effort - "low" | "high" | "max" (already validated by the caller).
31
+ */
32
+ export function thinkingParams(thinking, effort = 'high') {
33
+ if (!thinking) return { thinking: { type: 'disabled' } }
34
+ // Accept the API's compatibility aliases (minimal/low/high/max/ultra...) but
35
+ // only ever send one of the three real tiers.
36
+ const tier = effort === 'max' || effort === 'ultra'
37
+ ? 'max'
38
+ : effort === 'low' || effort === 'minimal'
39
+ ? 'low'
40
+ : 'high'
41
+ return {
42
+ thinking: { type: 'enabled' },
43
+ output_config: { effort: tier },
44
+ }
45
+ }
46
+
47
+ /** Search tools declared for each request; url reading is always available. */
48
+ export function serverTools(search) {
49
+ const tools = [{ type: 'deepseek_read_url', name: 'deepseek_read_url' }]
50
+ if (search) tools.push({ type: 'deepseek_web_search', name: 'deepseek_web_search' })
51
+ return tools
52
+ }
53
+
54
+ /** Trim a server title and keep it within the storage/UI bound. */
55
+ export function normalizeTitle(value) {
56
+ if (typeof value !== 'string') return ''
57
+ return value.replace(/\s+/g, ' ').trim().slice(0, 80)
58
+ }
59
+
60
+ /** A display title derived from the first human turn. */
61
+ export function titleFromUserMessage(message) {
62
+ const text = typeof message?.content === 'string' ? message.content : ''
63
+ const firstLine = text.split('\n').map(line => line.trim()).find(Boolean) ?? ''
64
+ const fallback = Array.isArray(message?.files) && message.files.length > 0
65
+ ? message.files[0].name
66
+ : ''
67
+ const title = normalizeTitle(firstLine || fallback)
68
+ return title || '新对话'
69
+ }
70
+
71
+ /** Date/weekday/region/platform/language marker understood by the model. */
72
+ export function createLatestReminder({ now = new Date(), locale = 'zh', timeZone } = {}) {
73
+ const zone = timeZone || undefined
74
+ let date
75
+ try {
76
+ date = new Intl.DateTimeFormat('en-CA', {
77
+ year: 'numeric', month: '2-digit', day: '2-digit', timeZone: zone,
78
+ }).format(now)
79
+ } catch {
80
+ date = now.toISOString().slice(0, 10)
81
+ }
82
+ let weekday
83
+ try {
84
+ weekday = new Intl.DateTimeFormat(locale === 'zh' ? 'zh-CN' : 'en-US', {
85
+ weekday: 'long', timeZone: zone,
86
+ }).format(now)
87
+ } catch {
88
+ weekday = ''
89
+ }
90
+ const language = locale === 'zh' ? '中文' : 'English'
91
+ return [date, weekday, '', 'Web', language].join(',')
92
+ }
93
+
94
+ /** Keep only fields the UI needs; encrypted search payloads are not persisted. */
95
+ function sanitizeSearchItem(item) {
96
+ if (item === null || typeof item !== 'object') return null
97
+ if (item.type === 'web_search_tool_result_error') {
98
+ return { type: 'web_search_tool_result_error', error_code: item.error_code ?? 'unavailable' }
99
+ }
100
+ if (item.type !== 'web_search_result') return null
101
+ const result = {
102
+ type: 'web_search_result',
103
+ title: typeof item.title === 'string' ? item.title : '',
104
+ url: typeof item.url === 'string' ? item.url : '',
105
+ snippet: typeof item.snippet === 'string' ? item.snippet : '',
106
+ site_name: typeof item.site_name === 'string' ? item.site_name : null,
107
+ site_icon: typeof item.site_icon === 'string' ? item.site_icon : null,
108
+ page_age: typeof item.page_age === 'string' ? item.page_age : null,
109
+ }
110
+ if (typeof item.image_url === 'string') result.image_url = item.image_url
111
+ return result
112
+ }
113
+
114
+ function sanitizeFetchContent(content) {
115
+ if (content === null || typeof content !== 'object') return content
116
+ if (content.type === 'web_fetch_tool_result_error') {
117
+ return { type: 'web_fetch_tool_result_error', error_code: content.error_code ?? 'unavailable' }
118
+ }
119
+ if (content.type !== 'web_fetch_result') return content
120
+ return {
121
+ type: 'web_fetch_result',
122
+ url: typeof content.url === 'string' ? content.url : '',
123
+ title: typeof content.title === 'string' ? content.title : null,
124
+ published_at: typeof content.published_at === 'string' ? content.published_at : null,
125
+ content: {
126
+ type: 'document',
127
+ source: { type: 'text', media_type: 'text/plain', data: '' },
128
+ title: typeof content.content?.title === 'string' ? content.content.title : null,
129
+ },
130
+ }
131
+ }
132
+
133
+ function sanitizeCitation(citation) {
134
+ if (citation === null || typeof citation !== 'object') return null
135
+ if (citation.type !== 'web_search_result_location') return null
136
+ return {
137
+ type: 'web_search_result_location',
138
+ url: typeof citation.url === 'string' ? citation.url : '',
139
+ title: typeof citation.title === 'string' ? citation.title : null,
140
+ cited_text: typeof citation.cited_text === 'string' ? citation.cited_text : '',
141
+ encrypted_index: typeof citation.encrypted_index === 'string' ? citation.encrypted_index : '',
142
+ }
143
+ }
144
+
145
+ /** System prompt used when Chat drafts an implementation brief for Agent mode. */
146
+ export const HANDOFF_SYSTEM_PROMPT = [
147
+ '你是 DeepSeek Harness 的资深软件工程师,负责把一次产品/技术讨论整理成可以直接交给编码 Agent 执行的任务说明。',
148
+ '输出要求:',
149
+ '1. 只输出任务说明本身,不要寒暄、不要复述这份要求、不要用代码块包裹整篇内容。',
150
+ '2. 使用与讨论相同的语言(默认中文)。',
151
+ '3. 用 Markdown 分节,顺序为:目标、背景与已确认的结论、需要修改或新增的内容、实现要点与约束、验收标准。',
152
+ '4. 具体、可执行:写出目录/文件、接口、数据结构、边界条件;不要写“优化一下”这类空话。',
153
+ '5. 只依据讨论中已经确认的信息;尚未确定的地方写成“待确认:…”。',
154
+ '6. 总长度控制在 900 字以内。',
155
+ ].join('\n')
156
+
157
+ const HANDOFF_MAX_MESSAGES = 16
158
+ const HANDOFF_MAX_CHARS = 3200
159
+
160
+ /** Flatten a stored conversation into the transcript lines the brief reuses. */
161
+ function handoffTranscript(messages, locale) {
162
+ const turns = Array.isArray(messages) ? messages.slice(-HANDOFF_MAX_MESSAGES) : []
163
+ return turns.flatMap((message) => {
164
+ if (message === null || typeof message !== 'object') return []
165
+ if (message.role === 'user') {
166
+ const files = Array.isArray(message.files) && message.files.length > 0
167
+ ? (locale === 'en' ? ` [files: ${message.files.map(file => file.name).join(', ')}]` : ` [附件:${message.files.map(file => file.name).join('、')}]`)
168
+ : ''
169
+ const text = typeof message.content === 'string' ? message.content.trim() : ''
170
+ if (text === '' && files === '') return []
171
+ return [`### ${locale === 'en' ? 'User' : '用户'}\n${text.slice(0, HANDOFF_MAX_CHARS)}${files}`]
172
+ }
173
+ const text = getReplyText(message).trim()
174
+ if (text === '') return []
175
+ return [`### ${locale === 'en' ? 'Assistant' : '助手'}\n${text.slice(0, HANDOFF_MAX_CHARS)}`]
176
+ })
177
+ }
178
+
179
+ /**
180
+ * Build the single Messages-API request that turns one conversation into an
181
+ * Agent-ready brief. `instruction` lets the user steer the draft.
182
+ */
183
+ export function buildHandoffRequest(messages, { locale = 'zh', instruction = '' } = {}) {
184
+ const transcript = handoffTranscript(messages, locale)
185
+ if (transcript.length === 0) return null
186
+ const ask = locale === 'en'
187
+ ? 'Write the implementation brief for a coding agent from the discussion below. Do not restate the whole conversation; extract the decisions and turn them into work.'
188
+ : '根据下面的讨论,写出交给编码 Agent 的任务说明。不要复述整段对话,提取已确认的结论并转成可执行的工作。'
189
+ const extra = instruction.trim() === ''
190
+ ? ''
191
+ : (locale === 'en' ? `\n\nExtra requirement from the user: ${instruction.trim()}` : `\n\n用户额外要求:${instruction.trim()}`)
192
+ return {
193
+ system: HANDOFF_SYSTEM_PROMPT,
194
+ messages: [{ role: 'user', content: `${ask}${extra}\n\n---\n\n${transcript.join('\n\n')}` }],
195
+ }
196
+ }
197
+
198
+ /** A deterministic brief used when the drafting request cannot run. */
199
+ export function fallbackHandoffBrief(messages, { locale = 'zh' } = {}) {
200
+ const list = Array.isArray(messages) ? messages : []
201
+ const lastUser = [...list].reverse().find(message => message?.role === 'user')
202
+ const lastReply = [...list].reverse().find(message => message?.role === 'assistant')
203
+ const request = typeof lastUser?.content === 'string' ? lastUser.content.trim().slice(0, 1500) : ''
204
+ const design = lastReply === undefined ? '' : getReplyText(lastReply).trim().slice(0, 2500)
205
+ const files = Array.isArray(lastUser?.files) && lastUser.files.length > 0
206
+ ? lastUser.files.map(file => file.name).join(locale === 'en' ? ', ' : '、')
207
+ : ''
208
+ if (locale === 'en') {
209
+ return [
210
+ '## Goal',
211
+ request || 'Implement the change discussed in the chat.',
212
+ files === '' ? '' : `\nAttached material: ${files}.`,
213
+ design === '' ? '' : `\n## Context and decisions\n${design}`,
214
+ '\n## Work\n- Read the relevant module before changing it and keep the existing structure.\n- Implement the change described above, including the error paths and empty states.\n- Keep the diff small; do not rewrite unrelated code.',
215
+ '\n## Acceptance\n- The behaviour described above works end to end.\n- Build, lint and the existing tests still pass; report how each was verified.',
216
+ ].filter(Boolean).join('\n')
217
+ }
218
+ return [
219
+ '## 目标',
220
+ request || '实现对话中讨论的改动。',
221
+ files === '' ? '' : `\n相关材料:${files}。`,
222
+ design === '' ? '' : `\n## 背景与已确认的结论\n${design}`,
223
+ '\n## 需要做的事\n- 先读相关模块再动手,沿用现有的结构和风格。\n- 实现上面的改动,包含错误分支与空状态。\n- 改动尽量小,不要重写无关代码。',
224
+ '\n## 验收标准\n- 上面的行为可以完整跑通。\n- 构建、lint 与现有测试仍然通过,并说明验证方式。',
225
+ ].filter(Boolean).join('\n')
226
+ }
227
+
228
+ /** Convert a streamed content-block start into the plugin's stored block shape. */
229
+ function sanitizeStartBlock(block, now) {
230
+ if (block === null || typeof block !== 'object') return null
231
+ switch (block.type) {
232
+ case 'text':
233
+ return { type: 'text', text: typeof block.text === 'string' ? block.text : '', citations: [] }
234
+ case 'thinking':
235
+ return {
236
+ type: 'thinking',
237
+ thinking: typeof block.thinking === 'string' ? block.thinking : '',
238
+ signature: typeof block.signature === 'string' ? block.signature : '',
239
+ startedAt: now,
240
+ endedAt: undefined,
241
+ }
242
+ case 'server_tool_use':
243
+ return {
244
+ type: 'server_tool_use',
245
+ id: typeof block.id === 'string' ? block.id : '',
246
+ name: block.name === 'deepseek_read_url' ? 'deepseek_read_url' : 'deepseek_web_search',
247
+ input: block.input !== null && typeof block.input === 'object' ? block.input : {},
248
+ kind: typeof block.kind === 'string' ? block.kind : 'search',
249
+ }
250
+ case 'web_search_tool_result':
251
+ return {
252
+ type: 'web_search_tool_result',
253
+ tool_use_id: typeof block.tool_use_id === 'string' ? block.tool_use_id : '',
254
+ kind: typeof block.kind === 'string' ? block.kind : 'search',
255
+ content: Array.isArray(block.content)
256
+ ? block.content.map(sanitizeSearchItem).filter(Boolean)
257
+ : [],
258
+ }
259
+ case 'web_fetch_tool_result':
260
+ return {
261
+ type: 'web_fetch_tool_result',
262
+ tool_use_id: typeof block.tool_use_id === 'string' ? block.tool_use_id : '',
263
+ kind: typeof block.kind === 'string' ? block.kind : 'deep_search',
264
+ content: sanitizeFetchContent(block.content),
265
+ ...(typeof block.signature === 'string' ? { signature: block.signature } : {}),
266
+ }
267
+ default:
268
+ return null
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Fold one streamed event into an assistant reply.
274
+ * The caller owns `blockIndexes` for one response.
275
+ */
276
+ export function applyEvent(reply, event, now = Date.now(), blockIndexes = new Map()) {
277
+ const next = reply.status === 'streaming' ? reply : { ...reply, status: 'streaming' }
278
+ if (event === null || typeof event !== 'object') return next
279
+ switch (event.type) {
280
+ case 'message_start':
281
+ return {
282
+ ...next,
283
+ usage: event.message?.usage ?? next.usage,
284
+ model: typeof event.message?.model === 'string' ? event.message.model : next.model,
285
+ }
286
+ case 'content_block_start': {
287
+ blockIndexes.delete(event.index)
288
+ const block = sanitizeStartBlock(event.content_block, now)
289
+ if (block === null) {
290
+ return event.content_block?.type === 'tool_use' ? { ...next, prefix: false } : next
291
+ }
292
+ blockIndexes.set(event.index, next.blocks.length)
293
+ return { ...next, blocks: [...next.blocks, block] }
294
+ }
295
+ case 'content_block_delta': {
296
+ const index = blockIndexes.get(event.index)
297
+ if (index === undefined) return next
298
+ const block = next.blocks[index]
299
+ const delta = event.delta
300
+ if (block === undefined || delta === null || typeof delta !== 'object') return next
301
+ const blocks = next.blocks.slice()
302
+ if (block.type === 'text' && delta.type === 'text_delta' && typeof delta.text === 'string') {
303
+ blocks[index] = { ...block, text: block.text + delta.text }
304
+ } else if (block.type === 'thinking' && delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
305
+ blocks[index] = { ...block, thinking: block.thinking + delta.thinking }
306
+ } else if (block.type === 'thinking' && delta.type === 'signature_delta' && typeof delta.signature === 'string') {
307
+ blocks[index] = { ...block, signature: block.signature + delta.signature }
308
+ } else if (block.type === 'text' && delta.type === 'citations_delta') {
309
+ const citation = sanitizeCitation(delta.citation)
310
+ if (citation !== null && !block.citations.some(item => item.url === citation.url)) {
311
+ blocks[index] = { ...block, citations: [...block.citations, citation] }
312
+ }
313
+ }
314
+ return { ...next, blocks }
315
+ }
316
+ case 'content_block_stop': {
317
+ const index = blockIndexes.get(event.index)
318
+ if (index === undefined) return next
319
+ blockIndexes.delete(event.index)
320
+ const block = next.blocks[index]
321
+ if (block?.type === 'thinking' && block.endedAt === undefined) {
322
+ const blocks = next.blocks.slice()
323
+ blocks[index] = { ...block, endedAt: now }
324
+ return { ...next, blocks }
325
+ }
326
+ return next
327
+ }
328
+ case 'message_delta': {
329
+ const delta = event.delta ?? {}
330
+ return {
331
+ ...next,
332
+ stopReason: delta.stop_reason ?? next.stopReason,
333
+ stopDetails: delta.stop_details ?? next.stopDetails,
334
+ usage: event.usage ?? next.usage,
335
+ title: normalizeTitle(delta.title) || next.title,
336
+ }
337
+ }
338
+ case 'message_stop':
339
+ return next
340
+ default:
341
+ return next
342
+ }
343
+ }
344
+
345
+ /** Finish a reply, closing open thinking blocks and dropping refused prose. */
346
+ export function settleReply(reply, status, now = Date.now(), error) {
347
+ const refused = reply.stopReason === 'refusal'
348
+ const blocks = reply.blocks.flatMap((block) => {
349
+ if (refused && (block.type === 'text' || block.type === 'thinking')) return []
350
+ if (block.type === 'thinking' && block.endedAt === undefined) {
351
+ return [{ ...block, endedAt: now }]
352
+ }
353
+ return [block]
354
+ })
355
+ return {
356
+ ...reply,
357
+ status,
358
+ ...(error === undefined ? {} : { error }),
359
+ blocks,
360
+ updatedAt: now,
361
+ }
362
+ }
363
+
364
+ /** Visible answer text, excluding reasoning and tool blocks. */
365
+ export function getReplyText(reply) {
366
+ if (reply?.stopReason === 'refusal') return ''
367
+ return (reply?.blocks ?? [])
368
+ .filter(block => block.type === 'text')
369
+ .map(block => block.text)
370
+ .join('')
371
+ }
372
+
373
+ /** Whether a completed reply belongs in later requests. */
374
+ export function hasUsableReply(reply) {
375
+ return reply?.role === 'assistant'
376
+ && (reply.status === 'done' || reply.status === 'stopped')
377
+ && reply.stopReason !== 'refusal'
378
+ && getReplyText(reply) !== ''
379
+ }
380
+
381
+ function fileBlockParams(files) {
382
+ if (!Array.isArray(files)) return []
383
+ return files.flatMap((file) => {
384
+ if (file === null || typeof file !== 'object' || typeof file.fileId !== 'string' || file.fileId === '') return []
385
+ // An attachment restored from an imported history has no file on DeepSeek's
386
+ // file service; sending its local marker would be a request the API rejects.
387
+ if (file.local === true) return []
388
+ return [{
389
+ type: file.isImage ? 'image' : 'document',
390
+ source: { type: 'file', file_id: file.fileId },
391
+ }]
392
+ })
393
+ }
394
+
395
+ function toUserParam(message) {
396
+ const files = fileBlockParams(message?.files)
397
+ const text = typeof message?.content === 'string' ? message.content : ''
398
+ if (files.length === 0) return { role: 'user', content: text }
399
+ return {
400
+ role: 'user',
401
+ content: [...files, ...(text === '' ? [] : [{ type: 'text', text }])],
402
+ }
403
+ }
404
+
405
+ function toAssistantParam(reply) {
406
+ const blocks = Array.isArray(reply?.blocks) ? reply.blocks : []
407
+ const unsignedReadLinks = new Set(blocks.flatMap((block) => (
408
+ block.type === 'web_fetch_tool_result'
409
+ && block.kind === 'read_link'
410
+ && block.content?.type === 'web_fetch_result'
411
+ && (typeof block.signature !== 'string' || block.signature.trim() === '')
412
+ ? [block.tool_use_id]
413
+ : []
414
+ )))
415
+ const content = []
416
+ let text = null
417
+ for (const block of blocks) {
418
+ if (block.type === 'text') {
419
+ if (text !== null) {
420
+ text.text += block.text
421
+ } else {
422
+ const previous = content.at(-1)
423
+ text = { type: 'text', text: `${previous?.type === 'text' ? '\n\n' : ''}${block.text}` }
424
+ content.push(text)
425
+ }
426
+ continue
427
+ }
428
+ text = null
429
+ if (
430
+ block.type === 'server_tool_use'
431
+ && block.kind === 'read_link'
432
+ && !unsignedReadLinks.has(block.id)
433
+ ) {
434
+ content.push({
435
+ type: 'server_tool_use',
436
+ id: block.id,
437
+ name: block.name,
438
+ input: block.input,
439
+ kind: block.kind,
440
+ })
441
+ } else if (
442
+ block.type === 'web_fetch_tool_result'
443
+ && block.kind === 'read_link'
444
+ && !unsignedReadLinks.has(block.tool_use_id)
445
+ ) {
446
+ content.push(block)
447
+ }
448
+ }
449
+ return {
450
+ role: 'assistant',
451
+ content: content.filter(block => block.type !== 'text' || block.text !== ''),
452
+ }
453
+ }
454
+
455
+ /** Complete question/answer pairs that may be replayed to the model. */
456
+ export function getContextRounds(messages) {
457
+ const rounds = []
458
+ if (!Array.isArray(messages)) return rounds
459
+ for (let index = 0; index + 1 < messages.length; index += 1) {
460
+ const user = messages[index]
461
+ const reply = messages[index + 1]
462
+ if (user?.role !== 'user' || reply?.role !== 'assistant') continue
463
+ if (!hasUsableReply(reply)) continue
464
+ if (
465
+ (typeof user.content !== 'string' || user.content.trim() === '')
466
+ && fileBlockParams(user.files).length === 0
467
+ ) {
468
+ continue
469
+ }
470
+ rounds.push([user, reply])
471
+ index += 1
472
+ }
473
+ return rounds
474
+ }
475
+
476
+ /**
477
+ * Build the Messages API `messages` array.
478
+ * `messages` includes the current user turn; the current turn is the last entry.
479
+ */
480
+ export function buildRequestMessages(messages, currentUserId, { reminder } = {}) {
481
+ const index = Array.isArray(messages) ? messages.findIndex(message => message.id === currentUserId) : -1
482
+ const history = index >= 0 ? messages.slice(0, index) : []
483
+ const current = index >= 0 ? messages[index] : null
484
+ const result = []
485
+ for (const [user, reply] of getContextRounds(history)) {
486
+ result.push(toUserParam(user), toAssistantParam(reply))
487
+ }
488
+ if (reminder) result.push({ role: 'latest_reminder', content: reminder })
489
+ if (current) result.push(toUserParam(current))
490
+ return result
491
+ }
492
+
493
+ /** Presentation summary for the sidebar. */
494
+ export function conversationSummary(conversation) {
495
+ return {
496
+ id: conversation.id,
497
+ title: conversation.title,
498
+ titleAuto: conversation.titleAuto === true,
499
+ createdAt: conversation.createdAt,
500
+ updatedAt: conversation.updatedAt,
501
+ messageCount: conversation.messages.length,
502
+ }
503
+ }
504
+
505
+ /** Whether a reply stopped before it could finish, from its own stored state. */
506
+ export function replyIsIncomplete(reply) {
507
+ if (reply?.role !== 'assistant') return false
508
+ if (reply.stopReason === 'refusal') return false
509
+ return reply.status === 'stopped' || reply.status === 'error' || reply.stopReason === 'max_tokens'
510
+ }
511
+
512
+ /**
513
+ * The assistant prefill used to resume a cut-off answer, or '' when the reply
514
+ * cannot be continued. The Messages API treats a trailing assistant message as
515
+ * a prefix: the model writes the missing remainder instead of repeating the
516
+ * answer. A trailing tool call has no result to replay, so `prefix === false`
517
+ * marks those replies as not resumable.
518
+ */
519
+ export function continuationPrefill(reply) {
520
+ if (reply?.role !== 'assistant') return ''
521
+ if (reply.stopReason === 'refusal' || reply.prefix === false) return ''
522
+ // Anthropic-style prefill must not end with whitespace.
523
+ return getReplyText(reply).replace(/\s+$/, '')
524
+ }
525
+
526
+ /** Whether the reply has visible text that can be resumed in place. */
527
+ export function canContinueReply(reply) {
528
+ return replyIsIncomplete(reply) && continuationPrefill(reply) !== ''
529
+ }
530
+
531
+ /**
532
+ * Build the Messages API `messages` array for continuing one stored reply.
533
+ * The conversation keeps the whole answer; only the request uses the visible
534
+ * text as an assistant prefill so the model continues the same sentence
535
+ * instead of producing an unrelated block after it.
536
+ * @param messages - the active path, including the reply being continued.
537
+ * @param assistantId - id of that reply.
538
+ */
539
+ export function buildContinuationMessages(messages, assistantId, { reminder } = {}) {
540
+ if (!Array.isArray(messages)) return null
541
+ const index = messages.findIndex(message => message.id === assistantId)
542
+ if (index < 1) return null
543
+ const reply = messages[index]
544
+ const user = messages[index - 1]
545
+ if (user?.role !== 'user') return null
546
+ const prefill = continuationPrefill(reply)
547
+ if (prefill === '') return null
548
+ const built = buildRequestMessages(messages, user.id, { reminder })
549
+ built.push({ role: 'assistant', content: [{ type: 'text', text: prefill }] })
550
+ return built
551
+ }
552
+
553
+
554
+ /** All unique cited/search sources of a reply, in reading order. */
555
+ export function replySources(reply) {
556
+ const byUrl = new Map()
557
+ for (const block of reply?.blocks ?? []) {
558
+ if (block.type === 'text') {
559
+ for (const citation of block.citations ?? []) {
560
+ if (!citation.url || byUrl.has(citation.url)) continue
561
+ byUrl.set(citation.url, {
562
+ url: citation.url,
563
+ title: citation.title || citation.url,
564
+ snippet: '',
565
+ siteName: '',
566
+ })
567
+ }
568
+ }
569
+ if (block.type === 'web_search_tool_result' && Array.isArray(block.content)) {
570
+ for (const item of block.content) {
571
+ if (item.type !== 'web_search_result' || !item.url || byUrl.has(item.url)) continue
572
+ byUrl.set(item.url, {
573
+ url: item.url,
574
+ title: item.title || item.url,
575
+ snippet: item.snippet || '',
576
+ siteName: item.site_name || '',
577
+ })
578
+ }
579
+ }
580
+ if (block.type === 'web_fetch_tool_result' && block.content?.type === 'web_fetch_result') {
581
+ const url = block.content.url
582
+ if (url && !byUrl.has(url)) {
583
+ byUrl.set(url, {
584
+ url,
585
+ title: block.content.title || url,
586
+ snippet: '',
587
+ siteName: '',
588
+ })
589
+ }
590
+ }
591
+ }
592
+ return [...byUrl.values()]
593
+ }