qwen-audio-agent 1.2.0 → 1.3.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/PRIVACY.md +5 -0
- package/README.md +65 -5
- package/README_EN.md +68 -7
- package/cli/bin/qwenaudio.mjs +21 -0
- package/cli/package.json +1 -1
- package/cli/src/gateway-service.mjs +4 -2
- package/cli/src/launcher.mjs +20 -0
- package/cli/src/runtime.mjs +88 -15
- package/docs/architecture.md +1 -1
- package/docs/configuration.md +42 -0
- package/package.json +2 -2
- package/server/package.json +2 -2
- package/server/src/agent/acp-process-client.mjs +27 -9
- package/server/src/agent/acp-session-registry.mjs +2 -1
- package/server/src/app/bootstrap.mjs +48 -2
- package/server/src/core/config.mjs +23 -19
- package/server/src/core/logger.mjs +16 -0
- package/server/src/index.mjs +45 -7
- package/server/src/process/managed-backend.mjs +15 -1
- package/server/src/task/task-manager.mjs +25 -0
- package/server/src/voice/active-voice-clients.mjs +7 -1
- package/server/src/voice/providers/dashscope.mjs +11 -3
- package/server/src/voice/providers/ga-protocol.mjs +114 -0
- package/server/src/voice/providers/openai-compatible-protocol.mjs +10 -0
- package/server/src/voice/providers/registry.mjs +67 -13
- package/server/src/voice/providers/s2s.mjs +140 -0
- package/server/src/voice/realtime-gateway.mjs +353 -96
- package/server/src/voice/realtime-provider.mjs +162 -16
- package/server/src/voice/response-context.mjs +37 -0
- package/server/src/voice/response-lifecycle.mjs +41 -0
- package/server/src/voice/turn-correlation.mjs +9 -3
- package/shared/gateway-instance-lock.mjs +184 -0
- package/shared/logger.mjs +301 -0
- package/shared/realtime-events.mjs +1 -0
- package/shared/realtime-provider-catalog.mjs +130 -0
- package/shared/runtime-environment.mjs +16 -0
- package/tui/package.json +1 -1
- package/tui/src/index.mjs +34 -5
- package/web/dist/assets/index-BVUqEVa4.js +38 -0
- package/web/dist/assets/index-DNCByEc_.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-BuB0EFih.css +0 -1
- package/web/dist/assets/index-DfCChshH.js +0 -38
|
@@ -4,6 +4,7 @@ import { stripVTControlCharacters } from 'node:util'
|
|
|
4
4
|
import * as acp from '@agentclientprotocol/sdk'
|
|
5
5
|
import { PACKAGE_VERSION } from '../core/package-version.mjs'
|
|
6
6
|
import { AgentError, requestSignal } from './backend-adapter.mjs'
|
|
7
|
+
import { logger } from '../core/logger.mjs'
|
|
7
8
|
|
|
8
9
|
const MAX_STDERR_CHARS = 12_000
|
|
9
10
|
|
|
@@ -123,6 +124,11 @@ export class AcpProcessClient {
|
|
|
123
124
|
env: this.env,
|
|
124
125
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
125
126
|
})
|
|
127
|
+
const processLogger = logger.child({ subsystem: 'acp', backend: this.label })
|
|
128
|
+
processLogger.info('acp.process_started', {
|
|
129
|
+
pid: child.pid,
|
|
130
|
+
command: this.command,
|
|
131
|
+
})
|
|
126
132
|
this.child = child
|
|
127
133
|
child.stderr?.on('data', chunk => this.appendStderr(chunk))
|
|
128
134
|
const stream = acp.ndJsonStream(
|
|
@@ -142,15 +148,21 @@ export class AcpProcessClient {
|
|
|
142
148
|
this.connection = connection
|
|
143
149
|
this.context = connection.agent
|
|
144
150
|
const exited = new Promise((_, reject) => {
|
|
145
|
-
child.once('error', error =>
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
151
|
+
child.once('error', error => {
|
|
152
|
+
processLogger.error('acp.process_start_failed', { error })
|
|
153
|
+
reject(processError(
|
|
154
|
+
this.label,
|
|
155
|
+
`进程启动失败(${error.message})`,
|
|
156
|
+
))
|
|
157
|
+
})
|
|
158
|
+
child.once('exit', (code, signal) => {
|
|
159
|
+
processLogger.warn('acp.process_exited', { code, signal })
|
|
160
|
+
reject(processError(
|
|
161
|
+
this.label,
|
|
162
|
+
`进程意外退出(${signal || code || 'unknown'})`,
|
|
163
|
+
clean(this.stderr),
|
|
164
|
+
))
|
|
165
|
+
})
|
|
154
166
|
})
|
|
155
167
|
// Promise.race stops observing the loser after initialization succeeds.
|
|
156
168
|
// Keep the process lifecycle rejection handled for the rest of the client.
|
|
@@ -172,6 +184,11 @@ export class AcpProcessClient {
|
|
|
172
184
|
),
|
|
173
185
|
exited,
|
|
174
186
|
])
|
|
187
|
+
processLogger.info('acp.initialized', {
|
|
188
|
+
protocolVersion: this.initializeResult?.protocolVersion,
|
|
189
|
+
agentName: this.initializeResult?.agentInfo?.name,
|
|
190
|
+
agentVersion: this.initializeResult?.agentInfo?.version,
|
|
191
|
+
})
|
|
175
192
|
if (
|
|
176
193
|
this.initializeResult?.protocolVersion !== acp.PROTOCOL_VERSION
|
|
177
194
|
) {
|
|
@@ -190,6 +207,7 @@ export class AcpProcessClient {
|
|
|
190
207
|
}).catch(() => {})
|
|
191
208
|
return this.initializeResult
|
|
192
209
|
} catch (error) {
|
|
210
|
+
processLogger.error('acp.initialization_failed', { error })
|
|
193
211
|
connection.close(error)
|
|
194
212
|
if (child.exitCode == null) child.kill('SIGTERM')
|
|
195
213
|
this.connection = null
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
renameSync,
|
|
5
5
|
writeFileSync,
|
|
6
6
|
} from 'node:fs'
|
|
7
|
+
import { logger } from '../core/logger.mjs'
|
|
7
8
|
import { dirname } from 'node:path'
|
|
8
9
|
|
|
9
10
|
const VERSION = 1
|
|
@@ -34,7 +35,7 @@ export class AcpSessionRegistry {
|
|
|
34
35
|
}
|
|
35
36
|
} catch (error) {
|
|
36
37
|
if (error.code !== 'ENOENT') {
|
|
37
|
-
|
|
38
|
+
logger.warn('acp.session_index_read_failed', { error })
|
|
38
39
|
}
|
|
39
40
|
}
|
|
40
41
|
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import express from 'express'
|
|
2
2
|
import { createServer } from 'http'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
3
4
|
import { resolve } from 'path'
|
|
4
5
|
import { agent } from '../agent/agent-client.mjs'
|
|
5
6
|
import { coordinator } from '../agent/coordinator.mjs'
|
|
6
7
|
import { config } from '../core/config.mjs'
|
|
8
|
+
import { logger, runWithLogContext } from '../core/logger.mjs'
|
|
7
9
|
import { conversationSync } from '../conversation/conversation-sync.mjs'
|
|
8
10
|
import { IdentityManager } from '../core/identity.mjs'
|
|
9
11
|
import { FrontendMemoryStore } from '../conversation/frontend-memory.mjs'
|
|
@@ -46,11 +48,17 @@ const dynamicMemory = new FrontendMemoryStore({
|
|
|
46
48
|
filePath: config.frontendMemoryPath,
|
|
47
49
|
maxOwners: config.maxFrontendMemoryOwners,
|
|
48
50
|
ownerTtlMs: config.frontendMemoryOwnerTtlMs,
|
|
51
|
+
onWarning: warning => logger.warn('memory.persistence_warning', { warning }),
|
|
49
52
|
})
|
|
50
53
|
const frontendMemory = new ProfiledMemoryStore({
|
|
51
54
|
memoryStore: dynamicMemory,
|
|
52
55
|
userProfile: config.identityMode === 'personal'
|
|
53
|
-
? new UserProfile({
|
|
56
|
+
? new UserProfile({
|
|
57
|
+
filePath: config.userProfilePath,
|
|
58
|
+
onWarning: warning => logger.warn('profile.persistence_warning', {
|
|
59
|
+
warning,
|
|
60
|
+
}),
|
|
61
|
+
})
|
|
54
62
|
: null,
|
|
55
63
|
})
|
|
56
64
|
const app = express()
|
|
@@ -63,6 +71,25 @@ app.disable('x-powered-by')
|
|
|
63
71
|
app.use(enforceSameOrigin)
|
|
64
72
|
app.use((req, res, next) => {
|
|
65
73
|
req.identity = identityManager.resolveHttp(req, res)
|
|
74
|
+
const requestId = randomUUID()
|
|
75
|
+
res.setHeader('X-Request-Id', requestId)
|
|
76
|
+
runWithLogContext({
|
|
77
|
+
requestId,
|
|
78
|
+
ownerId: req.identity?.ownerId,
|
|
79
|
+
}, next)
|
|
80
|
+
})
|
|
81
|
+
app.use((req, res, next) => {
|
|
82
|
+
const startedAt = Date.now()
|
|
83
|
+
res.once('finish', () => {
|
|
84
|
+
const fields = {
|
|
85
|
+
method: req.method,
|
|
86
|
+
path: req.path,
|
|
87
|
+
status: res.statusCode,
|
|
88
|
+
durationMs: Date.now() - startedAt,
|
|
89
|
+
}
|
|
90
|
+
if (res.statusCode >= 500) logger.warn('http.request_failed', fields)
|
|
91
|
+
else logger.debug('http.request_completed', fields)
|
|
92
|
+
})
|
|
66
93
|
next()
|
|
67
94
|
})
|
|
68
95
|
app.use(express.json({ limit: '1mb' }))
|
|
@@ -75,11 +102,17 @@ app.get('/api/health', async (req, res) => {
|
|
|
75
102
|
const realtime = describeActiveRealtime()
|
|
76
103
|
res.status(backend.ok ? 200 : 503).json({
|
|
77
104
|
ok: backend.ok,
|
|
105
|
+
gatewayInstanceId: process.env.QWEN_AUDIO_GATEWAY_INSTANCE_ID || null,
|
|
106
|
+
gatewayStartedAt: process.env.QWEN_AUDIO_GATEWAY_STARTED_AT || null,
|
|
78
107
|
voiceConfigured: realtime.configured,
|
|
79
108
|
realtimeProvider: realtime.provider,
|
|
80
109
|
realtimeLabel: realtime.label,
|
|
81
110
|
realtimeModel: realtime.model,
|
|
82
111
|
realtimeInputSampleRate: realtime.inputSampleRate,
|
|
112
|
+
realtimeConfigurationSignature: realtime.configurationSignature,
|
|
113
|
+
// Front ends a client may select for its session through the realtime
|
|
114
|
+
// connect event.
|
|
115
|
+
realtimeProviders: realtime.providers,
|
|
83
116
|
announceIntoContext: config.announceIntoContext,
|
|
84
117
|
resultContextMaxChars: config.resultContextMaxChars,
|
|
85
118
|
announcementBatchMs: config.announcementBatchMs,
|
|
@@ -227,6 +260,14 @@ app.get('/api/tasks/:id/events', (req, res) => {
|
|
|
227
260
|
const webDist = webDistributionPath()
|
|
228
261
|
app.use(express.static(webDist))
|
|
229
262
|
app.get('*', (req, res) => res.sendFile(resolve(webDist, 'index.html')))
|
|
263
|
+
app.use((error, req, res, next) => {
|
|
264
|
+
logger.error('http.unhandled_error', {
|
|
265
|
+
method: req.method,
|
|
266
|
+
path: req.path,
|
|
267
|
+
error,
|
|
268
|
+
})
|
|
269
|
+
next(error)
|
|
270
|
+
})
|
|
230
271
|
|
|
231
272
|
const server = createServer(app)
|
|
232
273
|
export { server }
|
|
@@ -251,7 +292,12 @@ server.listen(config.port, config.host, () => {
|
|
|
251
292
|
process.parentPort.postMessage({
|
|
252
293
|
type: 'qwen-audio-agent:gateway-ready',
|
|
253
294
|
origin,
|
|
295
|
+
instanceId: process.env.QWEN_AUDIO_GATEWAY_INSTANCE_ID || null,
|
|
254
296
|
})
|
|
255
297
|
}
|
|
256
|
-
|
|
298
|
+
logger.info('gateway.ready', {
|
|
299
|
+
origin,
|
|
300
|
+
backend: config.agentProtocol || 'none',
|
|
301
|
+
realtimeProvider: config.audioProvider,
|
|
302
|
+
}, `qwen-audio-agent running at ${origin}`)
|
|
257
303
|
})
|
|
@@ -6,6 +6,9 @@ import {
|
|
|
6
6
|
backendNames,
|
|
7
7
|
normalizeBackendProtocol,
|
|
8
8
|
} from '../../../shared/backend-catalog.mjs'
|
|
9
|
+
import {
|
|
10
|
+
resolveRealtimeFrontendConfiguration,
|
|
11
|
+
} from '../../../shared/realtime-provider-catalog.mjs'
|
|
9
12
|
|
|
10
13
|
const here = dirname(fileURLToPath(import.meta.url))
|
|
11
14
|
const sourceRoot = resolve(here, '../../..')
|
|
@@ -198,6 +201,8 @@ export function resolveOpenCodeCoordinatorAgent(env = process.env) {
|
|
|
198
201
|
].includes(selected) ? '' : selected
|
|
199
202
|
}
|
|
200
203
|
|
|
204
|
+
const realtimeFrontend = resolveRealtimeFrontendConfiguration(process.env)
|
|
205
|
+
|
|
201
206
|
export const config = {
|
|
202
207
|
root,
|
|
203
208
|
host: process.env.HOST || '127.0.0.1',
|
|
@@ -206,25 +211,24 @@ export const config = {
|
|
|
206
211
|
port: String(process.env.PORT || '').trim() === '0'
|
|
207
212
|
? 0
|
|
208
213
|
: numberSetting(process.env.PORT, 3101, { min: 1, max: 65535 }),
|
|
209
|
-
audioProvider:
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
audioVoice: process.env.QWEN_AUDIO_REALTIME_VOICE || 'longanqian',
|
|
214
|
+
audioProvider: realtimeFrontend.provider,
|
|
215
|
+
realtimeConfigSignature: realtimeFrontend.signature,
|
|
216
|
+
dashscopeApiKey: realtimeFrontend.dashscopeApiKey,
|
|
217
|
+
audioRealtimeBaseUrl: realtimeFrontend.dashscopeRealtimeUrl,
|
|
218
|
+
// User-managed huggingface/speech-to-speech OpenAI Realtime endpoint. The
|
|
219
|
+
// pipeline owns its STT, LLM, TTS and voice configuration; Gateway only
|
|
220
|
+
// connects to the endpoint and supplies the shared frontend instructions and
|
|
221
|
+
// tools for each realtime Session.
|
|
222
|
+
speechToSpeechRealtimeUrl: realtimeFrontend.speechToSpeechRealtimeUrl,
|
|
223
|
+
// Do not advertise a local service merely because a default endpoint
|
|
224
|
+
// exists. It becomes selectable when the user explicitly configures it or
|
|
225
|
+
// chooses it as the active frontend.
|
|
226
|
+
speechToSpeechConfigured: realtimeFrontend.speechToSpeechConfigured,
|
|
227
|
+
// The upstream WebSocket does not require authentication. This optional
|
|
228
|
+
// credential is useful only when users put it behind an authenticated proxy.
|
|
229
|
+
speechToSpeechAuthToken: realtimeFrontend.speechToSpeechAuthToken,
|
|
230
|
+
audioModel: realtimeFrontend.dashscopeModel,
|
|
231
|
+
audioVoice: realtimeFrontend.dashscopeVoice,
|
|
228
232
|
allowedOrigins: String(process.env.QWEN_AUDIO_AGENT_ALLOWED_ORIGINS || '')
|
|
229
233
|
.split(',')
|
|
230
234
|
.map(value => value.trim())
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createLogger,
|
|
3
|
+
runWithLogContext,
|
|
4
|
+
} from '../../../shared/logger.mjs'
|
|
5
|
+
|
|
6
|
+
export { runWithLogContext }
|
|
7
|
+
|
|
8
|
+
const testProcess = process.env.NODE_ENV === 'test'
|
|
9
|
+
|| process.argv.some(argument => /[\\/](?:test|tests)[\\/]/.test(argument))
|
|
10
|
+
|
|
11
|
+
export const logger = createLogger({
|
|
12
|
+
component: 'gateway',
|
|
13
|
+
fileName: 'gateway.log',
|
|
14
|
+
consoleEnabled: testProcess ? false : undefined,
|
|
15
|
+
fileEnabled: testProcess ? false : undefined,
|
|
16
|
+
})
|
package/server/src/index.mjs
CHANGED
|
@@ -1,24 +1,35 @@
|
|
|
1
1
|
import { dirname, resolve } from 'node:path'
|
|
2
|
+
import { once } from 'node:events'
|
|
2
3
|
import { fileURLToPath } from 'node:url'
|
|
3
4
|
import { loadRuntimeEnvironment } from '../../shared/runtime-environment.mjs'
|
|
5
|
+
import { createLogger } from '../../shared/logger.mjs'
|
|
6
|
+
import { acquireGatewayLease } from '../../shared/gateway-instance-lock.mjs'
|
|
4
7
|
import { startManagedBackend } from './process/managed-backend.mjs'
|
|
5
8
|
|
|
6
9
|
const sourceRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
|
|
7
10
|
const root = process.env.QWEN_AUDIO_AGENT_RUNTIME_ROOT || sourceRoot
|
|
8
|
-
loadRuntimeEnvironment({ root })
|
|
11
|
+
const runtimeEnvironment = loadRuntimeEnvironment({ root })
|
|
12
|
+
|
|
13
|
+
const logger = createLogger({
|
|
14
|
+
component: 'gateway',
|
|
15
|
+
fileName: 'gateway.log',
|
|
16
|
+
})
|
|
9
17
|
|
|
10
18
|
let backendRuntime
|
|
11
19
|
let agentClient
|
|
12
20
|
let stopPromise
|
|
13
21
|
let exitTimer
|
|
22
|
+
let gatewayLease
|
|
23
|
+
let gatewayHeartbeat
|
|
14
24
|
|
|
15
25
|
function stop(signal = 'SIGTERM') {
|
|
16
26
|
if (stopPromise) return stopPromise
|
|
27
|
+
clearInterval(gatewayHeartbeat)
|
|
17
28
|
stopPromise = Promise.all([
|
|
18
29
|
backendRuntime?.stop(signal),
|
|
19
30
|
agentClient?.close(),
|
|
20
31
|
]).catch(error => {
|
|
21
|
-
|
|
32
|
+
logger.error('backend.stop_failed', { error })
|
|
22
33
|
})
|
|
23
34
|
return stopPromise
|
|
24
35
|
}
|
|
@@ -31,14 +42,25 @@ function stopAndExit(signal) {
|
|
|
31
42
|
}
|
|
32
43
|
|
|
33
44
|
try {
|
|
34
|
-
|
|
45
|
+
gatewayLease = acquireGatewayLease(runtimeEnvironment.configDirectory, {
|
|
46
|
+
owner: process.env.QWEN_AUDIO_GATEWAY_OWNER
|
|
47
|
+
|| (process.env.QWEN_AUDIO_AGENT_DESKTOP === '1' ? 'desktop' : 'cli'),
|
|
48
|
+
})
|
|
49
|
+
process.env.QWEN_AUDIO_GATEWAY_INSTANCE_ID = gatewayLease.instanceId
|
|
50
|
+
process.env.QWEN_AUDIO_GATEWAY_STARTED_AT = new Date().toISOString()
|
|
51
|
+
logger.info('gateway.lease_acquired', {
|
|
52
|
+
instanceId: gatewayLease.instanceId,
|
|
53
|
+
owner: process.env.QWEN_AUDIO_GATEWAY_OWNER
|
|
54
|
+
|| (process.env.QWEN_AUDIO_AGENT_DESKTOP === '1' ? 'desktop' : 'cli'),
|
|
55
|
+
})
|
|
56
|
+
backendRuntime = await startManagedBackend({ root, logger })
|
|
35
57
|
const managedBackend = backendRuntime.child
|
|
36
58
|
const onManagedBackendExit = (code, signal) => {
|
|
37
59
|
if (stopPromise) return
|
|
38
60
|
const reason = signal || code || 'unknown'
|
|
39
|
-
|
|
61
|
+
logger.error('backend.exited', { code, signal, reason })
|
|
40
62
|
stopPromise = Promise.resolve(agentClient?.close()).catch(error => {
|
|
41
|
-
|
|
63
|
+
logger.error('backend.stop_failed', { error })
|
|
42
64
|
})
|
|
43
65
|
stopPromise.finally(() => process.exit(1))
|
|
44
66
|
}
|
|
@@ -64,12 +86,28 @@ try {
|
|
|
64
86
|
})
|
|
65
87
|
}
|
|
66
88
|
process.once('exit', () => {
|
|
89
|
+
clearInterval(gatewayHeartbeat)
|
|
67
90
|
backendRuntime?.close()
|
|
68
91
|
agentClient?.close()
|
|
92
|
+
gatewayLease?.release()
|
|
93
|
+
})
|
|
94
|
+
const { server } = await import('./app/bootstrap.mjs')
|
|
95
|
+
if (!server.listening) await once(server, 'listening')
|
|
96
|
+
const address = server.address()
|
|
97
|
+
const port = address && typeof address === 'object'
|
|
98
|
+
? address.port
|
|
99
|
+
: Number(process.env.PORT || 3101)
|
|
100
|
+
const host = process.env.HOST || '127.0.0.1'
|
|
101
|
+
gatewayLease.update({
|
|
102
|
+
state: 'ready',
|
|
103
|
+
origin: `http://${host}:${port}`,
|
|
69
104
|
})
|
|
70
|
-
|
|
105
|
+
gatewayHeartbeat = setInterval(() => gatewayLease?.update(), 15_000)
|
|
106
|
+
gatewayHeartbeat.unref?.()
|
|
71
107
|
} catch (error) {
|
|
108
|
+
clearInterval(gatewayHeartbeat)
|
|
72
109
|
stop()
|
|
73
|
-
|
|
110
|
+
gatewayLease?.release()
|
|
111
|
+
logger.fatal('gateway.start_failed', { error })
|
|
74
112
|
process.exitCode = 1
|
|
75
113
|
}
|
|
@@ -174,6 +174,7 @@ export async function startManagedBackend({
|
|
|
174
174
|
spawnImpl = spawn,
|
|
175
175
|
isAddressInUse = backendAddressInUse,
|
|
176
176
|
findFreeAddress = allocateBackendAddress,
|
|
177
|
+
logger,
|
|
177
178
|
} = {}) {
|
|
178
179
|
const backend = resolveManagedBackend(env)
|
|
179
180
|
if (!backend) return new ManagedBackendRuntime(null, { platform })
|
|
@@ -192,13 +193,26 @@ export async function startManagedBackend({
|
|
|
192
193
|
throw new Error(`Gateway 只能启动本机后台 Agent:${backend.baseUrl}`)
|
|
193
194
|
}
|
|
194
195
|
if (await isAddressInUse(backend.baseUrl)) {
|
|
196
|
+
logger?.info('backend.address_reallocated', {
|
|
197
|
+
backend: backend.protocol,
|
|
198
|
+
requestedBaseUrl: backend.baseUrl,
|
|
199
|
+
})
|
|
195
200
|
backend.baseUrl = await findFreeAddress(backend.baseUrl)
|
|
196
201
|
}
|
|
197
202
|
applyBackendAddress(env, backend)
|
|
198
203
|
const spec = spawnSpec(root, platform, env, driver)
|
|
199
204
|
const child = spawnImpl(spec.command, spec.args, spec.options)
|
|
205
|
+
logger?.info('backend.process_started', {
|
|
206
|
+
backend: backend.protocol,
|
|
207
|
+
pid: child.pid,
|
|
208
|
+
baseUrl: backend.baseUrl,
|
|
209
|
+
ownership: backend.ownership,
|
|
210
|
+
})
|
|
200
211
|
child.once?.('error', error => {
|
|
201
|
-
|
|
212
|
+
logger?.error('backend.process_start_failed', {
|
|
213
|
+
backend: backend.protocol,
|
|
214
|
+
error,
|
|
215
|
+
})
|
|
202
216
|
})
|
|
203
217
|
return new ManagedBackendRuntime(child, { platform })
|
|
204
218
|
}
|
|
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'
|
|
|
2
2
|
import { config } from '../core/config.mjs'
|
|
3
3
|
import { TaskScheduler } from './task-scheduler.mjs'
|
|
4
4
|
import { TaskStore } from './task-store.mjs'
|
|
5
|
+
import { logger } from '../core/logger.mjs'
|
|
5
6
|
|
|
6
7
|
const ACTIVE = new Set([
|
|
7
8
|
'queued',
|
|
@@ -90,6 +91,7 @@ export class TaskManager {
|
|
|
90
91
|
pendingNotificationTtlMs = 604_800_000,
|
|
91
92
|
notificationClaimTtlMs = 60_000,
|
|
92
93
|
maxTerminalTasksPerOwner = 100,
|
|
94
|
+
logger: taskLogger = null,
|
|
93
95
|
} = {}) {
|
|
94
96
|
this.runner = runner
|
|
95
97
|
this.store = store
|
|
@@ -101,6 +103,7 @@ export class TaskManager {
|
|
|
101
103
|
this.pendingNotificationTtlMs = pendingNotificationTtlMs
|
|
102
104
|
this.notificationClaimTtlMs = notificationClaimTtlMs
|
|
103
105
|
this.maxTerminalTasksPerOwner = maxTerminalTasksPerOwner
|
|
106
|
+
this.logger = taskLogger
|
|
104
107
|
this.tasks = new Map()
|
|
105
108
|
this.listeners = new Set()
|
|
106
109
|
this.recoveryCandidates = []
|
|
@@ -234,6 +237,26 @@ export class TaskManager {
|
|
|
234
237
|
task: snapshot,
|
|
235
238
|
...details,
|
|
236
239
|
}
|
|
240
|
+
const log = [
|
|
241
|
+
'task.created',
|
|
242
|
+
'task.running',
|
|
243
|
+
'task.delegated',
|
|
244
|
+
'task.permission.requested',
|
|
245
|
+
'task.permission.resolved',
|
|
246
|
+
'task.completed',
|
|
247
|
+
'task.failed',
|
|
248
|
+
'task.cancelled',
|
|
249
|
+
].includes(type) ? this.logger?.info : this.logger?.debug
|
|
250
|
+
log?.(type, {
|
|
251
|
+
taskId: task.id,
|
|
252
|
+
ownerId: task.ownerId,
|
|
253
|
+
sessionId: task.sessionId,
|
|
254
|
+
turnId: task.turnId,
|
|
255
|
+
kind: task.kind || 'work',
|
|
256
|
+
status: task.status,
|
|
257
|
+
elapsedMs: task.elapsedMs,
|
|
258
|
+
hasError: Boolean(task.error),
|
|
259
|
+
})
|
|
237
260
|
for (const listener of this.listeners) {
|
|
238
261
|
try {
|
|
239
262
|
listener(event)
|
|
@@ -714,10 +737,12 @@ export class TaskManager {
|
|
|
714
737
|
|
|
715
738
|
export const taskStore = new TaskStore({
|
|
716
739
|
filePath: config.taskStatePath,
|
|
740
|
+
onWarning: warning => logger.warn('task.persistence_warning', { warning }),
|
|
717
741
|
})
|
|
718
742
|
|
|
719
743
|
export const taskManager = new TaskManager({
|
|
720
744
|
store: taskStore,
|
|
745
|
+
logger,
|
|
721
746
|
maxConcurrent: config.taskMaxConcurrent,
|
|
722
747
|
maxConcurrentPerOwner: config.taskMaxConcurrentPerOwner,
|
|
723
748
|
terminalTtlMs: config.taskTerminalTtlMs,
|
|
@@ -9,7 +9,13 @@ export class ActiveVoiceClients {
|
|
|
9
9
|
if (previous === client) {
|
|
10
10
|
return { granted: true, previous: null }
|
|
11
11
|
}
|
|
12
|
-
|
|
12
|
+
// A previous owner whose socket already died (e.g. an unclean disconnect
|
|
13
|
+
// after a network drop that never fired ws close) must not hold the slot
|
|
14
|
+
// forever. Only a still-live owner can refuse a non-takeover claim; a dead
|
|
15
|
+
// one is treated as absent. isAlive() is optional, so callers/tests that
|
|
16
|
+
// omit it keep the original "previous always blocks" behaviour.
|
|
17
|
+
const previousAlive = previous ? previous.isAlive?.() !== false : false
|
|
18
|
+
if (previous && previousAlive && !takeover) {
|
|
13
19
|
return { granted: false, previous }
|
|
14
20
|
}
|
|
15
21
|
previous?.deactivate?.(client)
|
|
@@ -13,6 +13,14 @@ function classifyError(message) {
|
|
|
13
13
|
if (isRecoverableRealtimeInactivityError(message)) return 'inactivity'
|
|
14
14
|
if (/user is speaking/i.test(message)) return 'input_busy'
|
|
15
15
|
if (/no active response/i.test(message)) return 'no_active_response'
|
|
16
|
+
if (
|
|
17
|
+
/invalid[_ -]?api[_ -]?key|incorrect api key|authentication failed|unauthorized|unexpected server response: (?:401|403)/i
|
|
18
|
+
.test(message)
|
|
19
|
+
|| /\barrearage\b|account is not in good standing/i.test(message)
|
|
20
|
+
|| /allocationquota\.freetieronly|free allocated quota exceeded|free tier .* exhausted/i
|
|
21
|
+
.test(message)
|
|
22
|
+
|| /model(?:\.|_)?accessdenied|model[_ -]?not[_ -]?found/i.test(message)
|
|
23
|
+
) return 'fatal'
|
|
16
24
|
return 'other'
|
|
17
25
|
}
|
|
18
26
|
|
|
@@ -25,12 +33,12 @@ export const dashscopeProvider = {
|
|
|
25
33
|
|
|
26
34
|
model: () => config.audioModel,
|
|
27
35
|
voice: () => config.audioVoice,
|
|
28
|
-
|
|
29
|
-
|
|
36
|
+
isConfigured: () => Boolean(config.dashscopeApiKey),
|
|
37
|
+
missingConfigurationMessage: '请先配置 DASHSCOPE_API_KEY',
|
|
30
38
|
connectTimeoutMessage: '连接 Qwen Audio Realtime 超时',
|
|
31
39
|
|
|
32
40
|
url: () => realtimeUrl(config.audioRealtimeBaseUrl, config.audioModel),
|
|
33
|
-
headers:
|
|
41
|
+
headers: () => ({ Authorization: `Bearer ${config.dashscopeApiKey}` }),
|
|
34
42
|
classifyError,
|
|
35
43
|
|
|
36
44
|
buildSession: ({ configured, agentContext }) => {
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
function eventId() {
|
|
4
|
+
return `event_${randomUUID().replaceAll('-', '')}`
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
// The GA dialect names response payload modalities output_modalities. Shared
|
|
8
|
+
// frontend call sites still pass the beta modalities field, so the rewrite
|
|
9
|
+
// happens here once instead of leaking into every caller.
|
|
10
|
+
function gaResponse(response) {
|
|
11
|
+
if (!response) return response
|
|
12
|
+
const { modalities, ...rest } = response
|
|
13
|
+
return modalities ? { ...rest, output_modalities: modalities } : rest
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// The GA dialect derives a conversation item's id namespace from its type and
|
|
17
|
+
// rejects ids from the wrong namespace outright ("ID must start with 'fco_'").
|
|
18
|
+
// Items of an unlisted type keep the generic namespace.
|
|
19
|
+
const ID_PREFIXES = Object.freeze({
|
|
20
|
+
message: 'msg',
|
|
21
|
+
function_call: 'fc',
|
|
22
|
+
function_call_output: 'fco',
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
const RESPONSE_CORRELATION_KEY = 'qwen_audio_request_id'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Wire adapter for providers that speak the GA (2025+) dialect of the OpenAI
|
|
29
|
+
* Realtime protocol, e.g. huggingface/speech-to-speech. Differences from the
|
|
30
|
+
* beta dialect are confined to this file:
|
|
31
|
+
*
|
|
32
|
+
* - response payloads use output_modalities instead of modalities;
|
|
33
|
+
* - text deltas arrive as response.output_text.* instead of response.text.*;
|
|
34
|
+
* - conversation item ids are namespaced per item type.
|
|
35
|
+
*/
|
|
36
|
+
export const gaRealtimeProtocol = Object.freeze({
|
|
37
|
+
encodeOutgoing: payload => ({
|
|
38
|
+
event_id: eventId(),
|
|
39
|
+
...payload,
|
|
40
|
+
}),
|
|
41
|
+
|
|
42
|
+
normalizeIncoming: event => {
|
|
43
|
+
switch (event?.type) {
|
|
44
|
+
case 'response.output_text.delta':
|
|
45
|
+
return { ...event, type: 'response.text.delta' }
|
|
46
|
+
case 'response.output_text.done':
|
|
47
|
+
return { ...event, type: 'response.text.done' }
|
|
48
|
+
default:
|
|
49
|
+
return event
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
sessionUpdate: session => ({
|
|
54
|
+
type: 'session.update',
|
|
55
|
+
session,
|
|
56
|
+
}),
|
|
57
|
+
|
|
58
|
+
audioAppend: audio => ({
|
|
59
|
+
type: 'input_audio_buffer.append',
|
|
60
|
+
audio,
|
|
61
|
+
}),
|
|
62
|
+
|
|
63
|
+
conversationItemId: item => {
|
|
64
|
+
const prefix = ID_PREFIXES[item?.type] || 'item'
|
|
65
|
+
return `${prefix}_${randomUUID().replaceAll('-', '')}`
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
conversationItemCreate: item => ({
|
|
69
|
+
type: 'conversation.item.create',
|
|
70
|
+
item,
|
|
71
|
+
}),
|
|
72
|
+
|
|
73
|
+
responseCreate: response => {
|
|
74
|
+
const body = gaResponse(response)
|
|
75
|
+
return {
|
|
76
|
+
type: 'response.create',
|
|
77
|
+
...(body ? { response: body } : {}),
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
|
|
81
|
+
// GA response metadata is echoed by speech-to-speech on response.created
|
|
82
|
+
// and response.done. It lets the Gateway distinguish a response it requested
|
|
83
|
+
// from an automatic server-VAD response sharing the same Session.
|
|
84
|
+
correlateResponseCreate: (payload, requestId) => ({
|
|
85
|
+
...payload,
|
|
86
|
+
response: {
|
|
87
|
+
...(payload.response || {}),
|
|
88
|
+
metadata: {
|
|
89
|
+
...(payload.response?.metadata || {}),
|
|
90
|
+
[RESPONSE_CORRELATION_KEY]: requestId,
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
}),
|
|
94
|
+
|
|
95
|
+
responseCorrelationId: event => String(
|
|
96
|
+
event?.response?.metadata?.[RESPONSE_CORRELATION_KEY] || '',
|
|
97
|
+
),
|
|
98
|
+
|
|
99
|
+
responseCancel: () => ({
|
|
100
|
+
type: 'response.cancel',
|
|
101
|
+
}),
|
|
102
|
+
|
|
103
|
+
userTextItem: text => ({
|
|
104
|
+
type: 'message',
|
|
105
|
+
role: 'user',
|
|
106
|
+
content: [{ type: 'input_text', text }],
|
|
107
|
+
}),
|
|
108
|
+
|
|
109
|
+
functionOutputItem: (callId, output) => ({
|
|
110
|
+
type: 'function_call_output',
|
|
111
|
+
call_id: callId,
|
|
112
|
+
output: JSON.stringify(output),
|
|
113
|
+
}),
|
|
114
|
+
})
|
|
@@ -28,6 +28,10 @@ export const openAiCompatibleProtocol = Object.freeze({
|
|
|
28
28
|
audio,
|
|
29
29
|
}),
|
|
30
30
|
|
|
31
|
+
// Client-assigned id for a conversation item. The beta dialect accepts one
|
|
32
|
+
// opaque namespace for every item type.
|
|
33
|
+
conversationItemId: () => `item_${randomUUID().replaceAll('-', '')}`,
|
|
34
|
+
|
|
31
35
|
conversationItemCreate: item => ({
|
|
32
36
|
type: 'conversation.item.create',
|
|
33
37
|
item,
|
|
@@ -38,6 +42,12 @@ export const openAiCompatibleProtocol = Object.freeze({
|
|
|
38
42
|
...(response ? { response } : {}),
|
|
39
43
|
}),
|
|
40
44
|
|
|
45
|
+
// The DashScope beta dialect does not provide a portable response metadata
|
|
46
|
+
// correlation contract. RealtimeFrontend keeps its established FIFO
|
|
47
|
+
// correlation for providers with this protocol.
|
|
48
|
+
correlateResponseCreate: payload => payload,
|
|
49
|
+
responseCorrelationId: () => '',
|
|
50
|
+
|
|
41
51
|
responseCancel: () => ({
|
|
42
52
|
type: 'response.cancel',
|
|
43
53
|
}),
|