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,245 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { readFile } from 'node:fs/promises'
3
+ import { WebSocket } from 'ws'
4
+ import { PACKAGE_VERSION } from '../core/package-version.mjs'
5
+ import { AgentError, requestSignal } from './backend-adapter.mjs'
6
+
7
+ const WAIT_SLICE_MS = 30_000
8
+
9
+ function clean(value) {
10
+ return String(value || '').trim()
11
+ }
12
+
13
+ function websocketUrl(baseUrl) {
14
+ const url = new URL(baseUrl)
15
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
16
+ url.pathname = '/'
17
+ url.search = ''
18
+ url.hash = ''
19
+ return url.toString()
20
+ }
21
+
22
+ function messageText(data) {
23
+ if (typeof data === 'string') return data
24
+ if (Buffer.isBuffer(data)) return data.toString('utf8')
25
+ if (Array.isArray(data)) return Buffer.concat(data).toString('utf8')
26
+ return Buffer.from(data).toString('utf8')
27
+ }
28
+
29
+ function assistantText(message) {
30
+ if (Array.isArray(message?.content)) {
31
+ return message.content
32
+ .filter(part => part?.type === 'text')
33
+ .map(part => part.text || '')
34
+ .join('\n')
35
+ .trim()
36
+ }
37
+ return clean(message?.content)
38
+ }
39
+
40
+ class OpenClawGatewayRpc {
41
+ constructor({
42
+ baseUrl,
43
+ token = '',
44
+ WebSocketImpl = WebSocket,
45
+ } = {}) {
46
+ this.url = websocketUrl(baseUrl)
47
+ this.token = clean(token)
48
+ this.WebSocket = WebSocketImpl
49
+ }
50
+
51
+ call(method, params = {}, { signal, timeoutMs = 35_000 } = {}) {
52
+ const combined = requestSignal(signal, timeoutMs)
53
+ return new Promise((resolve, reject) => {
54
+ const ws = new this.WebSocket(this.url)
55
+ const pending = new Map()
56
+ let connected = false
57
+ let finished = false
58
+
59
+ const close = () => {
60
+ if (
61
+ ws.readyState === this.WebSocket.OPEN
62
+ || ws.readyState === this.WebSocket.CONNECTING
63
+ ) ws.close()
64
+ }
65
+ const finish = (error, value) => {
66
+ if (finished) return
67
+ finished = true
68
+ combined?.removeEventListener('abort', abort)
69
+ close()
70
+ if (error) reject(error)
71
+ else resolve(value)
72
+ }
73
+ const request = (requestMethod, requestParams) => {
74
+ const id = randomUUID()
75
+ pending.set(id, requestMethod)
76
+ ws.send(JSON.stringify({
77
+ type: 'req',
78
+ id,
79
+ method: requestMethod,
80
+ params: requestParams,
81
+ }))
82
+ }
83
+ const abort = () => finish(
84
+ combined?.reason || new Error('OpenClaw Gateway 请求已取消'),
85
+ )
86
+
87
+ combined?.addEventListener('abort', abort, { once: true })
88
+ if (combined?.aborted) return abort()
89
+
90
+ ws.on('message', data => {
91
+ let frame
92
+ try {
93
+ frame = JSON.parse(messageText(data))
94
+ } catch {
95
+ return
96
+ }
97
+ if (frame.type === 'event') {
98
+ if (frame.event === 'connect.challenge' && !connected) {
99
+ connected = true
100
+ request('connect', {
101
+ minProtocol: 3,
102
+ maxProtocol: 3,
103
+ client: {
104
+ id: 'gateway-client',
105
+ displayName: 'qwen-audio-agent',
106
+ version: PACKAGE_VERSION,
107
+ platform: process.platform,
108
+ mode: 'backend',
109
+ },
110
+ caps: ['tool-events'],
111
+ role: 'operator',
112
+ scopes: ['operator.read', 'operator.write'],
113
+ ...(this.token ? { auth: { token: this.token } } : {}),
114
+ })
115
+ }
116
+ return
117
+ }
118
+ if (frame.type !== 'res' || !pending.has(frame.id)) return
119
+ const requestMethod = pending.get(frame.id)
120
+ pending.delete(frame.id)
121
+ if (!frame.ok) {
122
+ finish(new AgentError(
123
+ `OpenClaw Gateway ${requestMethod} 失败:${
124
+ frame.error?.message || '未知错误'
125
+ }`,
126
+ {
127
+ body: JSON.stringify(frame.error || {}),
128
+ protocol: 'openclaw-gateway',
129
+ },
130
+ ))
131
+ return
132
+ }
133
+ if (requestMethod === 'connect') {
134
+ request(method, params)
135
+ return
136
+ }
137
+ finish(null, frame.payload)
138
+ })
139
+ ws.once('error', error => finish(new AgentError(
140
+ `无法连接 OpenClaw Gateway:${error.message}`,
141
+ { protocol: 'openclaw-gateway' },
142
+ )))
143
+ ws.once('close', () => {
144
+ if (!finished) finish(new AgentError(
145
+ 'OpenClaw Gateway 连接意外关闭',
146
+ { protocol: 'openclaw-gateway' },
147
+ ))
148
+ })
149
+ })
150
+ }
151
+ }
152
+
153
+ // ACP owns coordinator interaction. OpenClaw's Gateway RPC is used only for
154
+ // the native child-run lifecycle that its ACP bridge does not push after the
155
+ // coordinator prompt has ended.
156
+ export class OpenClawAcpDelegationAdapter {
157
+ constructor({
158
+ baseUrl,
159
+ token = '',
160
+ tokenFile = '',
161
+ WebSocketImpl,
162
+ } = {}) {
163
+ this.options = {
164
+ baseUrl,
165
+ token: clean(token),
166
+ tokenFile: clean(tokenFile),
167
+ WebSocketImpl,
168
+ }
169
+ this.gatewayPromise = null
170
+ }
171
+
172
+ async gateway() {
173
+ if (!this.gatewayPromise) {
174
+ this.gatewayPromise = (async () => {
175
+ let token = this.options.token
176
+ if (!token && this.options.tokenFile) {
177
+ token = await readFile(this.options.tokenFile, 'utf8')
178
+ .then(clean)
179
+ .catch(() => '')
180
+ }
181
+ return new OpenClawGatewayRpc({
182
+ baseUrl: this.options.baseUrl,
183
+ token,
184
+ ...(this.options.WebSocketImpl
185
+ ? { WebSocketImpl: this.options.WebSocketImpl }
186
+ : {}),
187
+ })
188
+ })()
189
+ }
190
+ return this.gatewayPromise
191
+ }
192
+
193
+ async wait({ runId, sessionId, signal }) {
194
+ const id = clean(runId)
195
+ if (!id) {
196
+ throw new AgentError('OpenClaw Session 工具没有返回 runId', {
197
+ protocol: 'openclaw-gateway',
198
+ })
199
+ }
200
+ const gateway = await this.gateway()
201
+ while (true) {
202
+ if (signal?.aborted) {
203
+ throw signal.reason || new Error('任务已取消')
204
+ }
205
+ const completion = await gateway.call('agent.wait', {
206
+ runId: id,
207
+ timeoutMs: WAIT_SLICE_MS,
208
+ }, {
209
+ signal,
210
+ timeoutMs: WAIT_SLICE_MS + 5000,
211
+ })
212
+ if (completion?.status === 'timeout') continue
213
+ if (!['ok', 'completed'].includes(completion?.status)) {
214
+ throw new AgentError(
215
+ completion?.error || `OpenClaw 子任务结束状态异常:${
216
+ completion?.status || 'unknown'
217
+ }`,
218
+ { protocol: 'openclaw-gateway' },
219
+ )
220
+ }
221
+ const history = await gateway.call('chat.history', {
222
+ sessionKey: clean(sessionId),
223
+ limit: 20,
224
+ }, { signal, timeoutMs: 15_000 })
225
+ const assistant = [...(history?.messages || [])]
226
+ .reverse()
227
+ .find(message => message?.role === 'assistant')
228
+ const content = assistantText(assistant)
229
+ if (!content) {
230
+ throw new AgentError('OpenClaw 子任务已完成,但没有返回文本', {
231
+ protocol: 'openclaw-gateway',
232
+ })
233
+ }
234
+ return { content, completion }
235
+ }
236
+ }
237
+
238
+ async cancel({ runId, sessionId, signal }) {
239
+ const gateway = await this.gateway()
240
+ return gateway.call('chat.abort', {
241
+ sessionKey: clean(sessionId),
242
+ runId: clean(runId),
243
+ }, { signal, timeoutMs: 10_000 })
244
+ }
245
+ }
@@ -0,0 +1,244 @@
1
+ import express from 'express'
2
+ import { createServer } from 'http'
3
+ import { resolve } from 'path'
4
+ import { agent } from '../agent/agent-client.mjs'
5
+ import { coordinator } from '../agent/coordinator.mjs'
6
+ import { config } from '../core/config.mjs'
7
+ import { conversationSync } from '../conversation/conversation-sync.mjs'
8
+ import { IdentityManager } from '../core/identity.mjs'
9
+ import { FrontendMemoryStore } from '../conversation/frontend-memory.mjs'
10
+ import { ProfiledMemoryStore } from '../conversation/profiled-memory-store.mjs'
11
+ import { UserProfile } from '../conversation/user-profile.mjs'
12
+ import { enforceSameOrigin } from '../core/request-security.mjs'
13
+ import { attachRealtimeGateway } from '../voice/realtime-gateway.mjs'
14
+ import { describeActiveRealtime } from '../voice/realtime-provider.mjs'
15
+ import { SessionPermissionPolicy } from '../voice/session-permission-policy.mjs'
16
+ import { taskManager, taskStore } from '../task/task-manager.mjs'
17
+ import { webDistributionPath } from '../core/install-paths.mjs'
18
+
19
+ const identityManager = new IdentityManager({
20
+ secret: config.authSecret,
21
+ mode: config.identityMode,
22
+ personalOwnerId: config.personalOwnerId,
23
+ })
24
+ taskManager.configureRetention({
25
+ terminalTtlMs: config.taskTerminalTtlMs,
26
+ pendingNotificationTtlMs: config.taskPendingNotificationTtlMs,
27
+ notificationClaimTtlMs: config.taskNotificationClaimTtlMs,
28
+ maxTerminalTasksPerOwner: config.maxTerminalTasksPerOwner,
29
+ })
30
+ taskManager.recoverDelegated({
31
+ canRecover: task => agent.canRecoverDelegatedWork(task),
32
+ runner: (task, context) => agent.recoverDelegatedWork(task, context),
33
+ canceler: async (task, { abort }) => {
34
+ const result = await agent.cancelDelegatedWork(task.id, {
35
+ ownerId: task.ownerId,
36
+ })
37
+ abort()
38
+ return result
39
+ },
40
+ })
41
+ conversationSync.configureRetention({
42
+ sessionTtlMs: config.conversationSessionTtlMs,
43
+ maxSessions: config.maxConversationSessions,
44
+ })
45
+ const dynamicMemory = new FrontendMemoryStore({
46
+ filePath: config.frontendMemoryPath,
47
+ maxOwners: config.maxFrontendMemoryOwners,
48
+ ownerTtlMs: config.frontendMemoryOwnerTtlMs,
49
+ })
50
+ const frontendMemory = new ProfiledMemoryStore({
51
+ memoryStore: dynamicMemory,
52
+ userProfile: config.identityMode === 'personal'
53
+ ? new UserProfile({ filePath: config.userProfilePath })
54
+ : null,
55
+ })
56
+ const app = express()
57
+ const permissionPolicy = new SessionPermissionPolicy({
58
+ ttlMs: config.conversationSessionTtlMs,
59
+ maxSessions: config.maxConversationSessions,
60
+ })
61
+
62
+ app.disable('x-powered-by')
63
+ app.use(enforceSameOrigin)
64
+ app.use((req, res, next) => {
65
+ req.identity = identityManager.resolveHttp(req, res)
66
+ next()
67
+ })
68
+ app.use(express.json({ limit: '1mb' }))
69
+
70
+ let realtimeGateway
71
+
72
+ app.get('/api/health', async (req, res) => {
73
+ const backend = await agent.health()
74
+ const backendDescription = agent.describe()
75
+ const realtime = describeActiveRealtime()
76
+ res.status(backend.ok ? 200 : 503).json({
77
+ ok: backend.ok,
78
+ voiceConfigured: realtime.configured,
79
+ realtimeProvider: realtime.provider,
80
+ realtimeLabel: realtime.label,
81
+ realtimeModel: realtime.model,
82
+ realtimeInputSampleRate: realtime.inputSampleRate,
83
+ announceIntoContext: config.announceIntoContext,
84
+ resultContextMaxChars: config.resultContextMaxChars,
85
+ announcementBatchMs: config.announcementBatchMs,
86
+ announcementQuietMs: config.announcementQuietMs,
87
+ frontendMemory: frontendMemory.health(),
88
+ taskStore: taskStore.health(),
89
+ identityMode: config.identityMode,
90
+ voiceClients: realtimeGateway?.status() || {
91
+ connected: 0,
92
+ activeOwners: 0,
93
+ byType: {},
94
+ },
95
+ backend: {
96
+ ...backendDescription,
97
+ ...backend,
98
+ },
99
+ })
100
+ })
101
+
102
+ app.get('/api/backend/ui', async (req, res, next) => {
103
+ if (!agent.describe().capabilities.backendUi) {
104
+ return res.status(404).json({ error: '当前后台 Agent 没有独立的 Web 地址' })
105
+ }
106
+ try {
107
+ const url = await agent.uiUrl({ ownerId: req.identity.ownerId })
108
+ if (!url) {
109
+ return res.status(404).json({
110
+ error: '当前后台 Agent 没有独立的 Web 地址',
111
+ })
112
+ }
113
+ return res.redirect(302, url)
114
+ } catch (error) {
115
+ return next(error)
116
+ }
117
+ })
118
+
119
+ app.get('/api/tasks', (req, res) => {
120
+ res.json({
121
+ tasks: taskManager.list({
122
+ ownerId: req.identity.ownerId,
123
+ sessionId: req.query.sessionId,
124
+ active: req.query.active === 'true',
125
+ }),
126
+ })
127
+ })
128
+
129
+ app.get('/api/timeline', (req, res) => {
130
+ const items = taskManager.list({
131
+ ownerId: req.identity.ownerId,
132
+ sessionId: req.query.sessionId,
133
+ })
134
+ .filter(task => task.resultMetadata?.presentation?.inline?.content)
135
+ .map(task => ({
136
+ id: `inline_${task.id}`,
137
+ taskId: task.id,
138
+ turnId: task.turnId || null,
139
+ createdAt: task.completedAt || task.createdAt,
140
+ ...task.resultMetadata.presentation.inline,
141
+ }))
142
+ .sort((left, right) => left.createdAt - right.createdAt)
143
+ res.json({ items })
144
+ })
145
+
146
+ app.get('/api/tasks/:id', (req, res) => {
147
+ const task = taskManager.get(req.params.id, { ownerId: req.identity.ownerId })
148
+ if (!task) return res.status(404).json({ error: 'task not found' })
149
+ res.json(task)
150
+ })
151
+
152
+ app.delete('/api/tasks/:id', async (req, res) => {
153
+ const existing = taskManager.get(req.params.id, {
154
+ ownerId: req.identity.ownerId,
155
+ })
156
+ if (!existing) return res.status(404).json({ error: 'task not found' })
157
+ const task = await taskManager.cancel(req.params.id, {
158
+ ownerId: req.identity.ownerId,
159
+ })
160
+ if (!task) {
161
+ return res.status(409).json({
162
+ error: 'task is no longer active',
163
+ task: existing,
164
+ })
165
+ }
166
+ res.json(task)
167
+ })
168
+
169
+ app.post('/api/permissions/:id', async (req, res, next) => {
170
+ const decision = String(req.body?.decision || '')
171
+ if (!['always', 'reject'].includes(decision)) {
172
+ return res.status(400).json({ error: 'decision must be always or reject' })
173
+ }
174
+ const permissionTask = taskManager.list({
175
+ ownerId: req.identity.ownerId,
176
+ active: true,
177
+ }).find(task => task.authorization?.id === req.params.id)
178
+ const previousPermissionMode = permissionTask
179
+ ? permissionPolicy.mode(req.identity.ownerId, permissionTask.sessionId)
180
+ : null
181
+ if (permissionTask) {
182
+ permissionPolicy.applyDecision(
183
+ req.identity.ownerId,
184
+ permissionTask.sessionId,
185
+ decision,
186
+ )
187
+ }
188
+ try {
189
+ const permission = await agent.respondPermission(
190
+ req.params.id,
191
+ decision,
192
+ { ownerId: req.identity.ownerId },
193
+ )
194
+ return res.json(permission)
195
+ } catch (error) {
196
+ if (permissionTask && previousPermissionMode) {
197
+ permissionPolicy.setMode(
198
+ req.identity.ownerId,
199
+ permissionTask.sessionId,
200
+ previousPermissionMode,
201
+ )
202
+ }
203
+ if (error?.status === 404) {
204
+ return res.status(404).json({ error: error.message })
205
+ }
206
+ return next(error)
207
+ }
208
+ })
209
+
210
+ app.get('/api/tasks/:id/events', (req, res) => {
211
+ const task = taskManager.get(req.params.id, { ownerId: req.identity.ownerId })
212
+ if (!task) return res.status(404).json({ error: 'task not found' })
213
+ res.setHeader('Content-Type', 'text/event-stream')
214
+ res.setHeader('Cache-Control', 'no-cache')
215
+ res.setHeader('Connection', 'keep-alive')
216
+ res.flushHeaders()
217
+ const write = event => res.write(`data: ${JSON.stringify(event)}\n\n`)
218
+ write({ type: 'task.snapshot', task })
219
+ const unsubscribe = taskManager.subscribe(event => {
220
+ if (event.ownerId === req.identity.ownerId && event.task.id === req.params.id) {
221
+ write({ type: event.type, task: event.task })
222
+ }
223
+ })
224
+ res.on('close', unsubscribe)
225
+ })
226
+
227
+ const webDist = webDistributionPath()
228
+ app.use(express.static(webDist))
229
+ app.get('*', (req, res) => res.sendFile(resolve(webDist, 'index.html')))
230
+
231
+ const server = createServer(app)
232
+ realtimeGateway = attachRealtimeGateway(server, {
233
+ identityManager,
234
+ memoryStore: frontendMemory,
235
+ coordinator,
236
+ coordinatorAvailable: async () => (await agent.health()).ok === true,
237
+ respondPermission: (id, decision, options) => (
238
+ agent.respondPermission(id, decision, options)
239
+ ),
240
+ permissionPolicy,
241
+ })
242
+ server.listen(config.port, config.host, () => {
243
+ console.log(`qwen-audio-agent running at http://${config.host}:${config.port}`)
244
+ })
@@ -0,0 +1,183 @@
1
+ function sessionKey(ownerId, sessionId) {
2
+ return `${ownerId}\u0000${sessionId}`
3
+ }
4
+
5
+ function clean(value) {
6
+ return String(value || '').replace(/\s+/g, ' ').trim()
7
+ }
8
+
9
+ function speechKey(value) {
10
+ return clean(value)
11
+ .toLocaleLowerCase()
12
+ .replace(/[\p{P}\p{S}\s]+/gu, '')
13
+ }
14
+
15
+ function speechNgrams(value, size = 2) {
16
+ const grams = new Set()
17
+ for (let index = 0; index <= value.length - size; index += 1) {
18
+ grams.add(value.slice(index, index + size))
19
+ }
20
+ return grams
21
+ }
22
+
23
+ function equivalentSpeech(left, right) {
24
+ if (left === right) return true
25
+ if (left.length < 8 || right.length < 8) return false
26
+ const leftGrams = speechNgrams(left)
27
+ const rightGrams = speechNgrams(right)
28
+ const shorterSize = Math.min(leftGrams.size, rightGrams.size)
29
+ if (!shorterSize) return false
30
+ let shared = 0
31
+ for (const gram of leftGrams) {
32
+ if (rightGrams.has(gram)) shared += 1
33
+ }
34
+ // Delegated acknowledgements often add details around the same short action
35
+ // preview. One third of the shorter message is enough to recognize that
36
+ // paraphrase without suppressing a genuinely different update.
37
+ return shared / shorterSize >= 1 / 3
38
+ }
39
+
40
+ export class ConversationSync {
41
+ constructor({
42
+ maxMessages = 100,
43
+ maxSessions = 500,
44
+ sessionTtlMs = 6 * 60 * 60 * 1000,
45
+ } = {}) {
46
+ this.maxMessages = maxMessages
47
+ this.maxSessions = maxSessions
48
+ this.sessionTtlMs = sessionTtlMs
49
+ this.sessions = new Map()
50
+ this.sequence = 0
51
+ }
52
+
53
+ configureRetention(options = {}) {
54
+ Object.assign(this, options)
55
+ }
56
+
57
+ state(ownerId, sessionId) {
58
+ this.prune()
59
+ const key = sessionKey(ownerId, sessionId)
60
+ let state = this.sessions.get(key)
61
+ if (!state) {
62
+ this.enforceSessionLimit()
63
+ state = { messages: [], byId: new Map(), lastAccessedAt: Date.now() }
64
+ this.sessions.set(key, state)
65
+ }
66
+ state.lastAccessedAt = Date.now()
67
+ return state
68
+ }
69
+
70
+ peek(ownerId, sessionId) {
71
+ const state = this.sessions.get(sessionKey(ownerId, sessionId))
72
+ if (state) state.lastAccessedAt = Date.now()
73
+ return state || null
74
+ }
75
+
76
+ prune(now = Date.now()) {
77
+ this.sessions.forEach((state, key) => {
78
+ if (now - state.lastAccessedAt >= this.sessionTtlMs) this.sessions.delete(key)
79
+ })
80
+ }
81
+
82
+ enforceSessionLimit() {
83
+ while (this.sessions.size >= this.maxSessions) {
84
+ const oldest = [...this.sessions.entries()]
85
+ .sort((a, b) => a[1].lastAccessedAt - b[1].lastAccessedAt)[0]
86
+ if (!oldest) break
87
+ this.sessions.delete(oldest[0])
88
+ }
89
+ }
90
+
91
+ record({
92
+ ownerId,
93
+ sessionId,
94
+ id,
95
+ role,
96
+ content,
97
+ source,
98
+ turnId = null,
99
+ taskId = null,
100
+ taskIds = [],
101
+ }) {
102
+ const normalized = clean(content)
103
+ if (!id || !normalized) return null
104
+ const state = this.state(ownerId, sessionId)
105
+ const existing = state.byId.get(id)
106
+ if (existing) {
107
+ Object.assign(existing, {
108
+ role,
109
+ content: normalized,
110
+ source,
111
+ turnId,
112
+ taskId,
113
+ taskIds: [...new Set((taskIds || []).filter(Boolean))],
114
+ })
115
+ return { ...existing }
116
+ }
117
+ const message = {
118
+ seq: ++this.sequence,
119
+ id,
120
+ role,
121
+ content: normalized,
122
+ source,
123
+ turnId,
124
+ taskId,
125
+ taskIds: [...new Set((taskIds || []).filter(Boolean))],
126
+ createdAt: Date.now(),
127
+ }
128
+ state.messages.push(message)
129
+ state.byId.set(id, message)
130
+ while (state.messages.length > this.maxMessages) {
131
+ const removed = state.messages.shift()
132
+ state.byId.delete(removed.id)
133
+ }
134
+ return { ...message }
135
+ }
136
+
137
+ list({ ownerId, sessionId }) {
138
+ this.prune()
139
+ return (this.peek(ownerId, sessionId)?.messages || [])
140
+ .map(message => ({ ...message }))
141
+ }
142
+
143
+ hasEquivalentAssistantSpeech({
144
+ ownerId,
145
+ sessionId,
146
+ turnId,
147
+ content,
148
+ }) {
149
+ const target = speechKey(content)
150
+ if (!target) return false
151
+ return this.list({ ownerId, sessionId }).some(message => (
152
+ message.role === 'assistant'
153
+ && message.turnId === turnId
154
+ && equivalentSpeech(speechKey(message.content), target)
155
+ ))
156
+ }
157
+
158
+ frontendContext({ ownerId, sessionId }) {
159
+ const messages = this.list({ ownerId, sessionId })
160
+ const presentedTaskIds = new Set()
161
+ messages
162
+ .filter(message => message.source === 'agent-presentation')
163
+ .forEach(message => {
164
+ if (message.taskId) presentedTaskIds.add(message.taskId)
165
+ message.taskIds?.forEach(taskId => presentedTaskIds.add(taskId))
166
+ })
167
+ return messages.filter(message => (
168
+ [
169
+ 'voice-user',
170
+ 'realtime-direct',
171
+ 'agent-presentation',
172
+ ].includes(message.source)
173
+ || (
174
+ message.source === 'agent-result'
175
+ && message.taskId
176
+ && !presentedTaskIds.has(message.taskId)
177
+ )
178
+ ))
179
+ }
180
+
181
+ }
182
+
183
+ export const conversationSync = new ConversationSync()