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,5 +1,7 @@
1
1
  import { backendPermissionDecision, PERMISSION_DECISIONS } from '../../../shared/permission-decisions.mjs'
2
2
  import { BackendEventType } from '../core/backend-events.mjs'
3
+ import { updateTask, inputWithUpdates } from './task-updates.mjs'
4
+ import { TaskDomainEvent } from '../task/task-events.mjs'
3
5
 
4
6
  export class TaskOperationError extends Error {
5
7
  constructor(code, message) {
@@ -32,13 +34,14 @@ function permissionReceipt(admission, permissionId) {
32
34
  * or public protocol events. System jobs keep their own execution entry point.
33
35
  */
34
36
  export class TaskOperations {
35
- constructor({ taskManager, backendRuntime, permissionPolicy, respondAuthorization, respondInput } = {}) {
37
+ constructor({ taskManager, backendRuntime, permissionPolicy, respondAuthorization, respondInput, conversationSnapshot } = {}) {
36
38
  if (!taskManager) throw new TypeError('taskManager is required')
37
39
  this.taskManager = taskManager
38
40
  this.backendRuntime = backendRuntime
39
41
  this.permissionPolicy = permissionPolicy
40
42
  this.respondAuthorization = respondAuthorization
41
43
  this.respondInput = respondInput
44
+ this.conversationSnapshot = conversationSnapshot
42
45
  // A backend can request several permissions before any is answered. The
43
46
  // Task snapshot projects the latest one; retain the live requests as well.
44
47
  this.permissions = new Map()
@@ -54,14 +57,19 @@ export class TaskOperations {
54
57
  return this.taskManager.list({ sessionId, active, ...filters, ownerId: owner(context) })
55
58
  }
56
59
 
57
- submit({ objective, inputParts = [], submissionKey }, context) {
60
+ submit({ objective, instruction, inputParts = [], submissionKey, notificationPolicy }, context) {
58
61
  const ownerId = owner(context)
59
62
  const { sessionId = 'main', turnId } = context
63
+ const conversation = this.conversationSnapshot?.(context)
60
64
  return this.taskManager.create({
61
- objective, ownerId, sessionId, turnId, submissionKey,
62
- laneKey: `backend:${ownerId}`,
63
- laneLimit: 1,
64
- runner: (_objective, execution) => this.run({ objective, inputParts }, {
65
+ objective, ownerId, sessionId, turnId, submissionKey, notificationPolicy,
66
+ runner: (_objective, execution) => this.run(inputWithUpdates(
67
+ this.taskManager.tasks.get(execution.taskId), {
68
+ objective, inputParts,
69
+ ...(instruction === undefined ? {} : { instruction }),
70
+ ...(conversation ? { conversation } : {}),
71
+ },
72
+ ), {
65
73
  ...execution, ownerId, sessionId, turnId,
66
74
  }),
67
75
  canceler: async ({ task, previousStatus, abort }) => {
@@ -75,15 +83,46 @@ export class TaskOperations {
75
83
  })
76
84
  }
77
85
 
86
+ update(input, context) { return updateTask(this, input, context) }
87
+
88
+ executionFor(task, input) {
89
+ return {
90
+ runner: (_objective, execution) => this.run(inputWithUpdates(task, {
91
+ objective: task.objective, ...input,
92
+ }), execution),
93
+ canceler: async ({ abort }) => {
94
+ const result = await this.backendRuntime.cancel(task.id, { ownerId: task.ownerId })
95
+ abort()
96
+ return result
97
+ },
98
+ }
99
+ }
100
+
78
101
  async run(input, context) {
79
102
  const ownerId = owner(context)
103
+ const task = this.taskManager.tasks.get(context.taskId)
104
+ const version = task?.executionVersion || 0
105
+ if (task) task.backendPhase = 'active'
106
+ const included = (task?.updates || []).filter(entry => entry.status === 'queued')
107
+ included.forEach(entry => { entry.status = 'pending' })
108
+ if (included.length) this.taskManager.emit(TaskDomainEvent.UPDATED, task)
80
109
  try {
81
- return await this.backendRuntime.run(input, {
110
+ const result = await this.backendRuntime.run(input, {
82
111
  ...context, ownerId,
83
- onEvent: event => this.forwardBackendEvent(context, event, context.onEvent),
112
+ onEvent: event => {
113
+ if (task && (task.terminalHandled || (task.executionVersion || 0) !== version)) return
114
+ this.forwardBackendEvent(context, event, context.onEvent)
115
+ },
84
116
  })
117
+ included.forEach(entry => { entry.status = 'delivered' })
118
+ return result
119
+ } catch (error) {
120
+ included.forEach(entry => { entry.status = 'failed'; entry.error = error.message })
121
+ throw error
85
122
  } finally {
86
- this.clearPermissions(context.taskId, ownerId)
123
+ if (task && (task.executionVersion || 0) === version) task.backendPhase = 'settled'
124
+ if (included.length) this.taskManager.emit(TaskDomainEvent.UPDATED, task)
125
+ this.clearPermissions(context.taskId, ownerId, version)
87
126
  }
88
127
  }
89
128
 
@@ -112,12 +151,14 @@ export class TaskOperations {
112
151
 
113
152
  cancel(taskId, context) {
114
153
  const ownerId = owner(context)
154
+ const revision = this.get(taskId, { ownerId })?.revision || 0
115
155
  return this.taskManager.cancel(taskId, { ownerId }).finally(() => {
116
- this.clearPermissions(taskId, ownerId)
156
+ this.clearPermissions(taskId, ownerId, revision)
117
157
  })
118
158
  }
119
159
 
120
- clearPermissions(taskId, ownerId) {
160
+ clearPermissions(taskId, ownerId, revision) {
161
+ if (revision !== undefined && (this.get(taskId, { ownerId })?.revision || 0) !== revision) return
121
162
  for (const [id, entry] of this.permissions) {
122
163
  if (entry.taskId === taskId && entry.ownerId === ownerId) this.permissions.delete(id)
123
164
  }
@@ -128,8 +169,9 @@ export class TaskOperations {
128
169
 
129
170
  cancelSeries(seriesId, context) {
130
171
  const ownerId = owner(context)
172
+ const revisions = new Map(this.list({ ownerId }).map(task => [task.id, task.revision || 0]))
131
173
  return this.taskManager.cancelSeries(seriesId, { ownerId }).then(tasks => {
132
- for (const task of tasks) this.clearPermissions(task.id, ownerId)
174
+ for (const task of tasks) this.clearPermissions(task.id, ownerId, revisions.get(task.id))
133
175
  return tasks
134
176
  })
135
177
  }
@@ -0,0 +1,82 @@
1
+ import { isTaskTerminal, isUserWork } from '../task/task-state.mjs'
2
+ import { TaskDomainEvent } from '../task/task-events.mjs'
3
+
4
+ function fail(code, message) { throw Object.assign(new Error(message), { code }) }
5
+
6
+ /** Admission and durable intent only; adapters own delivery and execution strategies. */
7
+ export function updateTask(operations, { taskId, instruction, inputParts = [], submissionKey }, context) {
8
+ const { taskManager: manager, backendRuntime: backend } = operations
9
+ const visible = operations.get(taskId, context)
10
+ if (!visible) fail('task_not_found', '没有找到指定工作。')
11
+ const task = manager.tasks.get(visible.id)
12
+ const text = String(instruction || '').trim()
13
+ if (!text || text.length > 16_000) fail('invalid_instruction', '调整要求不能为空或超过 16000 字符。')
14
+ if (!isUserWork(task) || task.kind !== 'work') fail('update_unsupported', '这种工作类型不支持调整。')
15
+ if (submissionKey && task.updates?.some(entry => entry.submissionKey === submissionKey)) {
16
+ return { status: 'duplicate', taskId: task.id }
17
+ }
18
+ if (!backend?.canUpdate?.()) fail('update_unsupported', '当前后台不支持调整已有工作。')
19
+ if (task.status === 'cancelling') fail('task_cancelling', '这项工作正在取消,请等待结束。')
20
+ if (task.inputRequest?.status === 'pending') fail('input_response_required', '请先回复或拒绝当前后台追问。')
21
+ if (task.status === 'finalizing') fail('update_busy', '这项工作正在整理最终结果,请稍后继续。')
22
+ if ((task.updates?.length || 0) >= 100) fail('update_limit', '这项工作的调整记录已达到上限。')
23
+ const terminal = isTaskTerminal(task.status)
24
+ if (!terminal && task.delegation && task.backendPhase !== 'active') {
25
+ fail('update_unsupported', '恢复的委托工作暂不支持调整,未提交追加要求。')
26
+ }
27
+ if (terminal && !task.backendContext) fail('context_unavailable', '原后台上下文不可用,不能自动重做。')
28
+ if (terminal && task.notificationStatus === 'delivering') fail('update_busy', '上一轮结果正在投递,请稍后继续。')
29
+ if (terminal && !task.terminalHandled && task.runner) fail('update_busy', '上一轮正在收尾,请稍后继续。')
30
+ if (!terminal && task.backendPhase === 'settled') fail('update_busy', '当前执行正在收尾,请稍后继续。')
31
+
32
+ let receipt
33
+ const conversation = operations.conversationSnapshot?.(context)
34
+ if (!terminal && task.status !== 'queued' && task.backendPhase === 'active') {
35
+ receipt = backend.update(task.id, {
36
+ instruction: text, inputParts, ...(conversation ? { conversation } : {}),
37
+ }, { ownerId: task.ownerId })
38
+ }
39
+ const entry = {
40
+ instruction: text, inputParts, submissionKey: submissionKey || null,
41
+ createdAt: Date.now(), status: receipt ? 'pending' : 'queued',
42
+ ...(conversation ? { conversation } : {}),
43
+ }
44
+ manager.recordUpdate(task, entry)
45
+ // A changed requirement is not permission for newly introduced operations.
46
+ operations.permissionPolicy?.tasks.delete(operations.permissionPolicy.taskKey(task))
47
+ if (terminal) {
48
+ // Continuation is adapter-owned, including completed delegated work. Capture
49
+ // it before resume clears the previous execution's delegation state.
50
+ manager.resume(task, operations.executionFor(task, {
51
+ resumeContext: task.backendContext,
52
+ }))
53
+ }
54
+ if (receipt) {
55
+ Promise.resolve(receipt.completion).then(() => {
56
+ entry.status = 'delivered'
57
+ manager.emit(TaskDomainEvent.UPDATED, task)
58
+ }, error => {
59
+ entry.status = 'failed'
60
+ entry.error = error.message
61
+ manager.emit(TaskDomainEvent.UPDATED, task)
62
+ })
63
+ }
64
+ return { status: 'accepted', taskId: task.id }
65
+ }
66
+
67
+ export function inputWithUpdates(task, input) {
68
+ const queued = (task.updates || []).filter(entry => entry.status === 'queued')
69
+ if (!queued.length) return input
70
+ const instruction = [
71
+ // Native delegation context can differ from the concise card title.
72
+ input.instruction || (input.resumeContext ? `继续此前工作:${task.objective}` : task.objective),
73
+ '以下是用户按时间顺序补充的要求;存在冲突时以较新的要求为准:',
74
+ ...queued.map(entry => entry.instruction),
75
+ ].join('\n\n')
76
+ const conversation = [input.conversation, ...queued.map(entry => entry.conversation)].flat().filter(Boolean)
77
+ return { ...input, instruction,
78
+ ...(conversation.length ? { conversation } : {}),
79
+ inputParts: [
80
+ ...(input.inputParts || []), ...queued.flatMap(entry => entry.inputParts || []),
81
+ ] }
82
+ }
@@ -2,6 +2,8 @@ import { TaskDomainEvent } from './task-events.mjs'
2
2
  import { TaskStatus, transitionTask } from './task-state.mjs'
3
3
  import { nextOccurrenceAt, normalizeRecurrence } from './recurrence.mjs'
4
4
 
5
+ const MAX_TIMEOUT_MS = 2_147_483_647
6
+
5
7
  function finiteTimestamp(value) {
6
8
  if (value === null || value === undefined || value === '') return null
7
9
  const timestamp = Number(value)
@@ -161,7 +163,9 @@ export class ReminderScheduler {
161
163
  .map(t => t.schedule.at)
162
164
  .sort((a, b) => a - b)[0]
163
165
  if (!next) return
164
- const delay = next - now
166
+ // Longer delays overflow Node's timer range and become 1 ms. Wake at the
167
+ // supported limit, then fire() rechecks the due time and arms the remainder.
168
+ const delay = Math.min(next - now, MAX_TIMEOUT_MS)
165
169
  this.timer = setTimeout(() => this.fire(), delay)
166
170
  this.timer.unref?.()
167
171
  }
@@ -57,8 +57,8 @@ export class TaskManager {
57
57
  constructor({
58
58
  runner = null,
59
59
  store = null,
60
- maxConcurrent = 4,
61
- maxConcurrentPerOwner = 2,
60
+ maxConcurrent = 1,
61
+ maxConcurrentPerOwner = 1,
62
62
  systemMaxConcurrent = 2,
63
63
  // 终态任务保留 3 天而非 24 小时:语音场景里「周五派的活周一问」很常见,
64
64
  // 24 小时会让隔天的查询就拿不到状态,用户只能重新派一次。
@@ -183,6 +183,12 @@ export class TaskManager {
183
183
  taskId: saved.id,
184
184
  })
185
185
  const recovery = taskRecoveryAction(saved)
186
+ for (const update of saved.updates || []) {
187
+ if (!['queued', 'pending'].includes(update.status)) continue
188
+ update.status = 'failed'
189
+ update.error = '网关重启,无法确认追加要求的投递结果;没有自动重发。'
190
+ recoveryChanged = true
191
+ }
186
192
  if (recovery !== TaskRecoveryAction.RESTORE) recoveryChanged = true
187
193
  if (saved.notificationStatus === 'delivering') recoveryChanged = true
188
194
  // Scheduled work survives intact. A reminder that was already firing
@@ -339,8 +345,8 @@ export class TaskManager {
339
345
  task.canceler = typeof canceler === 'function'
340
346
  ? context => canceler(snapshot, context)
341
347
  : null
342
- this.start(task)
343
348
  }
349
+ this.drain()
344
350
  }
345
351
 
346
352
  persist() {
@@ -355,6 +361,35 @@ export class TaskManager {
355
361
  return this.repository.allocateTaskId()
356
362
  }
357
363
 
364
+ recordUpdate(task, update) {
365
+ task.updates ||= []
366
+ task.updates.push(update)
367
+ this.emit(TaskDomainEvent.UPDATED, task)
368
+ }
369
+
370
+ resume(task, { runner, canceler }) {
371
+ if (!isTaskTerminal(task.status) || (!task.terminalHandled && task.runner)) {
372
+ throw new Error('Task has not finished settling')
373
+ }
374
+ task.previousResults = [...(task.previousResults || []), {
375
+ result: task.result, error: task.error, status: task.status, completedAt: task.completedAt,
376
+ }].slice(-10)
377
+ transitionTask(task, TaskStatus.QUEUED)
378
+ Object.assign(task, {
379
+ runner, canceler, executionVersion: (task.executionVersion || 0) + 1,
380
+ queuedAt: Date.now(),
381
+ backendPhase: null,
382
+ result: null, error: null, message: null, activity: [], delegation: null,
383
+ startedAt: null, completedAt: null, elapsedMs: 0, terminalHandled: false,
384
+ authorization: null, inputRequest: null, cancellation: null, cancelPromise: null,
385
+ notificationStatus: 'none', notificationClaimantId: null, notificationClaimedAt: null,
386
+ notificationDeliveredAt: null,
387
+ })
388
+ task.promise = new Promise(resolve => { task.resolve = resolve })
389
+ this.emit(TaskDomainEvent.UPDATED, task)
390
+ queueMicrotask(() => this.drain())
391
+ }
392
+
358
393
  subscribe(listener, { scope = TaskScope.USER } = {}) {
359
394
  const subscription = { listener, scope }
360
395
  this.listeners.add(subscription)
@@ -612,7 +647,7 @@ export class TaskManager {
612
647
  .filter(task => task.status === 'queued')
613
648
  .sort((left, right) => (
614
649
  Number(right.priority || 0) - Number(left.priority || 0)
615
- || left.createdAt - right.createdAt
650
+ || (left.queuedAt || left.createdAt) - (right.queuedAt || right.createdAt)
616
651
  ))
617
652
  for (const task of queued) {
618
653
  if (!this.schedulerFor(task).canStart(task)) continue
@@ -621,6 +656,8 @@ export class TaskManager {
621
656
  }
622
657
 
623
658
  start(task) {
659
+ const executionVersion = task.executionVersion || 0
660
+ const resolveExecution = task.resolve
624
661
  task.recoveryPersistedStatus = null
625
662
  transitionTask(task, TaskStatus.RUNNING)
626
663
  task.startedAt = Date.now()
@@ -635,6 +672,7 @@ export class TaskManager {
635
672
  }, this.progressEventIntervalMs)
636
673
  task.progressTimer.unref?.()
637
674
  const onEvent = event => {
675
+ if ((task.executionVersion || 0) !== executionVersion || task.terminalHandled) return
638
676
  if (
639
677
  event?.type === BackendEventType.AUTHORIZATION_REQUESTED
640
678
  && event.permission
@@ -696,7 +734,14 @@ export class TaskManager {
696
734
  transitionTask(task, TaskStatus.DELEGATED)
697
735
  const { presentation: _presentation, ...delegation } = event.delegation
698
736
  task.delegation = delegation
699
- this.releaseScheduler(task)
737
+ // Delegation changes the execution topology. Only a new successful
738
+ // outcome may checkpoint its adapter-owned continuation again.
739
+ task.backendContext = null
740
+ // Only an explicit adapter yield releases admission. Delegation alone
741
+ // (including ordinary A2A/native delegation) still occupies its slot.
742
+ // The Task and runner remain live while independent delegated work runs;
743
+ // releaseScheduler also makes repeated yields and terminal cleanup safe.
744
+ if (event.yielded === true) this.releaseScheduler(task)
700
745
  this.emit(TaskDomainEvent.DELEGATED, task)
701
746
  this.drain()
702
747
  return
@@ -796,12 +841,17 @@ export class TaskManager {
796
841
  })
797
842
  .then(outcome => {
798
843
  if (
799
- task.terminalHandled
844
+ (task.executionVersion || 0) !== executionVersion || task.terminalHandled
800
845
  || ['cancelling', 'cancelled'].includes(task.status)
801
846
  ) return
802
847
  this.flushProgress(task)
803
848
  transitionTask(task, TaskStatus.COMPLETED)
804
849
  task.result = String(outcome?.content ?? outcome ?? '').trim()
850
+ // Adapters may revoke an older continuation explicitly; omission keeps
851
+ // the prior context for backwards-compatible continuation outcomes.
852
+ if (outcome?.continuation || outcome?.continuation === null) {
853
+ task.backendContext = outcome.continuation
854
+ }
805
855
  task.artifacts = mergeArtifacts(
806
856
  task.artifacts,
807
857
  artifactsFromOutcome(outcome),
@@ -809,7 +859,7 @@ export class TaskManager {
809
859
  })
810
860
  .catch(error => {
811
861
  if (
812
- task.terminalHandled
862
+ (task.executionVersion || 0) !== executionVersion || task.terminalHandled
813
863
  || ['cancelling', 'cancelled'].includes(task.status)
814
864
  ) return
815
865
  this.flushProgress(task)
@@ -817,7 +867,7 @@ export class TaskManager {
817
867
  task.error = error?.message || String(error)
818
868
  })
819
869
  .finally(() => {
820
- if (task.terminalHandled) return
870
+ if ((task.executionVersion || 0) !== executionVersion || task.terminalHandled) return
821
871
  clearInterval(task.progressTimer)
822
872
  task.progressTimer = null
823
873
  if (task.timeoutTimer) { clearTimeout(task.timeoutTimer); task.timeoutTimer = null }
@@ -837,16 +887,17 @@ export class TaskManager {
837
887
  task.notificationStatus = shouldNotifyTaskCompletion(task) ? 'pending' : 'none'
838
888
  task.terminalHandled = true
839
889
  this.releaseScheduler(task)
890
+ const completedSnapshot = publicTask(task)
840
891
  this.emit(
841
892
  task.status === 'completed'
842
893
  ? TaskDomainEvent.COMPLETED
843
894
  : TaskDomainEvent.FAILED,
844
895
  task,
845
896
  )
846
- if (shouldNotifyTaskCompletion(task)) {
897
+ if ((task.executionVersion || 0) === executionVersion && shouldNotifyTaskCompletion(task)) {
847
898
  this.emit(TaskDomainEvent.NOTIFICATION_PENDING, task)
848
899
  }
849
- task.resolve?.(publicTask(task))
900
+ resolveExecution?.(completedSnapshot)
850
901
  this.prune()
851
902
  this.drain()
852
903
  })
@@ -890,6 +941,8 @@ export class TaskManager {
890
941
  return this.finishCancellation(task)
891
942
  })
892
943
  .catch(error => {
944
+ const executionVersion = task.executionVersion || 0
945
+ const resolveExecution = task.resolve
893
946
  task.abortController?.abort(
894
947
  error instanceof Error ? error : new Error(String(error)),
895
948
  )
@@ -908,14 +961,15 @@ export class TaskManager {
908
961
  task.notificationStatus = shouldNotifyTaskCompletion(task) ? 'pending' : 'none'
909
962
  task.terminalHandled = true
910
963
  this.releaseScheduler(task)
964
+ const failedSnapshot = publicTask(task)
911
965
  this.emit(TaskDomainEvent.FAILED, task)
912
- if (shouldNotifyTaskCompletion(task)) {
966
+ if ((task.executionVersion || 0) === executionVersion && shouldNotifyTaskCompletion(task)) {
913
967
  this.emit(TaskDomainEvent.NOTIFICATION_PENDING, task)
914
968
  }
915
- task.resolve?.(publicTask(task))
969
+ resolveExecution?.(failedSnapshot)
916
970
  this.prune()
917
971
  this.drain()
918
- return publicTask(task)
972
+ return failedSnapshot
919
973
  })
920
974
  return task.cancelPromise
921
975
  }
@@ -939,6 +993,8 @@ export class TaskManager {
939
993
  }
940
994
 
941
995
  finishCancellation(task) {
996
+ const resolveExecution = task.resolve
997
+ task.recoveryPersistedStatus = null
942
998
  transitionTask(task, TaskStatus.CANCELLED)
943
999
  task.authorization = null
944
1000
  task.inputRequest = null
@@ -954,11 +1010,12 @@ export class TaskManager {
954
1010
  if (task.timeoutTimer) { clearTimeout(task.timeoutTimer); task.timeoutTimer = null }
955
1011
  task.abortController = null
956
1012
  this.releaseScheduler(task)
1013
+ const cancelledSnapshot = publicTask(task)
957
1014
  this.emit(TaskDomainEvent.CANCELLED, task)
958
- task.resolve?.(publicTask(task))
1015
+ resolveExecution?.(cancelledSnapshot)
959
1016
  this.prune()
960
1017
  this.drain()
961
- return publicTask(task)
1018
+ return cancelledSnapshot
962
1019
  }
963
1020
 
964
1021
  get(id, { ownerId, scope = TaskScope.USER } = {}) {
@@ -18,6 +18,17 @@ const REPLAYABLE_REMINDER = new Set([
18
18
  TaskStatus.RUNNING,
19
19
  ])
20
20
 
21
+ function hasRecoverableDelegation(delegation) {
22
+ // A multi-target checkpoint is all-or-nothing: never reattach only its valid
23
+ // children, or fall back to a legacy top-level id when targets is malformed.
24
+ const targets = delegation && Object.hasOwn(delegation, 'targets')
25
+ ? delegation.targets : [delegation]
26
+ return Array.isArray(targets) && targets.length > 0 && targets.every(target => (
27
+ typeof target?.id === 'string' && target.id.trim()
28
+ && typeof target?.sessionId === 'string' && target.sessionId.trim()
29
+ ))
30
+ }
31
+
21
32
  export function taskRecoveryAction(task) {
22
33
  if (task?.status === TaskStatus.SCHEDULED) {
23
34
  return TaskRecoveryAction.RESCHEDULE
@@ -34,8 +45,7 @@ export function taskRecoveryAction(task) {
34
45
  if (
35
46
  isUserWork(task)
36
47
  && [TaskStatus.DELEGATED, TaskStatus.FINALIZING].includes(task?.status)
37
- && task?.delegation?.id
38
- && task?.delegation?.sessionId
48
+ && hasRecoverableDelegation(task?.delegation)
39
49
  ) {
40
50
  return TaskRecoveryAction.REATTACH
41
51
  }
@@ -1,15 +1,15 @@
1
1
  function limit(value, fallback) {
2
2
  const parsed = Number(value)
3
- return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback
3
+ return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : fallback
4
4
  }
5
5
 
6
6
  export class TaskScheduler {
7
7
  constructor({
8
- maxConcurrent = 4,
9
- maxConcurrentPerOwner = 2,
8
+ maxConcurrent = 1,
9
+ maxConcurrentPerOwner = 1,
10
10
  } = {}) {
11
- this.maxConcurrent = limit(maxConcurrent, 4)
12
- this.maxConcurrentPerOwner = limit(maxConcurrentPerOwner, 2)
11
+ this.maxConcurrent = limit(maxConcurrent, 1)
12
+ this.maxConcurrentPerOwner = limit(maxConcurrentPerOwner, 1)
13
13
  this.active = new Map()
14
14
  }
15
15
 
@@ -48,6 +48,8 @@ const TERMINAL = new Set([
48
48
  ])
49
49
  const KNOWN = new Set(Object.values(TaskStatus))
50
50
  const TRANSITIONS = new Map([
51
+ ...[TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED]
52
+ .map(status => [status, new Set([TaskStatus.QUEUED])]),
51
53
  [TaskStatus.SCHEDULED, new Set([
52
54
  TaskStatus.QUEUED,
53
55
  TaskStatus.FAILED,
@@ -151,6 +153,12 @@ export function publicTask(task, { now = Date.now() } = {}) {
151
153
  ...(task.seriesId ? { seriesId: task.seriesId } : {}),
152
154
  parentTaskId: task.parentTaskId || null,
153
155
  objective: task.objective,
156
+ ...(task.executionVersion ? { revision: task.executionVersion } : {}),
157
+ ...(task.updates?.length ? {
158
+ updates: task.updates.map(({ instruction, status, error, createdAt }) => ({
159
+ instruction, status, ...(error ? { error } : {}), createdAt,
160
+ })),
161
+ } : {}),
154
162
  ownerId: task.ownerId,
155
163
  sessionId: task.sessionId,
156
164
  turnId: task.turnId,
@@ -196,6 +204,11 @@ export function persistedTask(task) {
196
204
  saved.status = task.recoveryPersistedStatus
197
205
  }
198
206
  saved.submissionKey = task.submissionKey || null
207
+ if (task.updates?.length) saved.updates = task.updates.map(entry => ({ ...entry }))
208
+ if (task.backendContext) saved.backendContext = task.backendContext
209
+ if (task.previousResults?.length) saved.previousResults = task.previousResults
210
+ if (task.executionVersion) saved.executionVersion = task.executionVersion
211
+ if (task.queuedAt) saved.queuedAt = task.queuedAt
199
212
  saved.delegation = task.delegation
200
213
  ? { ...task.delegation }
201
214
  : null
@@ -190,11 +190,13 @@ export function attachGatewayClientTransport(server, {
190
190
  let admitted = false
191
191
  let clientLease = null
192
192
  let runtimeMessageChain = Promise.resolve()
193
+ const extensionCleanups = new Set()
193
194
  const voiceClient = {
194
195
  ws,
195
196
  descriptor,
196
197
  applyInputSuspension: status => sessionRuntime.applyInputSuspension(status),
197
198
  realtimeStatus: () => sessionRuntime.status(),
199
+ inputState: () => sessionRuntime.inputState(),
198
200
  isAlive: () => ws.readyState === WebSocket.OPEN,
199
201
  deactivate: replacement => sessionRuntime.deactivate(replacement?.descriptor),
200
202
  }
@@ -328,6 +330,18 @@ export function attachGatewayClientTransport(server, {
328
330
  const result = await clientEventRouter.publish(message, {
329
331
  source: runtimeSource(),
330
332
  effects: {
333
+ setExternalInput(enabled, options) { sessionRuntime.setExternalInput(enabled, options) },
334
+ onRealtimeEvent(listener) { return sessionRuntime.onRealtimeEvent(listener) },
335
+ appendAudio(audio) { sessionRuntime.handleClientEvent({ type: GatewayClientEvent.AUDIO_APPEND, audio }) },
336
+ setInputCollecting(active) { sessionRuntime.setInputCollecting(active) },
337
+ submitInput(parts) { sessionRuntime.submitExternalInput(parts) },
338
+ publishClientState(state, data) {
339
+ send(ws, { type: GatewayServerEvent.CLIENT_STATE, state, data })
340
+ },
341
+ onDisconnect(cleanup) {
342
+ extensionCleanups.add(cleanup)
343
+ return () => extensionCleanups.delete(cleanup)
344
+ },
331
345
  setAssistantProfile(profile) {
332
346
  // Only a server-registered Client Event handler can reach this
333
347
  // effect. The Client supplies a schema-validated identifier,
@@ -448,6 +462,7 @@ export function attachGatewayClientTransport(server, {
448
462
  sessionRuntime.handleClientEvent(event, {
449
463
  descriptor,
450
464
  capabilities: clientProtocol.capabilities,
465
+ capabilitiesNegotiated: clientProtocol.mode === 'v6',
451
466
  })
452
467
  })
453
468
 
@@ -463,6 +478,12 @@ export function attachGatewayClientTransport(server, {
463
478
  closeCode: Number(code),
464
479
  closeReason: reason?.toString() || undefined,
465
480
  })
481
+ for (const cleanup of extensionCleanups) {
482
+ try { cleanup() } catch (error) {
483
+ connectionLogger.warn('client_extension.cleanup_failed', { error: error.message })
484
+ }
485
+ }
486
+ extensionCleanups.clear()
466
487
  sessionRuntime.close()
467
488
  const connections = voiceConnections.get(ownerId)
468
489
  connections?.delete(voiceClient)
@@ -522,6 +543,20 @@ export function attachGatewayClientTransport(server, {
522
543
  wss.close(() => resolveClose())
523
544
  })
524
545
  },
546
+ inputStatus({ ownerId } = {}) {
547
+ const clients = []
548
+ for (const [owner, connections] of voiceConnections) {
549
+ if (ownerId !== undefined && owner !== ownerId) continue
550
+ const active = activeVoiceClients.active(owner)
551
+ if (!active || !connections.has(active) || !active.isAlive()) continue
552
+ clients.push({ clientType: active.descriptor.type, ...active.inputState() })
553
+ }
554
+ return {
555
+ inputEnabled: clients.length ? clients.some(client => client.inputEnabled) : null,
556
+ inputActive: clients.some(client => client.inputActive),
557
+ clients,
558
+ }
559
+ },
525
560
  status() {
526
561
  const byType = { desktop: 0, cli: 0, web: 0 }
527
562
  const realtime = {
@@ -39,7 +39,7 @@ export class WebRtcConnection extends EventEmitter {
39
39
  ![GatewayClientCapability.SESSION_HEARTBEAT, GatewayClientCapability.CLIENT_ACTION_ENTER_SLEEP].includes(capability)
40
40
  && (this.video || capability !== GatewayClientCapability.INPUT_IMAGE_BUFFER)
41
41
  )), ...this.clientActions.map(name => `client.actions.${name}`)])],
42
- connection: { provider: this.provider.key, voice_enabled: true, input_enabled: true, output_enabled: true },
42
+ connection: { provider: this.provider.provider || this.provider.key, voice_enabled: true, input_enabled: true, output_enabled: true },
43
43
  takeover: this.takeover,
44
44
  }))
45
45
  }
@@ -138,6 +138,7 @@ export class AnnouncementManager {
138
138
  kind: task.kind,
139
139
  objective: task.objective,
140
140
  result: task.result,
141
+ updates: task.updates,
141
142
  completedAt: task.completedAt,
142
143
  scheduledAt: task.schedule?.at,
143
144
  recurrence: task.schedule?.recurrence,
@@ -464,6 +465,8 @@ export function formatWorkResults(announcements) {
464
465
  `task_id: ${item.taskId}`,
465
466
  `状态: ${item.status}`,
466
467
  item.objective ? `工作: ${item.objective}` : '',
468
+ ...(item.updates || []).filter(update => update.status === 'failed')
469
+ .slice(-3).map(update => `未确认应用的调整: ${update.instruction}\n原因: ${update.error || '投递失败'}`),
467
470
  item.status === 'completed'
468
471
  ? `结果: ${String(item.result || '').trim()}`
469
472
  : `错误: ${String(item.error || '').trim()}`,