qwen-audio-agent 2.0.1 → 2.2.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 (208) hide show
  1. package/README.md +21 -10
  2. package/README_ZH.md +19 -10
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  4. package/cli/package.json +1 -1
  5. package/cli/src/arguments.mjs +4 -1
  6. package/cli/src/config-command.mjs +36 -6
  7. package/cli/src/gateway-service.mjs +7 -1
  8. package/cli/src/launcher.mjs +13 -0
  9. package/config/frontend-agent/LIVE_PROMPT.md +64 -0
  10. package/config/frontend-agent/PROMPT.md +29 -26
  11. package/desktop/src/i18n.mjs +6 -1
  12. package/desktop/src/settings-config.mjs +32 -40
  13. package/desktop/src/settings-store.mjs +19 -28
  14. package/docs/architecture/deep-dive.md +103 -66
  15. package/docs/architecture/deep-dive.zh.md +73 -50
  16. package/docs/backends/configuration.md +4 -4
  17. package/docs/backends/configuration.zh.md +4 -4
  18. package/docs/backends/overview.md +3 -0
  19. package/docs/backends/overview.zh.md +3 -0
  20. package/docs/configuration/backend.md +15 -1
  21. package/docs/configuration/backend.zh.md +15 -1
  22. package/docs/configuration/frontend.md +78 -28
  23. package/docs/configuration/frontend.zh.md +76 -28
  24. package/docs/configuration.md +1 -1
  25. package/docs/configuration.zh.md +1 -1
  26. package/docs/contract.md +24 -2
  27. package/docs/contract.zh.md +20 -2
  28. package/docs/extensions.md +14 -0
  29. package/docs/extensions.zh.md +11 -0
  30. package/docs/gateway-protocol.md +26 -0
  31. package/docs/gateway-protocol.zh.md +22 -0
  32. package/docs/gateway-webrtc-client.md +3 -3
  33. package/docs/gateway-webrtc-client.zh.md +3 -3
  34. package/docs/getting-started/install.md +4 -1
  35. package/docs/getting-started/install.zh.md +4 -1
  36. package/docs/getting-started/mobile.md +8 -2
  37. package/docs/getting-started/mobile.zh.md +5 -0
  38. package/docs/getting-started/quickstart.md +2 -2
  39. package/docs/getting-started/quickstart.zh.md +2 -2
  40. package/docs/getting-started/webui.md +2 -0
  41. package/docs/getting-started/webui.zh.md +2 -0
  42. package/docs/guides/knowledge.md +8 -5
  43. package/docs/guides/knowledge.zh.md +4 -3
  44. package/docs/guides/tasks.md +63 -2
  45. package/docs/guides/tasks.zh.md +45 -1
  46. package/docs/guides/web-search.md +32 -1
  47. package/docs/guides/web-search.zh.md +28 -1
  48. package/docs/operations/troubleshooting.md +30 -0
  49. package/docs/operations/troubleshooting.zh.md +26 -0
  50. package/docs/reference/backend-adapter-sdk.md +33 -2
  51. package/docs/reference/backend-adapter-sdk.zh.md +29 -2
  52. package/docs/reference/cli.md +3 -3
  53. package/docs/reference/cli.zh.md +3 -3
  54. package/docs/scenarios/lightrag.md +2 -2
  55. package/docs/scenarios/lightrag.zh.md +2 -2
  56. package/docs/scenarios/x-omni.md +5 -2
  57. package/docs/scenarios/x-omni.zh.md +5 -2
  58. package/docs/voice-agent-architecture-presentation.zh.md +34 -37
  59. package/docs/voice-frontends/custom-provider.md +22 -4
  60. package/docs/voice-frontends/custom-provider.zh.md +22 -4
  61. package/docs/voice-frontends/google-live.md +14 -8
  62. package/docs/voice-frontends/google-live.zh.md +13 -8
  63. package/docs/voice-frontends/gpt-live-1.md +149 -0
  64. package/docs/voice-frontends/gpt-live-1.zh.md +114 -0
  65. package/docs/voice-frontends/minicpm-o.md +8 -4
  66. package/docs/voice-frontends/minicpm-o.zh.md +7 -4
  67. package/docs/voice-frontends/{gpt-live.md → openai-realtime.md} +19 -10
  68. package/docs/voice-frontends/{gpt-live.zh.md → openai-realtime.zh.md} +18 -10
  69. package/docs/voice-frontends/qwen-audio-live.md +164 -0
  70. package/docs/voice-frontends/qwen-audio-live.zh.md +122 -0
  71. package/docs/voice-frontends/qwen-audio-realtime.md +41 -15
  72. package/docs/voice-frontends/qwen-audio-realtime.zh.md +34 -12
  73. package/docs/voice-frontends/qwen-omni-realtime.md +12 -9
  74. package/docs/voice-frontends/qwen-omni-realtime.zh.md +12 -9
  75. package/docs/voice-frontends/speech-to-speech.md +8 -4
  76. package/docs/voice-frontends/speech-to-speech.zh.md +7 -3
  77. package/docs/voice-frontends/stepfun.md +7 -4
  78. package/docs/voice-frontends/stepfun.zh.md +7 -4
  79. package/examples/webrtc/start.mjs +2 -1
  80. package/package.json +34 -16
  81. package/scripts/audit-dependencies.mjs +3 -25
  82. package/scripts/electron-smoke.mjs +5 -5
  83. package/scripts/patch-build-node-gyp.mjs +63 -0
  84. package/scripts/prepare-build.mjs +2 -0
  85. package/scripts/release-check +2 -2
  86. package/scripts/runtime/claude-code-acp.mjs +5 -5
  87. package/scripts/verify-package.mjs +3 -0
  88. package/server/package.json +5 -5
  89. package/server/src/app/gateway-application.mjs +3 -0
  90. package/server/src/app/gateway-http-routes.mjs +3 -0
  91. package/server/src/app/session-conversation-history.mjs +9 -1
  92. package/server/src/backend/adapters/a2a/backend-adapter.mjs +32 -26
  93. package/server/src/backend/adapters/acp/backend-adapter.mjs +703 -251
  94. package/server/src/backend/adapters/acp/coordinator-contract.mjs +2 -13
  95. package/server/src/backend/adapters/acp/coordinator-instructions.mjs +29 -8
  96. package/server/src/backend/adapters/acp/coordinator-queue.mjs +58 -0
  97. package/server/src/backend/adapters/acp/drivers/codex.mjs +1 -1
  98. package/server/src/backend/adapters/acp/drivers/openclaw.mjs +1 -2
  99. package/server/src/backend/adapters/acp/input-broker.mjs +2 -0
  100. package/server/src/backend/adapters/acp/process-client.mjs +111 -16
  101. package/server/src/backend/adapters/acp/session-configuration.mjs +2 -19
  102. package/server/src/backend/adapters/acp/session-registry.mjs +9 -0
  103. package/server/src/backend/adapters/acp/session-tools.mjs +1 -1
  104. package/server/src/backend/adapters/acp/turn-updates.mjs +188 -0
  105. package/server/src/backend/adapters/acp/work-continuation.mjs +48 -0
  106. package/server/src/backend/adapters/agent-client.mjs +24 -1
  107. package/server/src/backend/adapters/llm/backend-adapter.mjs +393 -0
  108. package/server/src/backend/adapters/muse/backend-adapter.mjs +2 -0
  109. package/server/src/backend/availability.mjs +12 -3
  110. package/server/src/backend/backend-adapter-sdk.mjs +3 -0
  111. package/server/src/backend/backend-port.mjs +13 -0
  112. package/server/src/backend/backend-work-runtime.mjs +23 -0
  113. package/server/src/client/client-command-runtime.mjs +14 -0
  114. package/server/src/conversation/conversation-sync.mjs +26 -2
  115. package/server/src/conversation/frontend-agent-context.mjs +18 -5
  116. package/server/src/conversation/frontend-notes.mjs +7 -5
  117. package/server/src/conversation/task-result-projector.mjs +1 -1
  118. package/server/src/core/backend-events.mjs +4 -0
  119. package/server/src/core/citation.mjs +8 -2
  120. package/server/src/core/config.mjs +46 -54
  121. package/server/src/core/gateway-protocol.mjs +4 -1
  122. package/server/src/core/request-security.mjs +7 -1
  123. package/server/src/core/work-conversation-context.mjs +138 -0
  124. package/server/src/core/work-input-request.mjs +1 -0
  125. package/server/src/frontend/frontend-tools.mjs +20 -7
  126. package/server/src/frontend/retrieval/providers/bing.mjs +23 -12
  127. package/server/src/frontend/retrieval/providers/factory.mjs +18 -1
  128. package/server/src/frontend/retrieval/providers/mcp.mjs +30 -11
  129. package/server/src/frontend/retrieval/providers/so360.mjs +23 -12
  130. package/server/src/frontend/tools/agent-task-runtime.mjs +119 -99
  131. package/server/src/frontend/tools/features/agent-task-tools.mjs +23 -42
  132. package/server/src/frontend/tools/frontend-tool-context.mjs +2 -2
  133. package/server/src/frontend/tools/spawn-thinking-tool.mjs +2 -2
  134. package/server/src/frontend/tools/tool-call-handler.mjs +166 -86
  135. package/server/src/knowledge/providers/local/library.mjs +26 -6
  136. package/server/src/knowledge/providers/local/provider.mjs +25 -6
  137. package/server/src/memory/providers/markdown/context-store.mjs +24 -11
  138. package/server/src/orchestration/session-task-coordinator.mjs +13 -3
  139. package/server/src/orchestration/task-operations.mjs +54 -12
  140. package/server/src/orchestration/task-updates.mjs +82 -0
  141. package/server/src/task/reminder-scheduler.mjs +5 -1
  142. package/server/src/task/task-manager.mjs +72 -15
  143. package/server/src/task/task-recovery.mjs +12 -2
  144. package/server/src/task/task-scheduler.mjs +5 -5
  145. package/server/src/task/task-state.mjs +13 -0
  146. package/server/src/transport/gateway-client-transport.mjs +35 -0
  147. package/server/src/transport/webrtc/protocol.mjs +1 -1
  148. package/server/src/voice/announcement/announcement-manager.mjs +3 -0
  149. package/server/src/voice/audio-stream-diagnostics.mjs +139 -0
  150. package/server/src/voice/native-delegation-runtime.mjs +360 -0
  151. package/server/src/voice/providers/dashscope-live.mjs +93 -0
  152. package/server/src/voice/providers/dashscope.mjs +45 -33
  153. package/server/src/voice/providers/doubao-seeduplex-protocol.mjs +54 -0
  154. package/server/src/voice/providers/doubao-seeduplex.mjs +16 -11
  155. package/server/src/voice/providers/ga-protocol.mjs +7 -2
  156. package/server/src/voice/providers/google-live-protocol.mjs +124 -34
  157. package/server/src/voice/providers/google-live.mjs +20 -14
  158. package/server/src/voice/providers/gpt-live-1-protocol.mjs +597 -0
  159. package/server/src/voice/providers/gpt-live-1.mjs +3 -0
  160. package/server/src/voice/providers/gpt-live-client-context.mjs +182 -0
  161. package/server/src/voice/providers/minicpm-o.mjs +9 -7
  162. package/server/src/voice/providers/openai-live.mjs +150 -0
  163. package/server/src/voice/providers/{gpt-live.mjs → openai-realtime.mjs} +23 -19
  164. package/server/src/voice/providers/provider-registry.mjs +11 -1
  165. package/server/src/voice/providers/qwen-live-protocol.mjs +399 -0
  166. package/server/src/voice/providers/registry.mjs +47 -12
  167. package/server/src/voice/providers/runtime-configuration.mjs +34 -0
  168. package/server/src/voice/providers/s2s.mjs +9 -7
  169. package/server/src/voice/providers/stepfun.mjs +14 -11
  170. package/server/src/voice/realtime-input-runtime.mjs +58 -20
  171. package/server/src/voice/realtime-presentation-runtime.mjs +111 -27
  172. package/server/src/voice/realtime-provider-session.mjs +59 -14
  173. package/server/src/voice/realtime-provider.mjs +358 -45
  174. package/server/src/voice/realtime-session-runtime.mjs +282 -35
  175. package/server/src/voice/realtime-task-presentation.mjs +8 -2
  176. package/server/src/voice/realtime-turn-state.mjs +33 -2
  177. package/shared/backend/catalog.mjs +26 -2
  178. package/shared/backend/install.mjs +3 -1
  179. package/shared/backend/setup.mjs +43 -0
  180. package/shared/gateway/client-sdk.mjs +21 -6
  181. package/shared/gateway/setup.mjs +13 -1
  182. package/shared/gateway/websocket-auth.mjs +2 -1
  183. package/shared/protocol/gateway-client-protocol.mjs +14 -0
  184. package/shared/protocol/gateway-events.mjs +39 -1
  185. package/shared/realtime-legacy-environment.mjs +81 -0
  186. package/shared/realtime-model-catalog.mjs +68 -194
  187. package/shared/realtime-models/README.md +33 -0
  188. package/shared/realtime-models/dashscope.mjs +57 -0
  189. package/shared/realtime-models/google.mjs +10 -0
  190. package/shared/realtime-models/openai.mjs +24 -0
  191. package/shared/realtime-models/profile.mjs +38 -0
  192. package/shared/realtime-models/stepfun.mjs +10 -0
  193. package/shared/realtime-models/volcengine.mjs +12 -0
  194. package/shared/realtime-provider-catalog.mjs +23 -11
  195. package/shared/realtime-provider-definitions.mjs +168 -235
  196. package/shared/runtime-environment.mjs +23 -30
  197. package/shared/skill-library.mjs +49 -13
  198. package/shared/web-search-configuration.mjs +25 -2
  199. package/tui/package.json +2 -2
  200. package/tui/src/index.mjs +14 -9
  201. package/tui/src/runtime-configuration.mjs +2 -0
  202. package/tui/src/terminal-commands.mjs +40 -0
  203. package/tui/src/text-cli.mjs +10 -1
  204. package/web/dist/assets/index-Bc2Q04J9.css +1 -0
  205. package/web/dist/assets/index-bY4DFXKT.js +96 -0
  206. package/web/dist/index.html +2 -2
  207. package/web/dist/assets/index-BRaiI-dW.js +0 -91
  208. package/web/dist/assets/index-D9k8R2JY.css +0 -1
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import { AgentError } from '../../agent-error.mjs'
3
3
  import { BackendEventType, backendEvent } from '../../../core/backend-events.mjs'
