@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/service.js ADDED
@@ -0,0 +1,2102 @@
1
+ /**
2
+ * Host side of DeepSeek Chat mode: route handlers, DeepSeek request assembly,
3
+ * streamed reply persistence, uploads, settings, and credential status.
4
+ */
5
+
6
+ import path from 'node:path'
7
+ import os from 'node:os'
8
+ import { readFileSync } from 'node:fs'
9
+ import { mkdir, readFile, realpath, stat } from 'node:fs/promises'
10
+ import { randomUUID } from 'node:crypto'
11
+ import {
12
+ ApiError, authSnapshot, isImageFile, resolveAuth, streamMessage, uploadFile, uploadPurpose,
13
+ } from './api.js'
14
+ import {
15
+ CHAT_MODEL, DEFAULT_SYSTEM_PROMPT, applyEvent, buildContinuationMessages,
16
+ buildHandoffRequest, buildRequestMessages, canContinueReply, createLatestReminder,
17
+ fallbackHandoffBrief, getReplyText, normalizeTitle, serverTools, settleReply, thinkingParams,
18
+ } from './protocol.js'
19
+ import {
20
+ DEFAULT_MODEL, MODEL_CATALOG, ModelConfigStore, findModel, resolveEffort, resolveModelId,
21
+ } from './model-config.js'
22
+ import { MemoryStore } from './memory-store.js'
23
+ import { MemoryService } from './memory.js'
24
+ import { normalizeMemoryContent } from './memory-text.js'
25
+ import { ChatStore } from './store.js'
26
+ import { ChatImportManager, ImportError } from './import/index.js'
27
+ import { ArtifactService } from './artifact/service.js'
28
+ import {
29
+ answerApproval, isArtifactSession, openApproval, pendingApprovalByKey,
30
+ } from './artifact/approval-bus.js'
31
+ import {
32
+ DOCUMENT_EXTENSIONS, PREVIEW_EXTENSIONS, fileExtension, fileMime, resolveInside, saveUpload,
33
+ } from './artifact/workspace.js'
34
+
35
+ const JSON_HEADERS = {
36
+ 'content-type': 'application/json; charset=utf-8',
37
+ 'cache-control': 'no-store',
38
+ }
39
+
40
+ const NDJSON_HEADERS = {
41
+ 'content-type': 'application/x-ndjson; charset=utf-8',
42
+ 'cache-control': 'no-store',
43
+ 'x-accel-buffering': 'no',
44
+ }
45
+
46
+ const MAX_TEXT = 100_000
47
+ const MAX_FILES = 10
48
+ const MAX_JSON_BYTES = 1_000_000
49
+ /** How many imported conversations one memory-extraction batch may analyze. */
50
+ const IMPORT_MEMORY_MAX_SESSIONS = 20
51
+ const MAX_USER_DATA_BYTES = 32 * 1024 * 1024
52
+ /** How long one successful account-name read stands in for the next greeting. */
53
+ const PROFILE_TTL_MS = 60 * 1000
54
+
55
+ function json(value, status = 200, extraHeaders = {}) {
56
+ return new Response(JSON.stringify(value), {
57
+ status,
58
+ headers: { ...JSON_HEADERS, ...extraHeaders },
59
+ })
60
+ }
61
+
62
+ function errorPayload(error) {
63
+ if (error instanceof ApiError) {
64
+ return {
65
+ message: error.message,
66
+ code: error.code,
67
+ kind: error.kind,
68
+ status: error.status,
69
+ }
70
+ }
71
+ if (error instanceof ImportError) {
72
+ return {
73
+ message: error.message,
74
+ code: error.code,
75
+ kind: 'import',
76
+ status: error.status,
77
+ }
78
+ }
79
+ return {
80
+ message: error instanceof Error ? error.message : String(error),
81
+ code: 'INTERNAL',
82
+ kind: 'internal',
83
+ }
84
+ }
85
+
86
+ function errorMessage(error) {
87
+ return error instanceof Error ? error.message : String(error)
88
+ }
89
+
90
+ function errorResponse(error) {
91
+ const payload = errorPayload(error)
92
+ const status = error instanceof ApiError
93
+ ? (error.code === 'AUTH_REQUIRED' ? 401 : error.status ?? (error.kind === 'network' ? 502 : 400))
94
+ : error instanceof ImportError ? error.status : 500
95
+ return json({ error: payload }, status)
96
+ }
97
+
98
+ async function readJson(request) {
99
+ const declared = Number(request.headers.get('content-length') ?? '0')
100
+ if (Number.isFinite(declared) && declared > MAX_JSON_BYTES) {
101
+ throw new ApiError('请求体过大。', { code: 'PAYLOAD_TOO_LARGE', status: 413 })
102
+ }
103
+ const text = await request.text()
104
+ if (text.length > MAX_JSON_BYTES) {
105
+ throw new ApiError('请求体过大。', { code: 'PAYLOAD_TOO_LARGE', status: 413 })
106
+ }
107
+ try {
108
+ return JSON.parse(text)
109
+ } catch {
110
+ throw new ApiError('请求体不是有效 JSON。', { code: 'INVALID_JSON', status: 400 })
111
+ }
112
+ }
113
+
114
+ function sanitizeFiles(input) {
115
+ if (!Array.isArray(input)) return []
116
+ return input.slice(0, MAX_FILES).flatMap((file) => {
117
+ if (file === null || typeof file !== 'object') return []
118
+ const fileId = typeof file.fileId === 'string' ? file.fileId.trim() : ''
119
+ if (fileId === '') return []
120
+ return [{
121
+ id: typeof file.id === 'string' && file.id !== '' ? file.id : randomUUID(),
122
+ fileId,
123
+ name: typeof file.name === 'string' ? file.name.slice(0, 200) : 'file',
124
+ size: typeof file.size === 'number' && Number.isFinite(file.size) ? file.size : 0,
125
+ mimeType: typeof file.mimeType === 'string' ? file.mimeType : '',
126
+ isImage: file.isImage === true,
127
+ }]
128
+ })
129
+ }
130
+
131
+ /** A credential provider can outlive the browser request or the plugin. */
132
+ async function resolveTurnAuth(ctx, settings, signal) {
133
+ const stopped = () => new ApiError('已停止生成。', { code: 'ABORTED', status: 499, kind: 'aborted' })
134
+ if (signal.aborted) throw stopped()
135
+ let onAbort
136
+ const canceled = new Promise((_, reject) => {
137
+ onAbort = () => reject(stopped())
138
+ signal.addEventListener('abort', onAbort, { once: true })
139
+ })
140
+ try {
141
+ return await Promise.race([resolveAuth(ctx, settings), canceled])
142
+ } finally {
143
+ signal.removeEventListener('abort', onAbort)
144
+ }
145
+ }
146
+
147
+ function sanitizeSettings(input) {
148
+ const patch = {}
149
+ if (input === null || typeof input !== 'object') return patch
150
+ if (input.authMode === 'auto' || input.authMode === 'account' || input.authMode === 'api-key') patch.authMode = input.authMode
151
+ if (typeof input.thinking === 'boolean') patch.thinking = input.thinking
152
+ if (typeof input.search === 'boolean') patch.search = input.search
153
+ if (typeof input.systemPrompt === 'string') patch.systemPrompt = input.systemPrompt.slice(0, 8000)
154
+ return patch
155
+ }
156
+
157
+ function resolveConfig(config) {
158
+ const value = config !== null && typeof config === 'object' ? config : {}
159
+ const positive = (input, fallback) => (typeof input === 'number' && Number.isFinite(input) && input > 0 ? Math.floor(input) : fallback)
160
+ return {
161
+ baseURL: typeof value.baseURL === 'string' && value.baseURL.trim() !== ''
162
+ ? value.baseURL.trim()
163
+ : 'https://api.deepseek.com/anthropic/v1',
164
+ maxUploadBytes: positive(value.maxUploadBytes, 64 * 1024 * 1024),
165
+ requestTimeoutMs: positive(value.requestTimeoutMs, 15 * 60 * 1000),
166
+ heartbeatMs: positive(value.heartbeatMs, 15_000),
167
+ handoffTimeoutMs: positive(value.handoffTimeoutMs, 90_000),
168
+ // One document task may legitimately run several Office conversions.
169
+ artifactTimeoutMs: positive(value.artifactTimeoutMs, 10 * 60 * 1000),
170
+ // The import's own upload cap; everything else keeps the importer defaults.
171
+ importLimits: positive(value.maxImportBytes, 0) > 0
172
+ ? { maxUploadBytes: positive(value.maxImportBytes, 0) }
173
+ : {},
174
+ memoryTimeoutMs: positive(value.memoryTimeoutMs, 60_000),
175
+ }
176
+ }
177
+
178
+ function dataDirectory() {
179
+ const home = process.env.DSH_HOME
180
+ return path.join(home !== undefined && home !== '' ? home : path.join(os.homedir(), '.dsh'), 'deepseek-chat')
181
+ }
182
+
183
+ /** Client identity reported to the Platform account API; a source launch may lack the manifest. */
184
+ let cachedAppVersion
185
+ function appVersion() {
186
+ if (cachedAppVersion !== undefined) return cachedAppVersion
187
+ cachedAppVersion = '0.1.0'
188
+ const installDir = process.env.DSH_INSTALL_DIR
189
+ if (typeof installDir === 'string' && installDir !== '') {
190
+ try {
191
+ const manifest = JSON.parse(readFileSync(path.join(installDir, 'package.json'), 'utf8'))
192
+ if (typeof manifest?.version === 'string' && manifest.version !== '') cachedAppVersion = manifest.version
193
+ } catch {
194
+ // The fallback still identifies the client; only display personalization depends on it.
195
+ }
196
+ }
197
+ return cachedAppVersion
198
+ }
199
+
200
+ /**
201
+ * The display name of a ready Platform profile, or null when the account has
202
+ * none. Contact details are deliberately not substituted: a greeting handle is
203
+ * a display name, not an email address or phone number.
204
+ */
205
+ export function accountDisplayName(profile) {
206
+ if (profile === null || typeof profile !== 'object' || profile.status !== 'ready') return null
207
+ const name = typeof profile.value?.name === 'string' ? profile.value.name.trim() : ''
208
+ return name === '' ? null : name
209
+ }
210
+
211
+ /** Locale tag for one profile read; only the two shipped UI languages reach the Platform. */
212
+ function profileLocale(request) {
213
+ try {
214
+ return new URL(request?.url ?? '', 'http://localhost').searchParams.get('locale') === 'en' ? 'en' : 'zh'
215
+ } catch {
216
+ return 'zh'
217
+ }
218
+ }
219
+
220
+ export class ChatService {
221
+ constructor(ctx, config) {
222
+ this.ctx = ctx
223
+ this.config = resolveConfig(config)
224
+ this.logger = ctx.logger ?? console
225
+ this.store = new ChatStore(dataDirectory(), { logger: this.logger })
226
+ this.modelConfig = new ModelConfigStore(dataDirectory(), { logger: this.logger })
227
+ // One importer per service: it owns the staged archive uploads, the local
228
+ // media store, and the single running import job.
229
+ this.importer = new ChatImportManager({
230
+ store: this.store,
231
+ directory: dataDirectory(),
232
+ logger: this.logger,
233
+ limits: this.config.importLimits,
234
+ })
235
+ this.memoryStore = new MemoryStore(dataDirectory(), { logger: this.logger })
236
+ this.artifacts = new ArtifactService({
237
+ ctx,
238
+ logger: this.logger,
239
+ baseDir: dataDirectory(),
240
+ timeoutMs: this.config.artifactTimeoutMs,
241
+ })
242
+ // Root-scoped (unscoped) listener: receives every Agent approval waterfall.
243
+ // Documents sessions park the request for their Chat card; every other
244
+ // Session delegates unchanged to the native answerers.
245
+ this.approvalListener = typeof ctx.on === 'function'
246
+ ? ctx.on('approval/request', async (request, next) => {
247
+ const sessionId = request?.agent?.id
248
+ if (typeof sessionId !== 'string' || !isArtifactSession(sessionId)) return next()
249
+ const outcome = await openApproval({
250
+ sessionId,
251
+ toolName: request.toolName,
252
+ reason: request.reason,
253
+ displayReason: request.displayReason,
254
+ signal: request.signal,
255
+ })
256
+ return outcome ?? next()
257
+ }, { prepend: true })
258
+ : null
259
+ this.memory = new MemoryService({
260
+ store: this.memoryStore,
261
+ logger: this.logger,
262
+ generate: args => this.generateMemoryText(args),
263
+ timeouts: {
264
+ extraction: this.config.memoryTimeoutMs,
265
+ summary: this.config.memoryTimeoutMs,
266
+ assist: this.config.memoryTimeoutMs,
267
+ },
268
+ })
269
+ this.readyPromise = null
270
+ this.routes = []
271
+ this.active = new Map()
272
+ this.pending = new Set()
273
+ /** Cancels in-flight memory model work when the plugin unloads. */
274
+ this.memoryAbort = new AbortController()
275
+ /** Conversations with an imported-memory analysis currently in flight. */
276
+ this.memoryExtractions = new Set()
277
+ this.disposed = false
278
+ this.profileCache = { at: 0, value: { name: null } }
279
+ this.profilePending = null
280
+ }
281
+
282
+ ready() {
283
+ if (this.readyPromise === null) {
284
+ this.readyPromise = Promise.all([this.store.load(), this.modelConfig.load(), this.memoryStore.load()])
285
+ }
286
+ return this.readyPromise
287
+ }
288
+
289
+ registerRoutes() {
290
+ const register = (route) => {
291
+ const dispose = this.ctx.connection.fetch.register(route)
292
+ this.routes.push(dispose)
293
+ }
294
+ register({
295
+ path: '/api/deepseek-chat/bootstrap',
296
+ methods: ['GET'],
297
+ requestBody: 'buffered',
298
+ fetch: request => this.guard(request, () => this.bootstrap()),
299
+ })
300
+ register({
301
+ path: '/api/deepseek-chat/profile',
302
+ methods: ['GET'],
303
+ requestBody: 'buffered',
304
+ fetch: request => this.guard(request, () => this.profile(request)),
305
+ })
306
+ register({
307
+ path: '/api/deepseek-chat/conversation',
308
+ methods: ['POST'],
309
+ requestBody: 'buffered',
310
+ fetch: request => this.guard(request, () => this.conversation(request)),
311
+ })
312
+ register({
313
+ path: '/api/deepseek-chat/upload',
314
+ methods: ['POST'],
315
+ requestBody: 'buffered',
316
+ fetch: request => this.guard(request, () => this.upload(request)),
317
+ })
318
+ register({
319
+ path: '/api/deepseek-chat/stream',
320
+ methods: ['POST'],
321
+ requestBody: 'buffered',
322
+ fetch: request => this.stream(request),
323
+ })
324
+ register({
325
+ path: '/api/deepseek-chat/settings',
326
+ methods: ['POST'],
327
+ requestBody: 'buffered',
328
+ fetch: request => this.guard(request, () => this.updateSettings(request)),
329
+ })
330
+ register({
331
+ path: '/api/deepseek-chat/model',
332
+ methods: ['POST'],
333
+ requestBody: 'buffered',
334
+ fetch: request => this.guard(request, () => this.modelConfigRoute(request)),
335
+ })
336
+ register({
337
+ path: '/api/deepseek-chat/memory',
338
+ methods: ['POST'],
339
+ requestBody: 'buffered',
340
+ fetch: request => this.guard(request, () => this.memoryRoute(request)),
341
+ })
342
+ register({
343
+ path: '/api/deepseek-chat/key',
344
+ methods: ['POST'],
345
+ requestBody: 'buffered',
346
+ fetch: request => this.guard(request, () => this.updateKey(request)),
347
+ })
348
+ register({
349
+ path: '/api/deepseek-chat/workspace',
350
+ methods: ['POST'],
351
+ requestBody: 'buffered',
352
+ fetch: request => this.guard(request, () => this.createWorkspace(request)),
353
+ })
354
+ register({
355
+ path: '/api/deepseek-chat/handoff',
356
+ methods: ['POST'],
357
+ requestBody: 'buffered',
358
+ fetch: request => this.guard(request, () => this.handoffBrief(request)),
359
+ })
360
+ register({
361
+ path: '/api/deepseek-chat/handoff/send',
362
+ methods: ['POST'],
363
+ requestBody: 'buffered',
364
+ fetch: request => this.guard(request, () => this.handoffSend(request)),
365
+ })
366
+ // Document mode: local copies for the Agent workspace, a PNG preview route
367
+ // backed by Office Kit, and the file itself for download / native open.
368
+ register({
369
+ path: '/api/deepseek-chat/artifact/upload',
370
+ methods: ['POST'],
371
+ requestBody: 'buffered',
372
+ fetch: request => this.guard(request, () => this.artifactUpload(request)),
373
+ })
374
+ register({
375
+ path: '/api/deepseek-chat/artifact/preview',
376
+ methods: ['GET'],
377
+ requestBody: 'buffered',
378
+ fetch: request => this.artifactPreview(request),
379
+ })
380
+ register({
381
+ path: '/api/deepseek-chat/artifact/file',
382
+ methods: ['GET'],
383
+ requestBody: 'buffered',
384
+ fetch: request => this.artifactFile(request),
385
+ })
386
+ register({
387
+ path: '/api/deepseek-chat/artifact/open',
388
+ methods: ['POST'],
389
+ requestBody: 'buffered',
390
+ fetch: request => this.guard(request, () => this.artifactOpen(request)),
391
+ })
392
+ register({
393
+ path: '/api/deepseek-chat/artifact/approval',
394
+ methods: ['POST'],
395
+ requestBody: 'buffered',
396
+ fetch: request => this.guard(request, () => this.artifactApproval(request)),
397
+ })
398
+ register({
399
+ path: '/api/deepseek-chat/artifact/steer',
400
+ methods: ['POST'],
401
+ requestBody: 'buffered',
402
+ fetch: request => this.guard(request, () => this.artifactSteer(request)),
403
+ })
404
+ // DeepSeek chat-export import: a staged upload, then a polled background job.
405
+ // The ZIP is read locally by this Host process and never leaves it.
406
+ register({
407
+ path: '/api/deepseek-chat/import/upload',
408
+ methods: ['POST'],
409
+ requestBody: 'buffered',
410
+ fetch: request => this.guard(request, () => this.importer.ingest(
411
+ request,
412
+ decodeURIComponent(request.headers.get('x-file-name') ?? ''),
413
+ )),
414
+ })
415
+ register({
416
+ path: '/api/deepseek-chat/import/start',
417
+ methods: ['POST'],
418
+ requestBody: 'buffered',
419
+ fetch: request => this.guard(request, async () => this.importer.start(await readJson(request))),
420
+ })
421
+ register({
422
+ path: '/api/deepseek-chat/import/status',
423
+ methods: ['GET'],
424
+ requestBody: 'buffered',
425
+ fetch: request => this.guard(request, () => this.importStatus(request)),
426
+ })
427
+ register({
428
+ path: '/api/deepseek-chat/import/cancel',
429
+ methods: ['POST'],
430
+ requestBody: 'buffered',
431
+ fetch: request => this.guard(request, async () => {
432
+ const body = await readJson(request)
433
+ return this.importer.cancel(typeof body?.job === 'string' ? body.job : '')
434
+ }),
435
+ })
436
+ register({
437
+ path: '/api/deepseek-chat/import/discard',
438
+ methods: ['POST'],
439
+ requestBody: 'buffered',
440
+ fetch: request => this.guard(request, async () => {
441
+ const body = await readJson(request)
442
+ const token = typeof body?.token === 'string' ? body.token : ''
443
+ return { discarded: await this.importer.dropStaged(token) }
444
+ }),
445
+ })
446
+ register({
447
+ path: '/api/deepseek-chat/import/media',
448
+ methods: ['GET'],
449
+ requestBody: 'buffered',
450
+ fetch: request => this.importMedia(request),
451
+ })
452
+ }
453
+
454
+ /** One import progress poll; `job` names the running or finished job. */
455
+ importStatus(request) {
456
+ let job = ''
457
+ try {
458
+ job = new URL(request.url, 'http://localhost').searchParams.get('job') ?? ''
459
+ } catch {
460
+ job = ''
461
+ }
462
+ const status = this.importer.status(job)
463
+ if (status === null) {
464
+ throw new ImportError('NOT_FOUND', 'the import job is unknown or has expired', { status: 404 })
465
+ }
466
+ return status
467
+ }
468
+
469
+ /**
470
+ * Serve one image recovered from an import. The name is a content address, so
471
+ * the response is immutable; an SVG is additionally served with a policy that
472
+ * keeps an opened file from running any script it carries.
473
+ */
474
+ async importMedia(request) {
475
+ try {
476
+ await this.ready()
477
+ let name = ''
478
+ try {
479
+ name = new URL(request.url, 'http://localhost').searchParams.get('f') ?? ''
480
+ } catch {
481
+ name = ''
482
+ }
483
+ const file = await this.importer.mediaFile(name)
484
+ if (file === undefined) {
485
+ return new Response('not found', { status: 404, headers: { 'cache-control': 'no-store' } })
486
+ }
487
+ const bytes = await readFile(file.path)
488
+ return new Response(bytes, {
489
+ status: 200,
490
+ headers: {
491
+ 'content-type': file.contentType,
492
+ 'content-length': String(bytes.length),
493
+ 'cache-control': 'private, max-age=31536000, immutable',
494
+ 'x-content-type-options': 'nosniff',
495
+ ...(file.contentType === 'image/svg+xml'
496
+ ? { 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox" }
497
+ : {}),
498
+ },
499
+ })
500
+ } catch (error) {
501
+ this.logger.warn?.('deepseek-chat: imported media could not be served', errorMessage(error))
502
+ return new Response('not found', { status: 404, headers: { 'cache-control': 'no-store' } })
503
+ }
504
+ }
505
+
506
+ async guard(_request, handler) {
507
+ try {
508
+ await this.ready()
509
+ if (this.disposed) throw new ApiError('Chat 插件已卸载。', { code: 'DISPOSED', status: 503 })
510
+ const value = await handler()
511
+ return json(value)
512
+ } catch (error) {
513
+ if (error instanceof ApiError && error.code === 'ABORTED') {
514
+ return json({ error: errorPayload(error) }, 499)
515
+ }
516
+ this.logger.warn?.('deepseek-chat: request failed', error instanceof Error ? error.message : error)
517
+ return errorResponse(error)
518
+ }
519
+ }
520
+
521
+ async auth() {
522
+ return authSnapshot(this.ctx, { ...this.store.getSettings(), baseURL: this.config.baseURL })
523
+ }
524
+
525
+ async bootstrap() {
526
+ const settings = this.store.getSettings()
527
+ const summaries = this.store.listSummaries()
528
+ // Drop model overrides whose conversation was removed outside this route
529
+ // (an older store, or an interrupted delete) before publishing them.
530
+ await this.modelConfig.prune(summaries.map(item => item.id))
531
+ const workspaces = this.listWorkspaces()
532
+ const registry = this.hostService('workspaceRegistry')
533
+ const defaults = this.modelConfig.getDefaults()
534
+ const defaultModel = findModel(defaults.model) ?? findModel(DEFAULT_MODEL)
535
+ return {
536
+ version: 2,
537
+ // `model` is the default-model summary for older clients; `models`
538
+ // carries the full catalog those clients ignore.
539
+ model: { id: defaultModel.id, name: defaultModel.name },
540
+ models: MODEL_CATALOG,
541
+ modelConfig: this.modelConfig.snapshot(),
542
+ settings,
543
+ conversations: summaries,
544
+ folders: this.store.listFolders(),
545
+ auth: await this.auth(),
546
+ workspaces,
547
+ handoff: {
548
+ enabled: this.hostService('sessionController') !== undefined,
549
+ // Creation is a separate Host capability: the browser only offers the
550
+ // inline form when this Host half can create the folder and register it.
551
+ workspaceCreate: registry !== undefined && typeof registry.create === 'function',
552
+ },
553
+ // Document mode. An older Host omits the block, so the browser disables the
554
+ // composer switch instead of offering a surface that cannot work.
555
+ artifacts: {
556
+ ...this.artifacts.capability(),
557
+ maxBytes: this.config.maxUploadBytes,
558
+ },
559
+ // Chat-history import. Older Host halves omit this block and the browser
560
+ // hides the entry instead of offering a surface that cannot work.
561
+ import: {
562
+ enabled: true,
563
+ maxUploadBytes: this.importer.limits.maxUploadBytes,
564
+ },
565
+ limits: {
566
+ maxFiles: MAX_FILES,
567
+ maxUploadBytes: this.config.maxUploadBytes,
568
+ maxUserDataBytes: MAX_USER_DATA_BYTES,
569
+ maxText: MAX_TEXT,
570
+ },
571
+ dataDir: dataDirectory(),
572
+ }
573
+ }
574
+
575
+ /**
576
+ * Read or write the model preference. The browser sends `conversationId: null`
577
+ * to change the default for new conversations, or a conversation id to pin a
578
+ * choice to that one conversation.
579
+ */
580
+ async modelConfigRoute(request) {
581
+ const body = await readJson(request)
582
+ const action = body?.action
583
+ if (action === 'get') {
584
+ return {
585
+ models: MODEL_CATALOG,
586
+ modelConfig: this.modelConfig.snapshot(),
587
+ }
588
+ }
589
+ if (action !== 'set') throw new ApiError('未知的模型操作。', { code: 'INVALID_REQUEST', status: 400 })
590
+ if (typeof body?.model === 'string' && findModel(body.model) === undefined) {
591
+ throw new ApiError(`不支持的模型:${body.model.slice(0, 80)}`, { code: 'INVALID_MODEL', status: 400 })
592
+ }
593
+ // The effort is clamped by the store to the model's real tiers, so an alias
594
+ // or an outdated client value can never reach the request raw.
595
+ const conversationId = typeof body?.conversationId === 'string' && body.conversationId !== ''
596
+ ? body.conversationId
597
+ : null
598
+ if (conversationId !== null && this.store.getConversation(conversationId) === undefined) {
599
+ throw new ApiError('会话不存在。', { code: 'NOT_FOUND', status: 404 })
600
+ }
601
+ const modelConfig = await this.modelConfig.set(conversationId, body)
602
+ return { models: MODEL_CATALOG, modelConfig, conversationId }
603
+ }
604
+
605
+ /**
606
+ * The signed-in DeepSeek account's display name for the personalized greeting.
607
+ * Personalization is optional: a signed-out account, an absent account service,
608
+ * or a failed Platform read all answer without an error, and the browser
609
+ * falls back to its localized greeting. `resolved: false` tells the browser
610
+ * that a temporary failure happened, so it keeps the last known name instead
611
+ * of clearing it.
612
+ */
613
+ async profile(request) {
614
+ const auth = await this.auth()
615
+ if (auth.accountSignedIn !== true) return { name: null, signedIn: false, resolved: true }
616
+ const now = Date.now()
617
+ if (now - this.profileCache.at < PROFILE_TTL_MS) return this.profileCache.value
618
+ if (this.profilePending !== null) return this.profilePending
619
+ const pending = this.readProfile(profileLocale(request))
620
+ this.profilePending = pending
621
+ try {
622
+ const value = await pending
623
+ this.profileCache = { at: Date.now(), value }
624
+ return value
625
+ } finally {
626
+ if (this.profilePending === pending) this.profilePending = null
627
+ }
628
+ }
629
+
630
+ /**
631
+ * Read the display name from the optional account service exactly once per
632
+ * cache window. Any failure is an absent name, never a Chat error.
633
+ * @param locale - UI language forwarded to the Platform request.
634
+ * @returns `{ name, signedIn, resolved }`; `resolved` is false on a read failure.
635
+ */
636
+ async readProfile(locale) {
637
+ const account = this.hostService('deepseekAccount')
638
+ if (account === undefined || typeof account.getProfile !== 'function') {
639
+ return { name: null, signedIn: false, resolved: true }
640
+ }
641
+ let profile
642
+ try {
643
+ profile = await account.getProfile({
644
+ version: appVersion(),
645
+ locale,
646
+ // Platform wants seconds east of UTC; Date reports minutes west.
647
+ timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
648
+ })
649
+ } catch (error) {
650
+ this.logger.warn?.('deepseek-chat: account profile read failed', error instanceof Error ? error.message : error)
651
+ return { name: null, signedIn: true, resolved: false }
652
+ }
653
+ return { name: accountDisplayName(profile), signedIn: true, resolved: true }
654
+ }
655
+
656
+ /** Optional Host service access that keeps this plugin loadable without it. */
657
+ hostService(name) {
658
+ try {
659
+ return this.ctx.get?.(name) ?? this.ctx[name]
660
+ } catch {
661
+ return undefined
662
+ }
663
+ }
664
+
665
+ listWorkspaces() {
666
+ const registry = this.hostService('workspaceRegistry')
667
+ if (registry === undefined || typeof registry.list !== 'function') return []
668
+ try {
669
+ return registry.list().map(workspace => ({
670
+ id: workspace.id,
671
+ title: workspace.title,
672
+ path: workspace.path,
673
+ }))
674
+ } catch {
675
+ return []
676
+ }
677
+ }
678
+
679
+ /**
680
+ * Whether a request path names one fixed location instead of a spelling
681
+ * resolved against the host process's working directory. Windows rooted,
682
+ * drive-less forms (`\foo`) pass `path.isAbsolute` yet depend on the current
683
+ * drive, so they are refused like relative paths.
684
+ * @param value - caller-supplied directory path.
685
+ * @returns true for a fully qualified POSIX or Windows path.
686
+ */
687
+ isFullyQualifiedPath(value) {
688
+ if (typeof value !== 'string' || value === '' || value.includes('\0')) return false
689
+ if (!path.isAbsolute(value)) return false
690
+ if (process.platform !== 'win32') return true
691
+ return /^[A-Za-z]:[\\/]/.test(value) || /^\\\\[^\\]/.test(value)
692
+ }
693
+
694
+ /**
695
+ * Create one local project folder when it does not exist yet, then register
696
+ * that directory through the Host's native Workspace registry. The two steps
697
+ * are separate on purpose: the folder is plain filesystem state, while the
698
+ * registration is what makes Agent mode able to open a Session there.
699
+ * Only the requested directory is created — no file inside it is touched.
700
+ */
701
+ async createWorkspace(request) {
702
+ const body = await readJson(request)
703
+ const requested = typeof body?.path === 'string' ? body.path.trim() : ''
704
+ const title = typeof body?.title === 'string'
705
+ ? body.title.replace(/\s+/g, ' ').trim().slice(0, 80)
706
+ : ''
707
+ if (requested === '') {
708
+ throw new ApiError('缺少项目文件夹路径。', { code: 'INVALID_REQUEST', status: 400 })
709
+ }
710
+ if (requested.length > 4096) {
711
+ throw new ApiError('项目文件夹路径过长。', { code: 'INVALID_REQUEST', status: 400 })
712
+ }
713
+ if (!this.isFullyQualifiedPath(requested)) {
714
+ throw new ApiError('请填写完整的绝对路径(例如 C:\\Projects\\My-App)。', {
715
+ code: 'INVALID_REQUEST', status: 400,
716
+ })
717
+ }
718
+ const registry = this.hostService('workspaceRegistry')
719
+ if (registry === undefined || typeof registry.create !== 'function') {
720
+ throw new ApiError('当前 DSH 版本没有可用的工作区服务,无法注册工作区。', {
721
+ code: 'WORKSPACE_UNAVAILABLE', status: 501,
722
+ })
723
+ }
724
+ const target = path.normalize(requested)
725
+ let info
726
+ try {
727
+ info = await stat(target)
728
+ } catch (error) {
729
+ if (error?.code !== 'ENOENT') {
730
+ throw new ApiError(`无法访问项目文件夹:${errorMessage(error)}`, { code: 'MKDIR_FAILED', status: 400 })
731
+ }
732
+ }
733
+ let existingDirectory = false
734
+ if (info !== undefined) {
735
+ if (!info.isDirectory()) {
736
+ throw new ApiError('该路径已存在,但不是文件夹。', { code: 'NOT_A_DIRECTORY', status: 400 })
737
+ }
738
+ existingDirectory = true
739
+ } else {
740
+ try {
741
+ await mkdir(target, { recursive: true })
742
+ } catch (error) {
743
+ throw new ApiError(`无法创建项目文件夹:${errorMessage(error)}`, { code: 'MKDIR_FAILED', status: 400 })
744
+ }
745
+ }
746
+ // Report whether the registration is new; the native registry returns the
747
+ // existing entity unchanged for a directory it already owns.
748
+ let existing
749
+ try {
750
+ existing = typeof registry.resolveByPath === 'function'
751
+ ? await registry.resolveByPath(target)
752
+ : registry.list().find(workspace => workspace.path === target)
753
+ } catch {
754
+ existing = undefined
755
+ }
756
+ let workspace
757
+ try {
758
+ workspace = await registry.create(target, title === '' ? undefined : title)
759
+ } catch (error) {
760
+ throw new ApiError(
761
+ `${existingDirectory ? '' : '文件夹已创建,但'}无法注册工作区:${errorMessage(error)}`,
762
+ { code: 'WORKSPACE_CREATE_FAILED', status: 502 },
763
+ )
764
+ }
765
+ return {
766
+ workspace: { id: workspace.id, title: workspace.title, path: workspace.path },
767
+ created: { directory: !existingDirectory, workspace: existing === undefined },
768
+ }
769
+ }
770
+
771
+ /** Resolve a conversation or fail the request with a clear 404. */
772
+ requireConversation(id) {
773
+ const conversation = typeof id === 'string' && id !== '' ? this.store.getConversation(id) : undefined
774
+ if (conversation === undefined) throw new ApiError('会话不存在。', { code: 'NOT_FOUND', status: 404 })
775
+ return conversation
776
+ }
777
+
778
+ /** Sidebar state after any organization change. */
779
+ organizationSnapshot() {
780
+ return { summaries: this.store.listSummaries(), folders: this.store.listFolders() }
781
+ }
782
+
783
+ async conversation(request) {
784
+ const body = await readJson(request)
785
+ const action = typeof body?.action === 'string' ? body.action : ''
786
+ const id = typeof body?.id === 'string' ? body.id : ''
787
+ if (action === 'list') {
788
+ return { conversations: this.store.listSummaries(), folders: this.store.listFolders() }
789
+ }
790
+ if (action === 'create') {
791
+ const conversation = await this.store.createConversation()
792
+ return { conversation: this.store.presentConversation(conversation), ...this.organizationSnapshot() }
793
+ }
794
+ if (action === 'get') {
795
+ const conversation = this.requireConversation(id)
796
+ // A history-search hit may live on an older branch; reopening it keeps the
797
+ // message the user searched for on screen instead of jumping to the tip.
798
+ const focusMessageId = typeof body?.focusMessageId === 'string' ? body.focusMessageId : ''
799
+ if (focusMessageId !== '' && !conversation.messages.some(message => message.id === focusMessageId)) {
800
+ const focused = await this.store.focusMessage(id, focusMessageId)
801
+ if (focused === undefined) throw new ApiError('消息不存在。', { code: 'NOT_FOUND', status: 404 })
802
+ }
803
+ return {
804
+ conversation: this.store.presentConversation(conversation),
805
+ folders: this.store.listFolders(),
806
+ }
807
+ }
808
+ if (action === 'rename') {
809
+ if (id === '') throw new ApiError('缺少会话 id。', { code: 'INVALID_REQUEST', status: 400 })
810
+ const title = normalizeTitle(body?.title)
811
+ const conversation = await this.store.renameConversation(id, title)
812
+ if (conversation === undefined) throw new ApiError('会话不存在。', { code: 'NOT_FOUND', status: 404 })
813
+ return { conversation: this.store.presentConversation(conversation), ...this.organizationSnapshot() }
814
+ }
815
+ if (action === 'delete') {
816
+ if (id === '') throw new ApiError('缺少会话 id。', { code: 'INVALID_REQUEST', status: 400 })
817
+ this.active.get(id)?.controller.abort()
818
+ const deleted = await this.store.deleteConversation(id)
819
+ if (!deleted) throw new ApiError('会话不存在。', { code: 'NOT_FOUND', status: 404 })
820
+ // The model preference is keyed by conversation id; drop it with the chat
821
+ // so a later conversation that reuses the id never inherits it.
822
+ await this.modelConfig.remove(id)
823
+ return { deleted: true, ...this.organizationSnapshot() }
824
+ }
825
+ if (action === 'pin') {
826
+ const conversation = await this.store.setPinned(id, body?.pinned === true)
827
+ if (conversation === undefined) throw new ApiError('会话不存在。', { code: 'NOT_FOUND', status: 404 })
828
+ return { conversation: this.store.presentConversation(conversation), ...this.organizationSnapshot() }
829
+ }
830
+ if (action === 'archive') {
831
+ const archived = body?.archived === true
832
+ const conversation = await this.store.setArchived(id, archived)
833
+ if (conversation === undefined) throw new ApiError('会话不存在。', { code: 'NOT_FOUND', status: 404 })
834
+ this.active.get(id)?.controller.abort()
835
+ return { conversation: this.store.presentConversation(conversation), ...this.organizationSnapshot() }
836
+ }
837
+ if (action === 'move') {
838
+ const ids = Array.isArray(body?.ids)
839
+ ? body.ids.filter(item => typeof item === 'string' && item !== '')
840
+ : []
841
+ if (ids.length === 0) throw new ApiError('缺少要移动的会话。', { code: 'INVALID_REQUEST', status: 400 })
842
+ const folderId = typeof body?.folderId === 'string' && body.folderId !== '' ? body.folderId : null
843
+ const moved = await this.store.moveConversations(ids, folderId)
844
+ if (moved === undefined) throw new ApiError('文件夹不存在。', { code: 'NOT_FOUND', status: 404 })
845
+ return { moved, ...this.organizationSnapshot() }
846
+ }
847
+ if (action === 'search') {
848
+ const query = typeof body?.query === 'string' ? body.query : ''
849
+ return this.store.search(query)
850
+ }
851
+ if (action === 'version') {
852
+ if (id === '') throw new ApiError('缺少会话 id。', { code: 'INVALID_REQUEST', status: 400 })
853
+ const messageId = typeof body?.messageId === 'string' ? body.messageId : ''
854
+ const direction = body?.direction === 'prev' ? -1 : body?.direction === 'next' ? 1 : 0
855
+ if (messageId === '' || direction === 0) {
856
+ throw new ApiError('缺少要切换的消息版本。', { code: 'INVALID_REQUEST', status: 400 })
857
+ }
858
+ this.requireConversation(id)
859
+ const result = await this.store.selectVersion(id, messageId, direction)
860
+ if (result === undefined) {
861
+ throw new ApiError('这条消息没有其他版本。', { code: 'NO_VERSIONS', status: 404 })
862
+ }
863
+ return {
864
+ conversation: this.store.presentConversation(result.conversation),
865
+ selectedId: result.selectedId,
866
+ ...this.organizationSnapshot(),
867
+ }
868
+ }
869
+ if (action.startsWith('folder.')) return this.folderAction(action.slice('folder.'.length), body)
870
+ throw new ApiError('未知的会话操作。', { code: 'INVALID_REQUEST', status: 400 })
871
+ }
872
+
873
+ async folderAction(action, body) {
874
+ const id = typeof body?.id === 'string' ? body.id : ''
875
+ if (action === 'create') {
876
+ const folder = await this.store.createFolder(body?.name)
877
+ if (folder === undefined) throw new ApiError('文件夹名称不能为空。', { code: 'INVALID_NAME', status: 400 })
878
+ return { folder, ...this.organizationSnapshot() }
879
+ }
880
+ if (action === 'rename') {
881
+ if (!this.store.listFolders().some(folder => folder.id === id)) {
882
+ throw new ApiError('文件夹不存在。', { code: 'NOT_FOUND', status: 404 })
883
+ }
884
+ const folder = await this.store.renameFolder(id, body?.name)
885
+ if (folder === undefined) throw new ApiError('文件夹名称不能为空。', { code: 'INVALID_NAME', status: 400 })
886
+ return { folder, ...this.organizationSnapshot() }
887
+ }
888
+ if (action === 'delete') {
889
+ const removed = await this.store.deleteFolder(id)
890
+ if (removed === undefined) throw new ApiError('文件夹不存在。', { code: 'NOT_FOUND', status: 404 })
891
+ return { moved: removed.moved, ...this.organizationSnapshot() }
892
+ }
893
+ if (action === 'collapse') {
894
+ const folder = await this.store.setFolderCollapsed(id, body?.collapsed === true)
895
+ if (folder === undefined) throw new ApiError('文件夹不存在。', { code: 'NOT_FOUND', status: 404 })
896
+ return { folder, ...this.organizationSnapshot() }
897
+ }
898
+ throw new ApiError('未知的文件夹操作。', { code: 'INVALID_REQUEST', status: 400 })
899
+ }
900
+
901
+ async updateSettings(request) {
902
+ const body = await readJson(request)
903
+ const settings = await this.store.updateSettings(sanitizeSettings(body))
904
+ return { settings, auth: await this.auth() }
905
+ }
906
+
907
+ /**
908
+ * One non-streaming Host completion for memory work (summary, extraction,
909
+ * import structuring). It uses the same credentials and transport as chat but
910
+ * an independent abort timer, so a client disconnect never cancels it.
911
+ */
912
+ async generateMemoryText({ system, messages, timeoutMs = this.config.memoryTimeoutMs, signal }) {
913
+ const settings = this.store.getSettings()
914
+ const auth = await resolveAuth(this.ctx, { ...settings, baseURL: this.config.baseURL })
915
+ const controller = new AbortController()
916
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
917
+ const signals = [this.memoryAbort.signal, controller.signal]
918
+ if (signal) signals.push(signal)
919
+ const requestSignal = AbortSignal.any(signals)
920
+ try {
921
+ requestSignal.throwIfAborted()
922
+ let reply = { id: 'memory', role: 'assistant', status: 'streaming', blocks: [], prefix: true }
923
+ const blockIndexes = new Map()
924
+ for await (const event of streamMessage({
925
+ baseURL: this.config.baseURL,
926
+ auth,
927
+ body: {
928
+ model: CHAT_MODEL,
929
+ system,
930
+ messages,
931
+ thinking: { type: 'disabled' },
932
+ },
933
+ signal: requestSignal,
934
+ })) {
935
+ if (event.type === 'error') {
936
+ throw new ApiError(
937
+ typeof event.error?.message === 'string' ? event.error.message : 'DeepSeek 未能完成记忆整理。',
938
+ { code: 'STREAM_ERROR', kind: 'stream' },
939
+ )
940
+ }
941
+ reply = applyEvent(reply, event, Date.now(), blockIndexes)
942
+ }
943
+ return getReplyText(settleReply(reply, 'done', Date.now())).trim()
944
+ } finally {
945
+ clearTimeout(timer)
946
+ }
947
+ }
948
+
949
+ /** Normalized source metadata for the future history-import integration. */
950
+ memorySessionSource(body) {
951
+ const source = body?.source
952
+ if (source === null || typeof source !== 'object') return undefined
953
+ return {
954
+ type: 'conversation',
955
+ conversationId: typeof source.conversationId === 'string' ? source.conversationId : null,
956
+ label: typeof source.label === 'string' ? source.label : null,
957
+ }
958
+ }
959
+
960
+ /**
961
+ * Long-term memory operations. The store is local; only `summary.refresh`,
962
+ * `assist` and `extract.session` call DeepSeek, and each of those is an
963
+ * explicit user action except summary refresh, which is only requested for a
964
+ * stale summary.
965
+ */
966
+ async memoryRoute(request) {
967
+ const body = await readJson(request)
968
+ const action = typeof body?.action === 'string' ? body.action : ''
969
+ const locale = body?.locale === 'en' ? 'en' : 'zh'
970
+ if (action === 'get') return this.memoryStore.snapshot()
971
+ if (action === 'settings') {
972
+ const patch = {}
973
+ if (typeof body?.enabled === 'boolean') patch.enabled = body.enabled
974
+ if (typeof body?.autoExtract === 'boolean') patch.autoExtract = body.autoExtract
975
+ await this.memoryStore.updateSettings(patch)
976
+ return this.memoryStore.snapshot()
977
+ }
978
+ if (action === 'add') {
979
+ const result = await this.memoryStore.add({
980
+ content: body?.content,
981
+ category: body?.category,
982
+ origin: 'manual',
983
+ source: { type: 'manual' },
984
+ })
985
+ if (result.status === 'invalid') throw new ApiError('记忆内容不能为空。', { code: 'INVALID_CONTENT', status: 400 })
986
+ if (result.status === 'limit') {
987
+ throw new ApiError(`记忆数量已达上限(${result.limit} 条)。`, { code: 'MEMORY_LIMIT', status: 409 })
988
+ }
989
+ return { ...this.memoryStore.snapshot(), result }
990
+ }
991
+ if (action === 'update') {
992
+ const id = typeof body?.id === 'string' ? body.id : ''
993
+ if (id === '') throw new ApiError('缺少记忆 id。', { code: 'INVALID_REQUEST', status: 400 })
994
+ const result = await this.memoryStore.update(id, { content: body?.content, category: body?.category })
995
+ if (result.status === 'not-found') throw new ApiError('记忆不存在。', { code: 'NOT_FOUND', status: 404 })
996
+ if (result.status === 'invalid') throw new ApiError('记忆内容不能为空。', { code: 'INVALID_CONTENT', status: 400 })
997
+ return { ...this.memoryStore.snapshot(), result }
998
+ }
999
+ if (action === 'delete') {
1000
+ const id = typeof body?.id === 'string' ? body.id : ''
1001
+ const deleted = await this.memoryStore.remove(id)
1002
+ if (!deleted) throw new ApiError('记忆不存在。', { code: 'NOT_FOUND', status: 404 })
1003
+ return { ...this.memoryStore.snapshot(), result: { status: 'deleted', id } }
1004
+ }
1005
+ if (action === 'clear') {
1006
+ const cleared = await this.memoryStore.clear()
1007
+ return { ...this.memoryStore.snapshot(), result: { cleared } }
1008
+ }
1009
+ if (action === 'preview') {
1010
+ return this.memoryStore.previewEntries(Array.isArray(body?.entries) ? body.entries : [])
1011
+ }
1012
+ if (action === 'import') {
1013
+ const platform = ['chatgpt', 'claude', 'gemini', 'other'].includes(body?.platform) ? body.platform : null
1014
+ const entries = Array.isArray(body?.entries) ? body.entries : []
1015
+ // Imported-chat extraction passes a conversation source so the resulting
1016
+ // memories are labelled as coming from a conversation instead of from a
1017
+ // foreign-AI export. Other callers keep the platform-based behaviour.
1018
+ const conversationSource = this.memorySessionSource(body)
1019
+ const source = conversationSource ?? { type: 'import', platform }
1020
+ const result = await this.memoryStore.absorb(entries, {
1021
+ origin: conversationSource === undefined ? 'import' : 'conversation',
1022
+ source,
1023
+ })
1024
+ return { ...this.memoryStore.snapshot(), result }
1025
+ }
1026
+ if (action === 'summary.refresh') {
1027
+ try {
1028
+ await this.memory.refreshSummary(locale)
1029
+ } catch (error) {
1030
+ throw new ApiError(`记忆概述生成失败:${errorMessage(error)}`, { code: 'SUMMARY_FAILED', status: 502 })
1031
+ }
1032
+ return this.memoryStore.snapshot()
1033
+ }
1034
+ if (action === 'ask') {
1035
+ const result = await this.memory.ask({ text: typeof body?.text === 'string' ? body.text : '', locale })
1036
+ return { ...this.memoryStore.snapshot(), ...result }
1037
+ }
1038
+ if (action === 'confirm') {
1039
+ const result = await this.memory.confirm({
1040
+ id: typeof body?.id === 'string' ? body.id : '',
1041
+ accept: body?.accept === true,
1042
+ locale,
1043
+ })
1044
+ return { ...this.memoryStore.snapshot(), ...result }
1045
+ }
1046
+ if (action === 'assist') {
1047
+ if (body?.consent !== true) {
1048
+ throw new ApiError('需要先确认再将文本发送到 DeepSeek API。', { code: 'CONSENT_REQUIRED', status: 400 })
1049
+ }
1050
+ const text = typeof body?.text === 'string' ? body.text : ''
1051
+ if (text.trim() === '') throw new ApiError('没有可整理的内容。', { code: 'INVALID_REQUEST', status: 400 })
1052
+ try {
1053
+ return await this.memory.assistImport(text, locale)
1054
+ } catch (error) {
1055
+ if (error instanceof ApiError && error.code === 'AUTH_REQUIRED') {
1056
+ throw new ApiError('当前没有可用的 DeepSeek 凭证,无法使用 AI 整理。', {
1057
+ code: 'AI_UNAVAILABLE', status: 503,
1058
+ })
1059
+ }
1060
+ throw new ApiError(`AI 整理失败:${errorMessage(error)}`, { code: 'ASSIST_FAILED', status: 502 })
1061
+ }
1062
+ }
1063
+ if (action === 'extract.session') {
1064
+ // Reserved interface for the DeepSeek chat-history import branch: analyze
1065
+ // a supplied session, then merge only the accepted candidates.
1066
+ const messages = Array.isArray(body?.messages) ? body.messages.slice(0, 500) : []
1067
+ if (messages.length === 0) throw new ApiError('没有可分析的会话消息。', { code: 'INVALID_REQUEST', status: 400 })
1068
+ const result = await this.memory.extractFromMessages({
1069
+ messages,
1070
+ title: typeof body?.title === 'string' ? body.title : '',
1071
+ locale,
1072
+ save: body?.save === true,
1073
+ source: this.memorySessionSource(body),
1074
+ })
1075
+ return { ...this.memoryStore.snapshot(), ...result }
1076
+ }
1077
+ if (action === 'extract.imported') {
1078
+ // Analyze conversations that came from a chat-history import. The browser
1079
+ // selects them and confirms the extra model calls first; this action only
1080
+ // returns preview candidates and never saves a memory on its own. A failed
1081
+ // conversation is reported in `failed` and never touches the imported chat.
1082
+ if (body?.consent !== true) {
1083
+ throw new ApiError('需要先确认再将会话内容发送到 DeepSeek API。', { code: 'CONSENT_REQUIRED', status: 400 })
1084
+ }
1085
+ const requested = []
1086
+ for (const id of Array.isArray(body?.conversationIds) ? body.conversationIds : []) {
1087
+ if (typeof id !== 'string' || id === '' || requested.includes(id)) continue
1088
+ requested.push(id)
1089
+ }
1090
+ if (requested.length === 0) throw new ApiError('没有选择要分析的会话。', { code: 'INVALID_REQUEST', status: 400 })
1091
+ // The browser enforces the same cap and never sends more, but a second
1092
+ // client must still be told exactly which selected chats were left out
1093
+ // instead of silently analyzing fewer than the consent promised.
1094
+ const ids = requested.slice(0, IMPORT_MEMORY_MAX_SESSIONS)
1095
+ const overLimit = requested.slice(IMPORT_MEMORY_MAX_SESSIONS)
1096
+ const reanalyze = body?.reanalyze === true
1097
+ const analyzed = []
1098
+ const skipped = overLimit.map(id => ({ id, reason: 'over-limit' }))
1099
+ const failed = []
1100
+ const candidates = []
1101
+ for (const id of ids) {
1102
+ const conversation = this.store.getConversation(id)
1103
+ if (conversation === undefined) {
1104
+ skipped.push({ id, reason: 'missing' })
1105
+ continue
1106
+ }
1107
+ if (conversation.source === null || typeof conversation.source !== 'object') {
1108
+ skipped.push({ id, reason: 'not-imported' })
1109
+ continue
1110
+ }
1111
+ if (!reanalyze && typeof conversation.source.memoryExtractedAt === 'number') {
1112
+ skipped.push({ id, reason: 'already-extracted' })
1113
+ continue
1114
+ }
1115
+ if (this.memoryExtractions.has(id)) {
1116
+ // Another request already reserved this conversation; running it a
1117
+ // second time would double the model cost for the same history.
1118
+ skipped.push({ id, reason: 'in-flight' })
1119
+ continue
1120
+ }
1121
+ this.memoryExtractions.add(id)
1122
+ try {
1123
+ const result = await this.memory.extractFromMessages({
1124
+ messages: this.store.presentPath(conversation),
1125
+ title: conversation.title,
1126
+ locale,
1127
+ save: false,
1128
+ source: {
1129
+ type: 'conversation',
1130
+ conversationId: conversation.source.id,
1131
+ label: conversation.title,
1132
+ },
1133
+ })
1134
+ if (result.analyzed === false) {
1135
+ // No usable transcript: no request was made, so the conversation
1136
+ // must stay eligible for a later attempt.
1137
+ skipped.push({ id, reason: 'empty' })
1138
+ continue
1139
+ }
1140
+ analyzed.push(id)
1141
+ candidates.push(...result.candidates)
1142
+ } catch (error) {
1143
+ failed.push({ id, reason: errorMessage(error) })
1144
+ } finally {
1145
+ this.memoryExtractions.delete(id)
1146
+ }
1147
+ }
1148
+ // Several conversations often mention the same fact; dedupe inside the
1149
+ // batch before the browser shows one row per candidate.
1150
+ const unique = []
1151
+ const seen = new Set()
1152
+ for (const candidate of candidates) {
1153
+ const key = normalizeMemoryContent(candidate.content)
1154
+ if (key === '' || seen.has(key)) continue
1155
+ seen.add(key)
1156
+ unique.push({ content: candidate.content, category: candidate.category })
1157
+ }
1158
+ const preview = this.memoryStore.previewEntries(unique)
1159
+ if (analyzed.length > 0) await this.store.markMemoryExtracted(analyzed)
1160
+ return {
1161
+ analyzed: analyzed.length,
1162
+ analyzedIds: analyzed,
1163
+ skipped,
1164
+ failed,
1165
+ entries: preview.entries,
1166
+ limits: preview.limits,
1167
+ }
1168
+ }
1169
+ throw new ApiError('未知的记忆操作。', { code: 'INVALID_REQUEST', status: 400 })
1170
+ }
1171
+
1172
+ async updateKey(request) {
1173
+ const body = await readJson(request)
1174
+ const credentials = this.ctx.get?.('credentials') ?? this.ctx.credentials
1175
+ if (credentials === undefined || typeof credentials.set !== 'function') {
1176
+ throw new ApiError('此 DSH 配置没有凭证存储,无法保存 API Key。请设置 DEEPSEEK_API_KEY 环境变量。', {
1177
+ code: 'CREDENTIAL_STORE_UNAVAILABLE', status: 501,
1178
+ })
1179
+ }
1180
+ if (body?.clear === true) {
1181
+ await credentials.unset('DEEPSEEK_CHAT_API_KEY')
1182
+ return { auth: await this.auth() }
1183
+ }
1184
+ const key = typeof body?.key === 'string' ? body.key.trim() : ''
1185
+ if (key.length < 8 || key.length > 512 || /\s/.test(key)) {
1186
+ throw new ApiError('API Key 格式无效。', { code: 'INVALID_KEY', status: 400 })
1187
+ }
1188
+ await credentials.set('DEEPSEEK_CHAT_API_KEY', key)
1189
+ return { auth: await this.auth() }
1190
+ }
1191
+
1192
+ /**
1193
+ * Draft one Agent-ready task brief from a finished conversation. The reply is
1194
+ * advisory: any failure still returns the deterministic local brief.
1195
+ */
1196
+ async handoffBrief(request) {
1197
+ const body = await readJson(request)
1198
+ const id = typeof body?.conversationId === 'string' ? body.conversationId : ''
1199
+ const conversation = this.store.getConversation(id)
1200
+ if (conversation === undefined) throw new ApiError('会话不存在。', { code: 'NOT_FOUND', status: 404 })
1201
+ const locale = body?.locale === 'en' ? 'en' : 'zh'
1202
+ const instruction = typeof body?.instruction === 'string' ? body.instruction.slice(0, 4000) : ''
1203
+ const fallback = () => fallbackHandoffBrief(conversation.messages, { locale })
1204
+ const built = buildHandoffRequest(conversation.messages, { locale, instruction })
1205
+ if (built === null) return { brief: fallback(), generated: false }
1206
+ const settings = this.store.getSettings()
1207
+ let auth
1208
+ try {
1209
+ auth = await resolveAuth(this.ctx, { ...settings, baseURL: this.config.baseURL })
1210
+ } catch (error) {
1211
+ return { brief: fallback(), generated: false, warning: error instanceof Error ? error.message : String(error) }
1212
+ }
1213
+ const controller = new AbortController()
1214
+ const timer = setTimeout(() => controller.abort(), this.config.handoffTimeoutMs)
1215
+ try {
1216
+ let reply = { id: 'handoff', role: 'assistant', status: 'streaming', blocks: [], prefix: true }
1217
+ const blockIndexes = new Map()
1218
+ for await (const event of streamMessage({
1219
+ baseURL: this.config.baseURL,
1220
+ auth,
1221
+ body: {
1222
+ model: CHAT_MODEL,
1223
+ system: built.system,
1224
+ messages: built.messages,
1225
+ thinking: { type: 'disabled' },
1226
+ },
1227
+ signal: controller.signal,
1228
+ })) {
1229
+ if (event.type === 'error') {
1230
+ throw new ApiError(
1231
+ typeof event.error?.message === 'string' ? event.error.message : 'DeepSeek 未能生成任务说明。',
1232
+ { code: 'STREAM_ERROR', kind: 'stream' },
1233
+ )
1234
+ }
1235
+ reply = applyEvent(reply, event, Date.now(), blockIndexes)
1236
+ }
1237
+ const text = getReplyText(settleReply(reply, 'done', Date.now())).trim()
1238
+ if (text === '') return { brief: fallback(), generated: false }
1239
+ return { brief: text, generated: true }
1240
+ } catch (error) {
1241
+ this.logger.warn?.('deepseek-chat: handoff draft failed', error instanceof Error ? error.message : error)
1242
+ return { brief: fallback(), generated: false, warning: error instanceof Error ? error.message : String(error) }
1243
+ } finally {
1244
+ clearTimeout(timer)
1245
+ }
1246
+ }
1247
+
1248
+ /**
1249
+ * Create one ordinary Agent Session in a Workspace and admit the brief as its
1250
+ * first prompt, so Agent mode opens on the task already running.
1251
+ */
1252
+ async handoffSend(request) {
1253
+ const body = await readJson(request)
1254
+ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : ''
1255
+ if (prompt === '') throw new ApiError('任务说明为空。', { code: 'EMPTY_MESSAGE', status: 400 })
1256
+ if (prompt.length > 60_000) throw new ApiError('任务说明过长。', { code: 'MESSAGE_TOO_LONG', status: 413 })
1257
+ const controller = this.hostService('sessionController')
1258
+ if (controller === undefined) {
1259
+ throw new ApiError('当前 DSH 版本没有可用的会话服务,无法创建 Agent 会话。', {
1260
+ code: 'HANDOFF_UNAVAILABLE', status: 501,
1261
+ })
1262
+ }
1263
+ const workspaceId = typeof body?.workspaceId === 'string' && body.workspaceId !== '' ? body.workspaceId : undefined
1264
+ if (workspaceId !== undefined && this.listWorkspaces().every(workspace => workspace.id !== workspaceId)) {
1265
+ throw new ApiError('工作区不存在。', { code: 'NOT_FOUND', status: 404 })
1266
+ }
1267
+ let created
1268
+ try {
1269
+ created = await controller.create(workspaceId === undefined ? {} : { workspaceId })
1270
+ } catch (error) {
1271
+ throw new ApiError(`无法创建 Agent 会话:${error instanceof Error ? error.message : String(error)}`, {
1272
+ code: 'HANDOFF_CREATE_FAILED', status: 502,
1273
+ })
1274
+ }
1275
+ const sessionId = created?.sessionId
1276
+ if (typeof sessionId !== 'string' || sessionId === '') {
1277
+ throw new ApiError('会话服务未返回会话 id。', { code: 'HANDOFF_CREATE_FAILED', status: 502 })
1278
+ }
1279
+ const title = typeof body?.title === 'string' ? body.title.replace(/\s+/g, ' ').trim().slice(0, 80) : ''
1280
+ if (title !== '') {
1281
+ try {
1282
+ await controller.rename({ sessionId, title })
1283
+ } catch (error) {
1284
+ this.logger.warn?.('deepseek-chat: could not rename the handed-off session', error instanceof Error ? error.message : error)
1285
+ }
1286
+ }
1287
+ const requestId = typeof body?.requestId === 'string' && body.requestId !== '' ? body.requestId : randomUUID()
1288
+ const timeZone = typeof body?.timeZone === 'string' && body.timeZone !== '' ? body.timeZone : undefined
1289
+ try {
1290
+ await controller.prompt({
1291
+ requestId,
1292
+ sessionId,
1293
+ mode: 'queue',
1294
+ content: [{ type: 'text', text: prompt }],
1295
+ ...(timeZone === undefined ? {} : { clientTimeZone: timeZone }),
1296
+ }, AbortSignal.timeout(this.config.handoffTimeoutMs))
1297
+ } catch (error) {
1298
+ // The Session exists, so report it instead of leaving an orphan: the
1299
+ // browser opens it and tells the user to paste the brief again.
1300
+ return {
1301
+ sessionId,
1302
+ workspaceId: workspaceId ?? null,
1303
+ warning: error instanceof Error ? error.message : String(error),
1304
+ }
1305
+ }
1306
+ return { sessionId, workspaceId: workspaceId ?? null }
1307
+ }
1308
+
1309
+ /**
1310
+ * Copy one document attachment into the conversation's workspace. Chat's
1311
+ * ordinary upload goes to the remote Files API, which Agent tools cannot read,
1312
+ * so document mode writes the same bytes locally before the task starts.
1313
+ */
1314
+ async artifactUpload(request) {
1315
+ const url = new URL(request.url, 'http://localhost')
1316
+ const conversationId = url.searchParams.get('conversationId') ?? ''
1317
+ const conversation = this.requireConversation(conversationId)
1318
+ const name = decodeURIComponent(request.headers.get('x-file-name') ?? '')
1319
+ if (name.trim() === '') throw new ApiError('缺少文件名。', { code: 'INVALID_REQUEST', status: 400 })
1320
+ if (!DOCUMENT_EXTENSIONS.has(fileExtension(name))) {
1321
+ throw new ApiError('文档编辑只支持 Word、Excel、PowerPoint、PDF 与文本文件。', {
1322
+ code: 'UNSUPPORTED_FILE', status: 415,
1323
+ })
1324
+ }
1325
+ const declared = Number(request.headers.get('content-length') ?? '0')
1326
+ if (Number.isFinite(declared) && declared > this.config.maxUploadBytes) {
1327
+ throw new ApiError(`文件超过 ${Math.round(this.config.maxUploadBytes / 1024 / 1024)} MB 上限。`, {
1328
+ code: 'FILE_TOO_LARGE', status: 413,
1329
+ })
1330
+ }
1331
+ const bytes = new Uint8Array(await request.arrayBuffer())
1332
+ if (bytes.length === 0) throw new ApiError('文件为空。', { code: 'INVALID_REQUEST', status: 400 })
1333
+ if (bytes.length > this.config.maxUploadBytes) {
1334
+ throw new ApiError(`文件超过 ${Math.round(this.config.maxUploadBytes / 1024 / 1024)} MB 上限。`, {
1335
+ code: 'FILE_TOO_LARGE', status: 413,
1336
+ })
1337
+ }
1338
+ const root = await this.artifacts.taskRootFor(conversationId, conversation.title)
1339
+ const file = await saveUpload(root, name, bytes)
1340
+ return { file }
1341
+ }
1342
+
1343
+ /** Image response for a workspace document, rendered through official Office Kit. */
1344
+ async artifactPreview(request) {
1345
+ try {
1346
+ await this.ready()
1347
+ const url = new URL(request.url, 'http://localhost')
1348
+ const conversationId = url.searchParams.get('conversationId') ?? ''
1349
+ this.requireConversation(conversationId)
1350
+ const officeKit = this.hostService('officeKit')
1351
+ if (officeKit === undefined || typeof officeKit.renderImages !== 'function') {
1352
+ return this.plainResponse('preview unavailable', 501)
1353
+ }
1354
+ const requested = url.searchParams.get('file') ?? ''
1355
+ const extension = fileExtension(requested)
1356
+ if (!PREVIEW_EXTENSIONS.has(extension)) return this.plainResponse('unsupported document type', 415)
1357
+ const { absolute, relPath } = await this.artifactPath(conversationId, requested)
1358
+ const info = await stat(absolute)
1359
+ if (!info.isFile()) return this.plainResponse('not found', 404)
1360
+ const page = Math.max(1, Math.floor(Number(url.searchParams.get('page') ?? '1')) || 1)
1361
+ const version = `${info.size}:${info.mtimeMs}`
1362
+ const result = await officeKit.renderImages({
1363
+ extension,
1364
+ source: {
1365
+ key: `deepseek-chat:${conversationId}:${relPath}`,
1366
+ version,
1367
+ bytes: info.size,
1368
+ read: async (_signal, maxBytes) => {
1369
+ if (info.size > maxBytes) throw new Error('document exceeds the preview byte limit')
1370
+ return { bytes: new Uint8Array(await readFile(absolute)), version }
1371
+ },
1372
+ },
1373
+ ...(extension === 'xlsx' || extension === 'xls' ? {} : { pages: [page] }),
1374
+ dpi: 144,
1375
+ maxImages: 1,
1376
+ maxPixels: 8_388_608,
1377
+ maxDimension: 8192,
1378
+ maxBytes: 32 * 1024 * 1024,
1379
+ })
1380
+ const image = result?.images?.[0]
1381
+ if (image === undefined) return this.plainResponse('no preview image', 500)
1382
+ return new Response(image.png, {
1383
+ status: 200,
1384
+ headers: {
1385
+ 'content-type': 'image/png',
1386
+ 'content-length': String(image.png.byteLength),
1387
+ 'cache-control': 'no-store',
1388
+ 'x-content-type-options': 'nosniff',
1389
+ 'x-page-count': String(result.pageCount ?? 1),
1390
+ 'x-missing-fonts': encodeURIComponent((result.missingFonts ?? []).join(', ')),
1391
+ },
1392
+ })
1393
+ } catch (error) {
1394
+ this.logger.warn?.('deepseek-chat: document preview failed', errorMessage(error))
1395
+ return this.plainResponse('preview failed', error instanceof ApiError && error.status === 404 ? 404 : 422)
1396
+ }
1397
+ }
1398
+
1399
+ /** The document bytes themselves: a download, never a page the browser runs. */
1400
+ async artifactFile(request) {
1401
+ try {
1402
+ await this.ready()
1403
+ const url = new URL(request.url, 'http://localhost')
1404
+ const conversationId = url.searchParams.get('conversationId') ?? ''
1405
+ this.requireConversation(conversationId)
1406
+ const { absolute } = await this.artifactPath(conversationId, url.searchParams.get('file') ?? '')
1407
+ const info = await stat(absolute)
1408
+ if (!info.isFile()) return this.plainResponse('not found', 404)
1409
+ const bytes = await readFile(absolute)
1410
+ const name = path.basename(absolute)
1411
+ const fallback = name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_')
1412
+ return new Response(bytes, {
1413
+ status: 200,
1414
+ headers: {
1415
+ 'content-type': fileMime(name),
1416
+ 'content-length': String(bytes.length),
1417
+ 'cache-control': 'no-store',
1418
+ 'x-content-type-options': 'nosniff',
1419
+ 'content-disposition': `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(name)}`,
1420
+ },
1421
+ })
1422
+ } catch (error) {
1423
+ this.logger.warn?.('deepseek-chat: document download failed', errorMessage(error))
1424
+ return this.plainResponse('not found', 404)
1425
+ }
1426
+ }
1427
+
1428
+ /** Hand one workspace document to the desktop's default application. */
1429
+ async artifactOpen(request) {
1430
+ const body = await readJson(request)
1431
+ const conversationId = typeof body?.conversationId === 'string' ? body.conversationId : ''
1432
+ this.requireConversation(conversationId)
1433
+ const controller = this.hostService('sessionController')
1434
+ if (controller === undefined || typeof controller.openWorkspacePath !== 'function') {
1435
+ throw new ApiError('当前环境无法用系统应用打开文件。', { code: 'OPEN_UNAVAILABLE', status: 501 })
1436
+ }
1437
+ const { absolute } = await this.artifactPath(conversationId, typeof body?.file === 'string' ? body.file : '')
1438
+ const info = await stat(absolute)
1439
+ if (!info.isFile()) throw new ApiError('文件不存在。', { code: 'NOT_FOUND', status: 404 })
1440
+ await controller.openWorkspacePath({ path: absolute }, AbortSignal.timeout(15_000))
1441
+ return { opened: true }
1442
+ }
1443
+
1444
+ /** Answer one pending Documents approval from its Chat card. */
1445
+ async artifactApproval(request) {
1446
+ const body = await readJson(request)
1447
+ const conversationId = typeof body?.conversationId === 'string' ? body.conversationId : ''
1448
+ this.requireConversation(conversationId)
1449
+ const key = typeof body?.key === 'string' ? body.key : ''
1450
+ const outcome = body?.outcome === 'allowed-once'
1451
+ ? 'allowed-once'
1452
+ : body?.outcome === 'rejected' ? 'rejected' : ''
1453
+ if (outcome === '') throw new ApiError('无效的授权结果。', { code: 'INVALID_REQUEST', status: 400 })
1454
+ const entry = pendingApprovalByKey(key)
1455
+ if (entry === undefined || entry.conversationId !== conversationId) {
1456
+ throw new ApiError('该授权请求已经结束。', { code: 'NOT_FOUND', status: 404 })
1457
+ }
1458
+ answerApproval(key, outcome)
1459
+ return { answered: true }
1460
+ }
1461
+
1462
+ /** Send one supplementary requirement into a running Documents turn. */
1463
+ async artifactSteer(request) {
1464
+ const body = await readJson(request)
1465
+ const conversationId = typeof body?.conversationId === 'string' ? body.conversationId : ''
1466
+ this.requireConversation(conversationId)
1467
+ const text = typeof body?.text === 'string' ? body.text.trim() : ''
1468
+ if (text === '') throw new ApiError('补充要求为空。', { code: 'EMPTY_MESSAGE', status: 400 })
1469
+ if (text.length > 4000) throw new ApiError('补充要求过长。', { code: 'MESSAGE_TOO_LONG', status: 413 })
1470
+ const result = await this.artifacts.steer(conversationId, text)
1471
+ return { sent: true, sessionId: result.sessionId }
1472
+ }
1473
+
1474
+ plainResponse(body, status) {
1475
+ return new Response(body, {
1476
+ status,
1477
+ headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
1478
+ })
1479
+ }
1480
+
1481
+ /**
1482
+ * Resolve one workspace-relative document for a binary route, also refusing a
1483
+ * symbolic link that points outside the conversation workspace.
1484
+ */
1485
+ async artifactPath(conversationId, relPath) {
1486
+ this.requireConversation(conversationId)
1487
+ const root = await this.artifacts.existingTaskRoot(conversationId)
1488
+ if (root === undefined) throw new ApiError('文件不存在。', { code: 'NOT_FOUND', status: 404 })
1489
+ const resolved = resolveInside(root, relPath)
1490
+ const [realRoot, realFile] = await Promise.all([realpath(root), realpath(resolved.absolute)])
1491
+ if (realFile !== realRoot && !realFile.startsWith(`${realRoot}${path.sep}`)) {
1492
+ throw new ApiError('文件路径无效。', { code: 'INVALID_PATH', status: 400 })
1493
+ }
1494
+ return resolved
1495
+ }
1496
+
1497
+ async upload(request) {
1498
+ const declared = Number(request.headers.get('content-length') ?? '0')
1499
+ if (Number.isFinite(declared) && declared > this.config.maxUploadBytes) {
1500
+ throw new ApiError(`文件超过 ${Math.round(this.config.maxUploadBytes / 1024 / 1024)} MB 上限。`, {
1501
+ code: 'FILE_TOO_LARGE', status: 413,
1502
+ })
1503
+ }
1504
+ const name = decodeURIComponent(request.headers.get('x-file-name') ?? '')
1505
+ const mimeType = request.headers.get('x-file-mime') ?? ''
1506
+ if (name.trim() === '') throw new ApiError('缺少文件名。', { code: 'INVALID_REQUEST', status: 400 })
1507
+ const purpose = uploadPurpose(name, mimeType)
1508
+ const purposeLimit = purpose === 'user_data' ? 32 * 1024 * 1024 : this.config.maxUploadBytes
1509
+ const bytes = new Uint8Array(await request.arrayBuffer())
1510
+ if (bytes.length === 0) throw new ApiError('文件为空。', { code: 'INVALID_REQUEST', status: 400 })
1511
+ if (bytes.length > purposeLimit) {
1512
+ throw new ApiError(`该文件类型最大允许 ${Math.round(purposeLimit / 1024 / 1024)} MB。`, {
1513
+ code: 'FILE_TOO_LARGE', status: 413,
1514
+ })
1515
+ }
1516
+ const settings = this.store.getSettings()
1517
+ const auth = await resolveAuth(this.ctx, { ...settings, baseURL: this.config.baseURL })
1518
+ const file = await uploadFile({
1519
+ baseURL: this.config.baseURL,
1520
+ auth,
1521
+ name,
1522
+ mimeType,
1523
+ bytes,
1524
+ signal: request.signal,
1525
+ })
1526
+ return {
1527
+ file: {
1528
+ ...file,
1529
+ isImage: isImageFile(name, mimeType) && purpose === null,
1530
+ },
1531
+ }
1532
+ }
1533
+
1534
+ /** Hold the conversation from credential lookup through the final disk write. */
1535
+ reserveTurn(conversationId, requestSignal) {
1536
+ if (this.active.has(conversationId)) {
1537
+ throw new ApiError('此会话正在生成回复。', { code: 'BUSY', status: 409 })
1538
+ }
1539
+ const controller = new AbortController()
1540
+ const onAbort = () => controller.abort()
1541
+ if (requestSignal.aborted) onAbort()
1542
+ else requestSignal.addEventListener('abort', onAbort, { once: true })
1543
+ let finish
1544
+ const finished = new Promise(resolve => { finish = resolve })
1545
+ this.pending.add(finished)
1546
+ this.active.set(conversationId, { controller })
1547
+ return {
1548
+ controller,
1549
+ release: () => {
1550
+ requestSignal.removeEventListener('abort', onAbort)
1551
+ if (this.active.get(conversationId)?.controller === controller) this.active.delete(conversationId)
1552
+ this.pending.delete(finished)
1553
+ finish()
1554
+ },
1555
+ }
1556
+ }
1557
+
1558
+ /**
1559
+ * One streaming entry point for every turn kind:
1560
+ * - `send` appends a new user/assistant turn to the active branch;
1561
+ * - `edit` turns an edited question into a new sibling branch and drops the
1562
+ * old replies from the active path (they stay stored as versions);
1563
+ * - `regenerate` adds a new sibling answer under the same question;
1564
+ * - `continue` resumes the existing answer from its visible-text prefix.
1565
+ */
1566
+ async stream(request) {
1567
+ let turn
1568
+ try {
1569
+ await this.ready()
1570
+ const body = await readJson(request)
1571
+ if (this.disposed) throw new ApiError('Chat 插件已卸载。', { code: 'DISPOSED', status: 503 })
1572
+ const conversationId = typeof body?.conversationId === 'string' ? body.conversationId : ''
1573
+ const conversation = this.requireConversation(conversationId)
1574
+ turn = this.reserveTurn(conversationId, request.signal)
1575
+ const abortController = turn.controller
1576
+ const mode = ['send', 'edit', 'regenerate', 'continue'].includes(body?.mode) ? body.mode : 'send'
1577
+ // Document mode is its own turn kind: the Agent Runtime does the work, so
1578
+ // Chat neither needs the DeepSeek Files API nor its own model request.
1579
+ const artifactMode = body?.artifact === true && mode === 'send'
1580
+ const targetId = typeof body?.targetMessageId === 'string' ? body.targetMessageId : ''
1581
+ const settings = this.store.getSettings()
1582
+ const auth = artifactMode
1583
+ ? null
1584
+ : await resolveTurnAuth(this.ctx, { ...settings, baseURL: this.config.baseURL }, abortController.signal)
1585
+ const locale = body?.locale === 'en' ? 'en' : 'zh'
1586
+ const reminder = createLatestReminder({ locale })
1587
+ // An explicit request model is validated against the real catalog. When a
1588
+ // client omits it (older browser half), the conversation preference wins.
1589
+ const preference = this.modelConfig.resolve(conversationId)
1590
+ const requestedModel = body?.model === undefined || body?.model === null || body?.model === ''
1591
+ ? preference.model
1592
+ : resolveModelId(body.model)
1593
+ if (requestedModel === null) {
1594
+ throw new ApiError(`不支持的模型:${String(body?.model).slice(0, 80)}`, { code: 'INVALID_MODEL', status: 400 })
1595
+ }
1596
+ const model = requestedModel
1597
+ const effort = resolveEffort(body?.effort ?? preference.effort, model)
1598
+ const now = Date.now()
1599
+ let userMessageId = null
1600
+ let reply = null
1601
+ let requestMessages = null
1602
+ let requestTitle = false
1603
+ let continuation = false
1604
+ let memoryQuery = ''
1605
+ let saveTurn
1606
+
1607
+ if (mode === 'continue') {
1608
+ const target = conversation.messages.find(message => message.id === targetId)
1609
+ if (target === undefined) throw new ApiError('要继续的消息不存在。', { code: 'NOT_FOUND', status: 404 })
1610
+ if (target.role !== 'assistant') {
1611
+ throw new ApiError('只能继续助手的回答。', { code: 'INVALID_REQUEST', status: 400 })
1612
+ }
1613
+ if (conversation.messages.at(-1)?.id !== target.id) {
1614
+ throw new ApiError('只能继续最后一条回答。', { code: 'INVALID_REQUEST', status: 400 })
1615
+ }
1616
+ if (!canContinueReply(target)) {
1617
+ throw new ApiError('这条回答没有可继续的正文,请选择重新生成。', { code: 'NOT_CONTINUABLE', status: 409 })
1618
+ }
1619
+ requestMessages = buildContinuationMessages(conversation.messages, target.id, { reminder })
1620
+ if (requestMessages === null) {
1621
+ throw new ApiError('这条回答没有可继续的正文,请选择重新生成。', { code: 'NOT_CONTINUABLE', status: 409 })
1622
+ }
1623
+ continuation = true
1624
+ reply = {
1625
+ ...target,
1626
+ status: 'streaming',
1627
+ updatedAt: now,
1628
+ error: undefined,
1629
+ // A continuation is a fresh request: record the model/effort that
1630
+ // actually handles it so the message footer never disagrees with the
1631
+ // request after the user switches models mid-conversation.
1632
+ model,
1633
+ effort,
1634
+ continueCount: (target.continueCount ?? 0) + 1,
1635
+ }
1636
+ // Persist the resumed state before the request starts: a crash or reload
1637
+ // then presents it as stopped and keeps whatever text already exists.
1638
+ saveTurn = () => this.store.replaceMessage(conversationId, reply)
1639
+ } else {
1640
+ const text = typeof body?.text === 'string' ? body.text.trim() : ''
1641
+ memoryQuery = text
1642
+ const files = sanitizeFiles(body?.files)
1643
+ // A regeneration reuses the stored question, so it carries no new body.
1644
+ if (mode !== 'regenerate') {
1645
+ if (text.length > MAX_TEXT) throw new ApiError('消息过长。', { code: 'MESSAGE_TOO_LONG', status: 413 })
1646
+ if (text === '' && files.length === 0) throw new ApiError('消息为空。', { code: 'EMPTY_MESSAGE', status: 400 })
1647
+ }
1648
+ const thinking = body?.thinking === true
1649
+ const search = body?.search === true
1650
+ requestTitle = mode === 'send'
1651
+ && !conversation.messages.some(message => message.role === 'assistant')
1652
+ && conversation.titleAuto !== false
1653
+ reply = {
1654
+ id: randomUUID(),
1655
+ role: 'assistant',
1656
+ createdAt: now,
1657
+ updatedAt: now,
1658
+ model,
1659
+ effort,
1660
+ thinking,
1661
+ search,
1662
+ status: 'streaming',
1663
+ blocks: [],
1664
+ prefix: true,
1665
+ }
1666
+ let requestPath = conversation.messages
1667
+ if (mode === 'edit') {
1668
+ const index = requestPath.findIndex(message => message.id === targetId)
1669
+ const target = requestPath[index]
1670
+ if (target === undefined || target.role !== 'user') {
1671
+ throw new ApiError('只能编辑当前对话中的用户消息。', { code: 'INVALID_REQUEST', status: 400 })
1672
+ }
1673
+ // The edited question becomes a sibling of the original one, under the
1674
+ // same parent, so everything before it stays shared and the old answer
1675
+ // subtree stays stored but off the active path.
1676
+ const parentId = conversation.nodes[target.id]?.parentId ?? null
1677
+ const userMessage = { id: randomUUID(), role: 'user', content: text, files, createdAt: now }
1678
+ userMessageId = userMessage.id
1679
+ requestPath = [...requestPath.slice(0, index), userMessage]
1680
+ saveTurn = async () => {
1681
+ await this.store.createUserBranch(conversationId, userMessage, parentId)
1682
+ return this.store.createAssistantBranch(conversationId, reply, userMessage.id)
1683
+ }
1684
+ } else if (mode === 'regenerate') {
1685
+ const target = conversation.messages.find(message => message.id === targetId)
1686
+ if (target === undefined || target.role !== 'assistant') {
1687
+ throw new ApiError('只能重新生成当前对话中的回答。', { code: 'INVALID_REQUEST', status: 400 })
1688
+ }
1689
+ const parentId = conversation.nodes[target.id]?.parentId ?? null
1690
+ const parent = parentId === null ? undefined : conversation.nodes[parentId]
1691
+ if (parent === undefined || parent.message.role !== 'user') {
1692
+ throw new ApiError('这条回答没有对应的提问,无法重新生成。', { code: 'INVALID_REQUEST', status: 400 })
1693
+ }
1694
+ userMessageId = parentId
1695
+ memoryQuery = parent.message.content
1696
+ saveTurn = () => this.store.createAssistantBranch(conversationId, reply, parentId)
1697
+ } else {
1698
+ const userMessage = { id: randomUUID(), role: 'user', content: text, files, createdAt: now }
1699
+ userMessageId = userMessage.id
1700
+ requestPath = [...requestPath, userMessage]
1701
+ saveTurn = () => this.store.appendTurn(conversationId, userMessage, reply)
1702
+ }
1703
+ requestMessages = buildRequestMessages(requestPath, userMessageId, { reminder })
1704
+ }
1705
+ // Validate the exact outgoing branch, including any replayed image, before
1706
+ // writing a new turn, switching a version, or resuming a stopped reply.
1707
+ if (!artifactMode && !findModel(model).capabilities.vision && requestMessages.some(message =>
1708
+ Array.isArray(message.content) && message.content.some(block => block.type === 'image')
1709
+ )) {
1710
+ throw new ApiError('DeepSeek V4 Pro 不支持图片输入,请改用 DeepSeek V4.1 Flash。', {
1711
+ code: 'UNSUPPORTED_INPUT', status: 400,
1712
+ })
1713
+ }
1714
+ const memoryBlock = artifactMode || continuation ? '' : this.memory.contextFor(memoryQuery, locale).block
1715
+ const systemPrompt = settings.systemPrompt.trim() === '' ? DEFAULT_SYSTEM_PROMPT : settings.systemPrompt
1716
+ const requestBody = artifactMode ? null : {
1717
+ model,
1718
+ system: memoryBlock === '' ? systemPrompt : `${systemPrompt}\n\n${memoryBlock}`,
1719
+ messages: requestMessages,
1720
+ // A resumed answer is a text continuation: reasoning is not replayed and
1721
+ // the prefix is only valid for a plain assistant turn.
1722
+ ...(continuation
1723
+ ? { thinking: { type: 'disabled' } }
1724
+ : thinkingParams(reply.thinking, reply.effort ?? effort)),
1725
+ tools: serverTools(continuation ? false : reply.search),
1726
+ safety_check: { level: 'high' },
1727
+ ...(requestTitle ? { title: { enabled: true } } : {}),
1728
+ }
1729
+ if (abortController.signal.aborted) throw new ApiError('已停止生成。', { code: 'ABORTED', status: 499, kind: 'aborted' })
1730
+ if (await saveTurn() === undefined) throw new ApiError('会话不存在。', { code: 'NOT_FOUND', status: 404 })
1731
+ if (artifactMode) {
1732
+ // The placeholder is already persisted; the Agent's progress and files
1733
+ // arrive as `artifact` frames on the same NDJSON transport, so the
1734
+ // browser's existing streaming, stop button and reload path keep working.
1735
+ const text = typeof body?.text === 'string' ? body.text.trim() : ''
1736
+ const stream = new ReadableStream({
1737
+ start: (streamController) => this.runArtifactStream({
1738
+ upstream: streamController,
1739
+ signal: abortController.signal,
1740
+ conversationId,
1741
+ conversation,
1742
+ userMessageId,
1743
+ reply,
1744
+ text,
1745
+ locale,
1746
+ title: conversation.title,
1747
+ abort: abortController,
1748
+ }).finally(() => turn.release()),
1749
+ cancel: () => {
1750
+ abortController.abort()
1751
+ },
1752
+ })
1753
+ return new Response(stream, { status: 200, headers: NDJSON_HEADERS })
1754
+ }
1755
+ let timedOut = false
1756
+ const timer = setTimeout(() => {
1757
+ timedOut = true
1758
+ abortController.abort()
1759
+ }, this.config.requestTimeoutMs)
1760
+
1761
+ const stream = new ReadableStream({
1762
+ start: (streamController) => {
1763
+ return this.runStream({
1764
+ upstream: streamController,
1765
+ signal: abortController.signal,
1766
+ conversationId,
1767
+ conversation,
1768
+ userMessageId,
1769
+ reply,
1770
+ requestBody,
1771
+ auth,
1772
+ abort: abortController,
1773
+ isTimedOut: () => timedOut,
1774
+ }).finally(() => {
1775
+ clearTimeout(timer)
1776
+ turn.release()
1777
+ // Auto extraction runs after the reply is finished and outside the
1778
+ // response stream, so it can never delay or fail the chat itself.
1779
+ if (!this.disposed && !continuation && (mode === 'send' || mode === 'edit')) {
1780
+ this.queueMemoryExtraction(conversationId, locale)
1781
+ }
1782
+ })
1783
+ },
1784
+ cancel: () => {
1785
+ abortController.abort()
1786
+ },
1787
+ })
1788
+ return new Response(stream, { status: 200, headers: NDJSON_HEADERS })
1789
+ } catch (error) {
1790
+ turn?.release()
1791
+ this.logger.warn?.('deepseek-chat: stream request failed', error instanceof Error ? error.message : error)
1792
+ return errorResponse(error)
1793
+ }
1794
+ }
1795
+
1796
+ /**
1797
+ * Schedule one automatic extraction attempt after a completed turn. The task
1798
+ * is tracked so plugin disposal waits for it, but nothing awaits it on the
1799
+ * chat path: a failing or slow extraction is invisible to the conversation.
1800
+ */
1801
+ queueMemoryExtraction(conversationId, locale) {
1802
+ const signal = this.memoryStore.getAutoExtractionSignal()
1803
+ if (signal === null || this.disposed) return
1804
+ const run = (async () => {
1805
+ // Yield first so the response body can close before any extra request.
1806
+ await new Promise(resolve => setTimeout(resolve, 0))
1807
+ const conversation = this.store.getConversation(conversationId)
1808
+ if (conversation === undefined) return
1809
+ await this.memory.maybeExtractConversation({
1810
+ conversationId,
1811
+ messages: conversation.messages,
1812
+ locale,
1813
+ signal,
1814
+ })
1815
+ })().catch((error) => {
1816
+ this.logger.warn?.('deepseek-chat: memory extraction task failed', errorMessage(error))
1817
+ }).finally(() => {
1818
+ this.pending.delete(run)
1819
+ })
1820
+ this.pending.add(run)
1821
+ }
1822
+
1823
+ async runStream({
1824
+ upstream, signal, conversationId, conversation, userMessageId, reply, requestBody, auth,
1825
+ abort, isTimedOut,
1826
+ }) {
1827
+ const encoder = new TextEncoder()
1828
+ let closed = false
1829
+ const send = (value) => {
1830
+ if (closed) return false
1831
+ try {
1832
+ upstream.enqueue(encoder.encode(`${JSON.stringify(value)}\n`))
1833
+ return true
1834
+ } catch {
1835
+ abort.abort()
1836
+ return false
1837
+ }
1838
+ }
1839
+ const heartbeat = setInterval(() => {
1840
+ send({ type: 'ping' })
1841
+ }, this.config.heartbeatMs)
1842
+ const update = (next) => { reply = next }
1843
+ const persist = async () => {
1844
+ // A mid-flight write carries the write time so a reload can close an open
1845
+ // thinking block against it instead of against the reload clock.
1846
+ const snapshot = reply.status === 'streaming' ? { ...reply, updatedAt: Date.now() } : reply
1847
+ await this.store.replaceMessage(conversationId, snapshot).catch((error) => {
1848
+ this.logger.warn?.('deepseek-chat: failed to persist reply', error)
1849
+ })
1850
+ }
1851
+ const latest = () => this.store.getConversation(conversationId) ?? conversation
1852
+ const outMessage = () => this.store.presentMessage(latest(), reply)
1853
+ let sawStop = false
1854
+ const blockIndexes = new Map()
1855
+ try {
1856
+ send({
1857
+ type: 'start',
1858
+ conversationId,
1859
+ userMessageId,
1860
+ assistantMessageId: reply.id,
1861
+ title: conversation.title,
1862
+ // The authoritative active path after this turn's branch was created.
1863
+ // The browser replaces its optimistic messages with it, so an edit or a
1864
+ // regeneration never leaves a stale answer in the visible context.
1865
+ messages: this.store.presentPath(latest()),
1866
+ })
1867
+ let titleSent = false
1868
+ signal.throwIfAborted()
1869
+ for await (const event of streamMessage({
1870
+ baseURL: this.config.baseURL,
1871
+ auth,
1872
+ body: requestBody,
1873
+ signal,
1874
+ })) {
1875
+ if (event.type === 'error') {
1876
+ throw new ApiError(
1877
+ typeof event.error?.message === 'string' ? event.error.message : 'DeepSeek 生成失败,请重试。',
1878
+ { code: 'STREAM_ERROR', kind: 'stream', status: 200 },
1879
+ )
1880
+ }
1881
+ if (event.type === 'message_stop') sawStop = true
1882
+ if (event.type === 'message_delta' && event.delta?.title) {
1883
+ const title = normalizeTitle(event.delta.title)
1884
+ if (title !== '' && !titleSent) {
1885
+ const changed = await this.store.applyAutoTitle(conversationId, title)
1886
+ if (changed) {
1887
+ titleSent = true
1888
+ send({ type: 'title', title })
1889
+ }
1890
+ }
1891
+ }
1892
+ update(applyEvent(reply, event, Date.now(), blockIndexes))
1893
+ send({ type: 'event', event })
1894
+ if (event.type === 'content_block_stop' || event.type === 'message_delta') {
1895
+ void persist()
1896
+ }
1897
+ }
1898
+ if (!sawStop && reply.stopReason === undefined) {
1899
+ throw new ApiError('DeepSeek 连接提前结束,请重试。', { code: 'INTERRUPTED', kind: 'interrupted' })
1900
+ }
1901
+ update(settleReply(reply, 'done', Date.now()))
1902
+ await persist()
1903
+ send({
1904
+ type: 'done',
1905
+ message: outMessage(),
1906
+ conversation: this.store.summary(latest()),
1907
+ })
1908
+ } catch (error) {
1909
+ if (abort.signal.aborted) {
1910
+ if (isTimedOut()) {
1911
+ const payload = {
1912
+ message: '生成超时,请重试。',
1913
+ code: 'TIMEOUT',
1914
+ kind: 'timeout',
1915
+ }
1916
+ update(settleReply(reply, 'error', Date.now(), payload))
1917
+ await persist()
1918
+ send({ type: 'error', error: payload, message: outMessage() })
1919
+ } else {
1920
+ update(settleReply(reply, 'stopped', Date.now()))
1921
+ await persist()
1922
+ send({ type: 'aborted', message: outMessage() })
1923
+ }
1924
+ } else {
1925
+ const payload = errorPayload(error)
1926
+ update(settleReply(reply, 'error', Date.now(), payload))
1927
+ await persist()
1928
+ send({ type: 'error', error: payload, message: outMessage() })
1929
+ }
1930
+ } finally {
1931
+ clearInterval(heartbeat)
1932
+ closed = true
1933
+ try {
1934
+ upstream.close()
1935
+ } catch {
1936
+ // The consumer may have gone away.
1937
+ }
1938
+ }
1939
+ }
1940
+
1941
+ /**
1942
+ * Stream one document turn. Progress and files travel as `artifact` frames
1943
+ * carrying the whole block list, so the browser replaces its optimistic reply
1944
+ * without inventing a second event vocabulary.
1945
+ */
1946
+ async runArtifactStream({
1947
+ upstream, signal, conversationId, conversation, userMessageId, reply, text, locale, title, abort,
1948
+ }) {
1949
+ const encoder = new TextEncoder()
1950
+ let closed = false
1951
+ const send = (value) => {
1952
+ if (closed) return false
1953
+ try {
1954
+ upstream.enqueue(encoder.encode(`${JSON.stringify(value)}\n`))
1955
+ return true
1956
+ } catch {
1957
+ abort.abort()
1958
+ return false
1959
+ }
1960
+ }
1961
+ const heartbeat = setInterval(() => send({ type: 'ping' }), this.config.heartbeatMs)
1962
+ const latest = () => this.store.getConversation(conversationId) ?? conversation
1963
+ const present = () => this.store.presentMessage(latest(), reply)
1964
+ let dirty = false
1965
+ let persistTimer = null
1966
+ const persist = async () => {
1967
+ dirty = false
1968
+ await this.store.replaceMessage(conversationId, reply).catch((error) => {
1969
+ this.logger.warn?.('deepseek-chat: failed to persist document reply', error)
1970
+ })
1971
+ }
1972
+ const schedulePersist = () => {
1973
+ dirty = true
1974
+ if (persistTimer !== null) return
1975
+ persistTimer = setTimeout(() => {
1976
+ persistTimer = null
1977
+ if (dirty) void persist()
1978
+ }, 900)
1979
+ }
1980
+ const artifact = {
1981
+ taskId: randomUUID(),
1982
+ conversationId,
1983
+ status: 'running',
1984
+ steps: [{ id: 'prepare', state: 'active' }],
1985
+ files: [],
1986
+ timeline: [],
1987
+ approval: null,
1988
+ usage: { inputTokens: 0, outputTokens: 0 },
1989
+ text: '',
1990
+ error: '',
1991
+ notice: '',
1992
+ }
1993
+ const blocks = () => {
1994
+ const list = [{
1995
+ type: 'artifact',
1996
+ ...artifact,
1997
+ steps: artifact.steps.map(step => ({ ...step })),
1998
+ files: artifact.files.map(file => ({ ...file })),
1999
+ usage: { ...artifact.usage },
2000
+ }]
2001
+ if (artifact.text !== '') list.push({ type: 'text', text: artifact.text, citations: [] })
2002
+ return list
2003
+ }
2004
+ const update = (next) => {
2005
+ Object.assign(artifact, next)
2006
+ reply = { ...reply, blocks: blocks(), updatedAt: Date.now() }
2007
+ send({ type: 'event', event: { type: 'artifact', blocks: blocks() } })
2008
+ schedulePersist()
2009
+ }
2010
+ try {
2011
+ send({
2012
+ type: 'start',
2013
+ conversationId,
2014
+ userMessageId,
2015
+ assistantMessageId: reply.id,
2016
+ title,
2017
+ messages: this.store.presentPath(latest()),
2018
+ })
2019
+ const result = await this.artifacts.run({
2020
+ conversationId,
2021
+ text,
2022
+ locale,
2023
+ title,
2024
+ signal,
2025
+ onUpdate: next => update(next),
2026
+ })
2027
+ update({
2028
+ status: result.status,
2029
+ steps: result.steps,
2030
+ files: result.files.map(file => ({ ...file, conversationId })),
2031
+ timeline: result.timeline,
2032
+ approval: result.approval ?? null,
2033
+ usage: result.usage,
2034
+ text: result.text,
2035
+ error: result.error,
2036
+ notice: result.notice,
2037
+ })
2038
+ // A document turn is a complete Agent answer, never a text prefix that
2039
+ // "Continue generating" could resume through the ordinary chat model.
2040
+ reply = { ...reply, prefix: false }
2041
+ if (persistTimer !== null) {
2042
+ clearTimeout(persistTimer)
2043
+ persistTimer = null
2044
+ }
2045
+ if (result.status === 'cancelled') {
2046
+ reply = settleReply(reply, 'stopped', Date.now())
2047
+ await persist()
2048
+ send({ type: 'aborted', message: present() })
2049
+ } else if (result.status === 'done') {
2050
+ reply = settleReply(reply, 'done', Date.now())
2051
+ await persist()
2052
+ send({ type: 'done', message: present(), conversation: this.store.summary(latest()) })
2053
+ } else {
2054
+ const payload = {
2055
+ message: result.error || '文档任务失败。',
2056
+ code: result.status === 'needs-approval' ? 'APPROVAL_REQUIRED' : 'ARTIFACT_FAILED',
2057
+ kind: 'artifact',
2058
+ status: 200,
2059
+ }
2060
+ reply = settleReply(reply, 'error', Date.now(), payload)
2061
+ await persist()
2062
+ send({ type: 'error', error: payload, message: present() })
2063
+ }
2064
+ } catch (error) {
2065
+ const payload = errorPayload(error)
2066
+ reply = settleReply(reply, 'error', Date.now(), payload)
2067
+ await persist()
2068
+ send({ type: 'error', error: payload, message: present() })
2069
+ } finally {
2070
+ if (persistTimer !== null) clearTimeout(persistTimer)
2071
+ clearInterval(heartbeat)
2072
+ closed = true
2073
+ try {
2074
+ upstream.close()
2075
+ } catch {
2076
+ // The consumer may have gone away.
2077
+ }
2078
+ }
2079
+ }
2080
+
2081
+ async dispose() {
2082
+ this.disposed = true
2083
+ if (typeof this.approvalListener === 'function') this.approvalListener()
2084
+ this.importer.dispose()
2085
+ this.memoryAbort.abort()
2086
+ for (const active of this.active.values()) {
2087
+ active.controller.abort()
2088
+ }
2089
+ await Promise.allSettled([...this.pending])
2090
+ await this.store.flush().catch(() => {})
2091
+ await this.modelConfig.flush().catch(() => {})
2092
+ await this.memoryStore.flush().catch(() => {})
2093
+ for (const dispose of this.routes.reverse()) {
2094
+ try {
2095
+ await dispose()
2096
+ } catch {
2097
+ // Route already removed with its owner.
2098
+ }
2099
+ }
2100
+ this.routes = []
2101
+ }
2102
+ }