qwen-audio-agent 0.9.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 (122) hide show
  1. package/CONTRIBUTING.md +58 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +5 -0
  4. package/PRIVACY.md +34 -0
  5. package/README.md +282 -0
  6. package/README_EN.md +316 -0
  7. package/SECURITY.md +32 -0
  8. package/THIRD_PARTY_NOTICES.md +26 -0
  9. package/cli/bin/qwenaudio.mjs +10 -0
  10. package/cli/package.json +13 -0
  11. package/cli/src/arguments.mjs +247 -0
  12. package/cli/src/gateway-service.mjs +386 -0
  13. package/cli/src/instance-lock.mjs +65 -0
  14. package/cli/src/launcher.mjs +217 -0
  15. package/cli/src/runtime.mjs +356 -0
  16. package/cli/src/webui.mjs +61 -0
  17. package/config/acp/workspace/AGENTS.md +13 -0
  18. package/config/codebuddy/workspace/.codebuddy/models.json +19 -0
  19. package/config/codebuddy/workspace/AGENTS.md +13 -0
  20. package/config/codex/workspace/AGENTS.md +13 -0
  21. package/config/frontend-agent/PROMPT.md +127 -0
  22. package/config/hermes/workspace/AGENTS.md +13 -0
  23. package/config/openclaw/openclaw.json5 +50 -0
  24. package/config/openclaw/workspace/AGENTS.md +9 -0
  25. package/config/opencode/agents/qwen-audio-agent-backend.md +65 -0
  26. package/config/opencode/workspace/AGENTS.md +16 -0
  27. package/config/qoder/workspace/AGENTS.md +16 -0
  28. package/docs/architecture-overview-en.png +0 -0
  29. package/docs/architecture-overview.png +0 -0
  30. package/docs/architecture.md +332 -0
  31. package/docs/configuration.md +386 -0
  32. package/docs/desktop-fluid-orb-thinking.gif +0 -0
  33. package/docs/desktop-goo-orb-thinking.gif +0 -0
  34. package/docs/qwen-audio-agent-three-layer-architecture-en.png +0 -0
  35. package/docs/qwen-audio-agent-three-layer-architecture.png +0 -0
  36. package/package.json +126 -0
  37. package/scripts/audit-dependencies.mjs +109 -0
  38. package/scripts/check-desktop-release-env.mjs +41 -0
  39. package/scripts/codex-acp +58 -0
  40. package/scripts/install-global.mjs +66 -0
  41. package/scripts/openclaw +194 -0
  42. package/scripts/openclaw-gateway +8 -0
  43. package/scripts/opencode-acp +6 -0
  44. package/scripts/opencode-server +179 -0
  45. package/scripts/prepare-build.mjs +38 -0
  46. package/scripts/release-check +182 -0
  47. package/scripts/set-version.mjs +133 -0
  48. package/scripts/start.mjs +43 -0
  49. package/scripts/verify-package.mjs +109 -0
  50. package/server/package.json +18 -0
  51. package/server/src/agent/acp-backend-adapter.mjs +1138 -0
  52. package/server/src/agent/acp-backend-profile.mjs +35 -0
  53. package/server/src/agent/acp-backend-session-utils.mjs +139 -0
  54. package/server/src/agent/acp-process-client.mjs +447 -0
  55. package/server/src/agent/acp-session-registry.mjs +106 -0
  56. package/server/src/agent/acp-session-tools.mjs +257 -0
  57. package/server/src/agent/agent-client.mjs +218 -0
  58. package/server/src/agent/backend-adapter.mjs +15 -0
  59. package/server/src/agent/backend-agent-instructions.mjs +8 -0
  60. package/server/src/agent/backends/codebuddy.mjs +47 -0
  61. package/server/src/agent/backends/codex.mjs +62 -0
  62. package/server/src/agent/backends/generic-acp.mjs +46 -0
  63. package/server/src/agent/backends/hermes.mjs +29 -0
  64. package/server/src/agent/backends/openclaw.mjs +101 -0
  65. package/server/src/agent/backends/opencode.mjs +36 -0
  66. package/server/src/agent/backends/qoder.mjs +47 -0
  67. package/server/src/agent/backends/registry.mjs +32 -0
  68. package/server/src/agent/backends/shared.mjs +46 -0
  69. package/server/src/agent/coordinator.mjs +308 -0
  70. package/server/src/agent/openclaw-adapter.mjs +245 -0
  71. package/server/src/app/bootstrap.mjs +244 -0
  72. package/server/src/conversation/conversation-sync.mjs +183 -0
  73. package/server/src/conversation/frontend-agent-context.mjs +162 -0
  74. package/server/src/conversation/frontend-memory.mjs +328 -0
  75. package/server/src/conversation/profiled-memory-store.mjs +87 -0
  76. package/server/src/conversation/task-result-projector.mjs +18 -0
  77. package/server/src/conversation/user-profile.mjs +234 -0
  78. package/server/src/core/config.mjs +388 -0
  79. package/server/src/core/identity.mjs +93 -0
  80. package/server/src/core/install-paths.mjs +8 -0
  81. package/server/src/core/package-version.mjs +10 -0
  82. package/server/src/core/request-security.mjs +80 -0
  83. package/server/src/index.mjs +67 -0
  84. package/server/src/process/backend-drivers/codebuddy.mjs +15 -0
  85. package/server/src/process/backend-drivers/codex.mjs +15 -0
  86. package/server/src/process/backend-drivers/generic-acp.mjs +18 -0
  87. package/server/src/process/backend-drivers/hermes.mjs +15 -0
  88. package/server/src/process/backend-drivers/openclaw.mjs +35 -0
  89. package/server/src/process/backend-drivers/opencode.mjs +75 -0
  90. package/server/src/process/backend-drivers/qoder.mjs +15 -0
  91. package/server/src/process/backend-drivers/registry.mjs +24 -0
  92. package/server/src/process/backend-drivers/shared.mjs +46 -0
  93. package/server/src/process/managed-backend.mjs +188 -0
  94. package/server/src/task/task-manager.mjs +704 -0
  95. package/server/src/task/task-scheduler.mjs +44 -0
  96. package/server/src/task/task-store.mjs +167 -0
  97. package/server/src/voice/active-voice-clients.mjs +58 -0
  98. package/server/src/voice/announcement/announcement-manager.mjs +402 -0
  99. package/server/src/voice/announcement/announcement-window.mjs +89 -0
  100. package/server/src/voice/input-transcript.mjs +9 -0
  101. package/server/src/voice/realtime-errors.mjs +6 -0
  102. package/server/src/voice/realtime-gateway.mjs +1366 -0
  103. package/server/src/voice/realtime-provider.mjs +771 -0
  104. package/server/src/voice/reconnect-backoff.mjs +30 -0
  105. package/server/src/voice/response-context.mjs +41 -0
  106. package/server/src/voice/session-permission-policy.mjs +56 -0
  107. package/server/src/voice/tools/tool-call-handler.mjs +823 -0
  108. package/server/src/voice/tools/turn-transcripts.mjs +59 -0
  109. package/server/src/voice/turn-correlation.mjs +41 -0
  110. package/shared/backend-catalog.mjs +56 -0
  111. package/shared/gateway-client.mjs +13 -0
  112. package/shared/realtime-events.mjs +55 -0
  113. package/shared/runtime-environment.mjs +422 -0
  114. package/tui/native/macos-voice-io.swift +552 -0
  115. package/tui/native/portaudio-voice-io.py +240 -0
  116. package/tui/package.json +13 -0
  117. package/tui/src/index.mjs +1217 -0
  118. package/tui/src/macos-voice-io.mjs +186 -0
  119. package/tui/src/portaudio-voice-io.mjs +158 -0
  120. package/web/dist/assets/index-BeamDvsE.js +38 -0
  121. package/web/dist/assets/index-BuB0EFih.css +1 -0
  122. package/web/dist/index.html +14 -0
