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.
- package/CONTRIBUTING.md +58 -0
- package/LICENSE +201 -0
- package/NOTICE +5 -0
- package/PRIVACY.md +34 -0
- package/README.md +282 -0
- package/README_EN.md +316 -0
- package/SECURITY.md +32 -0
- package/THIRD_PARTY_NOTICES.md +26 -0
- package/cli/bin/qwenaudio.mjs +10 -0
- package/cli/package.json +13 -0
- package/cli/src/arguments.mjs +247 -0
- package/cli/src/gateway-service.mjs +386 -0
- package/cli/src/instance-lock.mjs +65 -0
- package/cli/src/launcher.mjs +217 -0
- package/cli/src/runtime.mjs +356 -0
- package/cli/src/webui.mjs +61 -0
- package/config/acp/workspace/AGENTS.md +13 -0
- package/config/codebuddy/workspace/.codebuddy/models.json +19 -0
- package/config/codebuddy/workspace/AGENTS.md +13 -0
- package/config/codex/workspace/AGENTS.md +13 -0
- package/config/frontend-agent/PROMPT.md +127 -0
- package/config/hermes/workspace/AGENTS.md +13 -0
- package/config/openclaw/openclaw.json5 +50 -0
- package/config/openclaw/workspace/AGENTS.md +9 -0
- package/config/opencode/agents/qwen-audio-agent-backend.md +65 -0
- package/config/opencode/workspace/AGENTS.md +16 -0
- package/config/qoder/workspace/AGENTS.md +16 -0
- package/docs/architecture-overview-en.png +0 -0
- package/docs/architecture-overview.png +0 -0
- package/docs/architecture.md +332 -0
- package/docs/configuration.md +386 -0
- package/docs/desktop-fluid-orb-thinking.gif +0 -0
- package/docs/desktop-goo-orb-thinking.gif +0 -0
- package/docs/qwen-audio-agent-three-layer-architecture-en.png +0 -0
- package/docs/qwen-audio-agent-three-layer-architecture.png +0 -0
- package/package.json +126 -0
- package/scripts/audit-dependencies.mjs +109 -0
- package/scripts/check-desktop-release-env.mjs +41 -0
- package/scripts/codex-acp +58 -0
- package/scripts/install-global.mjs +66 -0
- package/scripts/openclaw +194 -0
- package/scripts/openclaw-gateway +8 -0
- package/scripts/opencode-acp +6 -0
- package/scripts/opencode-server +179 -0
- package/scripts/prepare-build.mjs +38 -0
- package/scripts/release-check +182 -0
- package/scripts/set-version.mjs +133 -0
- package/scripts/start.mjs +43 -0
- package/scripts/verify-package.mjs +109 -0
- package/server/package.json +18 -0
- package/server/src/agent/acp-backend-adapter.mjs +1138 -0
- package/server/src/agent/acp-backend-profile.mjs +35 -0
- package/server/src/agent/acp-backend-session-utils.mjs +139 -0
- package/server/src/agent/acp-process-client.mjs +447 -0
- package/server/src/agent/acp-session-registry.mjs +106 -0
- package/server/src/agent/acp-session-tools.mjs +257 -0
- package/server/src/agent/agent-client.mjs +218 -0
- package/server/src/agent/backend-adapter.mjs +15 -0
- package/server/src/agent/backend-agent-instructions.mjs +8 -0
- package/server/src/agent/backends/codebuddy.mjs +47 -0
- package/server/src/agent/backends/codex.mjs +62 -0
- package/server/src/agent/backends/generic-acp.mjs +46 -0
- package/server/src/agent/backends/hermes.mjs +29 -0
- package/server/src/agent/backends/openclaw.mjs +101 -0
- package/server/src/agent/backends/opencode.mjs +36 -0
- package/server/src/agent/backends/qoder.mjs +47 -0
- package/server/src/agent/backends/registry.mjs +32 -0
- package/server/src/agent/backends/shared.mjs +46 -0
- package/server/src/agent/coordinator.mjs +308 -0
- package/server/src/agent/openclaw-adapter.mjs +245 -0
- package/server/src/app/bootstrap.mjs +244 -0
- package/server/src/conversation/conversation-sync.mjs +183 -0
- package/server/src/conversation/frontend-agent-context.mjs +162 -0
- package/server/src/conversation/frontend-memory.mjs +328 -0
- package/server/src/conversation/profiled-memory-store.mjs +87 -0
- package/server/src/conversation/task-result-projector.mjs +18 -0
- package/server/src/conversation/user-profile.mjs +234 -0
- package/server/src/core/config.mjs +388 -0
- package/server/src/core/identity.mjs +93 -0
- package/server/src/core/install-paths.mjs +8 -0
- package/server/src/core/package-version.mjs +10 -0
- package/server/src/core/request-security.mjs +80 -0
- package/server/src/index.mjs +67 -0
- package/server/src/process/backend-drivers/codebuddy.mjs +15 -0
- package/server/src/process/backend-drivers/codex.mjs +15 -0
- package/server/src/process/backend-drivers/generic-acp.mjs +18 -0
- package/server/src/process/backend-drivers/hermes.mjs +15 -0
- package/server/src/process/backend-drivers/openclaw.mjs +35 -0
- package/server/src/process/backend-drivers/opencode.mjs +75 -0
- package/server/src/process/backend-drivers/qoder.mjs +15 -0
- package/server/src/process/backend-drivers/registry.mjs +24 -0
- package/server/src/process/backend-drivers/shared.mjs +46 -0
- package/server/src/process/managed-backend.mjs +188 -0
- package/server/src/task/task-manager.mjs +704 -0
- package/server/src/task/task-scheduler.mjs +44 -0
- package/server/src/task/task-store.mjs +167 -0
- package/server/src/voice/active-voice-clients.mjs +58 -0
- package/server/src/voice/announcement/announcement-manager.mjs +402 -0
- package/server/src/voice/announcement/announcement-window.mjs +89 -0
- package/server/src/voice/input-transcript.mjs +9 -0
- package/server/src/voice/realtime-errors.mjs +6 -0
- package/server/src/voice/realtime-gateway.mjs +1366 -0
- package/server/src/voice/realtime-provider.mjs +771 -0
- package/server/src/voice/reconnect-backoff.mjs +30 -0
- package/server/src/voice/response-context.mjs +41 -0
- package/server/src/voice/session-permission-policy.mjs +56 -0
- package/server/src/voice/tools/tool-call-handler.mjs +823 -0
- package/server/src/voice/tools/turn-transcripts.mjs +59 -0
- package/server/src/voice/turn-correlation.mjs +41 -0
- package/shared/backend-catalog.mjs +56 -0
- package/shared/gateway-client.mjs +13 -0
- package/shared/realtime-events.mjs +55 -0
- package/shared/runtime-environment.mjs +422 -0
- package/tui/native/macos-voice-io.swift +552 -0
- package/tui/native/portaudio-voice-io.py +240 -0
- package/tui/package.json +13 -0
- package/tui/src/index.mjs +1217 -0
- package/tui/src/macos-voice-io.mjs +186 -0
- package/tui/src/portaudio-voice-io.mjs +158 -0
- package/web/dist/assets/index-BeamDvsE.js +38 -0
- package/web/dist/assets/index-BuB0EFih.css +1 -0
- package/web/dist/index.html +14 -0
|
@@ -0,0 +1,1217 @@
|
|
|
1
|
+
import { emitKeypressEvents } from 'node:readline'
|
|
2
|
+
import { pathToFileURL } from 'node:url'
|
|
3
|
+
import WebSocket from 'ws'
|
|
4
|
+
import {
|
|
5
|
+
GatewayClientEvent,
|
|
6
|
+
GatewayServerEvent,
|
|
7
|
+
} from '../../shared/realtime-events.mjs'
|
|
8
|
+
import { startMacVoiceIO } from './macos-voice-io.mjs'
|
|
9
|
+
import { startPortAudioVoiceIO } from './portaudio-voice-io.mjs'
|
|
10
|
+
|
|
11
|
+
const OUTPUT_SAMPLE_RATE = 24000
|
|
12
|
+
const AUDIO_MODES = new Set(['half', 'full'])
|
|
13
|
+
const ANSI = {
|
|
14
|
+
bold: '\u001b[1m',
|
|
15
|
+
cyan: '\u001b[36m',
|
|
16
|
+
dim: '\u001b[90m',
|
|
17
|
+
green: '\u001b[32m',
|
|
18
|
+
red: '\u001b[31m',
|
|
19
|
+
reset: '\u001b[0m',
|
|
20
|
+
yellow: '\u001b[33m',
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function style(text, color) {
|
|
24
|
+
if (!process.stdout.isTTY || process.env.NO_COLOR) return text
|
|
25
|
+
return `${ANSI[color]}${text}${ANSI.reset}`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function normalizeAudioMode(value) {
|
|
29
|
+
const mode = String(value || 'half').toLowerCase()
|
|
30
|
+
if (!AUDIO_MODES.has(mode)) {
|
|
31
|
+
throw new Error(`不支持的音频模式:${value}(可选 half、full)`)
|
|
32
|
+
}
|
|
33
|
+
return mode
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function nextArgumentValue(argv, index, option) {
|
|
37
|
+
const value = argv[index + 1]
|
|
38
|
+
if (!value || value.startsWith('-')) {
|
|
39
|
+
throw new Error(`${option} 缺少参数`)
|
|
40
|
+
}
|
|
41
|
+
return value
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function normalizeGatewayUrl(value) {
|
|
45
|
+
let url
|
|
46
|
+
try {
|
|
47
|
+
url = new URL(value)
|
|
48
|
+
} catch {
|
|
49
|
+
throw new Error(`无效的 Gateway URL:${value}`)
|
|
50
|
+
}
|
|
51
|
+
if (!['http:', 'https:'].includes(url.protocol)) {
|
|
52
|
+
throw new Error('Gateway URL 只支持 http 或 https')
|
|
53
|
+
}
|
|
54
|
+
return url.origin
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function parseArguments(argv, env = process.env) {
|
|
58
|
+
const options = {
|
|
59
|
+
url: env.QWEN_AUDIO_AGENT_URL || 'http://127.0.0.1:3101',
|
|
60
|
+
sessionId: env.QWEN_AUDIO_AGENT_SESSION_ID || 'tui-main',
|
|
61
|
+
audioMode: env.QWEN_AUDIO_AGENT_TUI_AUDIO_MODE || 'half',
|
|
62
|
+
takeover: false,
|
|
63
|
+
}
|
|
64
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
65
|
+
const argument = argv[index]
|
|
66
|
+
if (argument === '--url') {
|
|
67
|
+
options.url = nextArgumentValue(argv, index++, '--url')
|
|
68
|
+
} else if (argument === '--session') {
|
|
69
|
+
options.sessionId = nextArgumentValue(argv, index++, '--session')
|
|
70
|
+
} else if (argv[index] === '--help' || argv[index] === '-h') {
|
|
71
|
+
options.help = true
|
|
72
|
+
} else if (argument === '--takeover') {
|
|
73
|
+
options.takeover = true
|
|
74
|
+
} else if (argument === '--audio-mode') {
|
|
75
|
+
options.audioMode = nextArgumentValue(argv, index++, '--audio-mode')
|
|
76
|
+
} else throw new Error(`未知参数:${argument}`)
|
|
77
|
+
}
|
|
78
|
+
options.url = normalizeGatewayUrl(options.url)
|
|
79
|
+
options.sessionId = String(options.sessionId || '').trim()
|
|
80
|
+
if (!options.sessionId) throw new Error('--session 不能为空')
|
|
81
|
+
options.audioMode = normalizeAudioMode(options.audioMode)
|
|
82
|
+
return options
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function websocketUrl(baseUrl, sessionId) {
|
|
86
|
+
const url = new URL('/api/realtime', baseUrl)
|
|
87
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
88
|
+
url.searchParams.set('sessionId', sessionId)
|
|
89
|
+
return url.toString()
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function connectMessage({
|
|
93
|
+
voiceEnabled,
|
|
94
|
+
inputEnabled,
|
|
95
|
+
outputEnabled,
|
|
96
|
+
takeover = false,
|
|
97
|
+
workingDirectory = process.cwd(),
|
|
98
|
+
timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
99
|
+
locale = Intl.DateTimeFormat().resolvedOptions().locale,
|
|
100
|
+
} = {}) {
|
|
101
|
+
return {
|
|
102
|
+
type: GatewayClientEvent.CONNECT,
|
|
103
|
+
voiceEnabled: voiceEnabled !== false,
|
|
104
|
+
...(inputEnabled === undefined
|
|
105
|
+
? {}
|
|
106
|
+
: { inputEnabled: inputEnabled === true }),
|
|
107
|
+
...(outputEnabled === undefined
|
|
108
|
+
? {}
|
|
109
|
+
: { outputEnabled: outputEnabled === true }),
|
|
110
|
+
clientType: 'cli',
|
|
111
|
+
clientLabel: 'CLI',
|
|
112
|
+
takeover: takeover === true,
|
|
113
|
+
workingDirectory,
|
|
114
|
+
timeZone,
|
|
115
|
+
locale,
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function microphoneControlEvent(muted) {
|
|
120
|
+
return muted
|
|
121
|
+
? { type: GatewayClientEvent.INPUT_MUTE }
|
|
122
|
+
: { type: GatewayClientEvent.INPUT_UNMUTE, takeover: false }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function permissionStatusText(task) {
|
|
126
|
+
return task?.authorization?.summary || '后台正在请求执行权限'
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function cookieFrom(response) {
|
|
130
|
+
const raw = response.headers.getSetCookie?.()[0]
|
|
131
|
+
|| response.headers.get('set-cookie')
|
|
132
|
+
|| ''
|
|
133
|
+
return raw.split(';', 1)[0]
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function assertInteractiveTerminal(stdin = process.stdin) {
|
|
137
|
+
if (!stdin.isTTY) {
|
|
138
|
+
throw new Error('minimal TUI 需要交互式终端,以支持按键控制')
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function readTuiHealth(baseUrl, {
|
|
143
|
+
fetchImpl = fetch,
|
|
144
|
+
timeoutMs = 5000,
|
|
145
|
+
} = {}) {
|
|
146
|
+
let response
|
|
147
|
+
try {
|
|
148
|
+
response = await fetchImpl(`${baseUrl}/api/health`, {
|
|
149
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
150
|
+
})
|
|
151
|
+
} catch (error) {
|
|
152
|
+
throw new Error(`无法连接 Gateway:${error.message}`)
|
|
153
|
+
}
|
|
154
|
+
let health
|
|
155
|
+
try {
|
|
156
|
+
health = await response.json()
|
|
157
|
+
} catch {
|
|
158
|
+
throw new Error('Gateway 健康检查返回了无效数据')
|
|
159
|
+
}
|
|
160
|
+
if (!response.ok) {
|
|
161
|
+
throw new Error(
|
|
162
|
+
health?.backend?.error || health?.error || 'Gateway 或后台 Agent 尚未就绪',
|
|
163
|
+
)
|
|
164
|
+
}
|
|
165
|
+
if (!health || typeof health !== 'object' || !health.backend) {
|
|
166
|
+
throw new Error('Gateway 健康检查缺少后台状态')
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
cookie: cookieFrom(response),
|
|
170
|
+
health,
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function audioModeForPlatform(
|
|
175
|
+
platform = process.platform,
|
|
176
|
+
requestedMode = 'half',
|
|
177
|
+
) {
|
|
178
|
+
if (platform === 'darwin') {
|
|
179
|
+
return {
|
|
180
|
+
audioBackend: 'coreaudio',
|
|
181
|
+
captureDuringPlayback: true,
|
|
182
|
+
fullDuplex: true,
|
|
183
|
+
manualInterrupt: false,
|
|
184
|
+
label: 'CoreAudio Voice Processing(全双工 AEC)',
|
|
185
|
+
shortLabel: 'CoreAudio AEC',
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (normalizeAudioMode(requestedMode) === 'full') {
|
|
189
|
+
return {
|
|
190
|
+
audioBackend: 'portaudio',
|
|
191
|
+
captureDuringPlayback: true,
|
|
192
|
+
fullDuplex: true,
|
|
193
|
+
manualInterrupt: false,
|
|
194
|
+
label: 'PortAudio(全双工,无 AEC,建议使用耳机)',
|
|
195
|
+
shortLabel: 'PortAudio 全双工',
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
audioBackend: 'portaudio',
|
|
200
|
+
captureDuringPlayback: false,
|
|
201
|
+
fullDuplex: false,
|
|
202
|
+
manualInterrupt: true,
|
|
203
|
+
label: 'PortAudio(半双工)',
|
|
204
|
+
shortLabel: 'PortAudio 半双工',
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function helpText(mode = audioModeForPlatform()) {
|
|
209
|
+
const description = mode.audioBackend === 'coreaudio'
|
|
210
|
+
? '语音模式:请直接说话;使用 macOS CoreAudio 全双工回声消除,可用语音打断回复。'
|
|
211
|
+
: mode.fullDuplex
|
|
212
|
+
? '语音模式:PortAudio 全双工不提供回声消除,请使用耳机;可直接说话打断回复。'
|
|
213
|
+
: '语音模式:回复播放完毕后可继续说话;按 x 可手动打断播放。'
|
|
214
|
+
return [
|
|
215
|
+
description,
|
|
216
|
+
'按键:',
|
|
217
|
+
...(mode.manualInterrupt ? [' x 手动打断当前回复'] : []),
|
|
218
|
+
' m 静音 / 恢复麦克风',
|
|
219
|
+
' h 显示帮助',
|
|
220
|
+
' q 退出',
|
|
221
|
+
].join('\n')
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function fullDuplexFallbackHint(mode) {
|
|
225
|
+
if (mode.audioBackend !== 'portaudio' || !mode.fullDuplex) return ''
|
|
226
|
+
return 'PortAudio 全双工出现异常;请重新运行 '
|
|
227
|
+
+ 'qwenaudio tui --audio-mode half 使用半双工。'
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function requestLabel(task) {
|
|
231
|
+
return String(task?.objective || '正在处理用户请求')
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function frontendLabel(holder) {
|
|
235
|
+
return holder?.label || {
|
|
236
|
+
desktop: '桌面端',
|
|
237
|
+
cli: '终端',
|
|
238
|
+
web: 'WebUI',
|
|
239
|
+
}[holder?.type] || '其他前端'
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function canSendMicrophoneAudio({
|
|
243
|
+
connected,
|
|
244
|
+
muted,
|
|
245
|
+
captureEnabled,
|
|
246
|
+
}) {
|
|
247
|
+
return Boolean(connected && !muted && captureEnabled)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function performManualInterrupt({
|
|
251
|
+
playback,
|
|
252
|
+
transcriptRenderer,
|
|
253
|
+
socket,
|
|
254
|
+
startMicrophone,
|
|
255
|
+
print,
|
|
256
|
+
}) {
|
|
257
|
+
playback.clear('user_interruption')
|
|
258
|
+
transcriptRenderer.cancel()
|
|
259
|
+
if (socket?.readyState === WebSocket.OPEN) {
|
|
260
|
+
socket.send(JSON.stringify({ type: 'interrupt' }))
|
|
261
|
+
}
|
|
262
|
+
startMicrophone()
|
|
263
|
+
print(style('[已手动打断,麦克风已恢复]', 'yellow'))
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function completeTranscript(streamed, final) {
|
|
267
|
+
const streamedText = String(streamed || '').trim()
|
|
268
|
+
const finalText = String(final || '').trim()
|
|
269
|
+
if (!finalText || streamedText.startsWith(finalText)) return streamedText
|
|
270
|
+
return finalText
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function createTurnStatusDisplay({
|
|
274
|
+
print,
|
|
275
|
+
maxRememberedTurns = 200,
|
|
276
|
+
} = {}) {
|
|
277
|
+
const awaitingAssistant = new Set()
|
|
278
|
+
const turnOrder = []
|
|
279
|
+
const pending = new Map()
|
|
280
|
+
|
|
281
|
+
const remember = turnId => {
|
|
282
|
+
const id = String(turnId || '')
|
|
283
|
+
if (!id || awaitingAssistant.has(id)) return
|
|
284
|
+
awaitingAssistant.add(id)
|
|
285
|
+
turnOrder.push(id)
|
|
286
|
+
while (turnOrder.length > maxRememberedTurns) {
|
|
287
|
+
const forgotten = turnOrder.shift()
|
|
288
|
+
awaitingAssistant.delete(forgotten)
|
|
289
|
+
for (const line of pending.get(forgotten) || []) print(line)
|
|
290
|
+
pending.delete(forgotten)
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const release = turnId => {
|
|
295
|
+
const id = String(turnId || '')
|
|
296
|
+
if (!id || !awaitingAssistant.delete(id)) return
|
|
297
|
+
for (const line of pending.get(id) || []) print(line)
|
|
298
|
+
pending.delete(id)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return {
|
|
302
|
+
begin(turnId) {
|
|
303
|
+
remember(turnId)
|
|
304
|
+
},
|
|
305
|
+
status(event, line) {
|
|
306
|
+
const turnId = String(event?.task?.turnId || '')
|
|
307
|
+
if (!turnId || !awaitingAssistant.has(turnId)) {
|
|
308
|
+
print(line)
|
|
309
|
+
return
|
|
310
|
+
}
|
|
311
|
+
const lines = pending.get(turnId) || []
|
|
312
|
+
lines.push(line)
|
|
313
|
+
pending.set(turnId, lines)
|
|
314
|
+
},
|
|
315
|
+
assistantFinished(turnId) {
|
|
316
|
+
release(turnId)
|
|
317
|
+
},
|
|
318
|
+
reset() {
|
|
319
|
+
for (const turnId of turnOrder) release(turnId)
|
|
320
|
+
turnOrder.length = 0
|
|
321
|
+
awaitingAssistant.clear()
|
|
322
|
+
},
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export function createTranscriptDisplay({
|
|
327
|
+
onUser,
|
|
328
|
+
onAssistant,
|
|
329
|
+
onUserDelta = () => {},
|
|
330
|
+
onUserDiscard = () => {},
|
|
331
|
+
onAssistantDelta = () => {},
|
|
332
|
+
onReset = () => {},
|
|
333
|
+
}) {
|
|
334
|
+
const maxRememberedTurns = 200
|
|
335
|
+
const maxRememberedResponses = 200
|
|
336
|
+
const userDeltas = new Map()
|
|
337
|
+
const assistantDeltas = new Map()
|
|
338
|
+
const completedUserTurns = new Set()
|
|
339
|
+
const completedUserTurnOrder = []
|
|
340
|
+
const completedAssistantResponses = new Set()
|
|
341
|
+
const completedAssistantResponseOrder = []
|
|
342
|
+
const pendingAssistants = new Map()
|
|
343
|
+
const assistantTurns = new Map()
|
|
344
|
+
|
|
345
|
+
const completeUserTurn = turnId => {
|
|
346
|
+
if (completedUserTurns.has(turnId)) return
|
|
347
|
+
completedUserTurns.add(turnId)
|
|
348
|
+
completedUserTurnOrder.push(turnId)
|
|
349
|
+
while (completedUserTurnOrder.length > maxRememberedTurns) {
|
|
350
|
+
completedUserTurns.delete(completedUserTurnOrder.shift())
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const flushTurn = turnId => {
|
|
355
|
+
const pending = pendingAssistants.get(turnId) || []
|
|
356
|
+
pendingAssistants.delete(turnId)
|
|
357
|
+
for (const item of pending) onAssistant(item.content, item.event)
|
|
358
|
+
for (const [responseId, content] of assistantDeltas) {
|
|
359
|
+
if (assistantTurns.get(responseId) === turnId) onAssistantDelta(content)
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const completeAssistantResponse = responseId => {
|
|
364
|
+
if (!responseId || completedAssistantResponses.has(responseId)) return
|
|
365
|
+
completedAssistantResponses.add(responseId)
|
|
366
|
+
completedAssistantResponseOrder.push(responseId)
|
|
367
|
+
while (completedAssistantResponseOrder.length > maxRememberedResponses) {
|
|
368
|
+
completedAssistantResponses.delete(completedAssistantResponseOrder.shift())
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return {
|
|
373
|
+
handle(event) {
|
|
374
|
+
if (!event?.type?.startsWith('transcript.')) return false
|
|
375
|
+
|
|
376
|
+
if (event.role === 'user' && event.type === 'transcript.delta') {
|
|
377
|
+
const turnId = String(event.turnId || '')
|
|
378
|
+
const incoming = String(event.content || '')
|
|
379
|
+
const content = event.replace === true
|
|
380
|
+
? incoming
|
|
381
|
+
: `${userDeltas.get(turnId) || ''}${incoming}`
|
|
382
|
+
if (turnId) userDeltas.set(turnId, content)
|
|
383
|
+
if (content) onUserDelta(content)
|
|
384
|
+
return true
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
if (event.role === 'user' && event.type === 'transcript.final') {
|
|
388
|
+
const turnId = String(event.turnId || '')
|
|
389
|
+
const content = completeTranscript(
|
|
390
|
+
userDeltas.get(turnId),
|
|
391
|
+
String(event.content || '').replace(/\s+/g, ' '),
|
|
392
|
+
)
|
|
393
|
+
userDeltas.delete(turnId)
|
|
394
|
+
if (content) onUser(content, event)
|
|
395
|
+
if (turnId) {
|
|
396
|
+
completeUserTurn(turnId)
|
|
397
|
+
flushTurn(turnId)
|
|
398
|
+
}
|
|
399
|
+
return true
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (event.role === 'user' && event.type === 'transcript.discard') {
|
|
403
|
+
const turnId = String(event.turnId || '')
|
|
404
|
+
userDeltas.delete(turnId)
|
|
405
|
+
onUserDiscard(turnId, event)
|
|
406
|
+
if (turnId) {
|
|
407
|
+
completeUserTurn(turnId)
|
|
408
|
+
flushTurn(turnId)
|
|
409
|
+
}
|
|
410
|
+
return true
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
if (event.role !== 'assistant') return true
|
|
414
|
+
const responseId = String(event.responseId || '')
|
|
415
|
+
if (responseId && completedAssistantResponses.has(responseId)) return true
|
|
416
|
+
if (event.type === 'transcript.delta') {
|
|
417
|
+
const previous = assistantDeltas.get(responseId) || ''
|
|
418
|
+
const content = previous + String(event.content || '')
|
|
419
|
+
assistantDeltas.set(responseId, content)
|
|
420
|
+
const turnId = String(event.turnId || '')
|
|
421
|
+
if (turnId) assistantTurns.set(responseId, turnId)
|
|
422
|
+
const waitsForUser = (
|
|
423
|
+
event.origin === 'model'
|
|
424
|
+
&& turnId
|
|
425
|
+
&& !completedUserTurns.has(turnId)
|
|
426
|
+
)
|
|
427
|
+
if (!waitsForUser && content) onAssistantDelta(content)
|
|
428
|
+
return true
|
|
429
|
+
}
|
|
430
|
+
if (event.type !== 'transcript.final') return true
|
|
431
|
+
|
|
432
|
+
const content = completeTranscript(
|
|
433
|
+
assistantDeltas.get(responseId),
|
|
434
|
+
event.content,
|
|
435
|
+
)
|
|
436
|
+
assistantDeltas.delete(responseId)
|
|
437
|
+
assistantTurns.delete(responseId)
|
|
438
|
+
completeAssistantResponse(responseId)
|
|
439
|
+
if (!content) return true
|
|
440
|
+
|
|
441
|
+
const turnId = String(event.turnId || '')
|
|
442
|
+
const waitsForUser = (
|
|
443
|
+
event.origin === 'model'
|
|
444
|
+
&& turnId
|
|
445
|
+
&& !completedUserTurns.has(turnId)
|
|
446
|
+
)
|
|
447
|
+
if (!waitsForUser) {
|
|
448
|
+
onAssistant(content, event)
|
|
449
|
+
return true
|
|
450
|
+
}
|
|
451
|
+
const pending = pendingAssistants.get(turnId) || []
|
|
452
|
+
pending.push({ content, event })
|
|
453
|
+
pendingAssistants.set(turnId, pending)
|
|
454
|
+
return true
|
|
455
|
+
},
|
|
456
|
+
reset() {
|
|
457
|
+
userDeltas.clear()
|
|
458
|
+
assistantDeltas.clear()
|
|
459
|
+
completedUserTurns.clear()
|
|
460
|
+
completedUserTurnOrder.length = 0
|
|
461
|
+
completedAssistantResponses.clear()
|
|
462
|
+
completedAssistantResponseOrder.length = 0
|
|
463
|
+
pendingAssistants.clear()
|
|
464
|
+
assistantTurns.clear()
|
|
465
|
+
onReset()
|
|
466
|
+
},
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
export function createTerminalTranscriptRenderer({
|
|
471
|
+
stdout = process.stdout,
|
|
472
|
+
} = {}) {
|
|
473
|
+
let active = null
|
|
474
|
+
let previewRows = 0
|
|
475
|
+
const pendingLines = []
|
|
476
|
+
const interactive = Boolean(stdout.isTTY)
|
|
477
|
+
const stripAnsi = text => String(text || '').replace(/\u001b\[[0-9;]*m/g, '')
|
|
478
|
+
const characterWidth = character => {
|
|
479
|
+
const codePoint = character.codePointAt(0) || 0
|
|
480
|
+
if (
|
|
481
|
+
codePoint === 0
|
|
482
|
+
|| codePoint < 32
|
|
483
|
+
|| (codePoint >= 0x7f && codePoint < 0xa0)
|
|
484
|
+
|| (codePoint >= 0x300 && codePoint <= 0x36f)
|
|
485
|
+
|| (codePoint >= 0xfe00 && codePoint <= 0xfe0f)
|
|
486
|
+
|| codePoint === 0x200d
|
|
487
|
+
) return 0
|
|
488
|
+
return codePoint <= 0x7e ? 1 : 2
|
|
489
|
+
}
|
|
490
|
+
const displayWidth = text => Array.from(stripAnsi(text))
|
|
491
|
+
.reduce((width, character) => width + characterWidth(character), 0)
|
|
492
|
+
const previewLines = (prefix, content) => {
|
|
493
|
+
const columns = Math.max(8, Number(stdout.columns) || 80)
|
|
494
|
+
// Leave one terminal column unused to avoid exact-width auto-wrap, whose
|
|
495
|
+
// cursor behavior differs between terminals.
|
|
496
|
+
const maxWidth = Math.max(7, columns - 1)
|
|
497
|
+
const firstPrefix = `${prefix} `
|
|
498
|
+
const prefixWidth = displayWidth(firstPrefix)
|
|
499
|
+
const continuation = ' '.repeat(Math.min(prefixWidth, maxWidth - 2))
|
|
500
|
+
const continuationWidth = displayWidth(continuation)
|
|
501
|
+
const points = Array.from(String(content || '').replace(/\s+/g, ' '))
|
|
502
|
+
const lines = []
|
|
503
|
+
let line = firstPrefix
|
|
504
|
+
let width = prefixWidth
|
|
505
|
+
for (const point of points) {
|
|
506
|
+
const pointWidth = characterWidth(point)
|
|
507
|
+
const minimumWidth = lines.length === 0 ? prefixWidth : continuationWidth
|
|
508
|
+
if (width > minimumWidth && width + pointWidth > maxWidth) {
|
|
509
|
+
lines.push(line)
|
|
510
|
+
line = continuation
|
|
511
|
+
width = continuationWidth
|
|
512
|
+
}
|
|
513
|
+
line += point
|
|
514
|
+
width += pointWidth
|
|
515
|
+
}
|
|
516
|
+
lines.push(line)
|
|
517
|
+
return lines
|
|
518
|
+
}
|
|
519
|
+
const clearPreview = () => {
|
|
520
|
+
if (!interactive || previewRows === 0) return
|
|
521
|
+
stdout.write('\r\u001b[2K')
|
|
522
|
+
for (let row = 1; row < previewRows; row += 1) {
|
|
523
|
+
stdout.write('\u001b[1A\r\u001b[2K')
|
|
524
|
+
}
|
|
525
|
+
previewRows = 0
|
|
526
|
+
}
|
|
527
|
+
const redrawPreview = () => {
|
|
528
|
+
if (!interactive || active?.kind !== 'preview') return
|
|
529
|
+
clearPreview()
|
|
530
|
+
const lines = previewLines(active.prefix, active.content)
|
|
531
|
+
stdout.write(lines.join('\n'))
|
|
532
|
+
previewRows = lines.length
|
|
533
|
+
}
|
|
534
|
+
const flushPending = () => {
|
|
535
|
+
while (pendingLines.length) stdout.write(`${pendingLines.shift()}\n`)
|
|
536
|
+
}
|
|
537
|
+
const closeActiveStream = () => {
|
|
538
|
+
if (active?.kind !== 'stream') return
|
|
539
|
+
stdout.write('\n')
|
|
540
|
+
active = null
|
|
541
|
+
flushPending()
|
|
542
|
+
}
|
|
543
|
+
return {
|
|
544
|
+
update(prefix, content) {
|
|
545
|
+
// A provisional user ASR snapshot can arrive while the assistant is
|
|
546
|
+
// still speaking (for example from residual playback). Do not let that
|
|
547
|
+
// ephemeral preview split the assistant's cumulative transcript into
|
|
548
|
+
// two terminal lines. A real interruption clears playback first, and a
|
|
549
|
+
// final user transcript will still close the stream in finish().
|
|
550
|
+
if (active?.kind === 'stream') return
|
|
551
|
+
active = {
|
|
552
|
+
kind: 'preview',
|
|
553
|
+
prefix: String(prefix || ''),
|
|
554
|
+
content: String(content || ''),
|
|
555
|
+
}
|
|
556
|
+
redrawPreview()
|
|
557
|
+
},
|
|
558
|
+
stream(prefix, content) {
|
|
559
|
+
const nextPrefix = String(prefix || '')
|
|
560
|
+
const nextContent = String(content || '')
|
|
561
|
+
if (active?.kind === 'preview') clearPreview()
|
|
562
|
+
if (active?.kind !== 'stream' || active.prefix !== nextPrefix) {
|
|
563
|
+
if (active?.kind === 'stream') closeActiveStream()
|
|
564
|
+
stdout.write(`${nextPrefix} ${nextContent}`)
|
|
565
|
+
} else if (nextContent.startsWith(active.content)) {
|
|
566
|
+
stdout.write(nextContent.slice(active.content.length))
|
|
567
|
+
} else if (!active.content.startsWith(nextContent)) {
|
|
568
|
+
stdout.write(`\n${nextPrefix} ${nextContent}`)
|
|
569
|
+
}
|
|
570
|
+
active = { kind: 'stream', prefix: nextPrefix, content: nextContent }
|
|
571
|
+
},
|
|
572
|
+
finish(prefix, content) {
|
|
573
|
+
const nextPrefix = String(prefix || '')
|
|
574
|
+
const nextContent = String(content || '')
|
|
575
|
+
if (active?.kind === 'preview') {
|
|
576
|
+
clearPreview()
|
|
577
|
+
stdout.write(`${nextPrefix} ${nextContent}\n`)
|
|
578
|
+
} else if (active?.kind === 'stream' && active.prefix === nextPrefix) {
|
|
579
|
+
const complete = completeTranscript(active.content, nextContent)
|
|
580
|
+
if (complete.startsWith(active.content)) {
|
|
581
|
+
stdout.write(`${complete.slice(active.content.length)}\n`)
|
|
582
|
+
} else if (active.content.startsWith(complete)) {
|
|
583
|
+
stdout.write('\n')
|
|
584
|
+
} else {
|
|
585
|
+
stdout.write(`\n${nextPrefix} ${complete}\n`)
|
|
586
|
+
}
|
|
587
|
+
} else {
|
|
588
|
+
if (active?.kind === 'stream') stdout.write('\n')
|
|
589
|
+
stdout.write(`${nextPrefix} ${nextContent}\n`)
|
|
590
|
+
}
|
|
591
|
+
active = null
|
|
592
|
+
flushPending()
|
|
593
|
+
},
|
|
594
|
+
print(line) {
|
|
595
|
+
if (active?.kind === 'stream') {
|
|
596
|
+
pendingLines.push(String(line))
|
|
597
|
+
return
|
|
598
|
+
}
|
|
599
|
+
if (active?.kind === 'preview') clearPreview()
|
|
600
|
+
stdout.write(`${line}\n`)
|
|
601
|
+
redrawPreview()
|
|
602
|
+
},
|
|
603
|
+
discardPreview() {
|
|
604
|
+
if (active?.kind !== 'preview') return
|
|
605
|
+
clearPreview()
|
|
606
|
+
active = null
|
|
607
|
+
flushPending()
|
|
608
|
+
},
|
|
609
|
+
cancel() {
|
|
610
|
+
if (active?.kind === 'preview') clearPreview()
|
|
611
|
+
else if (active?.kind === 'stream') stdout.write('\n')
|
|
612
|
+
active = null
|
|
613
|
+
flushPending()
|
|
614
|
+
},
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
export function createPlayback({
|
|
619
|
+
audioSink,
|
|
620
|
+
onError,
|
|
621
|
+
onStarted,
|
|
622
|
+
onEnded,
|
|
623
|
+
onCancelled,
|
|
624
|
+
onIdle,
|
|
625
|
+
}) {
|
|
626
|
+
const activeResponses = new Set()
|
|
627
|
+
const startedResponses = new Set()
|
|
628
|
+
const finishingResponses = new Set()
|
|
629
|
+
const cancelledResponses = new Set()
|
|
630
|
+
const cancelledResponseOrder = []
|
|
631
|
+
const rememberCancelled = responseId => {
|
|
632
|
+
if (!responseId || cancelledResponses.has(responseId)) return
|
|
633
|
+
cancelledResponses.add(responseId)
|
|
634
|
+
cancelledResponseOrder.push(responseId)
|
|
635
|
+
while (cancelledResponseOrder.length > 200) {
|
|
636
|
+
cancelledResponses.delete(cancelledResponseOrder.shift())
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
const stop = (reason = '') => {
|
|
640
|
+
for (const responseId of activeResponses) {
|
|
641
|
+
rememberCancelled(responseId)
|
|
642
|
+
onCancelled?.(responseId, reason)
|
|
643
|
+
}
|
|
644
|
+
activeResponses.clear()
|
|
645
|
+
startedResponses.clear()
|
|
646
|
+
finishingResponses.clear()
|
|
647
|
+
audioSink.clear()
|
|
648
|
+
}
|
|
649
|
+
return {
|
|
650
|
+
write(base64, rate = OUTPUT_SAMPLE_RATE, responseId = '') {
|
|
651
|
+
if (responseId && cancelledResponses.has(responseId)) return false
|
|
652
|
+
const buffer = Buffer.from(base64, 'base64')
|
|
653
|
+
if (!buffer.length) return true
|
|
654
|
+
if (!audioSink.write(buffer, rate, responseId)) {
|
|
655
|
+
onError?.('音频设备未接受播放数据')
|
|
656
|
+
if (responseId) {
|
|
657
|
+
rememberCancelled(responseId)
|
|
658
|
+
onCancelled?.(responseId)
|
|
659
|
+
}
|
|
660
|
+
return false
|
|
661
|
+
}
|
|
662
|
+
if (responseId) activeResponses.add(responseId)
|
|
663
|
+
return true
|
|
664
|
+
},
|
|
665
|
+
done(responseId = '') {
|
|
666
|
+
if (
|
|
667
|
+
!responseId
|
|
668
|
+
|| cancelledResponses.has(responseId)
|
|
669
|
+
|| !activeResponses.has(responseId)
|
|
670
|
+
|| finishingResponses.has(responseId)
|
|
671
|
+
) return
|
|
672
|
+
if (audioSink.done?.(responseId)) {
|
|
673
|
+
finishingResponses.add(responseId)
|
|
674
|
+
} else {
|
|
675
|
+
onError?.('音频设备未接受播放完成标记')
|
|
676
|
+
rememberCancelled(responseId)
|
|
677
|
+
activeResponses.delete(responseId)
|
|
678
|
+
startedResponses.delete(responseId)
|
|
679
|
+
finishingResponses.delete(responseId)
|
|
680
|
+
onCancelled?.(responseId)
|
|
681
|
+
if (activeResponses.size === 0) onIdle?.()
|
|
682
|
+
}
|
|
683
|
+
},
|
|
684
|
+
started(responseId = '') {
|
|
685
|
+
if (
|
|
686
|
+
!responseId
|
|
687
|
+
|| cancelledResponses.has(responseId)
|
|
688
|
+
|| !activeResponses.has(responseId)
|
|
689
|
+
|| startedResponses.has(responseId)
|
|
690
|
+
) return
|
|
691
|
+
startedResponses.add(responseId)
|
|
692
|
+
onStarted?.(responseId)
|
|
693
|
+
},
|
|
694
|
+
ended(responseId = '') {
|
|
695
|
+
if (
|
|
696
|
+
!responseId
|
|
697
|
+
|| cancelledResponses.has(responseId)
|
|
698
|
+
|| !activeResponses.delete(responseId)
|
|
699
|
+
) return
|
|
700
|
+
startedResponses.delete(responseId)
|
|
701
|
+
finishingResponses.delete(responseId)
|
|
702
|
+
onEnded?.(responseId)
|
|
703
|
+
if (activeResponses.size === 0) onIdle?.()
|
|
704
|
+
},
|
|
705
|
+
clear: stop,
|
|
706
|
+
close: stop,
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
export async function runTui(options = parseArguments(process.argv.slice(2))) {
|
|
711
|
+
const audioMode = audioModeForPlatform(process.platform, options.audioMode)
|
|
712
|
+
if (options.help) {
|
|
713
|
+
process.stdout.write(
|
|
714
|
+
'qwen-audio-agent Voice TUI\n\n'
|
|
715
|
+
+ '用法:qwenaudio tui [--url URL] [--session ID] '
|
|
716
|
+
+ '[--audio-mode half|full] [--takeover]\n\n'
|
|
717
|
+
+ `${helpText(audioMode)}\n`,
|
|
718
|
+
)
|
|
719
|
+
return
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
assertInteractiveTerminal()
|
|
723
|
+
const { cookie, health } = await readTuiHealth(options.url)
|
|
724
|
+
|
|
725
|
+
let headers = cookie ? { Cookie: cookie } : {}
|
|
726
|
+
let inputSampleRate = health.realtimeInputSampleRate || 16000
|
|
727
|
+
let muted = false
|
|
728
|
+
let closed = false
|
|
729
|
+
let socket = null
|
|
730
|
+
let reconnectTimer = null
|
|
731
|
+
let reconnectDelay = 500
|
|
732
|
+
let connectedOnce = false
|
|
733
|
+
let frontendReady = false
|
|
734
|
+
let ownsVoice = false
|
|
735
|
+
let everOwnedVoice = false
|
|
736
|
+
let captureEnabled = false
|
|
737
|
+
let captureStateSent = false
|
|
738
|
+
let audioBridge = null
|
|
739
|
+
let playback = null
|
|
740
|
+
let keypressHandler = null
|
|
741
|
+
const pendingPermissionTasks = new Set()
|
|
742
|
+
let close = () => {}
|
|
743
|
+
let resolveClosed
|
|
744
|
+
const closedPromise = new Promise(resolvePromise => {
|
|
745
|
+
resolveClosed = resolvePromise
|
|
746
|
+
})
|
|
747
|
+
|
|
748
|
+
const transcriptRenderer = createTerminalTranscriptRenderer()
|
|
749
|
+
const print = text => transcriptRenderer.print(text)
|
|
750
|
+
const userPrefix = style('你 >', 'cyan')
|
|
751
|
+
const assistantPrefix = style('qwen-audio >', 'bold')
|
|
752
|
+
const turnStatusDisplay = createTurnStatusDisplay({ print })
|
|
753
|
+
const transcriptDisplay = createTranscriptDisplay({
|
|
754
|
+
onUserDelta: content => transcriptRenderer.update(userPrefix, content),
|
|
755
|
+
onUser: (content, event) => {
|
|
756
|
+
transcriptRenderer.finish(userPrefix, content)
|
|
757
|
+
turnStatusDisplay.begin(event?.turnId)
|
|
758
|
+
},
|
|
759
|
+
onUserDiscard: (_turnId, event) => {
|
|
760
|
+
transcriptRenderer.discardPreview()
|
|
761
|
+
if (
|
|
762
|
+
event?.reason === 'turn_invalid'
|
|
763
|
+
&& pendingPermissionTasks.size > 0
|
|
764
|
+
) {
|
|
765
|
+
print(style('[没有听清授权回答,请再说一次]', 'yellow'))
|
|
766
|
+
}
|
|
767
|
+
},
|
|
768
|
+
onAssistantDelta: content => transcriptRenderer.stream(assistantPrefix, content),
|
|
769
|
+
onAssistant: (content, event) => {
|
|
770
|
+
transcriptRenderer.finish(assistantPrefix, content)
|
|
771
|
+
turnStatusDisplay.assistantFinished(event?.turnId)
|
|
772
|
+
},
|
|
773
|
+
onReset: () => {
|
|
774
|
+
transcriptRenderer.cancel()
|
|
775
|
+
turnStatusDisplay.reset()
|
|
776
|
+
},
|
|
777
|
+
})
|
|
778
|
+
const handleSigint = () => close()
|
|
779
|
+
const handleSigterm = () => close()
|
|
780
|
+
const cleanup = () => {
|
|
781
|
+
if (closed) return
|
|
782
|
+
closed = true
|
|
783
|
+
clearTimeout(reconnectTimer)
|
|
784
|
+
playback?.close()
|
|
785
|
+
audioBridge?.close()
|
|
786
|
+
if (keypressHandler) process.stdin.off('keypress', keypressHandler)
|
|
787
|
+
process.off('SIGINT', handleSigint)
|
|
788
|
+
process.off('SIGTERM', handleSigterm)
|
|
789
|
+
if (process.stdin.isTTY) {
|
|
790
|
+
try {
|
|
791
|
+
process.stdin.setRawMode(false)
|
|
792
|
+
} catch {
|
|
793
|
+
// The terminal may already have closed while the audio helper exited.
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
process.stdin.pause()
|
|
797
|
+
resolveClosed()
|
|
798
|
+
}
|
|
799
|
+
close = () => {
|
|
800
|
+
cleanup()
|
|
801
|
+
if (socket?.readyState < WebSocket.CLOSING) socket.close()
|
|
802
|
+
}
|
|
803
|
+
const sendMicrophoneAudio = chunk => {
|
|
804
|
+
if (canSendMicrophoneAudio({
|
|
805
|
+
connected: socket?.readyState === WebSocket.OPEN,
|
|
806
|
+
muted,
|
|
807
|
+
captureEnabled,
|
|
808
|
+
})) {
|
|
809
|
+
socket.send(JSON.stringify({
|
|
810
|
+
type: 'audio.append',
|
|
811
|
+
audio: chunk.toString('base64'),
|
|
812
|
+
}))
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
const startVoiceIO = audioMode.audioBackend === 'coreaudio'
|
|
817
|
+
? startMacVoiceIO
|
|
818
|
+
: startPortAudioVoiceIO
|
|
819
|
+
|
|
820
|
+
const fallbackHint = fullDuplexFallbackHint(audioMode)
|
|
821
|
+
let fallbackHintPrinted = false
|
|
822
|
+
const printFallbackHint = () => {
|
|
823
|
+
if (!fallbackHint || fallbackHintPrinted) return
|
|
824
|
+
fallbackHintPrinted = true
|
|
825
|
+
print(style(`[建议] ${fallbackHint}`, 'yellow'))
|
|
826
|
+
}
|
|
827
|
+
const reportAudioError = message => {
|
|
828
|
+
print(`${style('[音频]', 'red')} ${message}`)
|
|
829
|
+
printFallbackHint()
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
let bridgeExited = false
|
|
833
|
+
try {
|
|
834
|
+
audioBridge = await startVoiceIO({
|
|
835
|
+
captureSampleRate: inputSampleRate,
|
|
836
|
+
duplexMode: audioMode.fullDuplex ? 'full' : 'half',
|
|
837
|
+
onAudio: sendMicrophoneAudio,
|
|
838
|
+
onPlaybackStarted: responseId => playback?.started(responseId),
|
|
839
|
+
onPlaybackEnded: responseId => playback?.ended(responseId),
|
|
840
|
+
onError: reportAudioError,
|
|
841
|
+
onExit: ({ code, signal }) => {
|
|
842
|
+
bridgeExited = true
|
|
843
|
+
if (!closed) {
|
|
844
|
+
print(style(
|
|
845
|
+
`[音频设备已停止:${code ?? signal ?? 'unknown'}]`,
|
|
846
|
+
'red',
|
|
847
|
+
))
|
|
848
|
+
printFallbackHint()
|
|
849
|
+
close()
|
|
850
|
+
}
|
|
851
|
+
},
|
|
852
|
+
})
|
|
853
|
+
} catch (error) {
|
|
854
|
+
if (!fallbackHint) throw error
|
|
855
|
+
throw new Error(`${error.message}\n建议:${fallbackHint}`, { cause: error })
|
|
856
|
+
}
|
|
857
|
+
if (closed) {
|
|
858
|
+
audioBridge.close()
|
|
859
|
+
return
|
|
860
|
+
}
|
|
861
|
+
const setCaptureEnabled = enabled => {
|
|
862
|
+
const next = Boolean(enabled)
|
|
863
|
+
if (captureStateSent && captureEnabled === next) return false
|
|
864
|
+
captureEnabled = next
|
|
865
|
+
captureStateSent = true
|
|
866
|
+
audioBridge.setCaptureEnabled(next)
|
|
867
|
+
return true
|
|
868
|
+
}
|
|
869
|
+
setCaptureEnabled(false)
|
|
870
|
+
|
|
871
|
+
playback = createPlayback({
|
|
872
|
+
audioSink: audioBridge,
|
|
873
|
+
onError: message => print(`${style('[播放错误]', 'red')} ${message}`),
|
|
874
|
+
onStarted: responseId => {
|
|
875
|
+
if (socket?.readyState === WebSocket.OPEN) {
|
|
876
|
+
socket.send(JSON.stringify({
|
|
877
|
+
type: GatewayClientEvent.PLAYBACK_STARTED,
|
|
878
|
+
responseId,
|
|
879
|
+
}))
|
|
880
|
+
}
|
|
881
|
+
},
|
|
882
|
+
onEnded: responseId => {
|
|
883
|
+
if (socket?.readyState === WebSocket.OPEN) {
|
|
884
|
+
socket.send(JSON.stringify({
|
|
885
|
+
type: GatewayClientEvent.PLAYBACK_ENDED,
|
|
886
|
+
responseId,
|
|
887
|
+
}))
|
|
888
|
+
}
|
|
889
|
+
},
|
|
890
|
+
onCancelled: (responseId, reason = '') => {
|
|
891
|
+
if (socket?.readyState === WebSocket.OPEN) {
|
|
892
|
+
socket.send(JSON.stringify({
|
|
893
|
+
type: GatewayClientEvent.PLAYBACK_CANCELLED,
|
|
894
|
+
responseId,
|
|
895
|
+
...(reason ? { reason } : {}),
|
|
896
|
+
}))
|
|
897
|
+
}
|
|
898
|
+
},
|
|
899
|
+
onIdle: () => {
|
|
900
|
+
if (!audioMode.captureDuringPlayback) startMicrophone()
|
|
901
|
+
},
|
|
902
|
+
})
|
|
903
|
+
|
|
904
|
+
const startMicrophone = () => {
|
|
905
|
+
if (
|
|
906
|
+
muted
|
|
907
|
+
|| !frontendReady
|
|
908
|
+
|| !ownsVoice
|
|
909
|
+
|| closed
|
|
910
|
+
|| bridgeExited
|
|
911
|
+
|| socket?.readyState !== WebSocket.OPEN
|
|
912
|
+
) return
|
|
913
|
+
if (setCaptureEnabled(true)) {
|
|
914
|
+
print(`[麦克风已开启 · ${inputSampleRate} Hz · ${audioMode.shortLabel}]`)
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
const setMuted = value => {
|
|
919
|
+
muted = value
|
|
920
|
+
if (muted) {
|
|
921
|
+
setCaptureEnabled(false)
|
|
922
|
+
if (socket?.readyState === WebSocket.OPEN) {
|
|
923
|
+
socket.send(JSON.stringify(microphoneControlEvent(true)))
|
|
924
|
+
}
|
|
925
|
+
print(style(
|
|
926
|
+
'[麦克风已静音,语音输入不会被识别;按 m 恢复]',
|
|
927
|
+
'yellow',
|
|
928
|
+
))
|
|
929
|
+
if (pendingPermissionTasks.size > 0) {
|
|
930
|
+
print(style('[正在等待授权,恢复麦克风后再回答]', 'yellow'))
|
|
931
|
+
}
|
|
932
|
+
} else {
|
|
933
|
+
if (socket?.readyState === WebSocket.OPEN) {
|
|
934
|
+
socket.send(JSON.stringify(microphoneControlEvent(false)))
|
|
935
|
+
}
|
|
936
|
+
print(style('[麦克风已恢复]', 'green'))
|
|
937
|
+
startMicrophone()
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
const handleGatewayMessage = raw => {
|
|
942
|
+
let event
|
|
943
|
+
try {
|
|
944
|
+
event = JSON.parse(raw.toString())
|
|
945
|
+
} catch {
|
|
946
|
+
return
|
|
947
|
+
}
|
|
948
|
+
if (event.type === GatewayServerEvent.VOICE_READY) {
|
|
949
|
+
frontendReady = true
|
|
950
|
+
const nextRate = Number(event.inputSampleRate) || inputSampleRate
|
|
951
|
+
if (nextRate !== inputSampleRate) {
|
|
952
|
+
print(`${style('[音频配置错误]', 'red')} Gateway 要求 ${nextRate} Hz,`
|
|
953
|
+
+ `但音频设备已按 ${inputSampleRate} Hz 启动`)
|
|
954
|
+
close()
|
|
955
|
+
return
|
|
956
|
+
}
|
|
957
|
+
if (ownsVoice) startMicrophone()
|
|
958
|
+
}
|
|
959
|
+
if (event.type === GatewayServerEvent.VOICE_OWNERSHIP) {
|
|
960
|
+
if (event.state === 'active') {
|
|
961
|
+
ownsVoice = true
|
|
962
|
+
everOwnedVoice = true
|
|
963
|
+
startMicrophone()
|
|
964
|
+
} else if (event.state === 'busy') {
|
|
965
|
+
ownsVoice = false
|
|
966
|
+
setCaptureEnabled(false)
|
|
967
|
+
playback.clear()
|
|
968
|
+
const holder = frontendLabel(event.holder)
|
|
969
|
+
if (!everOwnedVoice) {
|
|
970
|
+
print(style(
|
|
971
|
+
`[语音正由${holder}使用;如需接管,请运行 qwenaudio tui --takeover]`,
|
|
972
|
+
'yellow',
|
|
973
|
+
))
|
|
974
|
+
close()
|
|
975
|
+
} else {
|
|
976
|
+
muted = true
|
|
977
|
+
print(style(`[语音正由${holder}使用]`, 'yellow'))
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
if (event.type === GatewayServerEvent.VOICE_DEACTIVATED) {
|
|
982
|
+
ownsVoice = false
|
|
983
|
+
muted = true
|
|
984
|
+
setCaptureEnabled(false)
|
|
985
|
+
playback.clear()
|
|
986
|
+
transcriptRenderer.cancel()
|
|
987
|
+
print(style('[语音已切换到另一窗口]', 'yellow'))
|
|
988
|
+
}
|
|
989
|
+
if (event.type === GatewayServerEvent.PLAYBACK_CLEAR) {
|
|
990
|
+
playback.clear(event.reason || '')
|
|
991
|
+
transcriptRenderer.cancel()
|
|
992
|
+
if (!audioMode.captureDuringPlayback) startMicrophone()
|
|
993
|
+
}
|
|
994
|
+
if (event.type === GatewayServerEvent.AUDIO_DELTA) {
|
|
995
|
+
if (!audioMode.captureDuringPlayback) setCaptureEnabled(false)
|
|
996
|
+
const accepted = playback.write(
|
|
997
|
+
event.audio,
|
|
998
|
+
Number(event.sampleRate) || OUTPUT_SAMPLE_RATE,
|
|
999
|
+
event.responseId,
|
|
1000
|
+
)
|
|
1001
|
+
if (!audioMode.captureDuringPlayback && !accepted) startMicrophone()
|
|
1002
|
+
}
|
|
1003
|
+
if (event.type === GatewayServerEvent.AUDIO_DONE) {
|
|
1004
|
+
playback.done(event.responseId)
|
|
1005
|
+
}
|
|
1006
|
+
transcriptDisplay.handle(event)
|
|
1007
|
+
if (event.type === 'timeline.inline') {
|
|
1008
|
+
const content = event.item?.content || event.item?.markdown || ''
|
|
1009
|
+
if (content) print(`${style('── 执行结果 ──', 'cyan')}\n${content}`)
|
|
1010
|
+
}
|
|
1011
|
+
if (event.type === 'task.running') {
|
|
1012
|
+
turnStatusDisplay.status(
|
|
1013
|
+
event,
|
|
1014
|
+
`${style('[正在处理]', 'yellow')} ${requestLabel(event.task)}`,
|
|
1015
|
+
)
|
|
1016
|
+
}
|
|
1017
|
+
if (event.type === 'task.delegated') {
|
|
1018
|
+
// A pending permission is the actionable state. Do not immediately
|
|
1019
|
+
// obscure it with the broader delegated state for the same task.
|
|
1020
|
+
if (event.task.authorization?.status !== 'pending') {
|
|
1021
|
+
turnStatusDisplay.status(
|
|
1022
|
+
event,
|
|
1023
|
+
`${style('[项目执行中]', 'yellow')} ${requestLabel(event.task)}`,
|
|
1024
|
+
)
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
if (event.type === 'task.finalizing') {
|
|
1028
|
+
turnStatusDisplay.status(
|
|
1029
|
+
event,
|
|
1030
|
+
`${style('[正在整理结果]', 'yellow')} ${requestLabel(event.task)}`,
|
|
1031
|
+
)
|
|
1032
|
+
}
|
|
1033
|
+
if (event.type === 'task.cancelling') {
|
|
1034
|
+
turnStatusDisplay.status(
|
|
1035
|
+
event,
|
|
1036
|
+
`${style('[正在取消]', 'yellow')} ${requestLabel(event.task)}`,
|
|
1037
|
+
)
|
|
1038
|
+
}
|
|
1039
|
+
if (event.type === 'task.permission.requested') {
|
|
1040
|
+
if (event.task?.id) pendingPermissionTasks.add(event.task.id)
|
|
1041
|
+
turnStatusDisplay.status(
|
|
1042
|
+
event,
|
|
1043
|
+
`${style('[需要确认]', 'yellow')} ${permissionStatusText(event.task)}`,
|
|
1044
|
+
)
|
|
1045
|
+
if (muted) {
|
|
1046
|
+
print(style(
|
|
1047
|
+
'[正在等待授权,但麦克风已静音;按 m 恢复后再回答]',
|
|
1048
|
+
'yellow',
|
|
1049
|
+
))
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
if (
|
|
1053
|
+
event.type === 'task.permission.resolved'
|
|
1054
|
+
|| event.type === 'task.completed'
|
|
1055
|
+
|| event.type === 'task.failed'
|
|
1056
|
+
|| event.type === 'task.cancelled'
|
|
1057
|
+
) {
|
|
1058
|
+
if (event.task?.id) pendingPermissionTasks.delete(event.task.id)
|
|
1059
|
+
}
|
|
1060
|
+
if (event.type === 'task.failed') {
|
|
1061
|
+
turnStatusDisplay.status(
|
|
1062
|
+
event,
|
|
1063
|
+
`${style('[处理失败]', 'red')} ${
|
|
1064
|
+
event.task.error || requestLabel(event.task)
|
|
1065
|
+
}`,
|
|
1066
|
+
)
|
|
1067
|
+
}
|
|
1068
|
+
if (event.type === 'error') {
|
|
1069
|
+
transcriptRenderer.cancel()
|
|
1070
|
+
print(`${style('[错误]', 'red')} ${event.message}`)
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
const syncActiveTasks = async () => {
|
|
1075
|
+
const url = new URL('/api/tasks', options.url)
|
|
1076
|
+
url.searchParams.set('sessionId', options.sessionId)
|
|
1077
|
+
url.searchParams.set('active', 'true')
|
|
1078
|
+
const response = await fetch(url, { headers })
|
|
1079
|
+
if (!response.ok) {
|
|
1080
|
+
throw new Error(`任务状态恢复失败(${response.status})`)
|
|
1081
|
+
}
|
|
1082
|
+
const payload = await response.json()
|
|
1083
|
+
for (const task of payload.tasks || []) {
|
|
1084
|
+
const type = task.authorization?.status === 'pending'
|
|
1085
|
+
? 'task.permission.requested'
|
|
1086
|
+
: `task.${task.status}`
|
|
1087
|
+
handleGatewayMessage(JSON.stringify({ type, task }))
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
const connectGateway = () => {
|
|
1092
|
+
if (closed || bridgeExited) return
|
|
1093
|
+
const nextSocket = new WebSocket(
|
|
1094
|
+
websocketUrl(options.url, options.sessionId),
|
|
1095
|
+
{ headers },
|
|
1096
|
+
)
|
|
1097
|
+
socket = nextSocket
|
|
1098
|
+
nextSocket.on('open', () => {
|
|
1099
|
+
if (socket !== nextSocket || closed) return
|
|
1100
|
+
reconnectDelay = 500
|
|
1101
|
+
nextSocket.send(JSON.stringify(connectMessage({
|
|
1102
|
+
voiceEnabled: true,
|
|
1103
|
+
inputEnabled: !muted,
|
|
1104
|
+
outputEnabled: true,
|
|
1105
|
+
takeover: options.takeover === true,
|
|
1106
|
+
})))
|
|
1107
|
+
syncActiveTasks().catch(error => {
|
|
1108
|
+
print(style(`[任务状态] ${error.message}`, 'yellow'))
|
|
1109
|
+
})
|
|
1110
|
+
if (connectedOnce) {
|
|
1111
|
+
print(style('[qwen-audio-agent 已重新连接]', 'green'))
|
|
1112
|
+
} else {
|
|
1113
|
+
connectedOnce = true
|
|
1114
|
+
print(
|
|
1115
|
+
`${style('qwen-audio-agent Voice TUI', 'bold')} · ${health.realtimeLabel} → ${health.backend.label}\n`
|
|
1116
|
+
+ `会话:${options.sessionId}\n`
|
|
1117
|
+
+ `音频:${audioMode.label}\n`
|
|
1118
|
+
+ `${helpText(audioMode)}\n`,
|
|
1119
|
+
)
|
|
1120
|
+
}
|
|
1121
|
+
})
|
|
1122
|
+
nextSocket.on('message', handleGatewayMessage)
|
|
1123
|
+
nextSocket.on('error', error => {
|
|
1124
|
+
if (!closed) print(`${style('[连接错误]', 'red')} ${error.message}`)
|
|
1125
|
+
})
|
|
1126
|
+
nextSocket.on('close', () => {
|
|
1127
|
+
if (socket !== nextSocket) return
|
|
1128
|
+
socket = null
|
|
1129
|
+
frontendReady = false
|
|
1130
|
+
ownsVoice = false
|
|
1131
|
+
setCaptureEnabled(false)
|
|
1132
|
+
playback.clear()
|
|
1133
|
+
transcriptDisplay.reset()
|
|
1134
|
+
if (closed) {
|
|
1135
|
+
print('qwen-audio-agent 连接已关闭。')
|
|
1136
|
+
return
|
|
1137
|
+
}
|
|
1138
|
+
if (bridgeExited) {
|
|
1139
|
+
cleanup()
|
|
1140
|
+
return
|
|
1141
|
+
}
|
|
1142
|
+
print(style('[qwen-audio-agent 连接中断,正在重连]', 'yellow'))
|
|
1143
|
+
scheduleReconnect()
|
|
1144
|
+
})
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
const scheduleReconnect = () => {
|
|
1148
|
+
if (closed || bridgeExited) return
|
|
1149
|
+
const delay = reconnectDelay
|
|
1150
|
+
reconnectDelay = Math.min(5000, reconnectDelay * 2)
|
|
1151
|
+
clearTimeout(reconnectTimer)
|
|
1152
|
+
reconnectTimer = setTimeout(async () => {
|
|
1153
|
+
if (closed || bridgeExited) return
|
|
1154
|
+
try {
|
|
1155
|
+
const refreshed = await readTuiHealth(options.url)
|
|
1156
|
+
const nextRate = Number(
|
|
1157
|
+
refreshed.health.realtimeInputSampleRate,
|
|
1158
|
+
) || inputSampleRate
|
|
1159
|
+
if (nextRate !== inputSampleRate) {
|
|
1160
|
+
print(
|
|
1161
|
+
`${style('[音频配置已变化]', 'red')} Gateway 现在要求 `
|
|
1162
|
+
+ `${nextRate} Hz,请重新启动 TUI`,
|
|
1163
|
+
)
|
|
1164
|
+
close()
|
|
1165
|
+
return
|
|
1166
|
+
}
|
|
1167
|
+
headers = refreshed.cookie ? { Cookie: refreshed.cookie } : {}
|
|
1168
|
+
connectGateway()
|
|
1169
|
+
} catch (error) {
|
|
1170
|
+
print(style(`[等待 Gateway] ${error.message}`, 'yellow'))
|
|
1171
|
+
scheduleReconnect()
|
|
1172
|
+
}
|
|
1173
|
+
}, delay)
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
connectGateway()
|
|
1177
|
+
|
|
1178
|
+
emitKeypressEvents(process.stdin)
|
|
1179
|
+
process.stdin.setRawMode(true)
|
|
1180
|
+
process.stdin.resume()
|
|
1181
|
+
keypressHandler = async (value, key = {}) => {
|
|
1182
|
+
try {
|
|
1183
|
+
if ((key.ctrl && key.name === 'c') || value === 'q') {
|
|
1184
|
+
close()
|
|
1185
|
+
} else if (value === 'm') {
|
|
1186
|
+
setMuted(!muted)
|
|
1187
|
+
} else if (value === 'x' && audioMode.manualInterrupt) {
|
|
1188
|
+
performManualInterrupt({
|
|
1189
|
+
playback,
|
|
1190
|
+
transcriptRenderer,
|
|
1191
|
+
socket,
|
|
1192
|
+
startMicrophone,
|
|
1193
|
+
print,
|
|
1194
|
+
})
|
|
1195
|
+
} else if (value === 'h') {
|
|
1196
|
+
print(helpText(audioMode))
|
|
1197
|
+
}
|
|
1198
|
+
} catch (error) {
|
|
1199
|
+
print(`[错误] ${error.message}`)
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
process.stdin.on('keypress', keypressHandler)
|
|
1203
|
+
|
|
1204
|
+
process.once('SIGINT', handleSigint)
|
|
1205
|
+
process.once('SIGTERM', handleSigterm)
|
|
1206
|
+
await closedPromise
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
const isMain = process.argv[1]
|
|
1210
|
+
&& import.meta.url === pathToFileURL(process.argv[1]).href
|
|
1211
|
+
|
|
1212
|
+
if (isMain) {
|
|
1213
|
+
runTui().catch(error => {
|
|
1214
|
+
process.stderr.write(`qwen-audio-agent TUI 启动失败:${error.message}\n`)
|
|
1215
|
+
process.exitCode = 1
|
|
1216
|
+
})
|
|
1217
|
+
}
|