4
+ import { logger } from '../../../core/logger.mjs'
4
5
  import {
5
6
  acpBackendProfile,
6
7
  endpointAvailable,
@@ -22,6 +23,15 @@ import {
22
23
  } from './builtin-mcp.mjs'
23
24
  import { BackendRuntimeState } from './runtime-state.mjs'
24
25
  import { KeyedSerialExecutor } from './keyed-serial-executor.mjs'
26
+ import { CoordinatorQueue } from './coordinator-queue.mjs'
27
+ import { AcpTurnUpdates, updateError } from './turn-updates.mjs'
28
+ import {
29
+ assertProjectUpdateDelivered,
30
+ projectTargets,
31
+ projectUpdatePrompt,
32
+ readWorkContinuation,
33
+ workContinuation,
34
+ } from './work-continuation.mjs'
25
35
  import { PermissionBroker } from './permission-broker.mjs'
26
36
  import { InputBroker } from './input-broker.mjs'
27
37
  import {
@@ -33,12 +43,16 @@ import {
33
43
  } from './content.mjs'
34
44
  import { assertMcpServerCapabilities } from './capabilities.mjs'
35
45
  import { buildAcpCoordinatorInstruction } from './coordinator-contract.mjs'
46
+ import {
47
+ COORDINATOR_PROMPT_REFRESH_INTERVAL,
48
+ coordinatorUsesMcpInstructions,
49
+ stableCoordinatorInstructions,
50
+ } from './coordinator-instructions.mjs'
51
+ import { conversationDelta, COORDINATOR_CONVERSATION_MAX_CHARS } from '../../../core/work-conversation-context.mjs'
36
52
  import {
37
53
  configureAcpSession,
38
54
  coordinatorMeta,
39
- coordinatorUsesMcpInstructions,
40
55
  normalizeAcpModel,
41
- stableCoordinatorInstructions,
42
56
  } from './session-configuration.mjs'
43
57
 
44
58
  const MAX_SESSION_RESULTS = 100
@@ -46,7 +60,7 @@ const MAX_DELEGATION_RESULT_CHARS = 12_000
46
60
  const MAX_DELEGATION_RECENT_UPDATES = 5
47
61
  // Persistent coordinator Sessions are valid only for the contract that
48
62
  // created them. Project Sessions are user work and remain independent.
49
- const COORDINATOR_CONTRACT_VERSION = 6
63
+ const COORDINATOR_CONTRACT_VERSION = 8
50
64
 
51
65
  export { acpBackendProfile } from './backend-profile.mjs'
52
66
 
@@ -83,6 +97,17 @@ function bounded(value, max = 300) {
83
97
  return clean(value).replace(/\s+/g, ' ').slice(0, max)
84
98
  }
85
99
 
100
+ function delegationSummary(records, coordinatorSessionId) {
101
+ const targets = records.map(({ id, sessionId, title, directory }) => ({
102
+ id, sessionId, title, directory, coordinatorSessionId,
103
+ }))
104
+ return targets.length === 1 ? targets[0] : {
105
+ targets,
106
+ title: targets.map(target => target.title).join(' / ').slice(0, 160),
107
+ coordinatorSessionId,
108
+ }
109
+ }
110
+
86
111
  function deferred() {
87
112
  let resolvePromise
88
113
  let rejectPromise
@@ -93,6 +118,19 @@ function deferred() {
93
118
  return { promise, resolve: resolvePromise, reject: rejectPromise }
94
119
  }
95
120
 
121
+ function waitForCancellation(promise, timeoutMs, protocol) {
122
+ let timer
123
+ return Promise.race([
124
+ promise,
125
+ new Promise((_, reject) => {
126
+ timer = setTimeout(() => reject(Object.assign(new AgentError(
127
+ '后台尚未确认当前执行已停止,不能立即续接。',
128
+ { status: 504, protocol },
129
+ ), { code: 'cancellation_unconfirmed' })), timeoutMs)
130
+ }),
131
+ ]).finally(() => clearTimeout(timer))
132
+ }
133
+
96
134
  function waitForRetry(delayMs, signal) {
97
135
  if (signal?.aborted) {
98
136
  return Promise.reject(signal.reason || new Error('任务已取消'))
@@ -120,6 +158,7 @@ export class AcpBackendAdapter {
120
158
  permissionMode = 'native',
121
159
  model = '',
122
160
  timeoutMs = 300_000,
161
+ cancelTimeoutMs = 20_000,
123
162
  directory = process.cwd(),
124
163
  cliPath = '',
125
164
  configDirectory = '',
@@ -148,6 +187,9 @@ export class AcpBackendAdapter {
148
187
  // spelling and is normalized to the same no-override state here.
149
188
  this.model = normalizeAcpModel(model)
150
189
  this.timeoutMs = timeoutMs
190
+ // Give the client's bounded cancellation handshake time to finish, while
191
+ // also bounding custom clients or delegation adapters that never settle.
192
+ this.cancelTimeoutMs = cancelTimeoutMs
151
193
  this.directory = directory
152
194
  this.baseUrl = clean(baseUrl) || null
153
195
  this.coordinatorAgent = clean(coordinatorAgent)
@@ -184,15 +226,18 @@ export class AcpBackendAdapter {
184
226
  this.coordinatorSessions = new Map()
185
227
  this.coordinatorSessionPromises = new Map()
186
228
  // ACP agents may cache the first MCP connection for a Session. Keep its
187
- // descriptor stable while serialized owner turns replace the run context.
229
+ // descriptor stable while serialized turns replace its run context.
188
230
  this.coordinatorToolRegistrations = new Map()
189
231
  this.coordinatorToolRegistrationPromises = new Map()
190
232
  this.sessionExecutor = new KeyedSerialExecutor()
233
+ this.coordinatorQueue = new CoordinatorQueue()
191
234
  this.activeCoordinatorTurns = new Set()
192
235
  // Track every request that reaches the persistent coordinator Session,
193
236
  // whether it stays there or delegates to a project Session.
194
237
  this.coordinationRuns = new Map()
195
238
  this.workControllers = new Map()
239
+ this.workUpdates = new Map()
240
+ this.uncertainUpdateSessions = new Set()
196
241
  this.workEventListeners = new Set()
197
242
  this.runtimeState = new BackendRuntimeState({
198
243
  protocol: this.protocol,
@@ -265,11 +310,12 @@ export class AcpBackendAdapter {
265
310
  transport: 'acp',
266
311
  acpConnection: this.profile.acpConnection?.kind || null,
267
312
  backendAgent: this.coordinatorAgent || null,
268
- sessionModel: 'one-persistent-backend-agent',
313
+ sessionModel: 'persistent-coordinator',
269
314
  capabilities: {
270
315
  ...this.profile.capabilities,
271
316
  taskUpdates: 'activity',
272
317
  inputRequests: 'elicitation',
318
+ workUpdates: true,
273
319
  },
274
320
  }
275
321
  }
@@ -285,11 +331,20 @@ export class AcpBackendAdapter {
285
331
  if (!run || (ownerId !== undefined && run.ownerId !== clean(ownerId))) {
286
332
  return { taskId: id, state: 'not_found', activity: [] }
287
333
  }
288
- const delegation = run.delegation
289
- if (!delegation) {
334
+ const targets = run.delegations || []
335
+ if (!targets.length) {
290
336
  return { taskId: id, state: 'working', activity: [] }
291
337
  }
292
- const current = this.statusForDelegation({ delegation_id: delegation.id })
338
+ const statuses = targets.map(target => this.statusForDelegation({ delegation_id: target.id }))
339
+ const current = statuses.length === 1 ? statuses[0] : {
340
+ status: statuses.some(item => ['running', 'cancelling'].includes(item.status))
341
+ ? 'running'
342
+ : statuses.some(item => item.status === 'failed') ? 'failed'
343
+ : statuses.some(item => item.status === 'cancelled') ? 'cancelled' : 'completed',
344
+ recent_updates: statuses.flatMap(item => item.recent_updates || []),
345
+ result: statuses.map(item => item.result).filter(Boolean).join('\n\n'),
346
+ error: statuses.map(item => item.error).filter(Boolean).join('\n'),
347
+ }
293
348
  return {
294
349
  taskId: id,
295
350
  state: current.status === 'running' ? 'working' : current.status,
@@ -422,7 +477,18 @@ export class AcpBackendAdapter {
422
477
  return () => this.workEventListeners.delete(listener)
423
478
  }
424
479
 
425
- async ensureCoordinatorSession(ownerId, mcpServers = []) {
480
+ coordinatorSessionKey(ownerId, sessionId = '') {
481
+ const key = coordinatorKey(ownerId, this.protocol)
482
+ const session = this.coordinatorSessions.get(key) || this.registry.get(key)
483
+ if (!sessionId || session?.sessionId === sessionId) return key
484
+ throw updateError('context_unavailable', '原后台会话已不可用,未在其他会话中自动重做。')
485
+ }
486
+
487
+ async acquireCoordinator(ownerId, { sessionId = '', signal } = {}) {
488
+ return this.coordinatorQueue.acquire(this.coordinatorSessionKey(ownerId, sessionId), { signal })
489
+ }
490
+
491
+ async ensureCoordinatorSession(ownerId, mcpServers = [], { expectedSessionId = '' } = {}) {
426
492
  if (this.builtinMcp.length) this.builtinMcpLifecycle.markUsed()
427
493
  const key = coordinatorKey(ownerId, this.protocol)
428
494
  if (this.coordinatorSessions.has(key)) {
@@ -450,7 +516,7 @@ export class AcpBackendAdapter {
450
516
  session = await this.client.resumeSession(stored.sessionId, {
451
517
  cwd: stored.cwd || this.directory,
452
518
  mcpServers,
453
- meta: this.coordinatorMeta(ownerId),
519
+ meta: this.coordinatorMeta(ownerId, key),
454
520
  ownerId,
455
521
  role: 'coordinator',
456
522
  })
@@ -464,16 +530,24 @@ export class AcpBackendAdapter {
464
530
  session = null
465
531
  } else {
466
532
  session.isNew = false
533
+ session.conversationCursors = stored.conversationCursors
534
+ session.coordinatorPromptTurns = stored.coordinatorPromptTurns
467
535
  }
468
536
  } catch {
537
+ if (expectedSessionId) {
538
+ throw updateError('context_unavailable', '原协调会话无法恢复,未创建替代会话。')
539
+ }
469
540
  this.registry.delete(key)
470
541
  }
471
542
  }
472
543
  if (!session) {
544
+ if (expectedSessionId) {
545
+ throw updateError('context_unavailable', '原协调会话不可用或不兼容,未创建替代会话。')
546
+ }
473
547
  session = await this.client.newSession({
474
548
  cwd: this.directory,
475
549
  mcpServers,
476
- meta: this.coordinatorMeta(ownerId),
550
+ meta: this.coordinatorMeta(ownerId, key),
477
551
  ownerId,
478
552
  role: 'coordinator',
479
553
  })
@@ -581,6 +655,9 @@ export class AcpBackendAdapter {
581
655
  }
582
656
 
583
657
  onSessionUpdate(run, update, { delegation = null } = {}) {
658
+ if (delegation
659
+ ? delegation.status !== 'running' || delegation.signal?.aborted
660
+ : run.closed || run.turnClosed) return
584
661
  run.receivedUpdate = true
585
662
  run.toolCalls ||= new Map()
586
663
  run.messageStreams ||= {}
@@ -596,7 +673,7 @@ export class AcpBackendAdapter {
596
673
  if (delegation && this.profile.externalMcp) {
597
674
  this.rememberDelegationUpdate(delegation, activity)
598
675
  }
599
- if (!this.profile.nativeDelegation || run.allowDelegation === false) return
676
+ if (delegation || !this.profile.nativeDelegation || run.allowDelegation === false) return
600
677
  if (!['tool_call', 'tool_call_update'].includes(update?.sessionUpdate)) {
601
678
  return
602
679
  }
@@ -606,7 +683,7 @@ export class AcpBackendAdapter {
606
683
  ...update,
607
684
  }
608
685
  run.nativeToolCalls.set(id, merged)
609
- if (merged.status !== 'completed' || run.delegation) return
686
+ if (merged.status !== 'completed') return
610
687
  const name = clean(merged.name || merged.title).toLowerCase()
611
688
  if (!/sessions_(spawn|send)/.test(name)) return
612
689
  const output = nativeToolOutput(merged.rawOutput)
@@ -618,8 +695,8 @@ export class AcpBackendAdapter {
618
695
  )
619
696
  if (!sessionId) return
620
697
  const delegationId = clean(output.runId)
621
- if (!delegationId) return
622
- run.delegation = this.createNativeDelegation(run, {
698
+ if (!delegationId || run.delegations.some(record => record.id === delegationId)) return
699
+ this.createNativeDelegation(run, {
623
700
  delegationId,
624
701
  sessionId,
625
702
  directory: clean(
@@ -640,15 +717,17 @@ export class AcpBackendAdapter {
640
717
  const sessions = await this.client.listSessions({
641
718
  limit: limit || 20,
642
719
  })
720
+ const coordinators = new Set([
721
+ ...this.coordinatorSessions.values(),
722
+ ...this.registry.coordinatorEntries().map(([, session]) => session),
723
+ ].map(item => item.sessionId))
643
724
  this.registry.setProjects(sessions
644
- .filter(session => clean(session?.sessionId) && clean(session?.cwd))
725
+ .filter(session => clean(session?.sessionId) && clean(session?.cwd)
726
+ && !coordinators.has(clean(session.sessionId)))
645
727
  .map(session => [
646
728
  projectSessionKey(this.protocol, session.sessionId),
647
729
  session,
648
730
  ]))
649
- const coordinators = new Set(
650
- [...this.coordinatorSessions.values()].map(item => item.sessionId),
651
- )
652
731
  const needle = clean(query).toLowerCase()
653
732
  return {
654
733
  sessions: sessions
@@ -671,7 +750,7 @@ export class AcpBackendAdapter {
671
750
 
672
751
  findDelegation({ delegation_id: delegationId, session_id: sessionId }) {
673
752
  return [...this.coordinationRuns.values()]
674
- .map(run => run.delegation)
753
+ .flatMap(run => run.delegations || []).reverse()
675
754
  .find(record => (
676
755
  (clean(delegationId) && record?.id === clean(delegationId))
677
756
  || (clean(sessionId) && record?.sessionId === clean(sessionId))
@@ -684,11 +763,6 @@ export class AcpBackendAdapter {
684
763
  directory,
685
764
  title,
686
765
  }) {
687
- if (run.delegation) {
688
- throw new AgentError('当前协调轮次已经启动了一个第三层任务', {
689
- protocol: this.protocol,
690
- })
691
- }
692
766
  const controller = new AbortController()
693
767
  const record = {
694
768
  id: `${this.protocol}_run_${randomUUID()}`,
@@ -699,11 +773,20 @@ export class AcpBackendAdapter {
699
773
  taskId: run.coordinationRunId,
700
774
  status: 'running',
701
775
  controller,
776
+ signal: run.signal ? AbortSignal.any([controller.signal, run.signal]) : controller.signal,
702
777
  recentUpdates: [],
703
778
  result: null,
704
779
  error: null,
705
780
  }
706
- run.delegation = record
781
+ // Continuations replace the previous result for this exact target, never
782
+ // another child's context. The collection is shared by all turns of a Work.
783
+ const previous = run.delegations.findIndex(item => item.sessionId === record.sessionId)
784
+ if (previous < 0) run.delegations.push(record)
785
+ else run.delegations.splice(previous, 1, record)
786
+ record.turnUpdates = new AcpTurnUpdates({
787
+ client: this.client, sessionId: record.sessionId, signal: record.signal,
788
+ onRestart: () => this.cancelPermissionsForScope(session.permissionScopeId),
789
+ })
707
790
  record.promise = this.serialize(`target:${record.sessionId}`, async () => {
708
791
  const permissionScopeId = `prompt_${randomUUID()}`
709
792
  try {
@@ -711,18 +794,17 @@ export class AcpBackendAdapter {
711
794
  session.coordinationRunId = run.coordinationRunId
712
795
  session.onEvent = run.onEvent
713
796
  session.permissionScopeId = permissionScopeId
714
- const result = assertCompletedAcpTurn(await this.client.prompt(
715
- record.sessionId,
797
+ const result = assertCompletedAcpTurn(await record.turnUpdates.run(
716
798
  appendPromptBlocks(prompt, run.inputBlocks),
717
799
  {
718
- signal: controller.signal,
800
+ signal: record.signal,
719
801
  timeoutMs: 0,
720
802
  onUpdate: update => this.onSessionUpdate(run, update, {
721
803
  delegation: record,
722
804
  }),
723
805
  },
724
806
  ), {
725
- signal: controller.signal,
807
+ signal: record.signal,
726
808
  label: `${this.label} 项目 Session`,
727
809
  protocol: this.protocol,
728
810
  })
@@ -737,7 +819,8 @@ export class AcpBackendAdapter {
737
819
  contentBlocks: result.contentBlocks || [],
738
820
  }
739
821
  } catch (error) {
740
- record.status = controller.signal.aborted ? 'cancelled' : 'failed'
822
+ if (error.contextUncertain) this.uncertainUpdateSessions.add(record.sessionId)
823
+ record.status = record.signal.aborted ? 'cancelled' : 'failed'
741
824
  record.error = error
742
825
  throw error
743
826
  } finally {
@@ -748,10 +831,31 @@ export class AcpBackendAdapter {
748
831
  }
749
832
  })
750
833
  record.promise.catch(() => {})
834
+ this.publishDelegation(run)
751
835
  return record
752
836
  }
753
837
 
838
+ publishDelegation(run, { yielded = false } = {}) {
839
+ run.onEvent?.({
840
+ type: BackendEventType.DELEGATED,
841
+ yielded,
842
+ delegation: delegationSummary(run.delegations, run.sessionId),
843
+ })
844
+ }
845
+
846
+ assertActiveCoordinatorRun(run) {
847
+ if (run.closed || run.turnClosed || run.signal?.aborted) {
848
+ throw new AgentError('原协调请求已结束,Session 工具上下文已失效', {
849
+ protocol: this.protocol,
850
+ })
851
+ }
852
+ }
853
+
754
854
  async startProjectSession(run, { prompt, title }) {
855
+ this.assertActiveCoordinatorRun(run)
856
+ if (run.allowDelegation === false || run.phase === 'update') {
857
+ throw updateError('invalid_session_route', '当前轮次只能处理已有工作的要求,不能创建新工作。')
858
+ }
755
859
  const cwd = clean(run.cwd) || this.directory
756
860
  const session = await this.client.newSession({
757
861
  cwd,
@@ -759,12 +863,14 @@ export class AcpBackendAdapter {
759
863
  ownerId: run.ownerId,
760
864
  role: 'project',
761
865
  })
866
+ this.assertActiveCoordinatorRun(run)
762
867
  this.rememberProjectSession({
763
868
  ...session,
764
869
  cwd,
765
870
  title: clean(title || prompt),
766
871
  })
767
872
  await this.configureSession(session, 'project')
873
+ this.assertActiveCoordinatorRun(run)
768
874
  const record = this.createDelegation(run, {
769
875
  session,
770
876
  prompt: clean(prompt),
@@ -781,22 +887,56 @@ export class AcpBackendAdapter {
781
887
  }
782
888
 
783
889
  async continueProjectSession(
890
+ run,
891
+ input,
892
+ ) {
893
+ return this.serialize(`target-setup:${clean(input.session_id)}`, () => (
894
+ this.continueIdleProjectSession(run, input)
895
+ ))
896
+ }
897
+
898
+ async continueIdleProjectSession(
784
899
  run,
785
900
  { session_id: sessionId, prompt },
786
901
  ) {
902
+ // A call admitted before this target's setup queue drained may belong to
903
+ // an already-ended coordinator turn. Do not resume or steer it afterward.
904
+ this.assertActiveCoordinatorRun(run)
905
+ if (this.uncertainUpdateSessions.has(sessionId)) {
906
+ throw updateError('context_unavailable', '目标会话未确认上一轮调整是否结束,请重启后台后再继续。')
907
+ }
787
908
  const active = this.findDelegation({ session_id: sessionId })
909
+ if (run.phase === 'update') {
910
+ if (!projectTargets(run).some(record => record.sessionId === sessionId)) {
911
+ throw updateError('invalid_session_route', '只能调整当前请求关联的项目 Session。')
912
+ }
913
+ if (active?.status === 'running' && active.taskId === run.coordinationRunId) {
914
+ if (!active.turnUpdates) throw updateError('update_unsupported', '目标未提供定向调整入口。')
915
+ await active.turnUpdates.enqueue(appendPromptBlocks(prompt, run.inputBlocks)).completion
916
+ run.updatedTargets += 1
917
+ return { status: 'updated', session_id: sessionId, delegation_id: active.id }
918
+ }
919
+ } else if (run.allowDelegation === false) {
920
+ throw updateError('invalid_session_route', '结果整理轮次不能重新执行工作。')
921
+ }
922
+ if (this.sessionExecutor.queues.has(`target:${sessionId}`)
923
+ || active?.status === 'running' || active?.status === 'cancelling') {
924
+ throw updateError('session_busy', '目标项目会话正在执行其他工作,请调整原任务或等待其结束。')
925
+ }
788
926
  const remembered = this.registry.getProject(
789
927
  projectSessionKey(this.protocol, sessionId),
790
928
  )
791
929
  let existing = null
792
930
  let cwd = clean(
793
931
  active?.directory
932
+ || run.projectTargets?.find(target => target.sessionId === sessionId)?.directory
794
933
  || remembered?.cwd,
795
934
  )
796
935
  if (!cwd) {
797
936
  const sessions = await this.client.listSessions({
798
937
  limit: MAX_SESSION_RESULTS,
799
938
  })
939
+ this.assertActiveCoordinatorRun(run)
800
940
  existing = sessions.find(item => (
801
941
  clean(item.sessionId) === clean(sessionId)
802
942
  ))
@@ -814,6 +954,7 @@ export class AcpBackendAdapter {
814
954
  ownerId: run.ownerId,
815
955
  role: 'project',
816
956
  })
957
+ this.assertActiveCoordinatorRun(run)
817
958
  this.rememberProjectSession({
818
959
  ...existing,
819
960
  ...session,
@@ -821,12 +962,14 @@ export class AcpBackendAdapter {
821
962
  title: existing?.title || remembered?.title,
822
963
  })
823
964
  await this.configureSession(session, 'project')
965
+ this.assertActiveCoordinatorRun(run)
824
966
  const record = this.createDelegation(run, {
825
967
  session,
826
968
  prompt: clean(prompt),
827
969
  directory: cwd,
828
970
  title: clean(prompt),
829
971
  })
972
+ if (run.phase === 'update') run.updatedTargets += 1
830
973
  return {
831
974
  status: 'started',
832
975
  delegation_id: record.id,
@@ -860,18 +1003,19 @@ export class AcpBackendAdapter {
860
1003
  async cancelDelegation(input) {
861
1004
  const record = this.findDelegation(input)
862
1005
  if (!record) return { status: 'not_found' }
863
- if (!['completed', 'failed', 'cancelled'].includes(record.status)) {
864
- record.status = 'cancelled'
865
- if (this.nativeDelegationAdapter) {
866
- await this.nativeDelegationAdapter.cancel({
867
- runId: record.id,
868
- sessionId: record.sessionId,
869
- }).catch(() => {})
870
- }
871
- record.controller.abort(new Error('用户已取消这项项目任务'))
872
- if (!this.nativeDelegationAdapter) {
873
- await this.client.cancelSession(record.sessionId).catch(() => {})
874
- }
1006
+ const nativeStillActive = record.nativeCompletion && !record.remoteStopped && record.status !== 'completed'
1007
+ if (nativeStillActive || !['completed', 'failed', 'cancelled'].includes(record.status)) {
1008
+ record.cancellation ||= (async () => {
1009
+ record.controller.abort(new Error('用户已取消这项项目任务'))
1010
+ if (record.nativeCompletion && this.nativeDelegationAdapter) {
1011
+ await this.nativeDelegationAdapter.cancel({ runId: record.id, sessionId: record.sessionId })
1012
+ } else {
1013
+ await this.client.cancelSession(record.sessionId)
1014
+ }
1015
+ record.remoteStopped = true
1016
+ record.status = 'cancelled'
1017
+ })()
1018
+ await record.cancellation
875
1019
  }
876
1020
  return {
877
1021
  status: record.status,
@@ -881,60 +1025,137 @@ export class AcpBackendAdapter {
881
1025
  }
882
1026
 
883
1027
  toolContext(run) {
1028
+ const active = operation => input => {
1029
+ this.assertActiveCoordinatorRun(run)
1030
+ return operation(input)
1031
+ }
884
1032
  return {
885
- listSessions: input => this.listProjectSessions(input),
886
- startSession: input => this.startProjectSession(run, input),
887
- sendSession: input => this.continueProjectSession(run, input),
888
- sessionStatus: input => this.statusForDelegation(input),
889
- cancelSession: input => this.cancelDelegation(input),
890
- }
891
- }
892
-
893
- coordinatorInstructions(message) {
894
- if (this.coordinatorUsesMcpInstructions()) return message
895
- const sessionInstructions = clean(this.profile.sessionInstructions)
896
- if (!sessionInstructions) return message
897
- return transformPromptText(message, content => [
898
- '<qwen_audio_agent_backend_profile>',
899
- sessionInstructions,
900
- '</qwen_audio_agent_backend_profile>',
901
- '',
902
- content,
903
- ].join('\n'))
1033
+ listSessions: active(input => this.listProjectSessions(input)),
1034
+ startSession: active(input => this.startProjectSession(run, input)),
1035
+ sendSession: active(input => this.continueProjectSession(run, input)),
1036
+ sessionStatus: active(input => this.statusForDelegation(input)),
1037
+ cancelSession: active(input => this.cancelDelegation(input)),
1038
+ }
1039
+ }
1040
+
1041
+ prepareCoordinatorInstructions(session, message) {
1042
+ const turns = Number.isSafeInteger(session.coordinatorPromptTurns) && session.coordinatorPromptTurns >= 0
1043
+ ? session.coordinatorPromptTurns : 0
1044
+ const instructions = turns % COORDINATOR_PROMPT_REFRESH_INTERVAL === 0
1045
+ ? this.stableCoordinatorInstructions() : ''
1046
+ let acknowledged = false
1047
+ return {
1048
+ prompt: instructions ? transformPromptText(message, content => [
1049
+ '<qwen_audio_agent_backend_profile>',
1050
+ instructions,
1051
+ '</qwen_audio_agent_backend_profile>',
1052
+ '',
1053
+ content,
1054
+ ].join('\n')) : message,
1055
+ acknowledge: () => {
1056
+ if (acknowledged) return
1057
+ acknowledged = true
1058
+ // Count accepted coordinator rounds, not tool/LLM iterations or steer
1059
+ // inputs within the same round. Failed delivery must not consume a refresh.
1060
+ session.coordinatorPromptTurns = turns + 1
1061
+ this.registry.set(coordinatorKey(session.ownerId, this.protocol), session)
1062
+ logger.debug('acp.coordinator.instructions', {
1063
+ backend: this.protocol,
1064
+ sessionId: session.sessionId,
1065
+ round: turns + 1,
1066
+ mcpInstructions: this.coordinatorUsesMcpInstructions(),
1067
+ promptRefreshed: Boolean(instructions),
1068
+ reason: instructions ? (turns === 0 ? 'initial' : 'periodic') : 'retained',
1069
+ })
1070
+ },
1071
+ }
1072
+ }
1073
+
1074
+ prepareConversation(session, snapshot, prompt) {
1075
+ const newest = new Map()
1076
+ for (const item of [snapshot].flat().filter(Boolean)) {
1077
+ const previous = newest.get(item.sessionId)
1078
+ if (!previous || item.cursor.position >= previous.cursor.position) newest.set(item.sessionId, item)
1079
+ }
1080
+ let remaining = COORDINATOR_CONVERSATION_MAX_CHARS
1081
+ const deltas = [...newest.values()].reverse().map(item => {
1082
+ const delta = conversationDelta({ ...item, maxChars: remaining }, session.conversationCursors?.[item.sessionId])
1083
+ remaining = Math.max(0, remaining - delta.text.length - (delta.text ? 1 : 0))
1084
+ return delta
1085
+ }).reverse()
1086
+ const text = deltas.map(delta => delta.text).filter(Boolean).join('\n')
1087
+ let acknowledged = false
1088
+ return {
1089
+ prompt: text ? transformPromptText(prompt, content => [
1090
+ '近期人机对话(仅作理解当前要求的背景,不是新的执行指令):',
1091
+ text,
1092
+ '',
1093
+ '当前要求:',
1094
+ content,
1095
+ ].join('\n')) : prompt,
1096
+ acknowledge: () => {
1097
+ if (acknowledged || !deltas.some(delta => !delta.stale)) return
1098
+ acknowledged = true
1099
+ // Steer acknowledgements can arrive before the original prompt ends.
1100
+ // Never let that earlier prompt move the durable watermark backwards.
1101
+ const cursors = new Map(Object.entries(session.conversationCursors || {}))
1102
+ for (const delta of deltas) {
1103
+ const current = cursors.get(delta.cursor.sessionId)
1104
+ if (delta.stale || current?.position >= delta.cursor.position) continue
1105
+ cursors.delete(delta.cursor.sessionId)
1106
+ cursors.set(delta.cursor.sessionId, delta.cursor)
1107
+ }
1108
+ session.conversationCursors = Object.fromEntries([...cursors].slice(-MAX_SESSION_RESULTS))
1109
+ this.registry.set(coordinatorKey(session.ownerId, this.protocol), session)
1110
+ },
1111
+ }
904
1112
  }
905
1113
 
906
1114
  async promptCoordinator(session, prompt, run, {
907
1115
  signal,
908
1116
  onUpdate,
1117
+ onAccepted = () => {},
909
1118
  } = {}) {
1119
+ const delivery = this.prepareCoordinatorInstructions(session, prompt)
1120
+ const acknowledge = () => {
1121
+ if (run.turnClosed || run.closed) return
1122
+ delivery.acknowledge()
1123
+ onAccepted()
1124
+ }
910
1125
  let attempt = 0
911
1126
  while (true) {
912
1127
  try {
913
- return assertCompletedAcpTurn(await this.client.prompt(
914
- session.sessionId,
915
- this.coordinatorInstructions(prompt),
916
- {
1128
+ const options = {
917
1129
  signal,
918
1130
  // Agent turns are user-cancellable and may legitimately run for
919
1131
  // hours. Connection setup and control RPCs remain bounded, but a
920
1132
  // live coding turn has no artificial wall-clock deadline.
921
1133
  timeoutMs: 0,
922
- onUpdate,
923
- },
924
- ), {
1134
+ onUpdate: update => { acknowledge(); onUpdate?.(update) },
1135
+ }
1136
+ const result = run.turnUpdates
1137
+ ? await run.turnUpdates.run(delivery.prompt, { ...options, onAccepted: acknowledge })
1138
+ : await this.client.prompt(session.sessionId, delivery.prompt, options)
1139
+ acknowledge()
1140
+ return assertCompletedAcpTurn(result, {
925
1141
  signal,
926
1142
  label: `${this.label} 协调 Session`,
927
1143
  protocol: this.protocol,
928
1144
  })
929
1145
  } catch (error) {
1146
+ if (error.contextUncertain) this.uncertainUpdateSessions.add(session.sessionId)
930
1147
  const retryIsSafe = !run.receivedUpdate
931
- && !run.delegation
1148
+ && !error.updateDeliveryFailed
1149
+ && !run.turnUpdates?.hasUpdates
1150
+ && !run.delegations.length
932
1151
  && run.nativeToolCalls.size === 0
933
1152
  && run.toolCalls.size === 0
934
1153
  const delayMs = retryIsSafe
935
1154
  ? this.profile.promptRetryDelay?.({ error, attempt })
936
1155
  : null
937
1156
  if (!Number.isFinite(delayMs) || delayMs < 0) throw error
1157
+ // No updates were admitted; retain the existing provider's safe initial retry.
1158
+ if (run.turnUpdates) run.turnUpdates.closed = false
938
1159
  attempt += 1
939
1160
  await waitForRetry(delayMs, signal)
940
1161
  }
@@ -947,6 +1168,11 @@ export class AcpBackendAdapter {
947
1168
  coordinationRequestId,
948
1169
  signal,
949
1170
  onEvent,
1171
+ delegations = [],
1172
+ projectTargets: savedProjectTargets = [],
1173
+ phase = 'execute',
1174
+ conversation,
1175
+ workObjective,
950
1176
  }) {
951
1177
  const run = {
952
1178
  ownerId: clean(ownerId),
@@ -954,21 +1180,31 @@ export class AcpBackendAdapter {
954
1180
  coordinationRequestId: clean(coordinationRequestId)
955
1181
  || clean(coordinationRunId),
956
1182
  onEvent,
957
- delegation: null,
1183
+ delegations,
1184
+ projectTargets: savedProjectTargets,
1185
+ signal,
1186
+ phase,
1187
+ updatedTargets: 0,
1188
+ objective: clean(workObjective),
1189
+ allowDelegation: phase === 'execute',
958
1190
  nativeToolCalls: new Map(),
959
1191
  toolCalls: new Map(),
960
1192
  initialPromptDone: false,
961
1193
  receivedUpdate: false,
962
1194
  inputBlocks: nonTextPromptBlocks(message),
1195
+ coordinatorKey: coordinatorKey(ownerId, this.protocol),
963
1196
  }
964
1197
  if (run.coordinationRunId) {
1198
+ const previous = this.coordinationRuns.get(run.coordinationRunId)
1199
+ if (previous) previous.closed = true
965
1200
  this.coordinationRuns.set(run.coordinationRunId, run)
966
1201
  }
967
- const key = coordinatorKey(ownerId, this.protocol)
1202
+ const key = run.coordinatorKey
968
1203
  const pendingFacts = this.registry.reconciliationsFor(key)
969
1204
  const prompt = pendingFacts.length
970
1205
  ? transformPromptText(message, content => [
971
- '上一请求已取消,不要续接其未完成内容。仅处理以下新请求。',
1206
+ '先前请求已取消,不要续接其未完成内容。仅处理以下新请求。',
1207
+ ...pendingFacts.filter(fact => fact.objective).map(fact => `已取消的要求:${fact.objective}`),
972
1208
  '',
973
1209
  content,
974
1210
  ].join('\n'))
@@ -976,12 +1212,22 @@ export class AcpBackendAdapter {
976
1212
  const registration = await this.ensureCoordinatorToolRegistration(
977
1213
  ownerId,
978
1214
  this.toolContext(run),
1215
+ key,
979
1216
  )
980
1217
  const mcpServers = [
981
1218
  ...(registration ? [registration.descriptor] : []),
982
1219
  ...this.builtinMcp,
983
1220
  ]
984
- const session = await this.ensureCoordinatorSession(ownerId, mcpServers)
1221
+ const updates = this.workUpdates.get(clean(coordinationRunId))
1222
+ const session = await this.ensureCoordinatorSession(ownerId, mcpServers, {
1223
+ expectedSessionId: updates?.expectedSessionId,
1224
+ })
1225
+ if (this.uncertainUpdateSessions.has(session.sessionId)) {
1226
+ throw updateError('context_unavailable', '后台未确认上一轮调整是否结束,请重启后台后再继续。')
1227
+ }
1228
+ if (updates?.expectedSessionId && updates.expectedSessionId !== session.sessionId) {
1229
+ throw updateError('context_unavailable', '原后台会话已不可用,未在其他会话中自动重做。')
1230
+ }
985
1231
  const permissionScopeId = `prompt_${randomUUID()}`
986
1232
  run.sessionId = session.sessionId
987
1233
  run.cwd = clean(session.cwd) || this.directory
@@ -990,12 +1236,39 @@ export class AcpBackendAdapter {
990
1236
  session.onEvent = onEvent
991
1237
  session.permissionScopeId = permissionScopeId
992
1238
  this.activeCoordinatorTurns.add(session.sessionId)
1239
+ if (updates) {
1240
+ run.turnUpdates = new AcpTurnUpdates({
1241
+ client: this.client, sessionId: session.sessionId, signal,
1242
+ onRestart: () => this.cancelPermissionsForScope(permissionScopeId),
1243
+ preparePrompt: (prompt, contexts = []) => this.prepareConversation(
1244
+ session, contexts, prompt,
1245
+ ),
1246
+ })
1247
+ updates.active = run.turnUpdates
1248
+ updates.started = true
1249
+ const pending = updates.pending.splice(0)
1250
+ conversation = [conversation, ...pending.map(entry => entry.conversation)].flat().filter(Boolean)
1251
+ for (const entry of pending) {
1252
+ // These updates are part of the initial prompt, whose snapshot is
1253
+ // prepared once below. Later steer batches carry their own snapshots.
1254
+ const receipt = run.turnUpdates.enqueue(entry.prompt)
1255
+ receipt.completion.then(async () => {
1256
+ // A queued requirement is not delivered to a project merely because
1257
+ // the coordinator accepted its prompt. Wait for its actual routing.
1258
+ const delivery = await updates.projectDelivery?.promise
1259
+ if (delivery?.error) entry.reject(delivery.error)
1260
+ else entry.resolve()
1261
+ }, entry.reject)
1262
+ }
1263
+ }
993
1264
  try {
994
1265
  // ensureCoordinatorSession supplies MCPs on create/restore. An active
995
1266
  // Session already owns those connections; resuming it again is not a
996
1267
  // valid refresh operation for every ACP implementation.
997
- const result = await this.promptCoordinator(session, prompt, run, {
1268
+ const delivery = this.prepareConversation(session, conversation, prompt)
1269
+ const result = await this.promptCoordinator(session, delivery.prompt, run, {
998
1270
  signal,
1271
+ onAccepted: delivery.acknowledge,
999
1272
  onUpdate: update => this.onSessionUpdate(run, update),
1000
1273
  })
1001
1274
  if (
@@ -1007,7 +1280,9 @@ export class AcpBackendAdapter {
1007
1280
  { status: 502, protocol: this.protocol },
1008
1281
  )
1009
1282
  error.recoverWithFreshCoordinator = !run.receivedUpdate
1010
- && !run.delegation
1283
+ && !updates?.expectedSessionId
1284
+ && !run.turnUpdates?.hasUpdates
1285
+ && !run.delegations.length
1011
1286
  && run.nativeToolCalls.size === 0
1012
1287
  && run.toolCalls.size === 0
1013
1288
  throw error
@@ -1018,7 +1293,7 @@ export class AcpBackendAdapter {
1018
1293
  this.registry.acknowledgeReconciliations(key, pendingFacts)
1019
1294
  }
1020
1295
  this.registry.set(
1021
- coordinatorKey(ownerId, this.protocol),
1296
+ key,
1022
1297
  session,
1023
1298
  )
1024
1299
  return {
@@ -1027,6 +1302,8 @@ export class AcpBackendAdapter {
1027
1302
  result,
1028
1303
  }
1029
1304
  } finally {
1305
+ run.turnClosed = true
1306
+ if (updates && updates.active === run.turnUpdates) updates.active = null
1030
1307
  this.activeCoordinatorTurns.delete(session.sessionId)
1031
1308
  this.cancelPermissionsForScope(permissionScopeId)
1032
1309
  if (session.permissionScopeId === permissionScopeId) {
@@ -1051,23 +1328,30 @@ export class AcpBackendAdapter {
1051
1328
  taskId: run.coordinationRunId,
1052
1329
  status: 'running',
1053
1330
  controller,
1331
+ signal: run.signal ? AbortSignal.any([controller.signal, run.signal]) : controller.signal,
1054
1332
  result: null,
1055
1333
  error: null,
1056
1334
  parentSessionId: run.sessionId,
1057
1335
  nativeCompletion: deferred(),
1058
1336
  }
1337
+ run.delegations.push(record)
1059
1338
  record.promise = this.waitForNativeDelegation(record, run)
1060
1339
  record.promise.catch(() => {})
1340
+ this.publishDelegation(run)
1061
1341
  return record
1062
1342
  }
1063
1343
 
1064
1344
  async waitForNativeDelegation(record) {
1345
+ const abort = () => record.nativeCompletion.reject(record.signal.reason)
1346
+ record.signal?.addEventListener('abort', abort, { once: true })
1347
+ record.nativeCompletion.promise.catch(() => {})
1065
1348
  try {
1349
+ record.signal?.throwIfAborted()
1066
1350
  const completed = this.nativeDelegationAdapter
1067
1351
  ? await this.nativeDelegationAdapter.wait({
1068
1352
  runId: record.id,
1069
1353
  sessionId: record.sessionId,
1070
- signal: record.controller.signal,
1354
+ signal: record.signal,
1071
1355
  })
1072
1356
  : { content: await record.nativeCompletion.promise }
1073
1357
  const content = clean(completed?.content)
@@ -1085,16 +1369,18 @@ export class AcpBackendAdapter {
1085
1369
  contentBlocks: completed?.contentBlocks || [],
1086
1370
  }
1087
1371
  } catch (error) {
1088
- record.status = record.controller.signal.aborted ? 'cancelled' : 'failed'
1372
+ record.status = record.signal?.aborted ? 'cancelled' : 'failed'
1089
1373
  record.error = error
1090
1374
  throw error
1375
+ } finally {
1376
+ record.signal?.removeEventListener('abort', abort)
1091
1377
  }
1092
1378
  }
1093
1379
 
1094
1380
  delegationResultPrompt(result, objective = '') {
1095
1381
  const task = clean(objective || result.title).slice(0, 2_000)
1096
1382
  const instruction = [
1097
- '刚才交给独立任务处理的工作已经完成。以下是与当前请求关联的可信最终结果:',
1383
+ '独立工作已结束。以下是与当前请求关联的可信执行结果(可能包含失败):',
1098
1384
  ...(task ? ['', `原任务:${task}`] : []),
1099
1385
  '',
1100
1386
  clean(result.content).slice(0, MAX_DELEGATION_RESULT_CHARS),
@@ -1110,6 +1396,7 @@ export class AcpBackendAdapter {
1110
1396
  resultEnvelope(initial, delegation = null, priorContentBlocks = []) {
1111
1397
  return {
1112
1398
  content: initial.result.content,
1399
+ continuation: workContinuation(this.protocol, initial.session.sessionId, initial.run),
1113
1400
  contentBlocks: [
1114
1401
  ...(priorContentBlocks || []),
1115
1402
  ...(delegation?.contentBlocks || []),
@@ -1126,12 +1413,7 @@ export class AcpBackendAdapter {
1126
1413
  },
1127
1414
  ...(delegation
1128
1415
  ? {
1129
- delegation: {
1130
- id: delegation.id,
1131
- sessionId: delegation.sessionId,
1132
- title: delegation.title,
1133
- directory: delegation.directory,
1134
- },
1416
+ delegation: delegationSummary(initial.run.delegations, initial.session.sessionId),
1135
1417
  }
1136
1418
  : {}),
1137
1419
  },
@@ -1157,6 +1439,42 @@ export class AcpBackendAdapter {
1157
1439
  }
1158
1440
  }
1159
1441
 
1442
+ beginWork(taskId, ownerId, { signal, expectedSessionId = '', continuingProjects = false } = {}) {
1443
+ if (this.closePromise) {
1444
+ throw new AgentError('BackendPort is closing or closed', {
1445
+ status: 503, protocol: this.protocol,
1446
+ })
1447
+ }
1448
+ if (this.workControllers.has(taskId)) {
1449
+ throw new AgentError('BackendPort Task is already active', {
1450
+ status: 409, protocol: this.protocol,
1451
+ })
1452
+ }
1453
+ const controller = new AbortController()
1454
+ const updates = {
1455
+ ownerId, active: null, pending: [], started: false, expectedSessionId,
1456
+ controls: Promise.resolve(), finalizing: false, settled: deferred(),
1457
+ projectDelivery: continuingProjects ? deferred() : null,
1458
+ }
1459
+ this.workControllers.set(taskId, controller)
1460
+ this.workUpdates.set(taskId, updates)
1461
+ return {
1462
+ signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
1463
+ updates,
1464
+ finish: error => {
1465
+ updates.projectDelivery?.resolve({ error: error || updateError(
1466
+ 'update_not_delivered', '后台执行结束前未将要求送达项目会话。',
1467
+ ) })
1468
+ updates.pending.splice(0).forEach(entry => entry.reject(
1469
+ updateError('update_not_delivered', '后台执行结束前未投递追加要求。'),
1470
+ ))
1471
+ if (this.workUpdates.get(taskId) === updates) this.workUpdates.delete(taskId)
1472
+ if (this.workControllers.get(taskId) === controller) this.workControllers.delete(taskId)
1473
+ updates.settled.resolve({ error })
1474
+ },
1475
+ }
1476
+ }
1477
+
1160
1478
  async submit(work, { signal, onEvent } = {}) {
1161
1479
  const taskId = clean(work?.id)
1162
1480
  const ownerId = clean(work?.ownerId)
@@ -1167,17 +1485,13 @@ export class AcpBackendAdapter {
1167
1485
  protocol: this.protocol,
1168
1486
  })
1169
1487
  }
1170
- if (this.workControllers.has(taskId)) {
1171
- throw new AgentError('BackendPort Task is already active', {
1172
- status: 409,
1173
- protocol: this.protocol,
1174
- })
1175
- }
1176
- const controller = new AbortController()
1177
- const workSignal = signal
1178
- ? AbortSignal.any([signal, controller.signal])
1179
- : controller.signal
1180
- this.workControllers.set(taskId, controller)
1488
+ const continuation = readWorkContinuation(work?.resumeContext, this.protocol)
1489
+ const execution = this.beginWork(taskId, ownerId, {
1490
+ signal, expectedSessionId: continuation?.token,
1491
+ continuingProjects: Boolean(continuation?.projects.length),
1492
+ })
1493
+ const workSignal = execution.signal
1494
+ let executionError
1181
1495
  try {
1182
1496
  if (work?.continuity === 'isolated') {
1183
1497
  return await this.submitIsolated(work, {
@@ -1191,13 +1505,14 @@ export class AcpBackendAdapter {
1191
1505
  const prompt = buildAcpCoordinatorInstruction({
1192
1506
  ...work,
1193
1507
  objective,
1194
- includeStableInstructions: !this.coordinatorUsesMcpInstructions(),
1195
1508
  })
1196
1509
  const run = message => this.runCoordinator(message, {
1197
1510
  ownerId,
1198
1511
  coordinationRunId: taskId,
1199
1512
  coordinationRequestId: taskId,
1200
1513
  workObjective: objective,
1514
+ conversation: work.conversation,
1515
+ projectTargets: continuation?.projects,
1201
1516
  signal: workSignal,
1202
1517
  onEvent,
1203
1518
  })
@@ -1212,12 +1527,64 @@ export class AcpBackendAdapter {
1212
1527
  return {
1213
1528
  content: clean(result?.content),
1214
1529
  artifacts,
1530
+ continuation: result.continuation,
1215
1531
  }
1532
+ } catch (error) {
1533
+ executionError = error
1534
+ throw error
1216
1535
  } finally {
1217
- if (this.workControllers.get(taskId) === controller) {
1218
- this.workControllers.delete(taskId)
1536
+ execution.finish(executionError)
1537
+ }
1538
+ }
1539
+
1540
+ update(taskId, input, { ownerId } = {}) {
1541
+ const id = clean(taskId)
1542
+ const updates = this.workUpdates.get(id)
1543
+ const run = this.coordinationRuns.get(id)
1544
+ if (!updates || updates.ownerId !== clean(ownerId)) {
1545
+ throw updateError('task_not_running', '指定工作没有可调整的活动执行。')
1546
+ }
1547
+ if (this.workControllers.get(id)?.signal.aborted) {
1548
+ throw updateError('task_cancelling', '指定工作正在取消。')
1549
+ }
1550
+ const instruction = clean(input?.instruction)
1551
+ if (!instruction) throw updateError('missing_instruction', '调整要求不能为空。')
1552
+ const prompt = promptWithInputParts(instruction, input?.inputParts)
1553
+ if (updates.finalizing) throw updateError('update_busy', '工作正在整理最终结果,请稍后继续。')
1554
+ if (run && projectTargets(run).length) {
1555
+ if (run.delegations.some(target => !target.turnUpdates)) {
1556
+ throw updateError('update_unsupported', '当前后台内部委托未提供可靠的定向调整入口。')
1219
1557
  }
1558
+ // The coordinator owns the requirements and target selection, even for
1559
+ // one child. Only its session_send performs the actual target update.
1560
+ const completion = updates.controls.then(() => this.routeDelegatedUpdate(run, prompt, input?.conversation))
1561
+ updates.controls = completion.catch(() => {})
1562
+ return { completion }
1220
1563
  }
1564
+ if (updates.active) return updates.active.enqueue(prompt, { context: input?.conversation })
1565
+ if (updates.started) throw updateError('task_not_running', '当前轮次已经结束,请稍后续接。')
1566
+ let resolve
1567
+ let reject
1568
+ const completion = new Promise((yes, no) => { resolve = yes; reject = no })
1569
+ completion.catch(() => {})
1570
+ updates.pending.push({ prompt, conversation: input?.conversation, resolve, reject })
1571
+ return { completion }
1572
+ }
1573
+
1574
+ async routeDelegatedUpdate(run, prompt, conversation) {
1575
+ const targets = projectTargets(run)
1576
+ const routed = await this.withCoordinatorTurn(projectUpdatePrompt(targets, prompt), {
1577
+ ownerId: run.ownerId,
1578
+ coordinationRunId: run.coordinationRunId,
1579
+ signal: run.signal,
1580
+ onEvent: run.onEvent,
1581
+ delegations: run.delegations,
1582
+ projectTargets: targets,
1583
+ phase: 'update',
1584
+ conversation,
1585
+ })
1586
+ assertProjectUpdateDelivered(routed.run)
1587
+ return { status: 'delivered' }
1221
1588
  }
1222
1589
 
1223
1590
  async submitIsolated(work, {
@@ -1310,6 +1677,8 @@ export class AcpBackendAdapter {
1310
1677
  coordinationRunId,
1311
1678
  coordinationRequestId,
1312
1679
  workObjective,
1680
+ conversation,
1681
+ projectTargets: savedProjectTargets = [],
1313
1682
  signal,
1314
1683
  onEvent,
1315
1684
  } = {}) {
@@ -1318,73 +1687,127 @@ export class AcpBackendAdapter {
1318
1687
  // the first task after a cold start cannot race its bridge.
1319
1688
  await this.start({ signal })
1320
1689
  const runId = clean(coordinationRunId)
1321
- const key = coordinatorKey(ownerId, this.protocol)
1322
1690
  const publish = event => this.publishWorkEvent(event, {
1323
1691
  taskId: runId,
1324
1692
  ownerId,
1325
1693
  onEvent,
1326
1694
  })
1327
1695
  try {
1328
- const initial = await this.serialize(
1329
- `coordinator:${key}`,
1330
- () => this.coordinatorTurnWithRecovery(message, {
1331
- ownerId,
1332
- coordinationRunId,
1333
- coordinationRequestId,
1334
- signal,
1335
- onEvent: publish,
1336
- }),
1337
- )
1338
- if (!initial.run.delegation) return this.resultEnvelope(initial)
1339
- const delegation = initial.run.delegation
1340
- publish({
1341
- type: BackendEventType.DELEGATED,
1342
- delegation: {
1343
- id: delegation.id,
1344
- sessionId: delegation.sessionId,
1345
- title: delegation.title,
1346
- directory: delegation.directory,
1347
- },
1348
- })
1349
- const target = await delegation.promise
1350
- publish({
1351
- type: BackendEventType.DELEGATION_COMPLETED,
1352
- delegation: {
1353
- id: target.id,
1354
- sessionId: target.sessionId,
1355
- title: target.title,
1356
- directory: target.directory,
1357
- },
1358
- })
1359
- const final = await this.serialize(
1360
- `coordinator:${key}`,
1361
- () => this.coordinatorTurnWithRecovery(
1362
- this.delegationResultPrompt(target, workObjective),
1363
- {
1364
- ownerId,
1365
- coordinationRunId,
1366
- coordinationRequestId,
1367
- signal,
1368
- onEvent: publish,
1369
- },
1370
- ),
1371
- )
1372
- return this.resultEnvelope(
1373
- final,
1374
- target,
1375
- initial.result.contentBlocks || [],
1696
+ const options = { ownerId, coordinationRunId, coordinationRequestId, workObjective,
1697
+ projectTargets: savedProjectTargets, signal, onEvent: publish }
1698
+ const continuingProjects = savedProjectTargets.length > 0
1699
+ const initial = await this.withCoordinatorTurn(
1700
+ continuingProjects ? projectUpdatePrompt(savedProjectTargets, message) : message,
1701
+ { ...options, conversation, phase: continuingProjects ? 'update' : 'execute' },
1376
1702
  )
1703
+ if (continuingProjects) {
1704
+ assertProjectUpdateDelivered(initial.run)
1705
+ this.workUpdates.get(runId)?.projectDelivery?.resolve({})
1706
+ }
1707
+ if (!initial.run.delegations.length) return this.resultEnvelope(initial)
1708
+ return await this.finishDelegatedWork(initial, { ...options, workObjective })
1709
+ } catch (error) {
1710
+ // A failed coordinator may have queued update turns. Stop and drain them
1711
+ // before releasing this Work; they must never outlive its cancellation handle.
1712
+ this.workControllers.get(runId)?.abort(error)
1713
+ await this.workUpdates.get(runId)?.controls
1714
+ throw error
1715
+ } finally {
1716
+ if (runId) {
1717
+ const run = this.coordinationRuns.get(runId)
1718
+ if (run) {
1719
+ run.closed = true
1720
+ // An initial/summary turn may fail after starting children. Never
1721
+ // leave those executions detached from their owning Work.
1722
+ await this.stopUnfinishedDelegations(run)
1723
+ }
1724
+ this.coordinationRuns.delete(runId)
1725
+ }
1726
+ }
1727
+ }
1728
+
1729
+ async withCoordinatorTurn(message, options) {
1730
+ const lease = await this.acquireCoordinator(options.ownerId, {
1731
+ sessionId: this.workUpdates.get(clean(options.coordinationRunId))?.expectedSessionId,
1732
+ signal: options.signal,
1733
+ })
1734
+ try {
1735
+ options.signal?.throwIfAborted()
1736
+ return await this.coordinatorTurnWithRecovery(message, options)
1377
1737
  } finally {
1378
- if (runId) this.coordinationRuns.delete(runId)
1738
+ lease.release()
1379
1739
  }
1380
1740
  }
1381
1741
 
1742
+ async stopUnfinishedDelegations(run) {
1743
+ const active = run.delegations.filter(target => (
1744
+ ['running', 'cancelling'].includes(target.status)
1745
+ || (target.nativeCompletion && !target.remoteStopped && target.status !== 'completed')
1746
+ ))
1747
+ if (!active.length) return
1748
+ await waitForCancellation(Promise.all(active.map(async target => {
1749
+ await this.cancelDelegation({ delegation_id: target.id })
1750
+ await target.promise.catch(() => {})
1751
+ })), this.cancelTimeoutMs, this.protocol).catch(() => {
1752
+ // A timeout must not silently permit this Session to be resumed later.
1753
+ active.forEach(target => this.uncertainUpdateSessions.add(target.sessionId))
1754
+ })
1755
+ }
1756
+
1757
+ async finishDelegatedWork(initial, options) {
1758
+ const { run, session } = initial
1759
+ const { signal, onEvent, workObjective } = options
1760
+ this.publishDelegation(run, { yielded: true })
1761
+ const updates = this.workUpdates.get(run.coordinationRunId)
1762
+ let outcomes
1763
+ while (true) {
1764
+ const targets = [...run.delegations]
1765
+ outcomes = await Promise.allSettled(targets.map(target => target.promise))
1766
+ const controls = updates?.controls
1767
+ await controls
1768
+ signal?.throwIfAborted()
1769
+ if (controls === updates?.controls
1770
+ && targets.length === run.delegations.length
1771
+ && targets.every((target, index) => target === run.delegations[index])) break
1772
+ }
1773
+ if (updates) updates.finalizing = true
1774
+ const failure = outcomes.find(outcome => outcome.status === 'rejected')
1775
+ if (failure && outcomes.length === 1) throw failure.reason
1776
+ const results = outcomes.map((outcome, index) => outcome.status === 'fulfilled'
1777
+ ? outcome.value : {
1778
+ ...delegationSummary([run.delegations[index]], session.sessionId),
1779
+ content: `执行失败:${clean(outcome.reason?.message || outcome.reason)}`,
1780
+ contentBlocks: [],
1781
+ })
1782
+ onEvent({
1783
+ type: BackendEventType.DELEGATION_COMPLETED,
1784
+ delegation: delegationSummary(results, session.sessionId),
1785
+ })
1786
+ // Bound each contribution, not just the joined prefix: a long first result
1787
+ // must not erase a later child's outcome (especially its failure).
1788
+ const resultBudget = Math.max(0, Math.floor(MAX_DELEGATION_RESULT_CHARS / results.length) - 2)
1789
+ const target = results.length === 1 ? results[0] : {
1790
+ content: results.map(result => `${result.title}\n${result.content}`.slice(0, resultBudget)).join('\n\n'),
1791
+ contentBlocks: results.flatMap(result => result.contentBlocks || []),
1792
+ }
1793
+ for (const artifact of artifactsFromAcpContentBlocks(target.contentBlocks)) {
1794
+ onEvent({ type: BackendEventType.ARTIFACT, artifact })
1795
+ }
1796
+ const final = await this.withCoordinatorTurn(this.delegationResultPrompt(target, workObjective), {
1797
+ ...options, delegations: run.delegations, phase: 'result',
1798
+ })
1799
+ if (failure) {
1800
+ throw new AgentError(`部分工作未完成:${clean(final.result.content)}`, { protocol: this.protocol })
1801
+ }
1802
+ return this.resultEnvelope(final, target, initial.result?.contentBlocks || [])
1803
+ }
1804
+
1382
1805
  canRecoverDelegatedWork(task) {
1383
- return Boolean(
1384
- this.nativeDelegationAdapter
1385
- && task?.delegation?.id
1386
- && task?.delegation?.sessionId,
1387
- )
1806
+ const saved = task?.delegation
1807
+ const targets = saved && ('targets' in saved ? saved.targets : [saved])
1808
+ return Boolean(this.nativeDelegationAdapter && Array.isArray(targets) && targets.length
1809
+ && targets.every(target => typeof target?.id === 'string' && target.id.trim()
1810
+ && typeof target?.sessionId === 'string' && target.sessionId.trim()))
1388
1811
  }
1389
1812
 
1390
1813
  async recoverDelegatedWork(task, {
@@ -1403,82 +1826,89 @@ export class AcpBackendAdapter {
1403
1826
  ownerId,
1404
1827
  onEvent,
1405
1828
  })
1406
- const key = coordinatorKey(ownerId, this.protocol)
1407
- const session = await this.ensureCoordinatorSession(ownerId)
1408
- const run = {
1409
- ownerId,
1410
- coordinationRunId,
1411
- coordinationRequestId: coordinationRunId,
1412
- onEvent: publish,
1413
- sessionId: session.sessionId,
1414
- nativeToolCalls: new Map(),
1415
- toolCalls: new Map(),
1416
- initialPromptDone: true,
1417
- delegation: null,
1418
- }
1419
1829
  const saved = task.delegation
1420
- const delegation = this.createNativeDelegation(run, {
1421
- delegationId: clean(saved.id),
1422
- sessionId: clean(saved.sessionId),
1423
- directory: clean(saved.directory || this.directory),
1424
- title: bounded(saved.title || task.objective, 160)
1425
- || this.profile.defaultDelegationTitle
1426
- || `${this.label} 项目任务`,
1427
- })
1428
- if (coordinationRunId) this.coordinationRuns.set(coordinationRunId, run)
1429
- signal?.addEventListener('abort', () => {
1430
- delegation.controller.abort(
1431
- signal.reason || new Error('用户已取消这项项目任务'),
1432
- )
1433
- }, { once: true })
1434
- publish({
1435
- type: BackendEventType.DELEGATED,
1436
- delegation: {
1437
- id: delegation.id,
1438
- sessionId: delegation.sessionId,
1439
- title: delegation.title,
1440
- directory: delegation.directory,
1441
- },
1830
+ const execution = this.beginWork(coordinationRunId, ownerId, {
1831
+ signal, expectedSessionId: clean(saved.coordinatorSessionId),
1442
1832
  })
1833
+ signal = execution.signal
1834
+ execution.updates.started = true
1835
+ let lease
1836
+ let executionError
1443
1837
  try {
1444
- const target = await delegation.promise
1445
- publish({
1446
- type: BackendEventType.DELEGATION_COMPLETED,
1447
- delegation: {
1448
- id: target.id,
1449
- sessionId: target.sessionId,
1450
- title: target.title,
1451
- directory: target.directory,
1452
- },
1838
+ lease = await this.acquireCoordinator(ownerId, {
1839
+ sessionId: clean(saved.coordinatorSessionId), signal,
1453
1840
  })
1454
- const final = await this.serialize(
1455
- `coordinator:${key}`,
1456
- () => this.coordinatorTurn(
1457
- this.delegationResultPrompt(target, task.objective),
1458
- {
1459
- ownerId,
1460
- coordinationRunId,
1461
- coordinationRequestId: coordinationRunId,
1462
- signal,
1463
- onEvent: publish,
1464
- },
1465
- ),
1466
- )
1467
- return this.resultEnvelope(final, target)
1841
+ const key = lease.key
1842
+ signal?.throwIfAborted()
1843
+ const run = {
1844
+ ownerId,
1845
+ coordinationRunId,
1846
+ coordinationRequestId: coordinationRunId,
1847
+ onEvent: publish,
1848
+ coordinatorKey: key,
1849
+ nativeToolCalls: new Map(),
1850
+ toolCalls: new Map(),
1851
+ initialPromptDone: true,
1852
+ objective: clean(task.objective),
1853
+ delegations: [],
1854
+ signal,
1855
+ turnClosed: true,
1856
+ }
1857
+ const registration = await this.ensureCoordinatorToolRegistration(ownerId, this.toolContext(run), key)
1858
+ const session = await this.ensureCoordinatorSession(ownerId, [
1859
+ ...(registration ? [registration.descriptor] : []), ...this.builtinMcp,
1860
+ ], key)
1861
+ if (saved.coordinatorSessionId && saved.coordinatorSessionId !== session.sessionId) {
1862
+ throw updateError('context_unavailable', '原后台会话已不可用,不能在其他会话中恢复委托。')
1863
+ }
1864
+ signal?.throwIfAborted()
1865
+ run.sessionId = session.sessionId
1866
+ for (const target of saved.targets || [saved]) {
1867
+ this.createNativeDelegation(run, {
1868
+ delegationId: clean(target.id),
1869
+ sessionId: clean(target.sessionId),
1870
+ directory: clean(target.directory || this.directory),
1871
+ title: bounded(target.title || task.objective, 160)
1872
+ || this.profile.defaultDelegationTitle
1873
+ || `${this.label} 项目任务`,
1874
+ })
1875
+ }
1876
+ if (coordinationRunId) this.coordinationRuns.set(coordinationRunId, run)
1877
+ lease.release()
1878
+ return await this.finishDelegatedWork({ run, session }, {
1879
+ ownerId, coordinationRunId, signal, onEvent: publish, workObjective: task.objective,
1880
+ })
1881
+ } catch (error) {
1882
+ executionError = error
1883
+ throw error
1468
1884
  } finally {
1885
+ const run = this.coordinationRuns.get(coordinationRunId)
1886
+ if (run) {
1887
+ run.closed = true
1888
+ await this.stopUnfinishedDelegations(run)
1889
+ }
1469
1890
  this.coordinationRuns.delete(coordinationRunId)
1891
+ lease?.release()
1892
+ execution.finish(executionError)
1470
1893
  }
1471
1894
  }
1472
1895
 
1473
1896
  async cancelWork(taskId, { ownerId } = {}) {
1474
1897
  const run = this.coordinationRuns.get(clean(taskId))
1475
- const record = run?.delegation
1476
- if (run && run.ownerId !== clean(ownerId)) {
1898
+ const records = run?.delegations || []
1899
+ const updates = this.workUpdates.get(clean(taskId))
1900
+ if ((run && run.ownerId !== clean(ownerId)) || (updates && updates.ownerId !== clean(ownerId))) {
1477
1901
  throw new AgentError(`没有找到可取消的 ${this.label} 任务`, {
1478
1902
  protocol: this.protocol,
1479
1903
  })
1480
1904
  }
1481
- if (record) await this.cancelDelegation({ delegation_id: record.id })
1905
+ // Stop the owning Work before child cancellation settles. Otherwise the
1906
+ // aggregate waiter could mistake cancelled children for a partial failure
1907
+ // and enqueue a new summary while cancel() is still waiting for them.
1908
+ this.workControllers.get(clean(taskId))?.abort(new AgentError('用户已取消这项工作', {
1909
+ status: 499, protocol: this.protocol,
1910
+ }))
1911
+ await Promise.all(records.map(record => this.cancelDelegation({ delegation_id: record.id })))
1482
1912
 
1483
1913
  // ACP cancellation interrupts execution but does not let a client rewrite
1484
1914
  // the backend-owned Session history. Record one terminal boundary only
@@ -1486,15 +1916,15 @@ export class AcpBackendAdapter {
1486
1916
  // projected into the next coordinator turn and acknowledged on success.
1487
1917
  if (run?.sessionId) {
1488
1918
  this.registry.appendReconciliation(
1489
- coordinatorKey(ownerId, this.protocol),
1919
+ run.coordinatorKey || coordinatorKey(ownerId, this.protocol),
1490
1920
  {
1491
1921
  kind: 'coordination_request_terminated',
1492
1922
  request_id: run.coordinationRequestId || clean(taskId),
1493
1923
  outcome: 'cancelled',
1494
- ...(record
1924
+ ...(run.objective ? { objective: run.objective.slice(0, 2_000) } : {}),
1925
+ ...(records.length
1495
1926
  ? {
1496
- delegation_id: record.id,
1497
- target_session_id: record.sessionId,
1927
+ targets: records.map(record => ({ delegation_id: record.id, target_session_id: record.sessionId })),
1498
1928
  }
1499
1929
  : {}),
1500
1930
  confirmed_at: new Date().toISOString(),
@@ -1503,11 +1933,11 @@ export class AcpBackendAdapter {
1503
1933
  }
1504
1934
  return {
1505
1935
  route: 'adapter',
1506
- layer: record ? 'delegated' : 'coordinator',
1507
- ...(record
1936
+ layer: records.length ? 'delegated' : 'coordinator',
1937
+ ...(records.length === 1
1508
1938
  ? {
1509
- delegationId: record.id,
1510
- sessionId: record.sessionId,
1939
+ delegationId: records[0].id,
1940
+ sessionId: records[0].sessionId,
1511
1941
  }
1512
1942
  : {}),
1513
1943
  }
@@ -1516,15 +1946,18 @@ export class AcpBackendAdapter {
1516
1946
  async cancel(taskId, options = {}) {
1517
1947
  const id = clean(taskId)
1518
1948
  const controller = this.workControllers.get(id)
1949
+ const updates = this.workUpdates.get(id)
1519
1950
  if (!controller && !this.coordinationRuns.has(id)) {
1520
1951
  return { taskId: id, state: 'not_found' }
1521
1952
  }
1522
- await this.cancelWork(id, options)
1523
- controller?.abort(new AgentError('用户已取消这项工作', {
1524
- status: 499,
1525
- protocol: this.protocol,
1526
- }))
1527
- return { taskId: id, state: 'cancelled' }
1953
+ return waitForCancellation((async () => {
1954
+ await this.cancelWork(id, options)
1955
+ // Keep the controller and Session lease until submit's finally has run.
1956
+ // A cancelled receipt must not race a continuation of the same task.
1957
+ const outcome = await updates?.settled.promise
1958
+ if (outcome?.error?.contextUncertain) throw outcome.error
1959
+ return { taskId: id, state: 'cancelled' }
1960
+ })(), this.cancelTimeoutMs, this.protocol)
1528
1961
  }
1529
1962
 
1530
1963
  async respondAuthorization(
@@ -1556,30 +1989,29 @@ export class AcpBackendAdapter {
1556
1989
 
1557
1990
  async queryDelegatedWork(taskId, _question, { ownerId } = {}) {
1558
1991
  const run = this.coordinationRuns.get(clean(taskId))
1559
- const record = run?.delegation
1560
- if (!record || record.ownerId !== clean(ownerId)) {
1992
+ if (!run?.delegations.length || run.ownerId !== clean(ownerId)) {
1561
1993
  throw new AgentError(`没有找到对应的 ${this.label} 项目任务`, {
1562
1994
  protocol: this.protocol,
1563
1995
  })
1564
1996
  }
1565
- const status = this.statusForDelegation({ delegation_id: record.id })
1566
- const latest = status.recent_updates?.at(-1)
1997
+ const status = this.status(taskId, { ownerId })
1998
+ const latest = status.activity?.at(-1)
1567
1999
  const latestDetail = bounded(
1568
2000
  latest?.detail || latest?.tool || latest?.kind,
1569
2001
  240,
1570
2002
  )
1571
- const answer = status.status === 'completed'
2003
+ const answer = status.state === 'completed'
1572
2004
  ? `这项工作已经完成:${clean(status.result)}`
1573
- : status.status === 'failed'
2005
+ : status.state === 'failed'
1574
2006
  ? `这项工作已经失败:${clean(status.error)}`
1575
- : status.status === 'cancelled'
2007
+ : status.state === 'cancelled'
1576
2008
  ? '这项工作已经取消。'
1577
2009
  : latestDetail
1578
2010
  ? `这项工作仍在执行中,最近进展:${latestDetail}`
1579
2011
  : '这项工作仍在执行中,当前没有新的详细进展。'
1580
2012
  return {
1581
2013
  content: JSON.stringify({
1582
- task_id: clean(record.taskId) || clean(taskId),
2014
+ task_id: clean(taskId),
1583
2015
  state: 'completed',
1584
2016
  mode: 'respond',
1585
2017
  result: answer,
@@ -1587,13 +2019,8 @@ export class AcpBackendAdapter {
1587
2019
  protocol: this.protocol,
1588
2020
  metadata: {
1589
2021
  statusSource: 'gateway',
1590
- recentUpdates: status.recent_updates || [],
1591
- delegation: {
1592
- id: record.id,
1593
- sessionId: record.sessionId,
1594
- title: record.title,
1595
- directory: record.directory,
1596
- },
2022
+ recentUpdates: status.activity || [],
2023
+ delegation: delegationSummary(run.delegations, run.sessionId),
1597
2024
  },
1598
2025
  }
1599
2026
  }
@@ -1609,21 +2036,41 @@ export class AcpBackendAdapter {
1609
2036
  })
1610
2037
  }
1611
2038
 
1612
- async close() {
2039
+ close() {
2040
+ this.closePromise ||= Promise.resolve().then(() => this.closeAfterCancellation())
2041
+ return this.closePromise
2042
+ }
2043
+
2044
+ async closeAfterCancellation() {
2045
+ this.coordinatorQueue.close()
2046
+ const executions = [...this.workUpdates.values()]
2047
+ const targets = [...this.coordinationRuns.values()].flatMap(run => run.delegations || [])
1613
2048
  for (const controller of this.workControllers.values()) {
1614
2049
  controller.abort(new AgentError('后台 Agent 已关闭', {
1615
2050
  status: 503,
1616
2051
  protocol: this.protocol,
1617
2052
  }))
1618
2053
  }
1619
- this.workControllers.clear()
1620
- for (const run of this.coordinationRuns.values()) {
1621
- run.delegation?.controller.abort(
1622
- new Error(`${this.label} backend is shutting down`),
1623
- )
2054
+ for (const target of targets) {
2055
+ target.controller.abort(new Error(`${this.label} backend is shutting down`))
1624
2056
  }
1625
2057
  this.permissionBroker.cancelAll()
1626
2058
  this.inputBroker.cancelAll()
2059
+ let cancellationError
2060
+ try {
2061
+ await waitForCancellation(Promise.all([
2062
+ ...targets.map(target => this.cancelDelegation({ delegation_id: target.id })),
2063
+ ...executions.map(async execution => {
2064
+ const outcome = await execution.settled.promise
2065
+ if (outcome?.error?.contextUncertain) throw outcome.error
2066
+ }),
2067
+ ]), this.cancelTimeoutMs, this.protocol)
2068
+ } catch (error) {
2069
+ cancellationError = error
2070
+ }
2071
+ // Closing the transport is also necessary for clients whose pending prompt
2072
+ // settles only on disconnect. Do not wait forever or mistake that local
2073
+ // cleanup for confirmation that an independently hosted native run stopped.
1627
2074
  await Promise.allSettled(
1628
2075
  [...this.coordinatorToolRegistrationPromises.values()],
1629
2076
  )
@@ -1638,6 +2085,11 @@ export class AcpBackendAdapter {
1638
2085
  ])
1639
2086
  await this.builtinMcpLifecycle.close()
1640
2087
  this.workEventListeners.clear()
2088
+ if (cancellationError) {
2089
+ this.runtimeState.failed(cancellationError)
2090
+ throw cancellationError
2091
+ }
2092
+ this.uncertainUpdateSessions.clear()
1641
2093
  this.runtimeState.stopped()
1642
2094
  }
1643
2095
  }