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,386 @@
1
+ import { execFile } from 'node:child_process'
2
+ import {
3
+ mkdirSync,
4
+ readFileSync,
5
+ unlinkSync,
6
+ writeFileSync,
7
+ } from 'node:fs'
8
+ import { homedir } from 'node:os'
9
+ import { dirname, resolve } from 'node:path'
10
+
11
+ export const GATEWAY_SERVICE_LABEL = 'com.qwen-audio-agent.gateway'
12
+
13
+ function xml(value) {
14
+ return String(value)
15
+ .replaceAll('&', '&')
16
+ .replaceAll('<', '&lt;')
17
+ .replaceAll('>', '&gt;')
18
+ .replaceAll('"', '&quot;')
19
+ .replaceAll("'", '&apos;')
20
+ }
21
+
22
+ function systemd(value) {
23
+ return `"${String(value)
24
+ .replaceAll('%', '%%')
25
+ .replaceAll('\\', '\\\\')
26
+ .replaceAll('"', '\\"')
27
+ .replaceAll('\n', '')}"`
28
+ }
29
+
30
+ function executeFile(command, args, options = {}) {
31
+ return new Promise((resolvePromise, rejectPromise) => {
32
+ execFile(command, args, options, (error, stdout, stderr) => {
33
+ if (error) {
34
+ error.stdout = stdout
35
+ error.stderr = stderr
36
+ rejectPromise(error)
37
+ } else {
38
+ resolvePromise({ stdout, stderr })
39
+ }
40
+ })
41
+ })
42
+ }
43
+
44
+ export function gatewayServiceDefinition({
45
+ platform = process.platform,
46
+ homeDirectory = homedir(),
47
+ xdgConfigHome = process.env.XDG_CONFIG_HOME
48
+ || resolve(homeDirectory, '.config'),
49
+ configDirectory,
50
+ nodePath = process.execPath,
51
+ gatewayPath,
52
+ pathEnvironment = process.env.PATH || '',
53
+ serviceEnvironment = {},
54
+ serviceMetadata = {},
55
+ } = {}) {
56
+ if (!configDirectory) throw new Error('缺少 qwen-audio-agent 配置目录')
57
+ if (!gatewayPath) throw new Error('缺少 qwen-audio-agent Gateway 路径')
58
+ const logsDirectory = resolve(configDirectory, 'logs')
59
+ const metadataPath = resolve(configDirectory, 'gateway-service.json')
60
+ const command = [nodePath, gatewayPath]
61
+ const workingDirectory = dirname(gatewayPath)
62
+ const environment = {
63
+ QWAUDIO_CONFIG_DIR: configDirectory,
64
+ PATH: pathEnvironment,
65
+ ...serviceEnvironment,
66
+ }
67
+
68
+ if (platform === 'darwin') {
69
+ const servicePath = resolve(
70
+ homeDirectory,
71
+ 'Library/LaunchAgents',
72
+ `${GATEWAY_SERVICE_LABEL}.plist`,
73
+ )
74
+ const content = `<?xml version="1.0" encoding="UTF-8"?>
75
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
76
+ <plist version="1.0">
77
+ <dict>
78
+ <key>Label</key>
79
+ <string>${GATEWAY_SERVICE_LABEL}</string>
80
+ <key>ProgramArguments</key>
81
+ <array>
82
+ ${command.map(value => ` <string>${xml(value)}</string>`).join('\n')}
83
+ </array>
84
+ <key>EnvironmentVariables</key>
85
+ <dict>
86
+ ${Object.entries(environment).map(([key, value]) => (
87
+ ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`
88
+ )).join('\n')}
89
+ </dict>
90
+ <key>WorkingDirectory</key>
91
+ <string>${xml(workingDirectory)}</string>
92
+ <key>RunAtLoad</key>
93
+ <true/>
94
+ <key>KeepAlive</key>
95
+ <true/>
96
+ <key>ThrottleInterval</key>
97
+ <integer>5</integer>
98
+ <key>ProcessType</key>
99
+ <string>Background</string>
100
+ <key>StandardOutPath</key>
101
+ <string>${xml(resolve(logsDirectory, 'gateway.log'))}</string>
102
+ <key>StandardErrorPath</key>
103
+ <string>${xml(resolve(logsDirectory, 'gateway.log'))}</string>
104
+ </dict>
105
+ </plist>
106
+ `
107
+ return {
108
+ kind: 'launchd',
109
+ servicePath,
110
+ metadataPath,
111
+ serviceMetadata,
112
+ logsDirectory,
113
+ logPath: resolve(logsDirectory, 'gateway.log'),
114
+ content,
115
+ }
116
+ }
117
+
118
+ if (platform === 'linux') {
119
+ const servicePath = resolve(
120
+ xdgConfigHome,
121
+ 'systemd/user/qwen-audio-agent-gateway.service',
122
+ )
123
+ const content = `[Unit]
124
+ Description=qwen-audio-agent Gateway
125
+ After=network-online.target
126
+ Wants=network-online.target
127
+
128
+ [Service]
129
+ Type=simple
130
+ WorkingDirectory=${systemd(workingDirectory)}
131
+ ExecStart=${command.map(systemd).join(' ')}
132
+ ${Object.entries(environment).map(([key, value]) => (
133
+ `Environment=${systemd(`${key}=${value}`)}`
134
+ )).join('\n')}
135
+ Restart=on-failure
136
+ RestartSec=5
137
+ TimeoutStopSec=30
138
+ KillMode=control-group
139
+
140
+ [Install]
141
+ WantedBy=default.target
142
+ `
143
+ return {
144
+ kind: 'systemd',
145
+ servicePath,
146
+ metadataPath,
147
+ serviceMetadata,
148
+ logsDirectory,
149
+ logPath: null,
150
+ content,
151
+ }
152
+ }
153
+
154
+ throw new Error(
155
+ `当前系统暂不支持 Gateway 后台服务:${platform}`,
156
+ )
157
+ }
158
+
159
+ function fileExists(path) {
160
+ try {
161
+ readFileSync(path)
162
+ return true
163
+ } catch (error) {
164
+ if (error?.code === 'ENOENT') return false
165
+ throw error
166
+ }
167
+ }
168
+
169
+ function installDefinition(definition) {
170
+ mkdirSync(dirname(definition.servicePath), {
171
+ recursive: true,
172
+ mode: 0o700,
173
+ })
174
+ mkdirSync(definition.logsDirectory, {
175
+ recursive: true,
176
+ mode: 0o700,
177
+ })
178
+ writeFileSync(definition.servicePath, definition.content, {
179
+ encoding: 'utf8',
180
+ mode: 0o600,
181
+ })
182
+ writeFileSync(
183
+ definition.metadataPath,
184
+ `${JSON.stringify(definition.serviceMetadata, null, 2)}\n`,
185
+ { encoding: 'utf8', mode: 0o600 },
186
+ )
187
+ }
188
+
189
+ function removeDefinition(definition) {
190
+ for (const path of [definition.servicePath, definition.metadataPath]) {
191
+ try {
192
+ unlinkSync(path)
193
+ } catch (error) {
194
+ if (error?.code !== 'ENOENT') throw error
195
+ }
196
+ }
197
+ }
198
+
199
+ function installedMetadata(definition) {
200
+ try {
201
+ return JSON.parse(readFileSync(definition.metadataPath, 'utf8'))
202
+ } catch (error) {
203
+ if (error?.code === 'ENOENT' || error instanceof SyntaxError) return null
204
+ throw error
205
+ }
206
+ }
207
+
208
+ async function launchdLoaded(execute, domain) {
209
+ try {
210
+ await execute('launchctl', ['print', `${domain}/${GATEWAY_SERVICE_LABEL}`])
211
+ return true
212
+ } catch {
213
+ return false
214
+ }
215
+ }
216
+
217
+ async function launchdAction(action, definition, {
218
+ execute,
219
+ uid,
220
+ } = {}) {
221
+ const domain = `gui/${uid}`
222
+ const loaded = await launchdLoaded(execute, domain)
223
+ const installed = fileExists(definition.servicePath)
224
+
225
+ if (action === 'status') return { installed, running: loaded }
226
+ if (action === 'install') {
227
+ if (loaded) {
228
+ await execute('launchctl', [
229
+ 'bootout',
230
+ `${domain}/${GATEWAY_SERVICE_LABEL}`,
231
+ ])
232
+ }
233
+ installDefinition(definition)
234
+ await execute('launchctl', [
235
+ 'bootstrap',
236
+ domain,
237
+ definition.servicePath,
238
+ ])
239
+ return { installed: true, running: true }
240
+ }
241
+ if (action === 'uninstall') {
242
+ if (loaded) {
243
+ await execute('launchctl', [
244
+ 'bootout',
245
+ `${domain}/${GATEWAY_SERVICE_LABEL}`,
246
+ ])
247
+ }
248
+ removeDefinition(definition)
249
+ return { installed: false, running: false }
250
+ }
251
+ if (!installed) {
252
+ throw new Error(
253
+ 'Gateway 后台服务尚未安装;请先执行 qwenaudio gateway install',
254
+ )
255
+ }
256
+ if (action === 'start') {
257
+ if (loaded) {
258
+ await execute('launchctl', [
259
+ 'kickstart',
260
+ `${domain}/${GATEWAY_SERVICE_LABEL}`,
261
+ ])
262
+ } else {
263
+ await execute('launchctl', [
264
+ 'bootstrap',
265
+ domain,
266
+ definition.servicePath,
267
+ ])
268
+ }
269
+ return { installed: true, running: true }
270
+ }
271
+ if (action === 'restart') {
272
+ if (loaded) {
273
+ await execute('launchctl', [
274
+ 'kickstart',
275
+ '-k',
276
+ `${domain}/${GATEWAY_SERVICE_LABEL}`,
277
+ ])
278
+ } else {
279
+ await execute('launchctl', [
280
+ 'bootstrap',
281
+ domain,
282
+ definition.servicePath,
283
+ ])
284
+ }
285
+ return { installed: true, running: true }
286
+ }
287
+ if (action === 'stop') {
288
+ if (loaded) {
289
+ await execute('launchctl', [
290
+ 'bootout',
291
+ `${domain}/${GATEWAY_SERVICE_LABEL}`,
292
+ ])
293
+ }
294
+ return { installed: true, running: false }
295
+ }
296
+ throw new Error(`不支持的 Gateway 服务操作:${action}`)
297
+ }
298
+
299
+ async function systemdStatus(execute) {
300
+ try {
301
+ await execute('systemctl', [
302
+ '--user',
303
+ 'is-active',
304
+ '--quiet',
305
+ 'qwen-audio-agent-gateway.service',
306
+ ])
307
+ return true
308
+ } catch {
309
+ return false
310
+ }
311
+ }
312
+
313
+ async function systemdAction(action, definition, { execute } = {}) {
314
+ const unit = 'qwen-audio-agent-gateway.service'
315
+ const installed = fileExists(definition.servicePath)
316
+ if (action === 'status') {
317
+ return {
318
+ installed,
319
+ running: installed ? await systemdStatus(execute) : false,
320
+ }
321
+ }
322
+ if (action === 'install') {
323
+ installDefinition(definition)
324
+ await execute('systemctl', ['--user', 'daemon-reload'])
325
+ await execute('systemctl', ['--user', 'enable', '--now', unit])
326
+ return { installed: true, running: true }
327
+ }
328
+ if (action === 'uninstall') {
329
+ if (installed) {
330
+ try {
331
+ await execute('systemctl', ['--user', 'disable', '--now', unit])
332
+ } catch {
333
+ // A stopped or partially installed unit can still be safely removed.
334
+ }
335
+ }
336
+ removeDefinition(definition)
337
+ await execute('systemctl', ['--user', 'daemon-reload'])
338
+ return { installed: false, running: false }
339
+ }
340
+ if (!installed) {
341
+ throw new Error(
342
+ 'Gateway 后台服务尚未安装;请先执行 qwenaudio gateway install',
343
+ )
344
+ }
345
+ await execute('systemctl', ['--user', action, unit])
346
+ return {
347
+ installed: true,
348
+ running: action !== 'stop',
349
+ }
350
+ }
351
+
352
+ export async function manageGatewayService(action, {
353
+ platform = process.platform,
354
+ homeDirectory = homedir(),
355
+ xdgConfigHome = process.env.XDG_CONFIG_HOME
356
+ || resolve(homeDirectory, '.config'),
357
+ configDirectory,
358
+ nodePath = process.execPath,
359
+ gatewayPath,
360
+ pathEnvironment = process.env.PATH || '',
361
+ serviceEnvironment = {},
362
+ serviceMetadata = {},
363
+ uid = process.getuid?.(),
364
+ execute = executeFile,
365
+ } = {}) {
366
+ const definition = gatewayServiceDefinition({
367
+ platform,
368
+ homeDirectory,
369
+ xdgConfigHome,
370
+ configDirectory,
371
+ nodePath,
372
+ gatewayPath,
373
+ pathEnvironment,
374
+ serviceEnvironment,
375
+ serviceMetadata,
376
+ })
377
+ const options = { execute, uid }
378
+ const state = definition.kind === 'launchd'
379
+ ? await launchdAction(action, definition, options)
380
+ : await systemdAction(action, definition, options)
381
+ return {
382
+ ...state,
383
+ ...definition,
384
+ installedMetadata: installedMetadata(definition),
385
+ }
386
+ }
@@ -0,0 +1,65 @@
1
+ import {
2
+ closeSync,
3
+ openSync,
4
+ readFileSync,
5
+ unlinkSync,
6
+ writeFileSync,
7
+ } from 'node:fs'
8
+ import { resolve } from 'node:path'
9
+ import { randomUUID } from 'node:crypto'
10
+
11
+ function processIsAlive(pid, killImpl) {
12
+ if (!Number.isInteger(pid) || pid <= 0) return false
13
+ try {
14
+ killImpl(pid, 0)
15
+ return true
16
+ } catch (error) {
17
+ return error?.code === 'EPERM'
18
+ }
19
+ }
20
+
21
+ export function acquireCliInstance(
22
+ configDirectory,
23
+ {
24
+ pid = process.pid,
25
+ killImpl = process.kill,
26
+ token = randomUUID(),
27
+ } = {},
28
+ ) {
29
+ const path = resolve(configDirectory, 'cli.lock')
30
+ for (let attempt = 0; attempt < 2; attempt += 1) {
31
+ try {
32
+ const fd = openSync(path, 'wx', 0o600)
33
+ writeFileSync(fd, JSON.stringify({ pid, token }), 'utf8')
34
+ closeSync(fd)
35
+ return {
36
+ path,
37
+ release() {
38
+ try {
39
+ const current = JSON.parse(readFileSync(path, 'utf8'))
40
+ if (current.pid === pid && current.token === token) unlinkSync(path)
41
+ } catch {
42
+ // A missing or replaced lock no longer belongs to this process.
43
+ }
44
+ },
45
+ }
46
+ } catch (error) {
47
+ if (error?.code !== 'EEXIST') throw error
48
+ let existing
49
+ try {
50
+ existing = JSON.parse(readFileSync(path, 'utf8'))
51
+ } catch {
52
+ existing = null
53
+ }
54
+ if (processIsAlive(Number(existing?.pid), killImpl)) {
55
+ throw new Error('另一个 qwenaudio CLI 已在运行')
56
+ }
57
+ try {
58
+ unlinkSync(path)
59
+ } catch (unlinkError) {
60
+ if (unlinkError?.code !== 'ENOENT') throw unlinkError
61
+ }
62
+ }
63
+ }
64
+ throw new Error('无法获取 qwenaudio CLI 实例锁')
65
+ }
@@ -0,0 +1,217 @@
1
+ import { dirname, resolve } from 'node:path'
2
+ import { fileURLToPath, pathToFileURL } from 'node:url'
3
+ import { loadRuntimeEnvironment } from '../../shared/runtime-environment.mjs'
4
+ import { backendDefinition } from '../../shared/backend-catalog.mjs'
5
+ import { helpText, parseArguments } from './arguments.mjs'
6
+ import {
7
+ ensureRuntime,
8
+ readGatewayHealth,
9
+ waitForGateway,
10
+ } from './runtime.mjs'
11
+ import { launchWebUi } from './webui.mjs'
12
+ import { acquireCliInstance } from './instance-lock.mjs'
13
+ import { manageGatewayService } from './gateway-service.mjs'
14
+
15
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
16
+ const gatewayPath = resolve(root, 'server/src/index.mjs')
17
+
18
+ async function runMinimal(options) {
19
+ const moduleUrl = pathToFileURL(resolve(root, 'tui/src/index.mjs'))
20
+ const { runTui } = await import(moduleUrl)
21
+ await runTui({
22
+ url: options.url,
23
+ sessionId: options.sessionId,
24
+ audioMode: options.audioMode,
25
+ takeover: options.takeover,
26
+ })
27
+ return 0
28
+ }
29
+
30
+ function applyGatewayOptions(env, options) {
31
+ env.AGENT_PROTOCOL = options.backend
32
+ env.QWEN_AUDIO_AGENT_BACKEND_MODE = options.backendMode
33
+ env.QWEN_AUDIO_AGENT_BACKEND_PERMISSION_MODE = options.backendPermissionMode
34
+ if (options.backendAgent) {
35
+ env.QWEN_AUDIO_AGENT_BACKEND_AGENT = options.backendAgent
36
+ } else {
37
+ delete env.QWEN_AUDIO_AGENT_BACKEND_AGENT
38
+ }
39
+ const definition = backendDefinition(options.backend)
40
+ if (definition?.baseUrlEnvironment) {
41
+ env[definition.baseUrlEnvironment] = options.backendUrl
42
+ }
43
+ }
44
+
45
+ function gatewaySummary(health) {
46
+ const label = health?.backend?.label
47
+ || health?.backend?.kind
48
+ || health?.backend?.protocol
49
+ || '后台 Agent'
50
+ const state = health?.backend?.ok ? '已连接' : '未连接'
51
+ return `${label} ${state}`
52
+ }
53
+
54
+ async function waitForGatewayStop(url, {
55
+ inspectGateway = readGatewayHealth,
56
+ timeoutMs = 15_000,
57
+ intervalMs = 100,
58
+ } = {}) {
59
+ const deadline = Date.now() + timeoutMs
60
+ while (Date.now() < deadline) {
61
+ if (!await inspectGateway(url)) return
62
+ await new Promise(resolvePromise => setTimeout(resolvePromise, intervalMs))
63
+ }
64
+ throw new Error(`Gateway 停止超时:${url}`)
65
+ }
66
+
67
+ export async function main(argv, {
68
+ env = process.env,
69
+ stdout = process.stdout,
70
+ signalSource = process,
71
+ prepareEnvironment = () => loadRuntimeEnvironment({ root, env }),
72
+ runMinimalTui = runMinimal,
73
+ prepareRuntime = options => ensureRuntime(options, { root, env }),
74
+ inspectGateway = url => readGatewayHealth(url),
75
+ manageService = (action, options) => manageGatewayService(action, options),
76
+ waitForService = url => waitForGateway(url, { requireBackend: true }),
77
+ waitForServiceStop = url => waitForGatewayStop(url, { inspectGateway }),
78
+ runWebUi = options => launchWebUi(options),
79
+ acquireInstance = directory => acquireCliInstance(directory),
80
+ } = {}) {
81
+ const environment = prepareEnvironment()
82
+ const options = parseArguments(argv, env)
83
+ if (options.help) {
84
+ stdout.write(`${helpText()}\n`)
85
+ return 0
86
+ }
87
+ if (options.command === 'config') {
88
+ stdout.write(`${environment.configPath
89
+ || resolve(environment.configDirectory, 'config.env')}\n`)
90
+ return 0
91
+ }
92
+
93
+ if (
94
+ (options.command === 'gateway' && options.gatewayAction !== 'run')
95
+ || options.command === 'status'
96
+ ) {
97
+ const serviceOptions = {
98
+ configDirectory: environment.configDirectory,
99
+ gatewayPath,
100
+ serviceMetadata: {
101
+ url: options.url,
102
+ },
103
+ }
104
+ if (options.gatewayAction === 'status') {
105
+ const service = await manageService('status', serviceOptions)
106
+ const serviceUrl = service.installedMetadata?.url || options.url
107
+ const health = await inspectGateway(serviceUrl)
108
+ stdout.write(
109
+ `Gateway 后台服务:${
110
+ service.running
111
+ ? '运行中'
112
+ : service.installed ? '已停止' : '未安装'
113
+ }\n`
114
+ + `连接状态:${health ? gatewaySummary(health) : '未连接'}\n`
115
+ + `地址:${serviceUrl}\n`,
116
+ )
117
+ return service.running && health ? 0 : 1
118
+ }
119
+
120
+ const current = await manageService('status', serviceOptions)
121
+ const currentUrl = current.installedMetadata?.url || options.url
122
+ const health = await inspectGateway(currentUrl)
123
+ if (
124
+ ['install', 'start', 'restart'].includes(options.gatewayAction)
125
+ && health
126
+ && !current.running
127
+ ) {
128
+ throw new Error(
129
+ 'Gateway 正在前台运行;请先结束前台进程,再启动后台服务',
130
+ )
131
+ }
132
+ const service = await manageService(
133
+ options.gatewayAction,
134
+ serviceOptions,
135
+ )
136
+ const serviceUrl = service.installedMetadata?.url || currentUrl
137
+ if (['install', 'start', 'restart'].includes(options.gatewayAction)) {
138
+ const ready = await waitForService(serviceUrl)
139
+ stdout.write(
140
+ `Gateway 后台服务已${
141
+ options.gatewayAction === 'restart' ? '重启' : '启动'
142
+ }:${serviceUrl}\n`
143
+ + `${gatewaySummary(ready)}\n`,
144
+ )
145
+ } else {
146
+ if (health && current.running) await waitForServiceStop(currentUrl)
147
+ stdout.write(
148
+ options.gatewayAction === 'uninstall'
149
+ ? 'Gateway 后台服务已移除\n'
150
+ : 'Gateway 后台服务已停止\n',
151
+ )
152
+ }
153
+ if (service.logPath) stdout.write(`日志:${service.logPath}\n`)
154
+ return 0
155
+ }
156
+
157
+ if (options.command === 'gateway') {
158
+ applyGatewayOptions(env, options)
159
+ let runtime
160
+ let shutdownSignal
161
+ const requestShutdown = signal => {
162
+ shutdownSignal ||= signal
163
+ runtime?.close(shutdownSignal)
164
+ }
165
+ const onSigint = () => requestShutdown('SIGINT')
166
+ const onSigterm = () => requestShutdown('SIGTERM')
167
+ // A terminal or SSH session closing sends SIGHUP rather than SIGINT.
168
+ // The Gateway runs in its own process group, so it would otherwise outlive
169
+ // this launcher and keep its ports occupied.
170
+ const onSighup = () => requestShutdown('SIGTERM')
171
+ // This is a final synchronous safeguard for unexpected launcher exits.
172
+ // ManagedRuntime.close only sends signals, so it is safe in an exit hook.
173
+ const onExit = () => runtime?.close('SIGTERM')
174
+ signalSource.once('SIGINT', onSigint)
175
+ signalSource.once('SIGTERM', onSigterm)
176
+ signalSource.once('SIGHUP', onSighup)
177
+ signalSource.once('exit', onExit)
178
+ try {
179
+ runtime = await prepareRuntime(options)
180
+ if (shutdownSignal) {
181
+ if (!runtime.ownsProcesses) return 0
182
+ const stopped = runtime.wait()
183
+ runtime.close(shutdownSignal)
184
+ return await stopped
185
+ }
186
+ const health = await inspectGateway(options.url)
187
+ stdout.write(
188
+ `Gateway ${runtime.ownsProcesses ? '已启动' : '已在运行'}:${options.url}\n`
189
+ + `WebUI:${options.url}/\n`
190
+ + `${gatewaySummary(health)}\n`,
191
+ )
192
+ if (!runtime.ownsProcesses) return 0
193
+ return await runtime.wait()
194
+ } finally {
195
+ signalSource.off('SIGINT', onSigint)
196
+ signalSource.off('SIGTERM', onSigterm)
197
+ signalSource.off('SIGHUP', onSighup)
198
+ signalSource.off('exit', onExit)
199
+ if (runtime?.ownsProcesses) runtime.close()
200
+ }
201
+ }
202
+
203
+ const health = await inspectGateway(options.url)
204
+ if (!health) {
205
+ throw new Error(
206
+ `Gateway 未运行:${options.url}。请先执行 qwenaudio gateway`,
207
+ )
208
+ }
209
+ if (options.command === 'webui') return runWebUi(options)
210
+
211
+ const instance = acquireInstance(environment.configDirectory)
212
+ try {
213
+ return await runMinimalTui(options)
214
+ } finally {
215
+ instance.release()
216
+ }
217
+ }