@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,602 @@
1
+ /**
2
+ * Document tasks executed by the official Agent Runtime.
3
+ *
4
+ * The Chat Host owns only the wiring: it creates (or resumes) one Agent Session
5
+ * inside the shared `Documents` workspace, sends one prompt confined to the
6
+ * conversation's subfolder, follows the durable session events for progress, and
7
+ * reports the files that landed there. Document creation, editing, conversion and
8
+ * rendering stay in the official Office skills, Office tools and Office Kit.
9
+ */
10
+
11
+ import path from 'node:path'
12
+ import { mkdir } from 'node:fs/promises'
13
+ import { randomUUID } from 'node:crypto'
14
+ import { buildArtifactPrompt } from './prompt.js'
15
+ import { pendingApprovalFor, registerArtifactSession } from './approval-bus.js'
16
+ import {
17
+ documentsRoot, ensureConversationRoot, ensureWorkspace, findConversationRoot, listDocuments,
18
+ listUploads, readMeta, writeMeta,
19
+ } from './workspace.js'
20
+
21
+ const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000
22
+ /** How long an unanswered approval may hold the task before Chat gives up. */
23
+ const APPROVAL_WAIT_MS = 5 * 60 * 1000
24
+ const PRESET_ID = 'artifacts'
25
+ /** The single Harness workspace every document Session is grouped under. */
26
+ const WORKSPACE_TITLE = 'Documents'
27
+
28
+ class ArtifactError extends Error {
29
+ constructor(code, message) {
30
+ super(message)
31
+ this.code = code
32
+ }
33
+ }
34
+
35
+ /** Map one Agent tool name to the progress row it advances. */
36
+ function stepForTool(name) {
37
+ if (name === 'skill') return 'skills'
38
+ if (name === 'present') return 'deliver'
39
+ if (name === 'office_convert' || name === 'office_recalculate') return 'convert'
40
+ if (name === 'office_render') return 'check'
41
+ if (name === 'write' || name === 'edit' || name === 'apply_patch' || name === 'bash'
42
+ || name === 'pwsh' || name === 'run_code') return 'write'
43
+ return null
44
+ }
45
+
46
+ function textOfMessage(message) {
47
+ const blocks = Array.isArray(message?.content) ? message.content : []
48
+ return blocks.filter(block => block?.type === 'text' && typeof block.text === 'string')
49
+ .map(block => block.text)
50
+ .join('')
51
+ .trim()
52
+ }
53
+
54
+ function addUsage(total, usage) {
55
+ if (usage === null || typeof usage !== 'object') return total
56
+ total.inputTokens += Number(usage.inputTokens) || 0
57
+ total.outputTokens += Number(usage.outputTokens) || 0
58
+ return total
59
+ }
60
+
61
+ /** One concise execution line; details are clipped, never raw tool arguments. */
62
+ const TIMELINE_LIMIT = 40
63
+
64
+ function clipText(value, max = 240) {
65
+ const text = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : ''
66
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`
67
+ }
68
+
69
+ function parseToolArgs(raw) {
70
+ try {
71
+ const value = JSON.parse(raw)
72
+ return value !== null && typeof value === 'object' ? value : {}
73
+ } catch {
74
+ return {}
75
+ }
76
+ }
77
+
78
+ function timelineKindOfTool(name) {
79
+ if (name === 'skill') return 'skill'
80
+ if (name === 'write' || name === 'edit' || name === 'apply_patch') return 'write'
81
+ if (name === 'bash' || name === 'pwsh') return 'shell'
82
+ if (name === 'office_convert' || name === 'office_recalculate') return 'convert'
83
+ if (name === 'office_render') return 'render'
84
+ if (name === 'present') return 'deliver'
85
+ return 'tool'
86
+ }
87
+
88
+ function timelineDetailOfTool(name, args) {
89
+ const file = typeof args.path === 'string'
90
+ ? args.path
91
+ : typeof args.file_path === 'string'
92
+ ? args.file_path
93
+ : typeof args.input === 'string' ? args.input : ''
94
+ if (name === 'skill') return clipText(args.name ?? '')
95
+ if (name === 'write' || name === 'edit' || name === 'apply_patch') return clipText(file)
96
+ if (name === 'bash' || name === 'pwsh') return clipText(args.command ?? '', 160)
97
+ if (name === 'office_convert') return clipText([file, args.format].filter(Boolean).join(' · '))
98
+ if (name === 'office_render') {
99
+ const pages = Array.isArray(args.pages) ? args.pages.join(',') : args.pages
100
+ return clipText([file, pages === undefined ? '' : `p.${pages}`].filter(Boolean).join(' · '))
101
+ }
102
+ if (name === 'office_recalculate') return clipText(file)
103
+ if (name === 'present') {
104
+ const files = Array.isArray(args.files) ? args.files : []
105
+ const names = files.map((item) => {
106
+ const value = typeof item === 'string' ? item : (typeof item?.path === 'string' ? item.path : '')
107
+ return value === '' ? '' : path.basename(value)
108
+ }).filter(Boolean)
109
+ return clipText(names.join(', '))
110
+ }
111
+ return ''
112
+ }
113
+
114
+ function presentedRelPath(sessionRoot, taskRoot, value) {
115
+ if (typeof value !== 'string' || value.trim() === '') return null
116
+ try {
117
+ const absolute = path.isAbsolute(value) ? path.resolve(value) : path.resolve(sessionRoot, value)
118
+ const relative = path.relative(taskRoot, absolute)
119
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) return null
120
+ return relative.split(path.sep).join('/')
121
+ } catch {
122
+ return null
123
+ }
124
+ }
125
+
126
+ export class ArtifactService {
127
+ constructor({ ctx, logger, baseDir, timeoutMs }) {
128
+ this.ctx = ctx
129
+ this.logger = logger
130
+ this.baseDir = baseDir
131
+ this.timeoutMs = timeoutMs ?? DEFAULT_TIMEOUT_MS
132
+ }
133
+
134
+ hostService(name) {
135
+ try {
136
+ return this.ctx.get?.(name) ?? this.ctx[name]
137
+ } catch {
138
+ return undefined
139
+ }
140
+ }
141
+
142
+ /** Whether this Host can run a document task at all. */
143
+ capability() {
144
+ return {
145
+ enabled: this.hostService('sessionController') !== undefined,
146
+ preview: this.hostService('officeKit') !== undefined,
147
+ }
148
+ }
149
+
150
+ /** The shared Documents workspace root (the Agent Session cwd). */
151
+ sessionRoot() {
152
+ return documentsRoot(this.baseDir)
153
+ }
154
+
155
+ /** The conversation's existing subfolder, for read-only routes. */
156
+ async existingTaskRoot(conversationId) {
157
+ return findConversationRoot(this.sessionRoot(), conversationId)
158
+ }
159
+
160
+ /** Ensure and return this conversation's subfolder inside Documents. */
161
+ async taskRootFor(conversationId, title) {
162
+ const { root } = await ensureConversationRoot(this.sessionRoot(), conversationId, title)
163
+ return root
164
+ }
165
+
166
+ /** Send one supplementary requirement into the conversation's running turn. */
167
+ async steer(conversationId, text) {
168
+ const controller = this.hostService('sessionController')
169
+ if (controller === undefined) throw new ArtifactError('UNAVAILABLE', 'Host 没有可用的 Agent 会话服务。')
170
+ const taskRoot = await this.existingTaskRoot(conversationId)
171
+ if (taskRoot === undefined) throw new ArtifactError('NO_TASK', '这个会话还没有文档任务。')
172
+ const meta = await readMeta(taskRoot)
173
+ if (typeof meta.sessionId !== 'string' || meta.sessionId === '') {
174
+ throw new ArtifactError('NO_TASK', '这个会话还没有文档任务。')
175
+ }
176
+ await controller.prompt({
177
+ requestId: randomUUID(),
178
+ sessionId: meta.sessionId,
179
+ mode: 'steer',
180
+ content: [{ type: 'text', text }],
181
+ }, AbortSignal.timeout(30_000))
182
+ return { sessionId: meta.sessionId }
183
+ }
184
+
185
+ /**
186
+ * Register the shared `Documents` Harness workspace on first use. A Host
187
+ * without a workspace registry still gets the shared directory, just without
188
+ * the Agent-side grouping.
189
+ */
190
+ async ensureDocumentsWorkspace() {
191
+ const root = this.sessionRoot()
192
+ await mkdir(root, { recursive: true })
193
+ const registry = this.hostService('workspaceRegistry')
194
+ if (registry === undefined || typeof registry.create !== 'function') return { root }
195
+ try {
196
+ const workspace = await registry.create(root, WORKSPACE_TITLE)
197
+ return { root: typeof workspace?.path === 'string' ? workspace.path : root, workspace }
198
+ } catch (error) {
199
+ this.logger.warn?.(
200
+ 'deepseek-chat: could not register the Documents workspace',
201
+ error instanceof Error ? error.message : error,
202
+ )
203
+ return { root }
204
+ }
205
+ }
206
+
207
+ /** Resolve the dedicated preset, falling back to the ordinary Agent preset. */
208
+ async presetId() {
209
+ const presets = this.hostService('agentPresets')
210
+ if (presets === undefined || typeof presets.resolve !== 'function') return undefined
211
+ for (const id of [PRESET_ID, 'standard']) {
212
+ try {
213
+ const preset = await presets.resolve(id)
214
+ if (preset?.broken === undefined || preset.broken === null) return id
215
+ } catch {
216
+ // Try the next identity.
217
+ }
218
+ }
219
+ return undefined
220
+ }
221
+
222
+ /** Reuse the conversation's Session, or create one inside Documents. */
223
+ async ensureSession({ conversationId, root, taskRoot, title, locale, workspace }) {
224
+ const controller = this.hostService('sessionController')
225
+ if (controller === undefined) throw new ArtifactError('UNAVAILABLE', 'Host 没有可用的 Agent 会话服务。')
226
+ const meta = await readMeta(taskRoot)
227
+ if (typeof meta.sessionId === 'string' && meta.sessionId !== '') {
228
+ try {
229
+ await controller.state({ sessionId: meta.sessionId })
230
+ registerArtifactSession(meta.sessionId, conversationId)
231
+ return { sessionId: meta.sessionId, reused: true }
232
+ } catch {
233
+ // The Session is gone; create a fresh one below.
234
+ }
235
+ }
236
+ const preset = await this.presetId()
237
+ let created
238
+ try {
239
+ created = await controller.create({
240
+ ...(workspace === undefined ? { cwd: root } : { workspaceId: workspace.id }),
241
+ ...(preset === undefined ? {} : { agentPreset: preset }),
242
+ })
243
+ } catch (error) {
244
+ throw new ArtifactError(
245
+ 'CREATE_FAILED',
246
+ `无法创建文档 Agent 会话:${error instanceof Error ? error.message : String(error)}`,
247
+ )
248
+ }
249
+ const sessionId = created?.sessionId
250
+ if (typeof sessionId !== 'string' || sessionId === '') {
251
+ throw new ArtifactError('CREATE_FAILED', 'Agent 会话服务没有返回会话 id。')
252
+ }
253
+ registerArtifactSession(sessionId, conversationId)
254
+ await writeMeta(taskRoot, {
255
+ ...meta,
256
+ sessionId,
257
+ preset: created.agentPreset ?? null,
258
+ workspace: workspace?.id ?? null,
259
+ updatedAt: Date.now(),
260
+ })
261
+ if (typeof title === 'string' && title.trim() !== '') {
262
+ const label = (locale === 'en' ? 'Documents · ' : '文档 · ') + title.trim()
263
+ try {
264
+ await controller.rename({ sessionId, title: label.slice(0, 80) })
265
+ } catch (error) {
266
+ this.logger.warn?.(
267
+ 'deepseek-chat: could not rename the document session',
268
+ error instanceof Error ? error.message : error,
269
+ )
270
+ }
271
+ }
272
+ return { sessionId, reused: false }
273
+ }
274
+
275
+ /**
276
+ * Run one document task to completion.
277
+ *
278
+ * @param request - conversation, user text, locale, optional title and signal.
279
+ * @param onUpdate - progress callback receiving the current artifact state.
280
+ * @returns status, final text, workspace files and token usage.
281
+ */
282
+ async run({ conversationId, text, locale = 'zh', title, signal, onUpdate = () => {} }) {
283
+ const controller = this.hostService('sessionController')
284
+ if (controller === undefined) throw new ArtifactError('UNAVAILABLE', 'Host 没有可用的 Agent 会话服务。')
285
+ const sessionRoot = this.sessionRoot()
286
+ const taskRoot = await this.taskRootFor(conversationId, title)
287
+ await ensureWorkspace(taskRoot)
288
+ const uploads = await listUploads(taskRoot)
289
+ const files = await listDocuments(taskRoot)
290
+ const documents = await this.ensureDocumentsWorkspace()
291
+ const { sessionId, reused } = await this.ensureSession({
292
+ conversationId,
293
+ root: documents.root,
294
+ taskRoot,
295
+ title,
296
+ locale,
297
+ workspace: documents.workspace,
298
+ })
299
+ const prompt = buildArtifactPrompt({
300
+ text,
301
+ taskDir: path.basename(taskRoot),
302
+ uploads,
303
+ files,
304
+ locale,
305
+ })
306
+ const task = {
307
+ status: 'running',
308
+ steps: [{ id: 'prepare', state: 'done' }, { id: 'write', state: 'active' }],
309
+ files: [],
310
+ usage: { inputTokens: 0, outputTokens: 0 },
311
+ text: '',
312
+ timeline: [],
313
+ sessionId,
314
+ }
315
+ if (!reused) task.steps = [{ id: 'prepare', state: 'active' }]
316
+ const emit = () => {
317
+ const pending = pendingApprovalFor(sessionId)
318
+ task.approval = pending === undefined
319
+ ? null
320
+ : { key: pending.key, toolName: pending.toolName, reason: pending.reason }
321
+ onUpdate({
322
+ status: task.status,
323
+ steps: task.steps.map(step => ({ ...step })),
324
+ files: task.files.map(file => ({ ...file })),
325
+ usage: { ...task.usage },
326
+ text: task.text,
327
+ timeline: task.timeline.map(entry => ({ ...entry })),
328
+ approval: task.approval,
329
+ })
330
+ }
331
+ const complete = async (status, options = {}) => {
332
+ task.text = options.text ?? task.text
333
+ const produced = await listDocuments(taskRoot)
334
+ const presented = options.presented ?? []
335
+ task.files = produced.map((file) => ({
336
+ ...file,
337
+ presented: presented.some(value => presentedRelPath(sessionRoot, taskRoot, value) === file.relPath),
338
+ }))
339
+ return this.finish(task, status, { locale, ...options })
340
+ }
341
+
342
+ const followAbort = new AbortController()
343
+ let externalAbort = false
344
+ let timedOut = false
345
+ let approvalBlocked = false
346
+ let endReason = null
347
+ let lastText = ''
348
+ const presented = []
349
+ const callSteps = new Map()
350
+ let approvalTimer = null
351
+ let thinkingId = null
352
+ let thinkingText = ''
353
+ let lastTimelineEmit = 0
354
+ const emitTimeline = (force = false) => {
355
+ const now = Date.now()
356
+ if (!force && now - lastTimelineEmit < 250) return
357
+ lastTimelineEmit = now
358
+ emit()
359
+ }
360
+ const pushTimeline = (entry) => {
361
+ task.timeline.push(entry)
362
+ if (task.timeline.length > TIMELINE_LIMIT) task.timeline.shift()
363
+ }
364
+ const updateTimeline = (id, patch) => {
365
+ const entry = task.timeline.find(item => item.id === id)
366
+ if (entry) Object.assign(entry, patch)
367
+ }
368
+
369
+ const cancelTurn = () => {
370
+ Promise.resolve(controller.cancel({ sessionId })).catch(() => {})
371
+ }
372
+ const onAbort = () => {
373
+ externalAbort = true
374
+ followAbort.abort()
375
+ cancelTurn()
376
+ }
377
+ if (signal.aborted) externalAbort = true
378
+ else signal.addEventListener('abort', onAbort, { once: true })
379
+ const timer = setTimeout(() => {
380
+ timedOut = true
381
+ followAbort.abort()
382
+ cancelTurn()
383
+ }, this.timeoutMs)
384
+
385
+ const nextStep = (id, state) => {
386
+ if (id === null) return
387
+ for (const step of task.steps) {
388
+ if (step.state === 'active') step.state = 'done'
389
+ }
390
+ const existing = task.steps.find(step => step.id === id)
391
+ if (existing) existing.state = state
392
+ else task.steps.push({ id, state })
393
+ }
394
+
395
+ try {
396
+ const iterator = controller.follow(
397
+ { address: { kind: 'session', sessionId }, activate: true, assistantStream: true },
398
+ followAbort.signal,
399
+ )[Symbol.asyncIterator]()
400
+ const opening = await iterator.next()
401
+ if (opening.done || opening.value?.type !== 'snapshot') {
402
+ throw new ArtifactError('FOLLOW_FAILED', '无法订阅文档 Agent 会话。')
403
+ }
404
+ if (externalAbort) {
405
+ await iterator.return?.()
406
+ return await complete('cancelled')
407
+ }
408
+ await controller.prompt({
409
+ requestId: randomUUID(),
410
+ sessionId,
411
+ mode: 'queue',
412
+ content: [{ type: 'text', text: prompt }],
413
+ }, AbortSignal.timeout(60_000))
414
+ nextStep('write', 'active')
415
+ emit()
416
+ for (;;) {
417
+ const next = await iterator.next()
418
+ if (next.done) break
419
+ const frame = next.value
420
+ if (frame?.type === 'assistant-stream') {
421
+ const streamFrame = frame.frame
422
+ if (streamFrame?.type === 'start') {
423
+ thinkingId = `think-${streamFrame.attemptId ?? `${streamFrame.turn}-${streamFrame.step}`}`
424
+ thinkingText = ''
425
+ pushTimeline({ id: thinkingId, kind: 'thinking', state: 'active', detail: '', at: Date.now() })
426
+ emitTimeline(true)
427
+ } else if (streamFrame?.type === 'chunk') {
428
+ const chunk = streamFrame.chunk
429
+ if (chunk?.type === 'reasoning-delta' && typeof chunk.text === 'string' && thinkingId !== null) {
430
+ thinkingText += chunk.text
431
+ updateTimeline(thinkingId, { detail: clipText(thinkingText.slice(-280), 240) })
432
+ emitTimeline()
433
+ }
434
+ } else if (streamFrame?.type === 'end') {
435
+ if (thinkingId !== null) {
436
+ updateTimeline(thinkingId, { state: 'done', detail: clipText(thinkingText.slice(-280), 240) })
437
+ emitTimeline(true)
438
+ }
439
+ thinkingId = null
440
+ thinkingText = ''
441
+ }
442
+ continue
443
+ }
444
+ if (frame?.type !== 'event') continue
445
+ const event = frame.event
446
+ const data = event?.data ?? {}
447
+ if (event.type === 'turn/start') {
448
+ nextStep('write', 'active')
449
+ emit()
450
+ } else if (event.type === 'tool/call') {
451
+ const step = stepForTool(data.name)
452
+ if (step !== null) {
453
+ nextStep(step, 'active')
454
+ callSteps.set(data.callId, step)
455
+ }
456
+ const args = parseToolArgs(data.arguments)
457
+ pushTimeline({
458
+ id: data.callId,
459
+ kind: timelineKindOfTool(data.name),
460
+ tool: data.name,
461
+ state: 'active',
462
+ detail: timelineDetailOfTool(data.name, args),
463
+ at: Date.now(),
464
+ })
465
+ emit()
466
+ } else if (event.type === 'tool/result') {
467
+ const step = callSteps.get(data.message?.toolCallId)
468
+ if (step !== undefined && data.message?.isError === true) {
469
+ const existing = task.steps.find(item => item.id === step)
470
+ if (existing) existing.state = 'error'
471
+ }
472
+ updateTimeline(data.message?.toolCallId, {
473
+ state: data.message?.isError === true ? 'error' : 'done',
474
+ })
475
+ emit()
476
+ } else if (event.type === 'assistant/message') {
477
+ const messageText = textOfMessage(data.message)
478
+ if (messageText !== '') lastText = messageText
479
+ addUsage(task.usage, data.usage)
480
+ task.text = lastText
481
+ emit()
482
+ } else if (event.type === 'deliverables/presented') {
483
+ const files = Array.isArray(data.files) ? data.files : []
484
+ for (const file of files) presented.push(file?.path)
485
+ const delivery = [...task.timeline].reverse().find(entry => entry.kind === 'deliver')
486
+ const names = files.map(file => path.basename(String(file?.path ?? ''))).filter(Boolean).join(', ')
487
+ if (delivery !== undefined && names !== '') {
488
+ delivery.state = 'done'
489
+ delivery.detail = clipText(names)
490
+ }
491
+ emit()
492
+ } else if (event.type === 'approval/asked') {
493
+ nextStep('approve', 'active')
494
+ pushTimeline({
495
+ id: `approval-${data.id ?? 'pending'}`,
496
+ kind: 'approve',
497
+ tool: data.toolName,
498
+ state: 'active',
499
+ detail: clipText(data.reason ?? ''),
500
+ at: Date.now(),
501
+ })
502
+ emit()
503
+ if (approvalTimer === null) {
504
+ approvalTimer = setTimeout(() => {
505
+ approvalBlocked = true
506
+ followAbort.abort()
507
+ cancelTurn()
508
+ }, APPROVAL_WAIT_MS)
509
+ }
510
+ // The approval service appends `approval/asked` before it dispatches
511
+ // the waterfall; the bridge entry exists one microtask later.
512
+ setTimeout(() => { if (pendingApprovalFor(sessionId) !== undefined) emit() }, 60)
513
+ } else if (event.type === 'approval/decided') {
514
+ if (approvalTimer !== null) {
515
+ clearTimeout(approvalTimer)
516
+ approvalTimer = null
517
+ }
518
+ const approveStep = task.steps.find(step => step.id === 'approve')
519
+ if (approveStep !== undefined && approveStep.state === 'active') approveStep.state = 'done'
520
+ updateTimeline(`approval-${data.id ?? 'pending'}`, {
521
+ state: data.outcome === 'allowed-once' ? 'done' : 'error',
522
+ })
523
+ emit()
524
+ } else if (event.type === 'turn/end') {
525
+ endReason = data.reason ?? null
526
+ break
527
+ }
528
+ }
529
+ await iterator.return?.()
530
+ } catch (error) {
531
+ if (timedOut) {
532
+ return await complete('error', { error: locale === 'en' ? 'The task timed out.' : '文档任务超时。' })
533
+ }
534
+ if (externalAbort) return await complete('cancelled')
535
+ return await complete('error', {
536
+ error: error instanceof ArtifactError ? error.message : (error instanceof Error ? error.message : String(error)),
537
+ })
538
+ } finally {
539
+ clearTimeout(timer)
540
+ if (approvalTimer !== null) clearTimeout(approvalTimer)
541
+ signal.removeEventListener('abort', onAbort)
542
+ followAbort.abort()
543
+ }
544
+
545
+ if (approvalBlocked) return await complete('needs-approval')
546
+ if (externalAbort) return await complete('cancelled')
547
+ if (timedOut) {
548
+ return await complete('error', { error: locale === 'en' ? 'The task timed out.' : '文档任务超时。' })
549
+ }
550
+ const kind = endReason?.kind ?? 'interrupted'
551
+ if (kind !== 'completed') {
552
+ const reason = kind === 'error'
553
+ ? (endReason?.error?.message ?? (locale === 'en' ? 'The document agent failed.' : '文档 Agent 执行失败。'))
554
+ : kind === 'max-tokens'
555
+ ? (locale === 'en' ? 'The task hit the output limit.' : '文档任务达到输出上限。')
556
+ : (locale === 'en' ? 'The document agent stopped before finishing.' : '文档 Agent 提前结束。')
557
+ return await complete(kind === 'aborted' ? 'cancelled' : 'error', { error: reason, presented })
558
+ }
559
+ for (const step of task.steps) step.state = 'done'
560
+ task.text = lastText
561
+ return await complete('done', { presented })
562
+ }
563
+
564
+ finish(task, status, { locale = 'zh', error = '' }) {
565
+ task.status = status
566
+ if (error !== '') task.error = error
567
+ // No progress row may keep spinning after the task has settled.
568
+ for (const step of task.steps) {
569
+ if (step.state !== 'active') continue
570
+ step.state = status === 'error' || status === 'needs-approval'
571
+ ? 'error'
572
+ : status === 'cancelled' ? 'pending' : 'done'
573
+ }
574
+ for (const entry of task.timeline) {
575
+ if (entry.state !== 'active') continue
576
+ entry.state = status === 'error' || status === 'needs-approval'
577
+ ? 'error'
578
+ : status === 'cancelled' ? 'pending' : 'done'
579
+ }
580
+ if (status === 'done' && task.files.length === 0) {
581
+ task.notice = locale === 'en' ? 'The task finished without a file.' : '任务结束,但没有生成文件。'
582
+ }
583
+ task.approval = null
584
+ if (status === 'needs-approval') {
585
+ task.error = locale === 'en'
586
+ ? 'Waiting for approval timed out. Retry the task or handle the approval in Agent mode.'
587
+ : '等待授权超时。请重新发起任务,或在 Agent 模式处理授权。'
588
+ }
589
+ return {
590
+ status,
591
+ steps: task.steps.map(step => ({ ...step })),
592
+ files: task.files.map(file => ({ ...file })),
593
+ timeline: task.timeline.map(entry => ({ ...entry })),
594
+ approval: task.approval,
595
+ usage: task.usage,
596
+ text: task.text,
597
+ notice: task.notice ?? '',
598
+ error: task.error ?? '',
599
+ sessionId: task.sessionId,
600
+ }
601
+ }
602
+ }