@@ -0,0 +1,44 @@
1
+ function limit(value, fallback) {
2
+ const parsed = Number(value)
3
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback
4
+ }
5
+
6
+ export class TaskScheduler {
7
+ constructor({
8
+ maxConcurrent = 4,
9
+ maxConcurrentPerOwner = 2,
10
+ } = {}) {
11
+ this.maxConcurrent = limit(maxConcurrent, 4)
12
+ this.maxConcurrentPerOwner = limit(maxConcurrentPerOwner, 2)
13
+ this.active = new Map()
14
+ }
15
+
16
+ count(predicate) {
17
+ let total = 0
18
+ for (const task of this.active.values()) {
19
+ if (predicate(task)) total += 1
20
+ }
21
+ return total
22
+ }
23
+
24
+ canStart(task) {
25
+ if (this.active.size >= this.maxConcurrent) return false
26
+ if (
27
+ this.count(active => active.ownerId === task.ownerId)
28
+ >= this.maxConcurrentPerOwner
29
+ ) return false
30
+ if (!task.laneKey) return true
31
+ return (
32
+ this.count(active => active.laneKey === task.laneKey)
33
+ < limit(task.laneLimit, 1)
34
+ )
35
+ }
36
+
37
+ acquire(task) {
38
+ this.active.set(task.id, task)
39
+ }
40
+
41
+ release(task) {
42
+ this.active.delete(task.id)
43
+ }
44
+ }
@@ -0,0 +1,167 @@
1
+ import {
2
+ mkdirSync,
3
+ readFileSync,
4
+ renameSync,
5
+ writeFileSync,
6
+ } from 'node:fs'
7
+ import {
8
+ mkdir,
9
+ rename,
10
+ unlink,
11
+ writeFile,
12
+ } from 'node:fs/promises'
13
+ import { dirname } from 'node:path'
14
+
15
+ const VERSION = 1
16
+
17
+ export class TaskStore {
18
+ constructor({
19
+ filePath = null,
20
+ now = () => Date.now(),
21
+ onWarning = warning => console.warn(warning.message),
22
+ deferredDelayMs = 250,
23
+ } = {}) {
24
+ this.filePath = filePath
25
+ this.now = now
26
+ this.onWarning = onWarning
27
+ this.warning = null
28
+ this.persistenceDisabled = false
29
+ this.deferredDelayMs = deferredDelayMs
30
+ this.deferredTimer = null
31
+ this.deferredContent = null
32
+ this.writeGeneration = 0
33
+ this.deferredWrites = Promise.resolve()
34
+ }
35
+
36
+ setWarning(message, quarantinePath = null) {
37
+ this.warning = { message, quarantinePath, at: this.now() }
38
+ try {
39
+ this.onWarning?.(this.warning)
40
+ } catch {
41
+ // Diagnostics must not prevent the service from starting.
42
+ }
43
+ }
44
+
45
+ quarantine(reason) {
46
+ const quarantinePath = `${this.filePath}.corrupt-${this.now()}`
47
+ try {
48
+ renameSync(this.filePath, quarantinePath)
49
+ this.setWarning(
50
+ `${reason};原文件已隔离为 ${quarantinePath},服务将使用空任务状态继续运行。`,
51
+ quarantinePath,
52
+ )
53
+ } catch (error) {
54
+ this.persistenceDisabled = true
55
+ this.setWarning(
56
+ `${reason};隔离失败(${error.message}),已禁用任务持久化以保护原文件。`,
57
+ )
58
+ }
59
+ }
60
+
61
+ load() {
62
+ if (!this.filePath || this.persistenceDisabled) return []
63
+ let parsed
64
+ try {
65
+ parsed = JSON.parse(readFileSync(this.filePath, 'utf8'))
66
+ } catch (error) {
67
+ if (error.code === 'ENOENT') return []
68
+ if (error instanceof SyntaxError) {
69
+ this.quarantine(`任务状态文件不是有效的 JSON:${error.message}`)
70
+ return []
71
+ }
72
+ this.persistenceDisabled = true
73
+ this.setWarning(`无法读取任务状态文件:${error.message}`)
74
+ return []
75
+ }
76
+ if (
77
+ !parsed
78
+ || parsed.version !== VERSION
79
+ || !Array.isArray(parsed.tasks)
80
+ ) {
81
+ this.quarantine('任务状态文件格式无效')
82
+ return []
83
+ }
84
+ return parsed.tasks.filter(task => task && typeof task === 'object')
85
+ }
86
+
87
+ save(tasks) {
88
+ if (!this.filePath || this.persistenceDisabled) return
89
+ clearTimeout(this.deferredTimer)
90
+ this.deferredTimer = null
91
+ this.deferredContent = null
92
+ this.writeGeneration += 1
93
+ try {
94
+ mkdirSync(dirname(this.filePath), { recursive: true })
95
+ const temporary = `${this.filePath}.${process.pid}.tmp`
96
+ writeFileSync(
97
+ temporary,
98
+ `${JSON.stringify({ version: VERSION, tasks }, null, 2)}\n`,
99
+ { encoding: 'utf8', mode: 0o600 },
100
+ )
101
+ renameSync(temporary, this.filePath)
102
+ } catch (error) {
103
+ this.persistenceDisabled = true
104
+ this.setWarning(`无法保存任务状态:${error.message}`)
105
+ }
106
+ }
107
+
108
+ saveDeferred(tasks) {
109
+ if (!this.filePath || this.persistenceDisabled) return
110
+ this.deferredContent = `${JSON.stringify({
111
+ version: VERSION,
112
+ tasks,
113
+ }, null, 2)}\n`
114
+ clearTimeout(this.deferredTimer)
115
+ this.deferredTimer = setTimeout(() => {
116
+ this.deferredTimer = null
117
+ this.startDeferredWrite()
118
+ }, this.deferredDelayMs)
119
+ this.deferredTimer.unref?.()
120
+ }
121
+
122
+ startDeferredWrite() {
123
+ const content = this.deferredContent
124
+ if (!content || !this.filePath || this.persistenceDisabled) {
125
+ return this.deferredWrites
126
+ }
127
+ this.deferredContent = null
128
+ const generation = ++this.writeGeneration
129
+ const temporary = `${this.filePath}.${process.pid}.${generation}.tmp`
130
+ const operation = async () => {
131
+ try {
132
+ await mkdir(dirname(this.filePath), { recursive: true })
133
+ await writeFile(temporary, content, {
134
+ encoding: 'utf8',
135
+ mode: 0o600,
136
+ })
137
+ if (generation !== this.writeGeneration) {
138
+ await unlink(temporary).catch(() => {})
139
+ return
140
+ }
141
+ await rename(temporary, this.filePath)
142
+ } catch (error) {
143
+ await unlink(temporary).catch(() => {})
144
+ if (generation !== this.writeGeneration) return
145
+ this.persistenceDisabled = true
146
+ this.setWarning(`无法保存任务状态:${error.message}`)
147
+ }
148
+ }
149
+ this.deferredWrites = this.deferredWrites.then(operation, operation)
150
+ return this.deferredWrites
151
+ }
152
+
153
+ async flush() {
154
+ clearTimeout(this.deferredTimer)
155
+ this.deferredTimer = null
156
+ this.startDeferredWrite()
157
+ await this.deferredWrites
158
+ }
159
+
160
+ health() {
161
+ return {
162
+ ok: !this.warning,
163
+ persistenceEnabled: Boolean(this.filePath) && !this.persistenceDisabled,
164
+ warning: this.warning,
165
+ }
166
+ }
167
+ }
@@ -0,0 +1,58 @@
1
+ export class ActiveVoiceClients {
2
+ constructor() {
3
+ this.clients = new Map()
4
+ }
5
+
6
+ activate(ownerId, client, { takeover = false } = {}) {
7
+ const key = String(ownerId || '')
8
+ const previous = this.clients.get(key)
9
+ if (previous === client) {
10
+ return { granted: true, previous: null }
11
+ }
12
+ if (previous && !takeover) {
13
+ return { granted: false, previous }
14
+ }
15
+ previous?.deactivate?.(client)
16
+ this.clients.set(key, client)
17
+ return { granted: true, previous: previous || null }
18
+ }
19
+
20
+ release(ownerId, client) {
21
+ const key = String(ownerId || '')
22
+ if (this.clients.get(key) !== client) return false
23
+ this.clients.delete(key)
24
+ return true
25
+ }
26
+
27
+ isActive(ownerId, client) {
28
+ return this.clients.get(String(ownerId || '')) === client
29
+ }
30
+
31
+ active(ownerId) {
32
+ return this.clients.get(String(ownerId || '')) || null
33
+ }
34
+
35
+ get size() {
36
+ return this.clients.size
37
+ }
38
+ }
39
+
40
+ export function clientVoiceCapabilities({
41
+ voiceEnabled = false,
42
+ inputEnabled,
43
+ outputEnabled,
44
+ textOnly = false,
45
+ } = {}) {
46
+ const canOutput = outputEnabled === undefined
47
+ ? voiceEnabled === true
48
+ : outputEnabled === true
49
+ const canInput = inputEnabled === undefined
50
+ ? canOutput && textOnly !== true
51
+ : inputEnabled === true && textOnly !== true
52
+ const participatesInVoiceArbitration = canOutput && textOnly !== true
53
+ return {
54
+ inputEnabled: canInput,
55
+ outputEnabled: canOutput,
56
+ participatesInVoiceArbitration,
57
+ }
58
+ }
@@ -0,0 +1,402 @@
1
+ export class AnnouncementManager {
2
+ constructor({
3
+ getFrontend,
4
+ isDeliveryBlocked,
5
+ announceIntoContext = true,
6
+ resultContextMaxChars = 6000,
7
+ maxBatchItems = 8,
8
+ batchWindowMs = 120,
9
+ retryBaseMs = 1000,
10
+ retryMaxMs = 10000,
11
+ acknowledgementTimeoutMs = 120000,
12
+ maxRetryAttempts = 8,
13
+ leaseRenewIntervalMs = 20000,
14
+ onDelivered = () => {},
15
+ onLeaseRenew = () => {},
16
+ onRelease = () => {},
17
+ onError = () => {},
18
+ }) {
19
+ this.getFrontend = getFrontend
20
+ this.isDeliveryBlocked = isDeliveryBlocked || (() => false)
21
+ this.announceIntoContext = announceIntoContext
22
+ this.resultContextMaxChars = resultContextMaxChars
23
+ this.maxBatchItems = maxBatchItems
24
+ this.batchWindowMs = batchWindowMs
25
+ this.retryBaseMs = retryBaseMs
26
+ this.retryMaxMs = retryMaxMs
27
+ this.acknowledgementTimeoutMs = acknowledgementTimeoutMs
28
+ this.maxRetryAttempts = maxRetryAttempts
29
+ this.leaseRenewIntervalMs = leaseRenewIntervalMs
30
+ this.onDelivered = onDelivered
31
+ this.onLeaseRenew = onLeaseRenew
32
+ this.onRelease = onRelease
33
+ this.onError = onError
34
+ this.pending = new Map()
35
+ this.activeBatch = null
36
+ this.delivering = false
37
+ this.deliveryGeneration = 0
38
+ this.sequence = 0
39
+ this.retryCount = 0
40
+ this.deliveryTimer = null
41
+ this.retryTimer = null
42
+ this.acknowledgementTimer = null
43
+ this.leaseRenewTimer = null
44
+ this.closed = false
45
+ }
46
+
47
+ has(taskId) {
48
+ return this.pending.has(taskId)
49
+ }
50
+
51
+ queue(taskId, announcement) {
52
+ this.pending.set(taskId, {
53
+ ...announcement,
54
+ taskId,
55
+ sequence: ++this.sequence,
56
+ })
57
+ this.scheduleDelivery(this.batchWindowMs)
58
+ }
59
+
60
+ completed(task) {
61
+ this.queue(task.id, {
62
+ event: 'task.completed',
63
+ status: 'completed',
64
+ objective: task.objective,
65
+ result: task.result,
66
+ turnId: task.turnId,
67
+ completedAt: task.completedAt,
68
+ })
69
+ }
70
+
71
+ failed(task) {
72
+ this.queue(task.id, {
73
+ event: 'task.failed',
74
+ status: 'failed',
75
+ objective: task.objective,
76
+ error: task.error,
77
+ turnId: task.turnId,
78
+ completedAt: task.completedAt,
79
+ })
80
+ }
81
+
82
+ remove(taskId) {
83
+ this.pending.delete(taskId)
84
+ if (this.activeBatch?.taskIds.includes(taskId)) {
85
+ this.activeBatch.acknowledged.add(taskId)
86
+ }
87
+ this.finishAcknowledgedBatch()
88
+ }
89
+
90
+ confirm(taskId) {
91
+ const tracked = this.pending.has(taskId) || this.activeBatch?.taskIds.includes(taskId)
92
+ this.remove(taskId)
93
+ if (tracked) this.onDelivered([taskId])
94
+ }
95
+
96
+ confirmMany(taskIds = []) {
97
+ taskIds.filter(Boolean).forEach(taskId => this.confirm(taskId))
98
+ }
99
+
100
+ dismissActive() {
101
+ this.confirmMany(this.activeBatch?.taskIds || [])
102
+ }
103
+
104
+ retryMany(taskIds = []) {
105
+ if (
106
+ !this.activeBatch
107
+ || !taskIds.some(taskId => this.activeBatch.taskIds.includes(taskId))
108
+ ) return
109
+ this.activeBatch.responseCompleted = false
110
+ this.activeBatch.retryRequested = true
111
+ this.clearAcknowledgementTimeout()
112
+ this.clearRetry()
113
+ if (!this.delivering) {
114
+ this.activeBatch.retryRequested = false
115
+ this.scheduleRetry()
116
+ }
117
+ }
118
+
119
+ finishAcknowledgedBatch() {
120
+ if (
121
+ !this.activeBatch
122
+ || !this.activeBatch.taskIds.every(taskId => (
123
+ this.activeBatch.acknowledged.has(taskId)
124
+ ))
125
+ ) return
126
+ this.activeBatch = null
127
+ this.retryCount = 0
128
+ this.clearRetry()
129
+ this.clearAcknowledgementTimeout()
130
+ this.clearLeaseRenewal()
131
+ if (!this.delivering && this.pending.size) this.scheduleDelivery(0)
132
+ }
133
+
134
+ clearDelivery() {
135
+ clearTimeout(this.deliveryTimer)
136
+ this.deliveryTimer = null
137
+ }
138
+
139
+ clearRetry() {
140
+ clearTimeout(this.retryTimer)
141
+ this.retryTimer = null
142
+ }
143
+
144
+ clearAcknowledgementTimeout() {
145
+ clearTimeout(this.acknowledgementTimer)
146
+ this.acknowledgementTimer = null
147
+ }
148
+
149
+ clearLeaseRenewal() {
150
+ clearInterval(this.leaseRenewTimer)
151
+ this.leaseRenewTimer = null
152
+ }
153
+
154
+ ensureLeaseRenewal() {
155
+ if (this.leaseRenewTimer || !this.activeBatch) return
156
+ this.onLeaseRenew(this.activeBatch.taskIds)
157
+ this.leaseRenewTimer = setInterval(() => {
158
+ if (!this.activeBatch) {
159
+ this.clearLeaseRenewal()
160
+ return
161
+ }
162
+ this.onLeaseRenew(this.activeBatch.taskIds)
163
+ }, this.leaseRenewIntervalMs)
164
+ this.leaseRenewTimer.unref?.()
165
+ }
166
+
167
+ scheduleAcknowledgementTimeout() {
168
+ this.clearAcknowledgementTimeout()
169
+ this.acknowledgementTimer = setTimeout(() => {
170
+ this.acknowledgementTimer = null
171
+ if (!this.activeBatch?.responseCompleted) return
172
+ // response.done means generation finished, not that the client finished
173
+ // playing it. Long or queued desktop audio may legitimately exceed the
174
+ // acknowledgement window. Never create a second spoken response while
175
+ // the first one is still queued, playing, or blocked by active speech.
176
+ if (this.isDeliveryBlocked()) {
177
+ this.scheduleAcknowledgementTimeout()
178
+ return
179
+ }
180
+ this.activeBatch.responseCompleted = false
181
+ this.activeBatch.retryRequested = true
182
+ if (!this.delivering) {
183
+ this.activeBatch.retryRequested = false
184
+ this.scheduleRetry()
185
+ }
186
+ }, this.acknowledgementTimeoutMs)
187
+ this.acknowledgementTimer.unref?.()
188
+ }
189
+
190
+ abandonActiveBatch() {
191
+ const taskIds = this.activeBatch?.taskIds || []
192
+ taskIds.forEach(taskId => this.pending.delete(taskId))
193
+ this.activeBatch = null
194
+ this.retryCount = 0
195
+ this.clearRetry()
196
+ this.clearAcknowledgementTimeout()
197
+ this.clearLeaseRenewal()
198
+ if (taskIds.length) this.onRelease(taskIds)
199
+ if (!this.delivering && this.pending.size) this.scheduleDelivery(0)
200
+ }
201
+
202
+ scheduleDelivery(delay = 0) {
203
+ if (
204
+ this.closed
205
+ || this.deliveryTimer
206
+ || this.retryTimer
207
+ || this.activeBatch
208
+ || !this.pending.size
209
+ ) return
210
+ this.deliveryTimer = setTimeout(() => {
211
+ this.deliveryTimer = null
212
+ this.deliver()
213
+ }, Math.max(0, delay))
214
+ this.deliveryTimer.unref?.()
215
+ }
216
+
217
+ scheduleRetry() {
218
+ if (this.closed || !this.activeBatch || this.retryTimer) return
219
+ if (this.retryCount >= this.maxRetryAttempts) {
220
+ this.abandonActiveBatch()
221
+ return
222
+ }
223
+ this.retryCount += 1
224
+ const delay = Math.min(
225
+ this.retryMaxMs,
226
+ this.retryBaseMs * (2 ** Math.min(this.retryCount - 1, 4)),
227
+ )
228
+ this.retryTimer = setTimeout(() => {
229
+ this.retryTimer = null
230
+ this.deliver()
231
+ }, delay)
232
+ this.retryTimer.unref?.()
233
+ }
234
+
235
+ createBatch() {
236
+ const pending = [...this.pending.values()]
237
+ .sort((a, b) => a.sequence - b.sequence)
238
+ if (!pending.length) return null
239
+ const queued = []
240
+ for (const item of pending) {
241
+ const candidate = [...queued, item]
242
+ const candidateText = formatWorkResults(
243
+ this.batchAnnouncements(candidate),
244
+ )
245
+ if (
246
+ queued.length
247
+ && (
248
+ queued.length >= this.maxBatchItems
249
+ || Array.from(candidateText).length > this.resultContextMaxChars
250
+ )
251
+ ) break
252
+ queued.push(item)
253
+ }
254
+ const announcements = this.batchAnnouncements(queued)
255
+ return {
256
+ announcements,
257
+ // Only events actually represented in this bounded model input may be
258
+ // acknowledged when playback ends. Remaining events stay pending.
259
+ taskIds: queued.map(item => item.taskId),
260
+ turnIds: announcements.map(item => item.turnId).filter(Boolean),
261
+ deliverySequence: queued[0].sequence,
262
+ contextInjected: false,
263
+ responseCompleted: false,
264
+ retryRequested: false,
265
+ acknowledged: new Set(),
266
+ }
267
+ }
268
+
269
+ batchAnnouncements(queued) {
270
+ return queued
271
+ }
272
+
273
+ async deliver() {
274
+ if (this.closed || this.delivering || this.isDeliveryBlocked()) return
275
+ const frontend = this.getFrontend()
276
+ if (!frontend?.ready) {
277
+ if (!this.activeBatch) this.activeBatch = this.createBatch()
278
+ this.ensureLeaseRenewal()
279
+ this.scheduleRetry()
280
+ return
281
+ }
282
+ if (!this.activeBatch) this.activeBatch = this.createBatch()
283
+ const batch = this.activeBatch
284
+ if (!batch) return
285
+ const deliveryGeneration = this.deliveryGeneration
286
+ this.ensureLeaseRenewal()
287
+ this.delivering = true
288
+ try {
289
+ const eventText = truncateResult(
290
+ formatWorkResults(batch.announcements),
291
+ this.resultContextMaxChars,
292
+ )
293
+ const context = {
294
+ turnId: batch.turnIds.length === 1 ? batch.turnIds[0] : null,
295
+ turnIds: batch.turnIds,
296
+ taskId: batch.taskIds.length === 1 ? batch.taskIds[0] : null,
297
+ taskIds: batch.taskIds,
298
+ deliverySequence: batch.deliverySequence,
299
+ }
300
+ const outcome = this.announceIntoContext && frontend.injectResult
301
+ ? await frontend.injectResult(
302
+ eventText,
303
+ 'announcement',
304
+ context,
305
+ { injectContext: !batch.contextInjected },
306
+ )
307
+ : await frontend.speak(eventText, 'announcement', context)
308
+ if (
309
+ this.deliveryGeneration !== deliveryGeneration
310
+ || this.activeBatch !== batch
311
+ ) return
312
+ if (outcome?.contextInjected) batch.contextInjected = true
313
+ if (outcome?.completed) {
314
+ // Realtime has generated the response, but the client may still have it
315
+ // queued behind earlier audio. Delivery is confirmed only by the
316
+ // client's playback.ended event.
317
+ batch.responseCompleted = true
318
+ this.scheduleAcknowledgementTimeout()
319
+ } else if (this.activeBatch) {
320
+ this.scheduleRetry()
321
+ }
322
+ } catch (error) {
323
+ try {
324
+ this.onError(error)
325
+ } catch {
326
+ // Diagnostics must never break announcement recovery.
327
+ }
328
+ if (
329
+ this.deliveryGeneration === deliveryGeneration
330
+ && this.activeBatch === batch
331
+ ) this.scheduleRetry()
332
+ } finally {
333
+ if (this.deliveryGeneration !== deliveryGeneration) return
334
+ this.delivering = false
335
+ this.finishAcknowledgedBatch()
336
+ if (this.activeBatch?.retryRequested) {
337
+ this.activeBatch.retryRequested = false
338
+ this.scheduleRetry()
339
+ }
340
+ if (!this.activeBatch && this.pending.size) this.scheduleDelivery(0)
341
+ }
342
+ }
343
+
344
+ flush() {
345
+ if (this.isDeliveryBlocked()) return
346
+ this.clearDelivery()
347
+ this.deliver()
348
+ }
349
+
350
+ pause() {
351
+ const taskIds = new Set([
352
+ ...this.pending.keys(),
353
+ ...(this.activeBatch?.taskIds || []),
354
+ ])
355
+ this.clearDelivery()
356
+ this.clearRetry()
357
+ this.clearAcknowledgementTimeout()
358
+ this.clearLeaseRenewal()
359
+ this.deliveryGeneration += 1
360
+ this.pending.clear()
361
+ this.activeBatch = null
362
+ this.delivering = false
363
+ this.retryCount = 0
364
+ if (taskIds.size) this.onRelease([...taskIds])
365
+ }
366
+
367
+ close() {
368
+ this.closed = true
369
+ this.pause()
370
+ }
371
+ }
372
+
373
+ export function formatWorkResults(announcements) {
374
+ const blocks = announcements.map((item, index) => [
375
+ `--- event ${index + 1} ---`,
376
+ `type: ${item.event}`,
377
+ `work_id: ${item.taskId}`,
378
+ item.objective ? `original_request: ${item.objective}` : '',
379
+ item.completedAt ? `completed_at: ${new Date(item.completedAt).toISOString()}` : '',
380
+ item.status === 'completed'
381
+ ? `result:\n${String(item.result || '').trim()}`
382
+ : `error:\n${String(item.error || '').trim()}`,
383
+ ].filter(Boolean).join('\n'))
384
+ return [
385
+ '[COMPLETE]',
386
+ '<qwen_audio_agent_work_results>',
387
+ '以下是先前提交工作的最终结果,不是用户的新请求。',
388
+ ...blocks,
389
+ '</qwen_audio_agent_work_results>',
390
+ ].join('\n')
391
+ }
392
+
393
+ export function truncateResult(value, maxChars) {
394
+ const text = String(value || '').trim()
395
+ const limit = Math.max(1, Number(maxChars) || 1)
396
+ const characters = Array.from(text)
397
+ if (characters.length <= limit) return text
398
+ const suffix = '\n…(事件内容过长,已截断;完整结果仍保留在任务记录中)'
399
+ const suffixLength = Array.from(suffix).length
400
+ if (limit <= suffixLength) return characters.slice(0, limit).join('')
401
+ return `${characters.slice(0, limit - suffixLength).join('')}${suffix}`
402
+ }