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,234 @@
1
+ import { createHash } from 'node:crypto'
2
+ import {
3
+ chmodSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ renameSync,
7
+ writeFileSync,
8
+ } from 'node:fs'
9
+ import { dirname } from 'node:path'
10
+
11
+ const MAX_PROFILE_CHARS = 6000
12
+ const MAX_ENTRY_CHARS = 500
13
+ const MAX_MANAGED_ENTRIES = 32
14
+ const MANAGED_START = '<!-- qwenaudio:managed-profile:start -->'
15
+ const MANAGED_END = '<!-- qwenaudio:managed-profile:end -->'
16
+ const MANAGED_HEADING = '## 千问Audio 维护的档案'
17
+
18
+ function bounded(value) {
19
+ return [...String(value || '').trim()].slice(0, MAX_PROFILE_CHARS).join('')
20
+ }
21
+
22
+ function hasProfileData(content) {
23
+ return content
24
+ .replace(/<!--[\s\S]*?-->/g, '')
25
+ .split('\n')
26
+ .map(line => line.trim())
27
+ .some(line => line && !line.startsWith('#') && line !== '-' && !/^- [^:]+:$/.test(line))
28
+ }
29
+
30
+ function clean(value, limit = MAX_ENTRY_CHARS) {
31
+ return [...String(value || '')
32
+ .replaceAll('<!--', '<!--')
33
+ .replaceAll('-->', '-->')
34
+ .replace(/\s+/g, ' ')
35
+ .trim()]
36
+ .slice(0, limit)
37
+ .join('')
38
+ }
39
+
40
+ function profileId(content) {
41
+ return `profile_${createHash('sha256').update(content).digest('hex').slice(0, 16)}`
42
+ }
43
+
44
+ function managedPattern() {
45
+ return new RegExp(
46
+ `\\n?${MANAGED_HEADING}\\n\\n${MANAGED_START}\\n([\\s\\S]*?)\\n${MANAGED_END}\\n?`,
47
+ )
48
+ }
49
+
50
+ function parseManaged(content) {
51
+ const block = content.match(managedPattern())?.[1] || ''
52
+ return block.split('\n').map(line => {
53
+ const match = line.match(/^- (.*?) <!-- (profile_[a-f0-9]{16}) -->$/)
54
+ if (!match) return null
55
+ return { id: match[2], content: clean(match[1]) }
56
+ }).filter(entry => entry?.content)
57
+ }
58
+
59
+ function withoutManaged(content) {
60
+ return content.replace(managedPattern(), '\n').trim()
61
+ }
62
+
63
+ function render(content, entries) {
64
+ const base = withoutManaged(content)
65
+ if (!entries.length) return `${base}\n`
66
+ return [
67
+ base,
68
+ '',
69
+ MANAGED_HEADING,
70
+ '',
71
+ MANAGED_START,
72
+ ...entries.map(entry => `- ${entry.content} <!-- ${entry.id} -->`),
73
+ MANAGED_END,
74
+ '',
75
+ ].join('\n')
76
+ }
77
+
78
+ export class UserProfile {
79
+ constructor({
80
+ filePath = null,
81
+ onWarning = warning => console.warn(warning.message),
82
+ } = {}) {
83
+ this.filePath = filePath
84
+ this.onWarning = onWarning
85
+ this.warning = null
86
+ }
87
+
88
+ read() {
89
+ if (!this.filePath) return ''
90
+ try {
91
+ const content = bounded(readFileSync(this.filePath, 'utf8'))
92
+ this.warning = null
93
+ return hasProfileData(content) ? content : ''
94
+ } catch (error) {
95
+ if (error.code === 'ENOENT') return ''
96
+ this.warning = {
97
+ message: `无法读取用户档案:${error.message}`,
98
+ at: Date.now(),
99
+ }
100
+ try {
101
+ this.onWarning?.(this.warning)
102
+ } catch {
103
+ // Diagnostics must not prevent the voice service from running.
104
+ }
105
+ return ''
106
+ }
107
+ }
108
+
109
+ list({ query = '' } = {}) {
110
+ const content = this.read()
111
+ if (!content) return []
112
+ const needle = clean(query).toLocaleLowerCase()
113
+ const base = withoutManaged(content)
114
+ const managed = parseManaged(content)
115
+ .filter(entry => !needle || entry.content.toLocaleLowerCase().includes(needle))
116
+ .map(entry => ({
117
+ ...entry,
118
+ scope: 'profile',
119
+ updated_at: null,
120
+ editable: true,
121
+ }))
122
+ const baseEntry = hasProfileData(base) && (!needle || base.toLocaleLowerCase().includes(needle))
123
+ ? [{
124
+ id: 'user_profile',
125
+ scope: 'profile',
126
+ content: base,
127
+ updated_at: null,
128
+ editable: false,
129
+ }]
130
+ : []
131
+ return [...baseEntry, ...managed]
132
+ }
133
+
134
+ remember(value) {
135
+ const content = clean(value)
136
+ if (!content) throw new Error('profile content is required')
137
+ const current = this.readRaw()
138
+ const entries = parseManaged(current)
139
+ const existing = entries.find(entry => (
140
+ entry.content.toLocaleLowerCase() === content.toLocaleLowerCase()
141
+ ))
142
+ if (existing) return { ...existing, scope: 'profile', updated_at: null, editable: true }
143
+ if (entries.length >= MAX_MANAGED_ENTRIES) {
144
+ throw new Error(`用户档案最多保存 ${MAX_MANAGED_ENTRIES} 条托管记录`)
145
+ }
146
+ const entry = { id: profileId(content), content }
147
+ entries.push(entry)
148
+ const next = render(current || '# USER', entries)
149
+ if ([...next].length > MAX_PROFILE_CHARS) {
150
+ throw new Error(`用户档案最多保存 ${MAX_PROFILE_CHARS} 个字符`)
151
+ }
152
+ this.persist(next)
153
+ return { ...entry, scope: 'profile', updated_at: null, editable: true }
154
+ }
155
+
156
+ replace({ ids = [], content: value } = {}) {
157
+ const content = clean(value)
158
+ const targets = new Set(ids.map(id => clean(id)).filter(Boolean))
159
+ if (!content) throw new Error('profile content is required')
160
+ if (!targets.size) throw new Error('profile ids are required')
161
+ const current = this.readRaw()
162
+ const entries = parseManaged(current)
163
+ const matched = entries.filter(entry => targets.has(entry.id))
164
+ if (!matched.length) return { replaced: 0, memory: null }
165
+ const retained = entries.filter(entry => !targets.has(entry.id))
166
+ let entry = retained.find(item => (
167
+ item.content.toLocaleLowerCase() === content.toLocaleLowerCase()
168
+ ))
169
+ if (!entry) {
170
+ entry = { id: profileId(content), content }
171
+ retained.push(entry)
172
+ }
173
+ const next = render(current || '# USER', retained)
174
+ if ([...next].length > MAX_PROFILE_CHARS) {
175
+ throw new Error(`用户档案最多保存 ${MAX_PROFILE_CHARS} 个字符`)
176
+ }
177
+ this.persist(next)
178
+ return {
179
+ replaced: matched.length,
180
+ memory: {
181
+ ...entry,
182
+ scope: 'profile',
183
+ updated_at: null,
184
+ editable: true,
185
+ },
186
+ }
187
+ }
188
+
189
+ forget({ query = '', all = false } = {}) {
190
+ const current = this.readRaw()
191
+ const entries = parseManaged(current)
192
+ const needle = clean(query).toLocaleLowerCase()
193
+ const retained = all
194
+ ? []
195
+ : entries.filter(entry => (
196
+ !needle
197
+ || (
198
+ entry.id.toLocaleLowerCase() !== needle
199
+ && !entry.content.toLocaleLowerCase().includes(needle)
200
+ )
201
+ ))
202
+ const removed = entries.length - retained.length
203
+ if (removed) this.persist(render(current, retained))
204
+ return removed
205
+ }
206
+
207
+ readRaw() {
208
+ if (!this.filePath) return ''
209
+ try {
210
+ return readFileSync(this.filePath, 'utf8')
211
+ } catch (error) {
212
+ if (error.code === 'ENOENT') return ''
213
+ throw error
214
+ }
215
+ }
216
+
217
+ persist(content) {
218
+ if (!this.filePath) throw new Error('user profile is unavailable')
219
+ mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 })
220
+ const temporary = `${this.filePath}.${process.pid}.tmp`
221
+ writeFileSync(temporary, content, { encoding: 'utf8', mode: 0o600 })
222
+ renameSync(temporary, this.filePath)
223
+ chmodSync(this.filePath, 0o600)
224
+ this.warning = null
225
+ }
226
+
227
+ health() {
228
+ return {
229
+ ok: !this.warning,
230
+ configured: Boolean(this.filePath),
231
+ warning: this.warning,
232
+ }
233
+ }
234
+ }
@@ -0,0 +1,388 @@
1
+ import { dirname, resolve } from 'path'
2
+ import { fileURLToPath } from 'url'
3
+ import { loadRuntimeEnvironment } from '../../../shared/runtime-environment.mjs'
4
+ import {
5
+ backendDefinition,
6
+ backendNames,
7
+ } from '../../../shared/backend-catalog.mjs'
8
+
9
+ const here = dirname(fileURLToPath(import.meta.url))
10
+ const root = resolve(here, '../../..')
11
+ const runtimeEnvironment = loadRuntimeEnvironment({ root })
12
+
13
+ function numberSetting(value, fallback, {
14
+ min = Number.NEGATIVE_INFINITY,
15
+ max = Number.POSITIVE_INFINITY,
16
+ } = {}) {
17
+ const parsed = Number(value)
18
+ if (!Number.isFinite(parsed)) return fallback
19
+ return Math.min(max, Math.max(min, parsed))
20
+ }
21
+
22
+ export function resolveOpenCodeWorkspace(
23
+ env = process.env,
24
+ configDirectory = runtimeEnvironment.configDirectory,
25
+ ) {
26
+ return env.OPENCODE_WORKSPACE
27
+ ? resolve(root, env.OPENCODE_WORKSPACE)
28
+ : resolve(configDirectory, 'workspaces/opencode')
29
+ }
30
+
31
+ export function resolveQoderWorkspace(
32
+ env = process.env,
33
+ configDirectory = runtimeEnvironment.configDirectory,
34
+ ) {
35
+ return env.QODER_WORKSPACE
36
+ ? resolve(root, env.QODER_WORKSPACE)
37
+ : resolve(configDirectory, 'workspaces/qoder')
38
+ }
39
+
40
+ export function resolveHermesWorkspace(
41
+ env = process.env,
42
+ configDirectory = runtimeEnvironment.configDirectory,
43
+ ) {
44
+ return env.HERMES_WORKSPACE
45
+ ? resolve(root, env.HERMES_WORKSPACE)
46
+ : resolve(configDirectory, 'workspaces/hermes')
47
+ }
48
+
49
+ export function resolveCodeBuddyWorkspace(
50
+ env = process.env,
51
+ configDirectory = runtimeEnvironment.configDirectory,
52
+ ) {
53
+ return env.CODEBUDDY_WORKSPACE
54
+ ? resolve(root, env.CODEBUDDY_WORKSPACE)
55
+ : resolve(configDirectory, 'workspaces/codebuddy')
56
+ }
57
+
58
+ export function resolveCodexWorkspace(
59
+ env = process.env,
60
+ configDirectory = runtimeEnvironment.configDirectory,
61
+ ) {
62
+ return env.CODEX_WORKSPACE
63
+ ? resolve(root, env.CODEX_WORKSPACE)
64
+ : resolve(configDirectory, 'workspaces/codex')
65
+ }
66
+
67
+ export function resolveOpenClawWorkspace(
68
+ env = process.env,
69
+ configDirectory = runtimeEnvironment.configDirectory,
70
+ ) {
71
+ return env.QWEN_AUDIO_AGENT_OPENCLAW_WORKSPACE
72
+ ? resolve(root, env.QWEN_AUDIO_AGENT_OPENCLAW_WORKSPACE)
73
+ : resolve(configDirectory, 'workspaces/openclaw')
74
+ }
75
+
76
+ export function resolveAcpWorkspace(
77
+ env = process.env,
78
+ configDirectory = runtimeEnvironment.configDirectory,
79
+ ) {
80
+ return env.ACP_WORKSPACE
81
+ ? resolve(root, env.ACP_WORKSPACE)
82
+ : resolve(configDirectory, 'workspaces/acp')
83
+ }
84
+
85
+ export function resolveAcpArgs(value) {
86
+ const source = String(value || '').trim()
87
+ if (!source) return []
88
+ if (source.startsWith('[')) {
89
+ let parsed
90
+ try {
91
+ parsed = JSON.parse(source)
92
+ } catch {
93
+ throw new Error('ACP_ARGS 不是有效的 JSON 数组')
94
+ }
95
+ if (!Array.isArray(parsed) || parsed.some(item => typeof item !== 'string')) {
96
+ throw new Error('ACP_ARGS 必须是字符串组成的 JSON 数组')
97
+ }
98
+ return parsed
99
+ }
100
+ return source.split(/\s+/)
101
+ }
102
+
103
+ const DEFAULT_BACKEND_MODEL = 'qwen3.7-max'
104
+
105
+ function backendModelName(value) {
106
+ const model = String(value || DEFAULT_BACKEND_MODEL).trim()
107
+ const separator = model.indexOf('/')
108
+ return separator >= 0 ? model.slice(separator + 1) : model
109
+ }
110
+
111
+ export function resolveBackendModels(env = process.env) {
112
+ const common = String(
113
+ env.QWEN_AUDIO_AGENT_BACKEND_MODEL || DEFAULT_BACKEND_MODEL,
114
+ ).trim() || DEFAULT_BACKEND_MODEL
115
+ return {
116
+ common,
117
+ openCode: String(
118
+ env.OPENCODE_MODEL
119
+ || `alibaba-cn/${backendModelName(common)}`,
120
+ ).trim(),
121
+ openClaw: String(
122
+ env.OPENCLAW_MODEL
123
+ || `bailian/${backendModelName(common)}`,
124
+ ).trim(),
125
+ }
126
+ }
127
+
128
+ const backendMode = (
129
+ String(process.env.QWEN_AUDIO_AGENT_BACKEND_MODE || 'managed').toLowerCase()
130
+ === 'compatible'
131
+ ? 'compatible'
132
+ : 'managed'
133
+ )
134
+ const backendModels = resolveBackendModels()
135
+ const backendPermissionMode = String(
136
+ process.env.QWEN_AUDIO_AGENT_BACKEND_PERMISSION_MODE || 'native',
137
+ ).toLowerCase()
138
+ if (!['native', 'full'].includes(backendPermissionMode)) {
139
+ throw new Error(
140
+ `不支持的后台权限模式:${backendPermissionMode}(可选 native、full)`,
141
+ )
142
+ }
143
+ const requestedAgentProtocol = String(
144
+ process.env.AGENT_PROTOCOL || '',
145
+ ).toLowerCase()
146
+ if (requestedAgentProtocol && !backendDefinition(requestedAgentProtocol)) {
147
+ throw new Error(
148
+ `不支持的后台 Agent:${requestedAgentProtocol}`
149
+ + `(可选 ${backendNames().join('、')})`,
150
+ )
151
+ }
152
+ const sharedBackendAgent = String(
153
+ process.env.QWEN_AUDIO_AGENT_BACKEND_AGENT || '',
154
+ ).trim()
155
+ function legacyBackendAgent(value, legacyDefault) {
156
+ const selected = String(value || '').trim()
157
+ return selected === legacyDefault ? 'qwen-audio-agent-backend' : selected
158
+ }
159
+
160
+ export const config = {
161
+ root,
162
+ host: process.env.HOST || '127.0.0.1',
163
+ port: numberSetting(process.env.PORT, 3101, { min: 1, max: 65535 }),
164
+ audioProvider: String(
165
+ process.env.QWEN_AUDIO_REALTIME_PROVIDER || 'dashscope',
166
+ ).trim().toLowerCase(),
167
+ dashscopeApiKey: (
168
+ process.env.QWEN_AUDIO_REALTIME_API_KEY
169
+ || process.env.DASHSCOPE_API_KEY
170
+ || ''
171
+ ),
172
+ audioRealtimeBaseUrl: (
173
+ process.env.QWEN_AUDIO_REALTIME_BASE_URL
174
+ || process.env.QWEN_AUDIO_REALTIME_URL
175
+ || (
176
+ process.env.DASHSCOPE_WORKSPACE_ID
177
+ ? `wss://${process.env.DASHSCOPE_WORKSPACE_ID}.cn-beijing.maas.aliyuncs.com/api-ws/v1/realtime`
178
+ : 'wss://dashscope.aliyuncs.com/api-ws/v1/realtime'
179
+ )
180
+ ).replace(/\?+$/, ''),
181
+ audioModel: process.env.QWEN_AUDIO_REALTIME_MODEL || 'qwen-audio-3.0-realtime-plus',
182
+ audioVoice: process.env.QWEN_AUDIO_REALTIME_VOICE || 'longanqian',
183
+ allowedOrigins: String(process.env.QWEN_AUDIO_AGENT_ALLOWED_ORIGINS || '')
184
+ .split(',')
185
+ .map(value => value.trim())
186
+ .filter(Boolean),
187
+ authSecret: process.env.QWEN_AUDIO_AGENT_AUTH_SECRET || '',
188
+ identityMode: (
189
+ process.env.QWEN_AUDIO_AGENT_IDENTITY_MODE || 'personal'
190
+ ).toLowerCase() === 'browser' ? 'browser' : 'personal',
191
+ personalOwnerId: process.env.QWEN_AUDIO_AGENT_PERSONAL_OWNER_ID || 'user_personal',
192
+ agentProtocol: requestedAgentProtocol,
193
+ backendMode,
194
+ backendPermissionMode,
195
+ agentTimeoutMs: numberSetting(process.env.AGENT_TIMEOUT_MS, 300000, { min: 10000 }),
196
+ openClawBaseUrl: (
197
+ process.env.OPENCLAW_BASE_URL
198
+ || 'http://127.0.0.1:18789'
199
+ ).replace(/\/+$/, ''),
200
+ openClawToken: (
201
+ process.env.OPENCLAW_GATEWAY_TOKEN
202
+ || process.env.AGENT_API_KEY
203
+ || process.env.QWEN_AUDIO_AGENT_AUTH_SECRET
204
+ || ''
205
+ ),
206
+ openClawTokenFile: (
207
+ process.env.OPENCLAW_GATEWAY_TOKEN_FILE
208
+ || resolve(runtimeEnvironment.openClawStateDirectory, 'gateway-token')
209
+ ),
210
+ openClawDirectory: resolveOpenClawWorkspace(),
211
+ openClawCoordinatorAgent: (
212
+ sharedBackendAgent
213
+ || legacyBackendAgent(
214
+ process.env.OPENCLAW_COORDINATOR_AGENT,
215
+ 'voice-coordinator',
216
+ )
217
+ || (backendMode === 'managed' ? 'qwen-audio-agent-backend' : '')
218
+ ),
219
+ openCodeBaseUrl: (
220
+ process.env.OPENCODE_BASE_URL
221
+ || 'http://127.0.0.1:4096'
222
+ ).replace(/\/+$/, ''),
223
+ openCodeDirectory: resolveOpenCodeWorkspace(),
224
+ qoderDirectory: resolveQoderWorkspace(),
225
+ qoderConfigDirectory: process.env.QODER_CONFIG_DIR
226
+ ? resolve(process.env.QODER_CONFIG_DIR)
227
+ : '',
228
+ qoderCliPath: String(
229
+ process.env.QODERCLI_PATH || process.env.QODER_CLI_PATH || '',
230
+ ).trim(),
231
+ qoderModel: String(process.env.QODER_MODEL || 'auto').trim() || 'auto',
232
+ hermesDirectory: resolveHermesWorkspace(),
233
+ hermesCliPath: String(process.env.HERMES_BIN || '').trim(),
234
+ codeBuddyDirectory: resolveCodeBuddyWorkspace(),
235
+ codeBuddyCliPath: String(process.env.CODEBUDDY_BIN || '').trim(),
236
+ codeBuddyModel: String(
237
+ process.env.CODEBUDDY_MODEL || backendModelName(backendModels.common),
238
+ ).trim(),
239
+ codeBuddyModelUrl: (
240
+ process.env.CODEBUDDY_MODEL_URL
241
+ || (
242
+ process.env.DASHSCOPE_WORKSPACE_ID
243
+ ? `https://${process.env.DASHSCOPE_WORKSPACE_ID}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions`
244
+ : 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'
245
+ )
246
+ ),
247
+ codexDirectory: resolveCodexWorkspace(),
248
+ codexCliPath: String(process.env.CODEX_ACP_BIN || '').trim(),
249
+ codexModel: String(
250
+ process.env.CODEX_MODEL || backendModelName(backendModels.common),
251
+ ).trim(),
252
+ codexModelUrl: (
253
+ process.env.CODEX_BASE_URL
254
+ || (
255
+ process.env.DASHSCOPE_WORKSPACE_ID
256
+ ? `https://${process.env.DASHSCOPE_WORKSPACE_ID}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`
257
+ : 'https://dashscope.aliyuncs.com/compatible-mode/v1'
258
+ )
259
+ ).replace(/\/+$/, ''),
260
+ acpCommand: String(process.env.ACP_COMMAND || '').trim(),
261
+ acpArgs: resolveAcpArgs(process.env.ACP_ARGS),
262
+ acpLabel: String(process.env.ACP_LABEL || 'ACP Agent').trim() || 'ACP Agent',
263
+ acpDirectory: resolveAcpWorkspace(),
264
+ acpModel: String(process.env.ACP_MODEL || 'auto').trim() || 'auto',
265
+ acpCoordinatorAgent: String(process.env.ACP_COORDINATOR_AGENT || '').trim(),
266
+ openCodeModel: (
267
+ process.env.OPENCODE_MODEL
268
+ || (backendMode === 'managed' ? backendModels.openCode : '')
269
+ ),
270
+ openClawModel: (
271
+ process.env.OPENCLAW_MODEL
272
+ || (backendMode === 'managed' ? backendModels.openClaw : '')
273
+ ),
274
+ backendModel: backendMode === 'managed' ? backendModels.common : '',
275
+ openCodeCoordinatorAgent: (
276
+ sharedBackendAgent
277
+ || legacyBackendAgent(
278
+ process.env.OPENCODE_COORDINATOR_AGENT,
279
+ 'qwen-audio-agent-coordinator',
280
+ )
281
+ || (backendMode === 'managed' ? 'qwen-audio-agent-backend' : '')
282
+ ),
283
+ announceIntoContext: (
284
+ String(process.env.QWEN_AUDIO_AGENT_ANNOUNCE_INTO_CONTEXT || 'true').toLowerCase()
285
+ === 'true'
286
+ ),
287
+ resultContextMaxChars: numberSetting(
288
+ process.env.QWEN_AUDIO_AGENT_RESULT_CONTEXT_MAX_CHARS,
289
+ 6000,
290
+ { min: 256 },
291
+ ),
292
+ announcementBatchMs: numberSetting(
293
+ process.env.QWEN_AUDIO_AGENT_ANNOUNCEMENT_BATCH_MS,
294
+ 120,
295
+ { min: 0, max: 1000 },
296
+ ),
297
+ announcementMaxBatchItems: numberSetting(
298
+ process.env.QWEN_AUDIO_AGENT_ANNOUNCEMENT_MAX_BATCH_ITEMS,
299
+ 8,
300
+ { min: 1, max: 32 },
301
+ ),
302
+ announcementQuietMs: numberSetting(
303
+ process.env.QWEN_AUDIO_AGENT_ANNOUNCEMENT_QUIET_MS,
304
+ 350,
305
+ { min: 0, max: 2000 },
306
+ ),
307
+ announcementAcknowledgementTimeoutMs: numberSetting(
308
+ process.env.QWEN_AUDIO_AGENT_ANNOUNCEMENT_ACK_TIMEOUT_MS,
309
+ 120_000,
310
+ { min: 10_000 },
311
+ ),
312
+ announcementMaxRetryAttempts: numberSetting(
313
+ process.env.QWEN_AUDIO_AGENT_ANNOUNCEMENT_MAX_RETRIES,
314
+ 8,
315
+ { min: 1, max: 32 },
316
+ ),
317
+ frontendPromptDir: process.env.QWEN_AUDIO_AGENT_FRONTEND_PROMPT_DIR
318
+ ? resolve(root, process.env.QWEN_AUDIO_AGENT_FRONTEND_PROMPT_DIR)
319
+ : resolve(root, 'config/frontend-agent'),
320
+ frontendMemoryPath: process.env.QWEN_AUDIO_AGENT_FRONTEND_MEMORY_PATH
321
+ ? resolve(root, process.env.QWEN_AUDIO_AGENT_FRONTEND_MEMORY_PATH)
322
+ : runtimeEnvironment.frontendMemoryPath,
323
+ userProfilePath: process.env.QWEN_AUDIO_AGENT_USER_PROFILE_PATH
324
+ ? resolve(root, process.env.QWEN_AUDIO_AGENT_USER_PROFILE_PATH)
325
+ : runtimeEnvironment.userProfilePath,
326
+ taskStatePath: process.env.QWEN_AUDIO_AGENT_TASK_STATE_PATH
327
+ ? resolve(root, process.env.QWEN_AUDIO_AGENT_TASK_STATE_PATH)
328
+ : runtimeEnvironment.taskStatePath,
329
+ backendSessionStatePath: process.env.QWEN_AUDIO_AGENT_BACKEND_SESSION_STATE_PATH
330
+ ? resolve(root, process.env.QWEN_AUDIO_AGENT_BACKEND_SESSION_STATE_PATH)
331
+ : resolve(runtimeEnvironment.configDirectory, 'state/acp-sessions.json'),
332
+ taskTerminalTtlMs: numberSetting(
333
+ process.env.QWEN_AUDIO_AGENT_TASK_TERMINAL_TTL_MS,
334
+ 86_400_000,
335
+ { min: 60_000 },
336
+ ),
337
+ taskPendingNotificationTtlMs: numberSetting(
338
+ process.env.QWEN_AUDIO_AGENT_TASK_NOTIFICATION_TTL_MS,
339
+ 604_800_000,
340
+ { min: 60_000 },
341
+ ),
342
+ taskNotificationClaimTtlMs: numberSetting(
343
+ process.env.QWEN_AUDIO_AGENT_TASK_NOTIFICATION_CLAIM_TTL_MS,
344
+ 60_000,
345
+ { min: 5_000 },
346
+ ),
347
+ maxTerminalTasksPerOwner: numberSetting(
348
+ process.env.QWEN_AUDIO_AGENT_MAX_TERMINAL_TASKS_PER_OWNER,
349
+ 100,
350
+ { min: 10 },
351
+ ),
352
+ taskMaxConcurrent: numberSetting(
353
+ process.env.QWEN_AUDIO_AGENT_TASK_MAX_CONCURRENT,
354
+ 4,
355
+ { min: 1, max: 64 },
356
+ ),
357
+ taskMaxConcurrentPerOwner: numberSetting(
358
+ process.env.QWEN_AUDIO_AGENT_TASK_MAX_CONCURRENT_PER_OWNER,
359
+ 2,
360
+ { min: 1, max: 16 },
361
+ ),
362
+ conversationSessionTtlMs: numberSetting(
363
+ process.env.QWEN_AUDIO_AGENT_SESSION_TTL_MS,
364
+ 21_600_000,
365
+ { min: 60_000 },
366
+ ),
367
+ maxConversationSessions: numberSetting(
368
+ process.env.QWEN_AUDIO_AGENT_MAX_SESSIONS,
369
+ 500,
370
+ { min: 10 },
371
+ ),
372
+ // Zero keeps explicit personal memories until the user removes them.
373
+ frontendMemoryOwnerTtlMs: numberSetting(
374
+ process.env.QWEN_AUDIO_AGENT_MEMORY_OWNER_TTL_MS,
375
+ 0,
376
+ { min: 0 },
377
+ ),
378
+ maxFrontendMemoryOwners: numberSetting(
379
+ process.env.QWEN_AUDIO_AGENT_MAX_MEMORY_OWNERS,
380
+ 1000,
381
+ { min: 10 },
382
+ ),
383
+ }
384
+
385
+ export function realtimeUrl(baseUrl, model) {
386
+ const separator = baseUrl.includes('?') ? '&' : '?'
387
+ return `${baseUrl}${separator}model=${encodeURIComponent(model)}`
388
+ }
@@ -0,0 +1,93 @@
1
+ import {
2
+ createHmac,
3
+ randomUUID,
4
+ timingSafeEqual,
5
+ } from 'node:crypto'
6
+
7
+ const COOKIE_NAME = 'qwen_audio_agent_identity'
8
+ const MAX_AGE_SECONDS = 7 * 24 * 60 * 60
9
+
10
+ function cookies(header = '') {
11
+ return Object.fromEntries(
12
+ header
13
+ .split(';')
14
+ .map(part => part.trim())
15
+ .filter(Boolean)
16
+ .map(part => {
17
+ const separator = part.indexOf('=')
18
+ if (separator < 0) return [part, '']
19
+ try {
20
+ return [part.slice(0, separator), decodeURIComponent(part.slice(separator + 1))]
21
+ } catch {
22
+ return [part.slice(0, separator), '']
23
+ }
24
+ }),
25
+ )
26
+ }
27
+
28
+ export class IdentityManager {
29
+ constructor({
30
+ secret,
31
+ cookieName = COOKIE_NAME,
32
+ mode = 'browser',
33
+ personalOwnerId = 'user_personal',
34
+ } = {}) {
35
+ if (!secret || String(secret).length < 32) {
36
+ throw new Error('QWEN_AUDIO_AGENT_AUTH_SECRET must contain at least 32 characters')
37
+ }
38
+ this.secret = String(secret)
39
+ this.cookieName = cookieName
40
+ this.mode = mode === 'personal' ? 'personal' : 'browser'
41
+ this.personalIdentity = {
42
+ ownerId: String(personalOwnerId || 'user_personal'),
43
+ }
44
+ }
45
+
46
+ sign(ownerId) {
47
+ return createHmac('sha256', this.secret).update(ownerId).digest('base64url')
48
+ }
49
+
50
+ resolveToken(header) {
51
+ const token = cookies(header)[this.cookieName]
52
+ if (!token) return null
53
+ const separator = token.lastIndexOf('.')
54
+ if (separator < 0) return null
55
+ const ownerId = token.slice(0, separator)
56
+ const supplied = Buffer.from(token.slice(separator + 1))
57
+ const expected = Buffer.from(this.sign(ownerId))
58
+ if (
59
+ !ownerId.startsWith('user_')
60
+ || supplied.length !== expected.length
61
+ || !timingSafeEqual(supplied, expected)
62
+ ) return null
63
+ return { ownerId }
64
+ }
65
+
66
+ issue(res, { secure = false } = {}) {
67
+ const identity = { ownerId: `user_${randomUUID()}` }
68
+ const token = `${identity.ownerId}.${this.sign(identity.ownerId)}`
69
+ const attributes = [
70
+ `${this.cookieName}=${encodeURIComponent(token)}`,
71
+ 'Path=/',
72
+ 'HttpOnly',
73
+ 'SameSite=Strict',
74
+ `Max-Age=${MAX_AGE_SECONDS}`,
75
+ ]
76
+ if (secure) attributes.push('Secure')
77
+ res.setHeader('Set-Cookie', attributes.join('; '))
78
+ return identity
79
+ }
80
+
81
+ resolveHttp(req, res) {
82
+ if (this.mode === 'personal') return this.personalIdentity
83
+ return this.resolveToken(req.headers.cookie)
84
+ || this.issue(res, {
85
+ secure: req.socket?.encrypted || req.headers['x-forwarded-proto'] === 'https',
86
+ })
87
+ }
88
+
89
+ resolveUpgrade(req) {
90
+ if (this.mode === 'personal') return this.personalIdentity
91
+ return this.resolveToken(req.headers.cookie)
92
+ }
93
+ }