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
@@ -0,0 +1,139 @@
1
+ const MIN_INTERVAL_MS = 5_000
2
+
3
+ // PCM16 length from base64 size. Never decode, retain, or report media.
4
+ function pcmBytes(base64) {
5
+ if (typeof base64 !== 'string' || !base64.length) return 0
6
+ const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0
7
+ return Math.max(0, Math.floor(base64.length * 3 / 4) - padding)
8
+ }
9
+
10
+ function windowCounters() {
11
+ return { packets: 0, bytes: 0, gapCount: 0, gapTotalMs: 0, gapMaxMs: 0 }
12
+ }
13
+
14
+ /** Numeric observations, independent of provider event names. Input includes
15
+ * synthetic silence accepted by the WebSocket, not confirmed remote receipt.
16
+ * Output measures normalized PCM, excluding native packets filtered by adapters.
17
+ * Regular reports are bounded to one per five seconds; close flushes the tail.
18
+ */
19
+ export function createAudioStreamDiagnostics({
20
+ inputSampleRate,
21
+ outputSampleRate,
22
+ onReport,
23
+ getBufferedAmount = () => 0,
24
+ intervalMs = MIN_INTERVAL_MS,
25
+ now = () => performance.now(),
26
+ schedule = (callback, delay) => setInterval(callback, delay),
27
+ cancel = timer => clearInterval(timer),
28
+ } = {}) {
29
+ const periodMs = Math.max(MIN_INTERVAL_MS, Number(intervalMs) || MIN_INTERVAL_MS)
30
+ let active = false
31
+ let timer = null
32
+ let startedAt = 0
33
+ let windowStartedAt = 0
34
+ let nextTickAt = 0
35
+ let monitorTickDelayMs = 0
36
+ let input = windowCounters()
37
+ let clientInput = windowCounters()
38
+ let output = windowCounters()
39
+ let lastInputAt = null
40
+ let lastClientInputAt = null
41
+ let lastOutputAt = null
42
+ let bufferedBytesPeak = 0
43
+
44
+ const sampleBuffer = () => {
45
+ let value = 0
46
+ try { value = Number(getBufferedAmount()) || 0 } catch { /* Observation is optional. */ }
47
+ value = Number.isFinite(value) ? Math.max(0, value) : 0
48
+ bufferedBytesPeak = Math.max(bufferedBytesPeak, value)
49
+ return value
50
+ }
51
+ const audioMs = (bytes, rate) => Number.isFinite(rate) && rate > 0
52
+ ? Math.round(bytes / (2 * rate) * 1_000) : null
53
+ const meanGap = counters => counters.gapCount ? Math.round(counters.gapTotalMs / counters.gapCount) : null
54
+ const report = reason => {
55
+ if (!active) return
56
+ const at = now()
57
+ const bufferedBytes = sampleBuffer()
58
+ const fields = {
59
+ reason,
60
+ inputScope: 'sent_pcm',
61
+ outputScope: 'normalized_pcm',
62
+ windowMs: Math.round(Math.max(0, at - windowStartedAt)),
63
+ sessionAgeMs: Math.round(Math.max(0, at - startedAt)),
64
+ monitorTickDelayMs,
65
+ inputPackets: input.packets,
66
+ inputPcmBytes: input.bytes,
67
+ inputAudioMs: audioMs(input.bytes, inputSampleRate),
68
+ inputGapMaxMs: Math.round(input.gapMaxMs),
69
+ inputGapMeanMs: meanGap(input),
70
+ clientInputPackets: clientInput.packets,
71
+ clientInputAudioMs: audioMs(clientInput.bytes, inputSampleRate),
72
+ lastClientInputAgeMs: lastClientInputAt === null ? null : Math.round(Math.max(0, at - lastClientInputAt)),
73
+ outputPackets: output.packets,
74
+ outputPcmBytes: output.bytes,
75
+ outputAudioMs: audioMs(output.bytes, outputSampleRate),
76
+ outputGapMaxMs: Math.round(output.gapMaxMs),
77
+ outputGapMeanMs: meanGap(output),
78
+ lastInputAgeMs: lastInputAt === null ? null : Math.round(Math.max(0, at - lastInputAt)),
79
+ lastOutputAgeMs: lastOutputAt === null ? null : Math.round(Math.max(0, at - lastOutputAt)),
80
+ bufferedBytes,
81
+ bufferedBytesPeak,
82
+ }
83
+ input = windowCounters()
84
+ clientInput = windowCounters()
85
+ output = windowCounters()
86
+ windowStartedAt = at
87
+ bufferedBytesPeak = bufferedBytes
88
+ try { onReport?.(fields) } catch { /* Diagnostics never control audio or transport. */ }
89
+ }
90
+ const observe = (counters, base64, previousAt) => {
91
+ if (!active) return previousAt
92
+ const bytes = pcmBytes(base64)
93
+ if (!bytes) return previousAt
94
+ const at = now()
95
+ counters.packets++
96
+ counters.bytes += bytes
97
+ if (previousAt !== null) {
98
+ const gap = Math.max(0, at - previousAt)
99
+ counters.gapCount++
100
+ counters.gapTotalMs += gap
101
+ counters.gapMaxMs = Math.max(counters.gapMaxMs, gap)
102
+ }
103
+ sampleBuffer()
104
+ return at
105
+ }
106
+
107
+ return {
108
+ start() {
109
+ if (active) return
110
+ active = true
111
+ startedAt = windowStartedAt = now()
112
+ nextTickAt = startedAt + periodMs
113
+ monitorTickDelayMs = 0
114
+ input = windowCounters()
115
+ clientInput = windowCounters()
116
+ output = windowCounters()
117
+ lastInputAt = lastClientInputAt = lastOutputAt = null
118
+ bufferedBytesPeak = 0
119
+ timer = schedule(() => {
120
+ const at = now()
121
+ monitorTickDelayMs = Math.round(Math.max(0, at - nextTickAt))
122
+ nextTickAt = at + periodMs
123
+ report('interval')
124
+ }, periodMs)
125
+ timer?.unref?.()
126
+ },
127
+ input(base64) { lastInputAt = observe(input, base64, lastInputAt) },
128
+ clientInput(base64) { lastClientInputAt = observe(clientInput, base64, lastClientInputAt) },
129
+ output(base64) { lastOutputAt = observe(output, base64, lastOutputAt) },
130
+ sampleBuffer,
131
+ stop() {
132
+ if (!active) return
133
+ cancel(timer)
134
+ timer = null
135
+ report('closed')
136
+ active = false
137
+ },
138
+ }
139
+ }
@@ -0,0 +1,360 @@
1
+ import { TaskDomainEvent as Event } from '../task/task-events.mjs'
2
+ import { TaskNotificationPolicy } from '../task/task-state.mjs'
3
+ import { frontendInputProjection, inputFileParts, inputPartRef, inputText } from '../../../shared/input-parts.mjs'
4
+
5
+ const TERMINAL = new Set([Event.COMPLETED, Event.FAILED, Event.CANCELLED])
6
+ const STATE_CHANGES = new Set([Event.ACCEPTED, Event.SCHEDULED, Event.SCHEDULED_FIRED,
7
+ Event.RUNNING, Event.DELEGATED, Event.FINALIZING, Event.CANCELLING,
8
+ Event.PERMISSION_REQUESTED, Event.PERMISSION_RESOLVED, Event.INPUT_REQUESTED, Event.INPUT_RESOLVED,
9
+ ...TERMINAL])
10
+ const MAX_DELEGATIONS = 256
11
+ const MAX_UPDATES = 256
12
+ const text = value => typeof value === 'string' ? value.trim() : ''
13
+
14
+ function taskStateText(task) {
15
+ return `task_id: ${task.id}\nstatus: ${task.status}\npending_permission: ${
16
+ task.authorization?.status === 'pending'}\npending_input: ${task.inputRequest?.status === 'pending'}`
17
+ }
18
+
19
+ function taskInput(units, assets, context) {
20
+ const instruction = units.map(unit => text(unit.instruction)).join('\n\n')
21
+ // Native delegations have no reliable local turn correlation. Resolve only
22
+ // explicit shared input metadata, never the latest turn's files, filenames,
23
+ // arbitrary URLs, or identifiers mentioned in ordinary task prose.
24
+ const refs = new Set()
25
+ for (const match of instruction.matchAll(/<input_parts>\s*([\s\S]*?)\s*<\/input_parts>/g)) {
26
+ let parts
27
+ try { parts = JSON.parse(match[1]) } catch { throw new Error('附件引用格式不完整,请保留原始 input_parts 元数据后重试。') }
28
+ if (!Array.isArray(parts)) throw new Error('附件引用必须使用原始 input_parts 元数据。')
29
+ for (const part of parts) {
30
+ if (part?.type !== 'file') continue
31
+ if (!/^input_[1-9]\d*$/.test(part.id || '')) throw new Error('附件缺少有效的输入引用,请重新提供附件。')
32
+ refs.add(part.id)
33
+ }
34
+ }
35
+ return { instruction, inputParts: refs.size ? assets.resolve({ ...context, refs: [...refs] }) : [] }
36
+ }
37
+
38
+ /** Connect native voice delegations to the existing execution core, not to a
39
+ * speech queue. Bindings belong to one frontend connection; Tasks do not.
40
+ * Providers normalize each input/addition to { objective, instruction } and
41
+ * render structured input requests using their own supported reply mechanism. */
42
+ export class NativeDelegationRuntime {
43
+ constructor({ taskManager, taskOperations, ownerId, sessionId, backendAvailability,
44
+ getFrontend, getTurn, getInputContext = () => null, inputAssets, onResult = () => {},
45
+ onPresentRequest = () => {}, onError = () => {},
46
+ }) {
47
+ Object.assign(this, { taskManager, taskOperations, ownerId, sessionId, backendAvailability,
48
+ getFrontend, getTurn, getInputContext, inputAssets, onResult, onPresentRequest, onError })
49
+ this.bindings = new Map()
50
+ this.tasks = new Map()
51
+ this.stateBinding = null
52
+ this.closed = false
53
+ this.unsubscribe = taskManager.subscribe(event => this.observe(event))
54
+ }
55
+
56
+ current(binding) {
57
+ return !this.closed && !binding.detached && binding.frontend === this.getFrontend()
58
+ && binding.frontend.ready === true
59
+ }
60
+
61
+ binding(key, delegationId, providerSessionId = null) {
62
+ if (this.bindings.has(key)) return this.bindings.get(key)
63
+ if (this.bindings.size >= MAX_DELEGATIONS) {
64
+ this.onError(new Error('当前语音会话的委派数量已达上限,请新建会话。'))
65
+ return null
66
+ }
67
+ const binding = { frontend: this.getFrontend(), delegationId, providerSessionId, events: new Set(), inputs: new Set(),
68
+ queue: [], results: new Set(), requests: new Map(), taskId: null, detached: false }
69
+ this.bindings.set(key, binding)
70
+ return binding
71
+ }
72
+
73
+ // A new cloud connection restores conversation, not live request state.
74
+ // Refresh facts quietly, using no old delegation ID and no replayed result.
75
+ syncTaskState() {
76
+ const frontend = this.getFrontend()
77
+ if (this.closed || !frontend?.ready || !frontend.capabilities?.nativeDelegation
78
+ || !frontend.capabilities?.nativeSessionContext) return
79
+ const tasks = this.taskOperations.list(this)
80
+ const active = this.taskOperations.list(this, { active: true })
81
+ const permissions = this.taskOperations.pendingPermissions(this)
82
+ const inputs = active.filter(task => task.status !== 'cancelling' && task.inputRequest?.status === 'pending')
83
+ const pendingIds = new Set([...permissions.values()].map(entry => entry.task.id).concat(inputs.map(task => task.id)))
84
+ const ordered = [...tasks].sort((a, b) => Number(pendingIds.has(b.id)) - Number(pendingIds.has(a.id)))
85
+ const content = [
86
+ 'Current session task state:',
87
+ `pending_permissions: ${permissions.size}`,
88
+ `pending_inputs: ${inputs.length}`,
89
+ `active_tasks: ${active.length}`,
90
+ `task_sample (${Math.min(tasks.length, 6)} of ${tasks.length}):`,
91
+ ...ordered.slice(0, 6).map(task => `${task.id}: ${task.status}${
92
+ task.workState && task.workState !== task.status ? ` (${task.workState})` : ''}`),
93
+ ].join('\n')
94
+ if (!this.current(this.stateBinding || {})) {
95
+ this.stateBinding = { frontend, delegationId: null, queue: [], detached: false }
96
+ }
97
+ if (this.stateBinding.content === content) return
98
+ this.stateBinding.content = content
99
+ this.enqueue(this.stateBinding, { kind: 'progress', content })
100
+ }
101
+
102
+ assertAvailable() {
103
+ const availability = this.backendAvailability?.snapshot()
104
+ if (availability?.configured === false || (availability?.known && availability.ok === false)) {
105
+ throw new Error('后台 Agent 未配置或当前不可用,未开始执行任务。')
106
+ }
107
+ }
108
+
109
+ submit(binding, input, context, submissionKey) {
110
+ this.assertAvailable()
111
+ // A new ordinary delegation is not a correlated answer to a pending
112
+ // request. Avoid queueing a spoken "yes" behind the very backend session
113
+ // that is waiting for approval; the existing client controls resolve it.
114
+ if (this.taskOperations.pendingPermissions(context).size
115
+ || this.taskOperations.list(context, { active: true }).some(task => task.inputRequest?.status === 'pending')) {
116
+ throw new Error('当前任务正在等待确认,请先通过客户端处理权限请求或补充问题;尚未开始新的工作。')
117
+ }
118
+ if (!text(input.objective) || !text(input.instruction)) throw new Error('委派缺少明确的任务内容,未开始执行。')
119
+ if (input.instruction.length > 16_000) throw new Error('委派内容过长,请缩小任务范围后重试。')
120
+ const task = this.taskOperations.submit({ ...input, submissionKey,
121
+ notificationPolicy: TaskNotificationPolicy.SILENT }, context)
122
+ binding.taskId = task.id
123
+ this.tasks.set(task.id, binding)
124
+ return task
125
+ }
126
+
127
+ accepted(binding) {
128
+ this.enqueue(binding, { kind: 'progress', content: `task_id: ${binding.taskId}\n请求已受理,尚未完成。` })
129
+ }
130
+
131
+ rejected(binding, error) {
132
+ // Rejecting an addition does not finish the task it tried to update.
133
+ // Only a rejected initial delegation has no execution left to report.
134
+ this.enqueue(binding, { kind: binding.taskId ? 'progress' : 'result',
135
+ content: `${binding.taskId ? `task_id: ${binding.taskId}\n` : ''}${error.message}`,
136
+ ...(!binding.taskId ? { error: { code: error.code || 'delegation_rejected', message: error.message } } : {}) })
137
+ return false
138
+ }
139
+
140
+ // Client-owned typed input does not receive a cloud delegation ID. It still
141
+ // uses the same Task and result channel, with a session-wide update (null ID).
142
+ // Only registered parts from this real user turn are accepted; no historical
143
+ // file or authorization is inferred from ordinary prose.
144
+ handleUserInput({ parts, context = {} }) {
145
+ const frontend = this.getFrontend()
146
+ if (this.closed || !frontend?.ready || !frontend.capabilities?.nativeDelegation) return false
147
+ if (!text(context.turnId) || !Array.isArray(parts) || !parts.length) return false
148
+ const key = JSON.stringify(['user', frontend.connectionId, context.turnId])
149
+ const binding = this.binding(key, null)
150
+ if (!binding || !this.current(binding)) return false
151
+ if (binding.events.has(context.turnId)) return Boolean(binding.taskId)
152
+ binding.events.add(context.turnId)
153
+ const taskContext = { ownerId: this.ownerId, sessionId: this.sessionId,
154
+ turnId: context.turnId, turnGeneration: context.turnGeneration }
155
+ try {
156
+ const refs = inputFileParts(parts).map(part => {
157
+ const ref = inputPartRef(part)
158
+ if (!ref) throw new Error('附件尚未登记,请重新提交。')
159
+ return ref
160
+ })
161
+ const inputParts = refs.length ? this.inputAssets.resolve({ ...taskContext, refs }) : []
162
+ const objective = inputText(parts) || (inputParts.length ? '用户提交的附件' : '')
163
+ const instruction = frontendInputProjection(parts)
164
+ this.submit(binding, { objective, instruction: inputText(parts) ? instruction
165
+ : `用户只提交了附件,尚未说明目的。先询问一个必要问题,不要自行决定执行操作。\n${instruction}`,
166
+ inputParts }, taskContext, JSON.stringify(['native', key]))
167
+ this.accepted(binding)
168
+ return true
169
+ } catch (error) {
170
+ return this.rejected(binding, error)
171
+ }
172
+ }
173
+
174
+ handle(event) {
175
+ const frontend = this.getFrontend()
176
+ if (this.closed || !frontend?.ready || !frontend.capabilities?.nativeDelegation) return false
177
+ if (!text(event.delegationId) || !text(event.eventId)) return false
178
+ const key = JSON.stringify([frontend.connectionId, event.providerSessionId, event.delegationId])
179
+ const binding = this.binding(key, event.delegationId, event.providerSessionId)
180
+ if (!binding || !this.current(binding)) return false
181
+ if (binding.events.has(event.eventId)) return Boolean(binding.taskId)
182
+ if (binding.events.size >= MAX_UPDATES) {
183
+ this.onError(new Error('当前委派的更新数量已达上限。'))
184
+ return false
185
+ }
186
+ binding.events.add(event.eventId)
187
+ // Timestamp-based providers can finish resolving delegation text after a
188
+ // newer input has begun. An unresolved explicit input must not borrow that
189
+ // newer turn; providers without input correlation keep their existing path.
190
+ const inputContext = Object.hasOwn(event, 'inputItemId')
191
+ ? (text(event.inputItemId) ? this.getInputContext(event.inputItemId) : null)
192
+ : this.getTurn()
193
+ const context = { ownerId: this.ownerId, sessionId: this.sessionId,
194
+ ...(inputContext ? { turnId: inputContext.turnId, turnGeneration: inputContext.turnGeneration } : {}) }
195
+ try {
196
+ this.assertAvailable()
197
+ // Providers supply execution-ready text, not their native context schema.
198
+ // Later additions update the same task without resubmitting its base input.
199
+ const additions = Array.isArray(event.additions) ? event.additions : []
200
+ const candidates = binding.taskId && additions.length ? additions : [event.input, ...additions]
201
+ const inputs = new Set(binding.inputs)
202
+ const units = candidates.filter(unit => {
203
+ const identity = text(unit?.instruction)
204
+ if (!text(unit?.objective) || !identity || inputs.has(identity)) return false
205
+ inputs.add(identity)
206
+ return true
207
+ })
208
+ if (!units.length) {
209
+ if (!binding.taskId) throw new Error('委派缺少明确的任务内容,未开始执行。')
210
+ return true
211
+ }
212
+ const input = taskInput(units, this.inputAssets, context)
213
+ if (input.instruction.length > 16_000) throw new Error('委派内容过长,请缩小任务范围后重试。')
214
+ const submissionKey = JSON.stringify(['native', key, event.eventId])
215
+ if (!binding.taskId) {
216
+ this.submit(binding, { ...input, objective: text(event.input?.objective) || text(units[0].objective) }, context, submissionKey)
217
+ } else {
218
+ const task = this.taskOperations.get(binding.taskId, context)
219
+ // Task additions are not an authorization or a correlated user reply.
220
+ if (task?.authorization?.status === 'pending' || task?.inputRequest?.status === 'pending') {
221
+ throw new Error('任务正在等待用户回答。请先回复对应的权限或任务提问,不要作为普通任务补充。')
222
+ }
223
+ this.taskOperations.update({ ...input, taskId: binding.taskId, submissionKey }, context)
224
+ }
225
+ binding.inputs = inputs
226
+ this.accepted(binding)
227
+ return true
228
+ } catch (error) {
229
+ return this.rejected(binding, error)
230
+ }
231
+ }
232
+
233
+ observe(event) {
234
+ const task = event.task
235
+ if (event.ownerId !== this.ownerId || task?.sessionId !== this.sessionId) return
236
+ const binding = this.tasks.get(task.id)
237
+ // Work can outlive its original Live connection. Keep the replacement's
238
+ // status accurate without reviving that connection's delegation or speech.
239
+ if (this.stateBinding && (STATE_CHANGES.has(event.type)
240
+ || (event.type === Event.UPDATED && task.status === 'queued'))) this.syncTaskState()
241
+ if (!binding) return
242
+ if (TERMINAL.has(event.type)) {
243
+ const revision = `${task.revision || 0}:${event.type}`
244
+ if (binding.results.has(revision)) return
245
+ binding.results.add(revision)
246
+ // Record execution facts even when the cloud connection has gone away.
247
+ this.onResult(task)
248
+ binding.queue = binding.queue.filter(update => update.kind !== 'progress')
249
+ this.enqueue(binding, { kind: 'result', content: `${taskStateText(task)}\n${
250
+ task.status === 'completed' ? task.result || '任务已完成。'
251
+ : task.status === 'cancelled' ? '任务已取消。' : task.error || '任务执行失败。'}`,
252
+ ...(task.status === 'failed' ? { error: { code: 'task_failed', message: task.error || '任务执行失败。' } } : {}) })
253
+ } else if (event.type === Event.UPDATED && event.message
254
+ && task.authorization?.status !== 'pending' && task.inputRequest?.status !== 'pending') {
255
+ this.enqueue(binding, { kind: 'progress', content: `task_id: ${task.id}\n${event.message}` })
256
+ } else if ([Event.PERMISSION_REQUESTED, Event.INPUT_REQUESTED].includes(event.type)) {
257
+ const permission = event.type === Event.PERMISSION_REQUESTED
258
+ const request = permission ? event.permission || task.authorization : event.input || task.inputRequest
259
+ if (!request || binding.requests.has(request.id)) return
260
+ binding.requests.set(request.id, { permission, request })
261
+ this.presentRequest(binding, task.id, request, permission)
262
+ } else if ([Event.PERMISSION_RESOLVED, Event.INPUT_RESOLVED].includes(event.type)) {
263
+ const request = event.permission || event.input
264
+ if (request) binding.requests.delete(request.id)
265
+ const resolution = event.type === Event.PERMISSION_RESOLVED && request
266
+ ? `permission_status: ${request.status}` : '用户请求已处理。'
267
+ this.enqueue(binding, { kind: 'progress', content: `${taskStateText(task)}\n${resolution}` })
268
+ }
269
+ }
270
+
271
+ presentRequest(binding, taskId, request, permission) {
272
+ const current = () => {
273
+ const task = this.taskOperations.get(taskId, this)
274
+ if (task?.status === 'cancelling') return false
275
+ return binding.requests.has(request.id) && (permission
276
+ ? this.taskOperations.pendingPermissions(this).has(request.id)
277
+ : task?.inputRequest?.id === request.id && task.inputRequest.status === 'pending')
278
+ }
279
+ this.enqueue(binding, { kind: 'input', requestId: request.id, current, taskId,
280
+ request: { kind: permission ? 'permission' : 'input', id: request.id,
281
+ prompt: permission ? request.summary : request.prompt,
282
+ ...(!permission && request.schema ? { schema: request.schema } : {}),
283
+ ...(!permission && request.url ? { url: request.url } : {}),
284
+ },
285
+ })
286
+ }
287
+
288
+ retryPermission(requestId) {
289
+ for (const binding of this.tasks.values()) {
290
+ const entry = binding.requests.get(requestId)
291
+ if (entry?.permission) this.presentRequest(binding, binding.taskId, entry.request, true)
292
+ }
293
+ }
294
+
295
+ deliveryContext(binding, update) {
296
+ // Correlation only: never log the task text, request prompt, schema or files.
297
+ return { provider: binding.frontend.provider?.key || '', connectionId: binding.frontend.connectionId,
298
+ providerSessionId: binding.providerSessionId ?? null, taskId: binding.taskId ?? null,
299
+ delegationId: binding.delegationId, updateKind: update.kind,
300
+ taskRequestId: update.requestId ?? null, requestKind: update.request?.kind ?? null }
301
+ }
302
+
303
+ enqueue(binding, update) {
304
+ if (!this.current(binding)) return
305
+ // Coalesce unsent progress only. Requests and terminal results are ordered,
306
+ // bounded and never wait for a local speech/announcement window.
307
+ binding.queue = binding.queue.filter(pending => pending.kind !== 'progress')
308
+ if (binding.queue.length >= 64) {
309
+ this.onError(new Error('Live 任务更新积压,未自动重发;请通过客户端查看状态。'), this.deliveryContext(binding, update))
310
+ return
311
+ }
312
+ binding.queue.push(update)
313
+ if (!binding.sending) void this.flush(binding)
314
+ }
315
+
316
+ async flush(binding) {
317
+ binding.sending = true
318
+ try {
319
+ while (this.current(binding) && binding.queue.length) {
320
+ const update = binding.queue.shift()
321
+ if (update.current && !update.current()) continue
322
+ try {
323
+ const receipt = await binding.frontend.sendDelegationUpdate({ delegationId: binding.delegationId,
324
+ kind: update.kind, taskId: binding.taskId ?? null, providerSessionId: binding.providerSessionId ?? null,
325
+ ...(update.request ? { request: update.request } : { content: update.content }),
326
+ ...(update.error ? { error: update.error } : {}),
327
+ })
328
+ if (this.current(binding) && receipt?.accepted && update.requestId && update.current()) {
329
+ this.onPresentRequest(update.requestId)
330
+ }
331
+ } catch (error) {
332
+ // An uncertain receipt must not cause duplicate speech or execution.
333
+ if (this.current(binding)) this.onError(error, this.deliveryContext(binding, update))
334
+ }
335
+ }
336
+ } finally {
337
+ binding.sending = false
338
+ }
339
+ }
340
+
341
+ detach() {
342
+ if (this.stateBinding) {
343
+ this.stateBinding.detached = true
344
+ this.stateBinding.queue = []
345
+ }
346
+ for (const binding of this.bindings.values()) {
347
+ binding.detached = true
348
+ binding.queue = []
349
+ }
350
+ }
351
+
352
+ close() {
353
+ this.closed = true
354
+ this.detach()
355
+ this.unsubscribe()
356
+ this.bindings.clear()
357
+ this.tasks.clear()
358
+ this.stateBinding = null
359
+ }
360
+ }
@@ -0,0 +1,93 @@
1
+ import { config } from '../../core/config.mjs'
2
+ import { providerRuntimeConfiguration } from './runtime-configuration.mjs'
3
+ import { realtimeModelCatalog, resolveRealtimeModelProfile } from '../../../../shared/realtime-model-catalog.mjs'
4
+ import { buildLiveFrontendInstructions } from '../../frontend/frontend-tools.mjs'
5
+ import { buildRecentConversationContext } from '../../conversation/frontend-agent-context.mjs'
6
+ import { RealtimeConfigurationError } from '../realtime-errors.mjs'
7
+ import { createQwenLiveProtocol } from './qwen-live-protocol.mjs'
8
+
9
+ const connection = providerRuntimeConfiguration('dashscope-live', { provider: 'dashscope' })
10
+ const modelProfile = () => resolveRealtimeModelProfile(connection.model, 'dashscope', config.realtimeModelCatalogs)
11
+
12
+ // The endpoint model selects the Live service. session.model selects its voice
13
+ // model; keep that wire detail inside this adapter, not as a second UI setting.
14
+ const LIVE_SERVICE_MODEL = 'qwen-audio-3.1-live'
15
+ const LIVE_VOICE_MODEL = 'qwen-audio-4.0-realtime-preview'
16
+
17
+ export function qwenLiveUrl(endpoint) {
18
+ let url
19
+ try { url = new URL(endpoint) } catch {
20
+ throw new RealtimeConfigurationError('Qwen Live 需要完整的业务空间 WebSocket 服务地址,请配置 QWEN_AUDIO_REALTIME_URL')
21
+ }
22
+ if (!['wss:', 'ws:'].includes(url.protocol) || url.username || url.password) {
23
+ throw new RealtimeConfigurationError('Qwen Live 服务地址必须是无内嵌凭据的 ws:// 或 wss:// 地址')
24
+ }
25
+ if (['dashscope.aliyuncs.com', 'dashscope-intl.aliyuncs.com', 'dashscope-us.aliyuncs.com'].includes(url.hostname)
26
+ || url.pathname.endsWith('/realtime')) {
27
+ throw new RealtimeConfigurationError('Qwen Live 需要业务空间专属 /api-ws/v1/live 地址,不是 Realtime 地址')
28
+ }
29
+ url.searchParams.set('model', LIVE_SERVICE_MODEL)
30
+ return url.toString()
31
+ }
32
+
33
+ export const dashscopeLiveProvider = {
34
+ key: 'dashscope-live',
35
+ provider: 'dashscope',
36
+ label: 'DashScope',
37
+ aliases: ['qwen-audio-live'],
38
+ inputSampleRate: 16000,
39
+ outputSampleRate: 24000,
40
+ createProtocol: context => createQwenLiveProtocol(context),
41
+ capabilities: {
42
+ acknowledgesSessionUpdate: true,
43
+ mutableSession: false,
44
+ nativeDelegation: true,
45
+ nativeSessionContext: false,
46
+ automaticUserResponses: true,
47
+ contextOnlyItems: false,
48
+ clientResponses: false,
49
+ acknowledgesConversationItems: false,
50
+ conversationItemIdEcho: false,
51
+ restoreConversationContext: false,
52
+ perResponseInstructions: false,
53
+ sessionOutputVoice: true,
54
+ concurrentVoicePlayback: true,
55
+ interruptionPlaysOut: true,
56
+ pacedOutputAudio: true,
57
+ inputMuteOnSleep: true,
58
+ },
59
+ model: () => connection.model,
60
+ modelProfile,
61
+ modelCatalog: () => realtimeModelCatalog('dashscope', config.realtimeModelCatalogs).profiles,
62
+ voice: () => String(connection.voice || '').trim() || modelProfile().sessionDefaults.voice,
63
+ isConfigured: () => connection.configured && Boolean(connection.endpoint),
64
+ missingConfigurationMessage: '请配置 Qwen Live 的 API Key 与业务空间专属 WebSocket 服务地址',
65
+ connectTimeoutMessage: '连接 Qwen Audio Live 超时',
66
+ url: () => qwenLiveUrl(connection.endpoint),
67
+ headers: () => ({ Authorization: `Bearer ${connection.credential}` }),
68
+ validateSessionOptions: () => qwenLiveUrl(connection.endpoint),
69
+ classifyError: message => {
70
+ if (/unexpected server response: (?:401|403)|invalid[_ -]?api[_ -]?key|unauthorized|model[_ -]?not[_ -]?found|invalid_session_configuration/i.test(message)) return 'fatal'
71
+ if (/unexpected server response: 429|too many .*sessions|concurrent[_ -]?sessions?/i.test(message)) return 'capacity_busy'
72
+ if (/\bsession_closed.*\bcontent\b/i.test(message)) return 'content_safety'
73
+ return 'other'
74
+ },
75
+ buildSession: ({ agentContext = {}, sessionOptions = {} } = {}) => ({
76
+ instructions: [
77
+ buildLiveFrontendInstructions(agentContext),
78
+ buildRecentConversationContext(agentContext.recentMessages),
79
+ ].filter(Boolean).join('\n\n'),
80
+ model: LIVE_VOICE_MODEL,
81
+ voice: String(sessionOptions.voice || '').trim() || dashscopeLiveProvider.voice(),
82
+ modalities: ['text', 'audio'],
83
+ turn_detection: { type: 'duplex' },
84
+ input_audio_format: 'pcm',
85
+ output_audio_format: 'pcm',
86
+ tools: [],
87
+ delegation: { type: 'client' },
88
+ }),
89
+ // Native task facts travel only with a delegation received on this connection.
90
+ buildSpeakResponse: () => null,
91
+ buildResultInjection: () => null,
92
+ buildPermissionInjection: () => null,
93
+ }