qwen-audio-agent 2.1.0 → 2.2.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/README.md +6 -3
- package/README_ZH.md +6 -3
- package/cli/package.json +1 -1
- package/cli/src/config-command.mjs +33 -2
- package/cli/src/gateway-service.mjs +7 -1
- package/config/frontend-agent/LIVE_PROMPT.md +64 -0
- package/desktop/src/i18n.mjs +1 -1
- package/desktop/src/settings-config.mjs +10 -24
- package/docs/configuration/frontend.md +29 -12
- package/docs/configuration/frontend.zh.md +28 -12
- package/docs/contract.md +2 -0
- package/docs/contract.zh.md +2 -0
- package/docs/extensions.md +14 -0
- package/docs/extensions.zh.md +11 -0
- package/docs/getting-started/install.md +3 -0
- package/docs/getting-started/install.zh.md +3 -0
- package/docs/getting-started/mobile.md +8 -2
- package/docs/getting-started/mobile.zh.md +5 -0
- package/docs/guides/web-search.md +17 -1
- package/docs/guides/web-search.zh.md +15 -1
- package/docs/operations/troubleshooting.md +30 -0
- package/docs/operations/troubleshooting.zh.md +26 -0
- package/docs/voice-frontends/custom-provider.md +18 -3
- package/docs/voice-frontends/custom-provider.zh.md +18 -3
- package/docs/voice-frontends/google-live.md +7 -3
- package/docs/voice-frontends/google-live.zh.md +6 -3
- package/docs/voice-frontends/gpt-live-1.md +149 -0
- package/docs/voice-frontends/gpt-live-1.zh.md +114 -0
- package/docs/voice-frontends/{gpt-live.md → openai-realtime.md} +12 -5
- package/docs/voice-frontends/{gpt-live.zh.md → openai-realtime.zh.md} +11 -5
- package/docs/voice-frontends/qwen-audio-live.md +164 -0
- package/docs/voice-frontends/qwen-audio-live.zh.md +122 -0
- package/docs/voice-frontends/qwen-audio-realtime.md +2 -1
- package/docs/voice-frontends/qwen-audio-realtime.zh.md +2 -1
- package/docs/voice-frontends/qwen-omni-realtime.md +1 -1
- package/docs/voice-frontends/qwen-omni-realtime.zh.md +1 -1
- package/package.json +13 -4
- package/scripts/patch-build-node-gyp.mjs +63 -0
- package/scripts/prepare-build.mjs +2 -0
- package/scripts/verify-package.mjs +3 -0
- package/server/package.json +2 -2
- package/server/src/conversation/frontend-agent-context.mjs +18 -5
- package/server/src/core/citation.mjs +8 -2
- package/server/src/core/config.mjs +16 -5
- package/server/src/core/request-security.mjs +7 -1
- package/server/src/frontend/frontend-tools.mjs +14 -1
- package/server/src/frontend/retrieval/providers/bing.mjs +23 -12
- package/server/src/frontend/retrieval/providers/factory.mjs +9 -1
- package/server/src/frontend/retrieval/providers/mcp.mjs +17 -9
- package/server/src/frontend/retrieval/providers/so360.mjs +23 -12
- package/server/src/frontend/tools/agent-task-runtime.mjs +22 -4
- package/server/src/frontend/tools/tool-call-handler.mjs +56 -20
- package/server/src/memory/providers/markdown/context-store.mjs +3 -1
- package/server/src/orchestration/session-task-coordinator.mjs +4 -1
- package/server/src/orchestration/task-operations.mjs +5 -3
- package/server/src/orchestration/task-updates.mjs +2 -1
- package/server/src/transport/gateway-client-transport.mjs +19 -0
- package/server/src/transport/webrtc/protocol.mjs +1 -1
- package/server/src/voice/audio-stream-diagnostics.mjs +139 -0
- package/server/src/voice/native-delegation-runtime.mjs +360 -0
- package/server/src/voice/providers/dashscope-live.mjs +93 -0
- package/server/src/voice/providers/dashscope.mjs +12 -4
- package/server/src/voice/providers/doubao-seeduplex-protocol.mjs +54 -0
- package/server/src/voice/providers/doubao-seeduplex.mjs +6 -5
- package/server/src/voice/providers/ga-protocol.mjs +7 -2
- package/server/src/voice/providers/google-live-protocol.mjs +124 -34
- package/server/src/voice/providers/google-live.mjs +6 -5
- package/server/src/voice/providers/gpt-live-1-protocol.mjs +597 -0
- package/server/src/voice/providers/gpt-live-1.mjs +3 -0
- package/server/src/voice/providers/gpt-live-client-context.mjs +182 -0
- package/server/src/voice/providers/openai-live.mjs +150 -0
- package/server/src/voice/providers/{gpt-live.mjs → openai-realtime.mjs} +15 -14
- package/server/src/voice/providers/provider-registry.mjs +11 -1
- package/server/src/voice/providers/qwen-live-protocol.mjs +399 -0
- package/server/src/voice/providers/registry.mjs +45 -10
- package/server/src/voice/providers/runtime-configuration.mjs +17 -6
- package/server/src/voice/providers/stepfun.mjs +1 -1
- package/server/src/voice/realtime-input-runtime.mjs +56 -20
- package/server/src/voice/realtime-presentation-runtime.mjs +21 -4
- package/server/src/voice/realtime-provider-session.mjs +59 -14
- package/server/src/voice/realtime-provider.mjs +332 -36
- package/server/src/voice/realtime-session-runtime.mjs +207 -16
- package/server/src/voice/realtime-task-presentation.mjs +6 -2
- package/server/src/voice/realtime-turn-state.mjs +33 -2
- package/shared/gateway/client-sdk.mjs +15 -5
- package/shared/gateway/websocket-auth.mjs +2 -1
- package/shared/protocol/gateway-events.mjs +31 -0
- package/shared/realtime-legacy-environment.mjs +37 -8
- package/shared/realtime-model-catalog.mjs +12 -10
- package/shared/realtime-models/README.md +10 -2
- package/shared/realtime-models/dashscope.mjs +11 -0
- package/shared/realtime-models/{google-live.mjs → google.mjs} +1 -1
- package/shared/realtime-models/openai.mjs +24 -0
- package/shared/realtime-models/profile.mjs +6 -3
- package/shared/realtime-models/{doubao-seeduplex.mjs → volcengine.mjs} +1 -1
- package/shared/realtime-provider-catalog.mjs +7 -6
- package/shared/realtime-provider-definitions.mjs +87 -22
- package/shared/runtime-environment.mjs +2 -2
- package/shared/web-search-configuration.mjs +14 -2
- package/tui/package.json +2 -2
- package/tui/src/index.mjs +14 -9
- package/tui/src/runtime-configuration.mjs +2 -0
- package/tui/src/terminal-commands.mjs +40 -0
- package/tui/src/text-cli.mjs +10 -1
- package/web/dist/assets/index-Bc2Q04J9.css +1 -0
- package/web/dist/assets/index-bY4DFXKT.js +96 -0
- package/web/dist/index.html +2 -2
- package/shared/realtime-models/gpt-live.mjs +0 -10
- package/web/dist/assets/index-8erKDCr2.css +0 -1
- package/web/dist/assets/index-Cs4hYWbS.js +0 -96
|
@@ -2,10 +2,12 @@ import { randomUUID } from 'node:crypto'
|
|
|
2
2
|
import { normalizeInputParts } from '../../../shared/input-parts.mjs'
|
|
3
3
|
import { GatewayClientEvent, GatewayServerEvent } from '../../../shared/protocol/realtime-events.mjs'
|
|
4
4
|
import { GatewayClientCapability } from '../../../shared/protocol/gateway-client-protocol.mjs'
|
|
5
|
+
import { normalizeAudioPlaybackDiagnostics } from '../../../shared/protocol/gateway-events.mjs'
|
|
5
6
|
import { AnnouncementWindow } from './announcement/announcement-window.mjs'
|
|
6
7
|
import { normalizeClientContext } from '../conversation/frontend-agent-context.mjs'
|
|
7
8
|
import { realtimeEventErrorMessage } from './realtime-provider.mjs'
|
|
8
9
|
import { SessionTaskCoordinator } from '../orchestration/session-task-coordinator.mjs'
|
|
10
|
+
import { NativeDelegationRuntime } from './native-delegation-runtime.mjs'
|
|
9
11
|
import { createRealtimeTaskPresentation } from './realtime-task-presentation.mjs'
|
|
10
12
|
import { recordTaskResult } from '../conversation/task-result-projector.mjs'
|
|
11
13
|
import { ToolCallHandler } from '../frontend/tools/tool-call-handler.mjs'
|
|
@@ -35,6 +37,11 @@ const PERMISSION_RESPONSE_GRACE_MS = 800
|
|
|
35
37
|
const RESPONSE_CONTEXT_CLEANUP_MS = 30000
|
|
36
38
|
const REALTIME_STABLE_CONNECTION_MS = 10000
|
|
37
39
|
|
|
40
|
+
function playbackDiagnosticFields(event) {
|
|
41
|
+
const audioDiagnostics = normalizeAudioPlaybackDiagnostics(event.audioDiagnostics)
|
|
42
|
+
return audioDiagnostics ? { audioDiagnostics } : {}
|
|
43
|
+
}
|
|
44
|
+
|
|
38
45
|
function gatewayTurnId() {
|
|
39
46
|
return `gateway_${randomUUID().replaceAll('-', '')}`
|
|
40
47
|
}
|
|
@@ -92,6 +99,11 @@ export function createRealtimeSessionRuntime({
|
|
|
92
99
|
send(event)
|
|
93
100
|
}
|
|
94
101
|
let inputEnabled = false
|
|
102
|
+
let externalInput = false
|
|
103
|
+
let externalAudioInput = false
|
|
104
|
+
let inputCollecting = false
|
|
105
|
+
const realtimeEventListeners = new Set()
|
|
106
|
+
const pendingProviderInputs = new Map()
|
|
95
107
|
let outputEnabled = false
|
|
96
108
|
// Set only by host arbitration. Unlike inputEnabled (which the client
|
|
97
109
|
// declares about itself) this means the client has been ordered to stop
|
|
@@ -128,6 +140,7 @@ export function createRealtimeSessionRuntime({
|
|
|
128
140
|
beforeSleep: async () => {
|
|
129
141
|
inputEnabled = false
|
|
130
142
|
realtimeSession.clearPendingAudio()
|
|
143
|
+
syncProviderInputMute()
|
|
131
144
|
},
|
|
132
145
|
onSleeping: () => enterSleep(),
|
|
133
146
|
onFailure: ({ error }) => connectionLogger.warn('presence.sleep_failed', {
|
|
@@ -143,6 +156,15 @@ export function createRealtimeSessionRuntime({
|
|
|
143
156
|
const transcripts = new TurnTranscripts()
|
|
144
157
|
const turnCitations = new TurnCitations()
|
|
145
158
|
let realtimeSession
|
|
159
|
+
let nativeDelegations
|
|
160
|
+
// Only opted-in protocols need a cloud mute for client sleep. Derive their
|
|
161
|
+
// state from all input gates so wake/unmute event ordering cannot reopen it.
|
|
162
|
+
const syncProviderInputMute = requestedMuted => {
|
|
163
|
+
const sleepAware = realtimeSession.provider()?.capabilities?.inputMuteOnSleep === true
|
|
164
|
+
if (!sleepAware && requestedMuted === undefined) return
|
|
165
|
+
const muted = sleepAware ? sleeping || inputSuspended || !inputEnabled : requestedMuted
|
|
166
|
+
if (!sleepAware || muted !== realtimeSession.inputMuted) realtimeSession.setInputMuted(muted)
|
|
167
|
+
}
|
|
146
168
|
let visualInput
|
|
147
169
|
const clearVisualInput = () => {
|
|
148
170
|
realtimeSession?.clearPendingImage?.()
|
|
@@ -152,6 +174,7 @@ export function createRealtimeSessionRuntime({
|
|
|
152
174
|
getFrontend: () => realtimeSession?.frontend,
|
|
153
175
|
isDeliveryBlocked: delivery => (
|
|
154
176
|
closed
|
|
177
|
+
|| inputCollecting
|
|
155
178
|
|| !realtimeSession?.ready
|
|
156
179
|
|| (delivery.mode !== 'context' && (sleeping || waking || !outputEnabled))
|
|
157
180
|
),
|
|
@@ -197,7 +220,9 @@ export function createRealtimeSessionRuntime({
|
|
|
197
220
|
getState: () => ({
|
|
198
221
|
ready: realtimeSession?.ready === true,
|
|
199
222
|
outputEnabled, sleeping, waking,
|
|
200
|
-
|
|
223
|
+
nativeTaskDelivery: realtimeSession?.provider()?.capabilities?.nativeDelegation === true,
|
|
224
|
+
notificationDeliverySupported: realtimeSession?.frontend?.capabilities?.clientResponses !== false
|
|
225
|
+
&& (nonVoiceClient || playbackReceipts),
|
|
201
226
|
windowBlocked: announcementWindow.isBlocked(),
|
|
202
227
|
busy: turns.userSpeaking || announcementWindow.isBlocked(),
|
|
203
228
|
}),
|
|
@@ -211,6 +236,9 @@ export function createRealtimeSessionRuntime({
|
|
|
211
236
|
onProgressError: error => connectionLogger.warn('progress.injection_failed', {
|
|
212
237
|
error: error.message,
|
|
213
238
|
}),
|
|
239
|
+
onPresentRequest: requestId => {
|
|
240
|
+
if (realtimeSession.frontend?.capabilities?.concurrentVoicePlayback) turns.noteRequest(requestId)
|
|
241
|
+
},
|
|
214
242
|
}),
|
|
215
243
|
onTaskEvent,
|
|
216
244
|
onResult: task => recordTaskResult({ conversationSync, ownerId, sessionId, task }),
|
|
@@ -233,7 +261,13 @@ export function createRealtimeSessionRuntime({
|
|
|
233
261
|
onEvent: event => handleEvent(event),
|
|
234
262
|
onDiagnostic: diagnostic => {
|
|
235
263
|
const { event, ...fields } = diagnostic
|
|
236
|
-
const
|
|
264
|
+
const delegationUpdate = ['realtime.delegation.update_sent', 'realtime.delegation.update_acknowledged'].includes(event)
|
|
265
|
+
if (delegationUpdate && fields.updateKind === 'progress') {
|
|
266
|
+
connectionLogger.debug(event, fields)
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
const informational = ['realtime.response_requested', 'realtime.response_started', 'realtime.audio.transport'].includes(event)
|
|
270
|
+
|| delegationUpdate
|
|
237
271
|
|| (event === 'realtime.transport_closed' && fields.code === 1000)
|
|
238
272
|
if (informational) connectionLogger.info(event, fields)
|
|
239
273
|
else connectionLogger.warn(event, fields)
|
|
@@ -248,6 +282,7 @@ export function createRealtimeSessionRuntime({
|
|
|
248
282
|
announcements.flush()
|
|
249
283
|
},
|
|
250
284
|
onConnected: () => {
|
|
285
|
+
nativeDelegations?.syncTaskState()
|
|
251
286
|
taskCoordinator.announcePendingPermissions()
|
|
252
287
|
taskCoordinator.announcePendingInputs()
|
|
253
288
|
},
|
|
@@ -258,8 +293,10 @@ export function createRealtimeSessionRuntime({
|
|
|
258
293
|
emit({
|
|
259
294
|
type: GatewayServerEvent.VOICE_READY,
|
|
260
295
|
inputSampleRate: createdFrontend.provider.inputSampleRate,
|
|
261
|
-
provider: createdFrontend.provider.key,
|
|
296
|
+
provider: createdFrontend.provider.provider || createdFrontend.provider.key,
|
|
262
297
|
providerLabel: createdFrontend.provider.label,
|
|
298
|
+
...(createdFrontend.capabilities?.interruptionPlaysOut ? { interruptionPlaysOut: true } : {}),
|
|
299
|
+
...(createdFrontend.capabilities?.pacedOutputAudio ? { pacedOutputAudio: true } : {}),
|
|
263
300
|
})
|
|
264
301
|
sleepController.recordActivity()
|
|
265
302
|
progressAnnouncements.flush()
|
|
@@ -275,6 +312,9 @@ export function createRealtimeSessionRuntime({
|
|
|
275
312
|
}
|
|
276
313
|
},
|
|
277
314
|
onDisconnected: () => {
|
|
315
|
+
nativeDelegations?.detach()
|
|
316
|
+
pendingProviderInputs.clear()
|
|
317
|
+
for (const listener of realtimeEventListeners) listener({ type: 'session.disconnected' })
|
|
278
318
|
taskCoordinator.resetPresentation()
|
|
279
319
|
clearVisualInput()
|
|
280
320
|
clearResponseCandidate()
|
|
@@ -304,6 +344,23 @@ export function createRealtimeSessionRuntime({
|
|
|
304
344
|
? { createFrontend: realtimeFrontendFactory }
|
|
305
345
|
: {}),
|
|
306
346
|
})
|
|
347
|
+
nativeDelegations = new NativeDelegationRuntime({
|
|
348
|
+
taskManager, taskOperations, ownerId, sessionId, backendAvailability, inputAssets,
|
|
349
|
+
getFrontend: () => realtimeSession.frontend,
|
|
350
|
+
getTurn: () => turns.committed(),
|
|
351
|
+
getInputContext: itemId => turns.resolveInput(itemId, { fallbackToCurrent: false }),
|
|
352
|
+
onResult: task => recordTaskResult({ conversationSync, ownerId, sessionId, task }),
|
|
353
|
+
onPresentRequest: requestId => turns.noteRequest(requestId),
|
|
354
|
+
onError: (error, fields = {}) => {
|
|
355
|
+
connectionLogger.warn('realtime.delegation.delivery_failed', { ...fields,
|
|
356
|
+
...(typeof error.requestId === 'string' ? { requestId: error.requestId } : {}),
|
|
357
|
+
...(typeof error.eventType === 'string' ? { eventType: error.eventType } : {}),
|
|
358
|
+
...(typeof error.code === 'string' ? { errorCode: error.code } : {}),
|
|
359
|
+
...(Number.isFinite(error.elapsedMs) ? { elapsedMs: error.elapsedMs } : {}),
|
|
360
|
+
error: error.message })
|
|
361
|
+
emit({ type: GatewayServerEvent.ERROR, message: `Live 任务消息未确认送达:${error.message}` })
|
|
362
|
+
},
|
|
363
|
+
})
|
|
307
364
|
visualInput = new VisualInputBuffer({
|
|
308
365
|
onFrame: image => realtimeSession.appendImage(image),
|
|
309
366
|
})
|
|
@@ -315,7 +372,7 @@ export function createRealtimeSessionRuntime({
|
|
|
315
372
|
if (suspend) {
|
|
316
373
|
// Buffered audio predates the suspension and is no longer wanted.
|
|
317
374
|
realtimeSession.clearPendingAudio()
|
|
318
|
-
|
|
375
|
+
syncProviderInputMute(true)
|
|
319
376
|
clearVisualInput()
|
|
320
377
|
sleepController?.disable()
|
|
321
378
|
realtimeSession.cancelResponse()
|
|
@@ -328,7 +385,7 @@ export function createRealtimeSessionRuntime({
|
|
|
328
385
|
})
|
|
329
386
|
return
|
|
330
387
|
}
|
|
331
|
-
if (inputEnabled)
|
|
388
|
+
if (inputEnabled) syncProviderInputMute(false)
|
|
332
389
|
emit({ type: GatewayServerEvent.INPUT_RESUME })
|
|
333
390
|
}
|
|
334
391
|
const deactivate = holder => {
|
|
@@ -384,6 +441,11 @@ export function createRealtimeSessionRuntime({
|
|
|
384
441
|
})
|
|
385
442
|
})
|
|
386
443
|
: () => {}
|
|
444
|
+
// Full duplex: only a turn that began after the Gateway asked answers a request.
|
|
445
|
+
const answersRequest = (turnId, requestId) => (
|
|
446
|
+
!realtimeSession.frontend?.capabilities?.concurrentVoicePlayback
|
|
447
|
+
|| turns.beganAfterRequest(turnId, requestId)
|
|
448
|
+
)
|
|
387
449
|
const toolCalls = new ToolCallHandler({
|
|
388
450
|
taskManager,
|
|
389
451
|
taskOperations,
|
|
@@ -393,6 +455,9 @@ export function createRealtimeSessionRuntime({
|
|
|
393
455
|
getFrontend: () => realtimeSession.frontend,
|
|
394
456
|
getTurnId: () => turns.committedTurnId,
|
|
395
457
|
getTurnGeneration: () => turns.committedTurnGeneration,
|
|
458
|
+
isUserTurnSinceBoundary: context => turns.isUserTurnSinceBoundary(context),
|
|
459
|
+
userTurnBeganAfter: (laterId, turnId) => turns.beganAfterTurn(laterId, turnId),
|
|
460
|
+
answersRequest,
|
|
396
461
|
memoryService,
|
|
397
462
|
notesStore,
|
|
398
463
|
getClientContext: () => clientContext,
|
|
@@ -424,7 +489,8 @@ export function createRealtimeSessionRuntime({
|
|
|
424
489
|
authorizationId,
|
|
425
490
|
error,
|
|
426
491
|
})
|
|
427
|
-
|
|
492
|
+
if (realtimeSession.frontend?.capabilities?.nativeDelegation) nativeDelegations.retryPermission(authorizationId)
|
|
493
|
+
else taskCoordinator.retryPermission(authorizationId)
|
|
428
494
|
},
|
|
429
495
|
onToolResultReady: ({ callId, turnId, toolName, failed, errorCode }) => {
|
|
430
496
|
const timing = toolCallTimings.get(callId)
|
|
@@ -476,17 +542,24 @@ export function createRealtimeSessionRuntime({
|
|
|
476
542
|
turnCitations,
|
|
477
543
|
sessionDigests,
|
|
478
544
|
})
|
|
479
|
-
const
|
|
545
|
+
const clearResponseWatchdog = () => {
|
|
480
546
|
clearTimeout(responseStartWatchdog)
|
|
481
|
-
clearTimeout(permissionResponseTimer)
|
|
482
547
|
responseStartWatchdog = null
|
|
548
|
+
}
|
|
549
|
+
const clearResponseCandidate = () => {
|
|
550
|
+
clearResponseWatchdog()
|
|
551
|
+
clearTimeout(permissionResponseTimer)
|
|
483
552
|
permissionResponseTimer = null
|
|
484
553
|
responseTurnCandidate = null
|
|
485
554
|
}
|
|
486
555
|
|
|
487
556
|
const ensurePermissionResponseFor = context => {
|
|
488
557
|
clearTimeout(permissionResponseTimer)
|
|
489
|
-
const hasPendingPermission = () =>
|
|
558
|
+
const hasPendingPermission = () => (realtimeSession.frontend?.capabilities?.concurrentVoicePlayback
|
|
559
|
+
? taskCoordinator.activeTasks().some(({ authorization }) => (
|
|
560
|
+
authorization?.status === 'pending' && turns.beganAfterRequest(context.turnId, authorization.id)
|
|
561
|
+
))
|
|
562
|
+
: taskCoordinator.hasPendingPermission())
|
|
490
563
|
if (!hasPendingPermission()) return
|
|
491
564
|
permissionResponseTimer = setTimeout(() => {
|
|
492
565
|
permissionResponseTimer = null
|
|
@@ -514,6 +587,11 @@ export function createRealtimeSessionRuntime({
|
|
|
514
587
|
clearResponseCandidate()
|
|
515
588
|
// The turn is given up: Gateway requests no longer wait for its reply.
|
|
516
589
|
announcementWindow.responseDone({ turnId: context.turnId, failed: true })
|
|
590
|
+
// A full-duplex model may leave a turn unanswered: not a stall.
|
|
591
|
+
if (realtimeSession.frontend?.capabilities?.concurrentVoicePlayback) {
|
|
592
|
+
if (!turns.userSpeaking) emit({ type: 'voice.state', state: 'idle', turnId: context.turnId, origin: 'model' })
|
|
593
|
+
return
|
|
594
|
+
}
|
|
517
595
|
emit({
|
|
518
596
|
type: 'error',
|
|
519
597
|
message: '实时模型没有开始回复,语音连接已自动恢复,请再说一次。',
|
|
@@ -545,6 +623,20 @@ export function createRealtimeSessionRuntime({
|
|
|
545
623
|
send: event => emit(event),
|
|
546
624
|
getFrontend: () => realtimeSession.frontend,
|
|
547
625
|
ensureFrontend: () => realtimeSession.ensure(),
|
|
626
|
+
submitUserInput: async (parts, context) => {
|
|
627
|
+
const frontend = realtimeSession.frontend
|
|
628
|
+
if (!frontend?.capabilities?.nativeDelegation || frontend.capabilities.automaticUserResponses) {
|
|
629
|
+
return frontend.sendUserInput(parts, context)
|
|
630
|
+
}
|
|
631
|
+
// Services without native typed requests leave execution to the local
|
|
632
|
+
// backend. Mirror context without creating a second cloud delegation.
|
|
633
|
+
await frontend.appendUserInputContext(parts)
|
|
634
|
+
if (!nativeDelegations.handleUserInput({ parts, context })) {
|
|
635
|
+
throw new Error('未受理本次输入,请检查后台任务或连接状态。')
|
|
636
|
+
}
|
|
637
|
+
expectResponseFor(context)
|
|
638
|
+
return { delegated: true }
|
|
639
|
+
},
|
|
548
640
|
clearResponseCandidate,
|
|
549
641
|
expectResponseFor,
|
|
550
642
|
shouldEnsurePermissionResponse: context => responseTurnCandidate === context,
|
|
@@ -572,9 +664,10 @@ export function createRealtimeSessionRuntime({
|
|
|
572
664
|
getFrontend: () => realtimeSession.frontend,
|
|
573
665
|
getOutputEnabled: () => outputEnabled,
|
|
574
666
|
getNonVoiceClient: () => nonVoiceClient,
|
|
575
|
-
getPlaybackReceipts: () => playbackReceipts,
|
|
667
|
+
getPlaybackReceipts: () => playbackReceipts && outputEnabled,
|
|
576
668
|
getResponseTurnCandidate: () => responseTurnCandidate,
|
|
577
669
|
clearResponseCandidate,
|
|
670
|
+
clearResponseWatchdog,
|
|
578
671
|
announcementQuietMs: config.announcementQuietMs,
|
|
579
672
|
responseContextCleanupMs: RESPONSE_CONTEXT_CLEANUP_MS,
|
|
580
673
|
turnCitations,
|
|
@@ -584,8 +677,45 @@ export function createRealtimeSessionRuntime({
|
|
|
584
677
|
|
|
585
678
|
const handleEvent = event => {
|
|
586
679
|
if (closed) return
|
|
680
|
+
if (event.type === 'input_audio_buffer.speech_started') {
|
|
681
|
+
pendingProviderInputs.set(event.item_id, { events: [event], suppressed: externalInput, ended: false })
|
|
682
|
+
} else if (inputs.handles(event)) {
|
|
683
|
+
const pending = pendingProviderInputs.get(event.item_id)
|
|
684
|
+
if (pending) {
|
|
685
|
+
pending.events = pending.events.filter(previous => previous.type !== event.type)
|
|
686
|
+
pending.events.push(event)
|
|
687
|
+
if (event.type === 'input_audio_buffer.speech_stopped') {
|
|
688
|
+
pending.ended = true
|
|
689
|
+
if (event.reason === 'turn_invalid') pendingProviderInputs.delete(event.item_id)
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
let cancelAutomaticResponse = false
|
|
694
|
+
if (event.type === 'response.created' && !event.__voiceContext?.turnId) {
|
|
695
|
+
for (const [id, pending] of pendingProviderInputs) {
|
|
696
|
+
if (!pending.ended) continue
|
|
697
|
+
cancelAutomaticResponse ||= pending.suppressed
|
|
698
|
+
pendingProviderInputs.delete(id)
|
|
699
|
+
}
|
|
700
|
+
cancelAutomaticResponse ||= externalInput
|
|
701
|
+
if (cancelAutomaticResponse) event.__voiceContext = { ...event.__voiceContext, suppressed: true }
|
|
702
|
+
}
|
|
703
|
+
for (const listener of realtimeEventListeners) listener(event)
|
|
704
|
+
if (event.type === 'delegation.created') {
|
|
705
|
+
if (!inputCollecting && !externalInput) nativeDelegations.handle(event)
|
|
706
|
+
return
|
|
707
|
+
}
|
|
708
|
+
if (externalInput && inputs.handles(event)) return
|
|
709
|
+
if ((inputCollecting && isResponseActivityEvent(event))
|
|
710
|
+
|| (externalInput && event.type === 'response.created' && !event.__voiceContext?.turnId)) {
|
|
711
|
+
event.__voiceContext = { ...event.__voiceContext, suppressed: true }
|
|
712
|
+
}
|
|
713
|
+
// A late final may finish an existing presentation, never create a new turn
|
|
714
|
+
// after its original response context has already expired or been removed.
|
|
715
|
+
if (event.__voiceLateFinal && !presentationRuntime.has(realtimeResponseId(event))) return
|
|
587
716
|
if (isSleepActivityEvent(event)) sleepController?.recordActivity()
|
|
588
717
|
if (isResponseActivityEvent(event)) presentationRuntime.begin(event)
|
|
718
|
+
if (cancelAutomaticResponse) realtimeSession.cancelResponse()
|
|
589
719
|
if (inputs.handleProviderEvent(event)) return
|
|
590
720
|
const responseFailed = event.type === 'response.done' && event.response?.status === 'failed'
|
|
591
721
|
// Terminal handling may remove or suppress the context; retain its original
|
|
@@ -633,7 +763,10 @@ export function createRealtimeSessionRuntime({
|
|
|
633
763
|
startedAt,
|
|
634
764
|
resultReady: false,
|
|
635
765
|
})
|
|
636
|
-
toolCalls.handle(event, {
|
|
766
|
+
toolCalls.handle(event, {
|
|
767
|
+
...callContext, responseId: id,
|
|
768
|
+
...(inputCollecting || callContext.suppressed ? { turnGeneration: -1 } : {}),
|
|
769
|
+
})
|
|
637
770
|
.catch(error => {
|
|
638
771
|
connectionLogger.warn('realtime.tool_call.failed', {
|
|
639
772
|
...callFields,
|
|
@@ -791,6 +924,7 @@ export function createRealtimeSessionRuntime({
|
|
|
791
924
|
clearVisualInput()
|
|
792
925
|
sleeping = true
|
|
793
926
|
waking = false
|
|
927
|
+
syncProviderInputMute()
|
|
794
928
|
announcementWindow.reset()
|
|
795
929
|
progressAnnouncements.clear()
|
|
796
930
|
emit({
|
|
@@ -817,8 +951,12 @@ export function createRealtimeSessionRuntime({
|
|
|
817
951
|
if (!sleeping || waking) return
|
|
818
952
|
sleeping = false
|
|
819
953
|
waking = false
|
|
954
|
+
syncProviderInputMute()
|
|
820
955
|
presenceController.wake()
|
|
821
956
|
sleepController.wake()
|
|
957
|
+
if (realtimeSession.provider()?.capabilities?.inputMuteOnSleep && (inputEnabled || outputEnabled)) {
|
|
958
|
+
realtimeSession.ensure().catch(reportFrontendError)
|
|
959
|
+
}
|
|
822
960
|
emit({
|
|
823
961
|
type: GatewayServerEvent.VOICE_SLEEP,
|
|
824
962
|
state: 'awake',
|
|
@@ -1018,6 +1156,7 @@ export function createRealtimeSessionRuntime({
|
|
|
1018
1156
|
if (negotiatedCapabilities.includes('client.presence')) enterSleep()
|
|
1019
1157
|
else requestExplicitSleep()
|
|
1020
1158
|
} else if (inputEnabled || outputEnabled) {
|
|
1159
|
+
syncProviderInputMute()
|
|
1021
1160
|
realtimeSession.ensure().catch(reportFrontendError)
|
|
1022
1161
|
}
|
|
1023
1162
|
}).catch(reportFrontendError)
|
|
@@ -1029,7 +1168,7 @@ export function createRealtimeSessionRuntime({
|
|
|
1029
1168
|
} else {
|
|
1030
1169
|
activateVoiceClient()
|
|
1031
1170
|
}
|
|
1032
|
-
|
|
1171
|
+
syncProviderInputMute(false)
|
|
1033
1172
|
realtimeSession.ensure()
|
|
1034
1173
|
.then(() => {
|
|
1035
1174
|
taskCoordinator.announcePendingPermissions()
|
|
@@ -1047,7 +1186,7 @@ export function createRealtimeSessionRuntime({
|
|
|
1047
1186
|
} else {
|
|
1048
1187
|
activateVoiceClient()
|
|
1049
1188
|
}
|
|
1050
|
-
|
|
1189
|
+
syncProviderInputMute(false)
|
|
1051
1190
|
if (sleeping) {
|
|
1052
1191
|
return
|
|
1053
1192
|
}
|
|
@@ -1066,6 +1205,7 @@ export function createRealtimeSessionRuntime({
|
|
|
1066
1205
|
// Defence in depth: a client that has not yet acted on the suspension
|
|
1067
1206
|
// must not be able to feed audio through it.
|
|
1068
1207
|
|| inputSuspended
|
|
1208
|
+
|| (externalInput && !externalAudioInput)
|
|
1069
1209
|
|| !voiceAccess.isActive()
|
|
1070
1210
|
) {
|
|
1071
1211
|
return
|
|
@@ -1102,6 +1242,7 @@ export function createRealtimeSessionRuntime({
|
|
|
1102
1242
|
event.type === GatewayClientEvent.TEXT_MESSAGE
|
|
1103
1243
|
|| event.type === GatewayClientEvent.INPUT_MESSAGE
|
|
1104
1244
|
) {
|
|
1245
|
+
if (externalInput) return
|
|
1105
1246
|
if (sleeping || waking) {
|
|
1106
1247
|
emit({
|
|
1107
1248
|
type: 'error',
|
|
@@ -1117,7 +1258,10 @@ export function createRealtimeSessionRuntime({
|
|
|
1117
1258
|
announcementWindow.interrupt()
|
|
1118
1259
|
announcements.dismissActive()
|
|
1119
1260
|
realtimeSession.cancelResponse()
|
|
1120
|
-
|
|
1261
|
+
// A frontend whose model finishes the speech it already generated plays it out, then stops.
|
|
1262
|
+
if (!realtimeSession.frontend?.capabilities?.interruptionPlaysOut) {
|
|
1263
|
+
emit({ type: GatewayServerEvent.PLAYBACK_CLEAR, reason: 'user_interruption' })
|
|
1264
|
+
}
|
|
1121
1265
|
} else if (event.type === GatewayClientEvent.PLAYBACK_STARTED) {
|
|
1122
1266
|
const id = String(event.responseId || '')
|
|
1123
1267
|
const playbackContext = presentationRuntime.get(id)
|
|
@@ -1130,6 +1274,7 @@ export function createRealtimeSessionRuntime({
|
|
|
1130
1274
|
responseId: id,
|
|
1131
1275
|
turnId: playbackContext?.turnId || '',
|
|
1132
1276
|
origin: playbackContext?.origin || 'model',
|
|
1277
|
+
...playbackDiagnosticFields(event),
|
|
1133
1278
|
})
|
|
1134
1279
|
presentationRuntime.startPlayback(id)
|
|
1135
1280
|
}
|
|
@@ -1140,7 +1285,7 @@ export function createRealtimeSessionRuntime({
|
|
|
1140
1285
|
active: voiceAccess.isActive(),
|
|
1141
1286
|
responseKnown: presentationRuntime.has(id),
|
|
1142
1287
|
})
|
|
1143
|
-
connectionLogger.info('realtime.playback.ended', { responseId: id, accepted })
|
|
1288
|
+
connectionLogger.info('realtime.playback.ended', { responseId: id, accepted, ...playbackDiagnosticFields(event) })
|
|
1144
1289
|
if (accepted) presentationRuntime.finishPlayback(id)
|
|
1145
1290
|
} else if (event.type === GatewayClientEvent.PLAYBACK_CANCELLED) {
|
|
1146
1291
|
const id = String(event.responseId || '')
|
|
@@ -1151,6 +1296,7 @@ export function createRealtimeSessionRuntime({
|
|
|
1151
1296
|
})
|
|
1152
1297
|
connectionLogger.info('realtime.playback.cancelled', {
|
|
1153
1298
|
responseId: id, accepted, reason: String(event.reason || ''),
|
|
1299
|
+
...playbackDiagnosticFields(event),
|
|
1154
1300
|
})
|
|
1155
1301
|
if (accepted) {
|
|
1156
1302
|
presentationRuntime.cancelPlayback(id, {
|
|
@@ -1171,7 +1317,7 @@ export function createRealtimeSessionRuntime({
|
|
|
1171
1317
|
} else if (event.type === GatewayClientEvent.INPUT_MUTE) {
|
|
1172
1318
|
inputEnabled = false
|
|
1173
1319
|
realtimeSession.clearPendingAudio()
|
|
1174
|
-
|
|
1320
|
+
syncProviderInputMute(true)
|
|
1175
1321
|
} else if (event.type === GatewayClientEvent.SLEEP) {
|
|
1176
1322
|
requestExplicitSleep('client')
|
|
1177
1323
|
} else if (event.type === GatewayClientEvent.WAKE) {
|
|
@@ -1209,6 +1355,48 @@ export function createRealtimeSessionRuntime({
|
|
|
1209
1355
|
inputActive: inputEnabled && !inputSuspended && !sleeping && !closed && voiceAccess.isActive(),
|
|
1210
1356
|
}),
|
|
1211
1357
|
updateOutputVoice: updateSessionOutputVoice,
|
|
1358
|
+
// Trusted extensions observe native input or collect external turns.
|
|
1359
|
+
// Business batching stays outside the framework; submission reuses the
|
|
1360
|
+
// ordinary user-turn lifecycle without replacing provider turn detection.
|
|
1361
|
+
setExternalInput(enabled, { audioInput = false } = {}) {
|
|
1362
|
+
const next = enabled === true
|
|
1363
|
+
if (closed) return
|
|
1364
|
+
externalAudioInput = next && audioInput === true
|
|
1365
|
+
if (next === externalInput) return
|
|
1366
|
+
externalInput = next
|
|
1367
|
+
if (!externalAudioInput) realtimeSession.clearPendingAudio()
|
|
1368
|
+
if (externalInput) {
|
|
1369
|
+
for (const pending of pendingProviderInputs.values()) pending.suppressed = true
|
|
1370
|
+
handleClientEvent({ type: GatewayClientEvent.INTERRUPT })
|
|
1371
|
+
}
|
|
1372
|
+
connectionLogger.info('realtime.input_mode.changed', {
|
|
1373
|
+
externalInput, audioInput: externalAudioInput, rebuild: false, provider: realtimeSession.providerKey,
|
|
1374
|
+
})
|
|
1375
|
+
},
|
|
1376
|
+
onRealtimeEvent(listener) {
|
|
1377
|
+
realtimeEventListeners.add(listener)
|
|
1378
|
+
for (const pending of pendingProviderInputs.values()) {
|
|
1379
|
+
for (const event of pending.events) listener(event)
|
|
1380
|
+
}
|
|
1381
|
+
return () => realtimeEventListeners.delete(listener)
|
|
1382
|
+
},
|
|
1383
|
+
setInputCollecting(active) {
|
|
1384
|
+
if (closed || inputCollecting === (active === true)) return
|
|
1385
|
+
inputCollecting = active === true
|
|
1386
|
+
if (inputCollecting) {
|
|
1387
|
+
if (sleeping) wakeFromSleep()
|
|
1388
|
+
handleClientEvent({ type: GatewayClientEvent.INTERRUPT })
|
|
1389
|
+
announcementWindow.beginTurn(gatewayTurnId())
|
|
1390
|
+
} else {
|
|
1391
|
+
announcementWindow.reset()
|
|
1392
|
+
}
|
|
1393
|
+
},
|
|
1394
|
+
submitExternalInput(parts) {
|
|
1395
|
+
if (closed || sleeping || waking) throw new Error('Frontend session is unavailable')
|
|
1396
|
+
if (inputCollecting) throw new Error('External input is not ready')
|
|
1397
|
+
sleepController.recordActivity()
|
|
1398
|
+
inputs.submit({ parts })
|
|
1399
|
+
},
|
|
1212
1400
|
setAssistantProfile(profile) {
|
|
1213
1401
|
if (closed) return
|
|
1214
1402
|
sessionAssistantProfile = String(profile || '').trim()
|
|
@@ -1228,9 +1416,12 @@ export function createRealtimeSessionRuntime({
|
|
|
1228
1416
|
close() {
|
|
1229
1417
|
if (closed) return
|
|
1230
1418
|
closed = true
|
|
1419
|
+
realtimeEventListeners.clear()
|
|
1420
|
+
pendingProviderInputs.clear()
|
|
1231
1421
|
toolScope.abort(new Error('Client disconnected'))
|
|
1232
1422
|
releaseVoiceClient()
|
|
1233
1423
|
taskCoordinator.close()
|
|
1424
|
+
nativeDelegations.close()
|
|
1234
1425
|
unsubscribeMemory()
|
|
1235
1426
|
clearResponseCandidate()
|
|
1236
1427
|
turns.close()
|
|
@@ -26,7 +26,7 @@ function inputSchemaSummary(schema) {
|
|
|
26
26
|
/** Realtime presentation adapter; no Task state, execution or transport ownership. */
|
|
27
27
|
export function createRealtimeTaskPresentation({
|
|
28
28
|
getState, getFrontend, deliveryRuntime, updateContext, cancelPermission,
|
|
29
|
-
taskAnnouncementFactory, config, onError, onProgressError,
|
|
29
|
+
taskAnnouncementFactory, config, onError, onProgressError, onPresentRequest = () => {},
|
|
30
30
|
}) {
|
|
31
31
|
return {
|
|
32
32
|
state: getState,
|
|
@@ -103,7 +103,11 @@ export function createRealtimeTaskPresentation({
|
|
|
103
103
|
instructions: permission ? permissionResponseInstructions : inputRequestResponseInstructions,
|
|
104
104
|
contextTiming: 'immediate',
|
|
105
105
|
},
|
|
106
|
-
}), options)
|
|
106
|
+
}), options).then(outcome => {
|
|
107
|
+
// Asked once the question was put to the user, not while it waited.
|
|
108
|
+
if (outcome?.completed) onPresentRequest(request.id)
|
|
109
|
+
return outcome
|
|
110
|
+
})
|
|
107
111
|
},
|
|
108
112
|
resolveRequest(kind, id, { announced }) {
|
|
109
113
|
const frontend = getFrontend()
|
|
@@ -24,6 +24,12 @@ export class RealtimeTurnState {
|
|
|
24
24
|
this.turnSequence = 0
|
|
25
25
|
this.committedTurnId = ''
|
|
26
26
|
this.committedTurnGeneration = 0
|
|
27
|
+
// Each committed user turn and the generation it began in.
|
|
28
|
+
this.userTurns = new Map()
|
|
29
|
+
// The generation of the last boundary (interrupt, mute, close).
|
|
30
|
+
this.boundaryGeneration = 0
|
|
31
|
+
// The turn sequence when the Gateway first asked each request.
|
|
32
|
+
this.requestTurns = new Map()
|
|
27
33
|
this.userSpeaking = false
|
|
28
34
|
this.voiceStartItemId = ''
|
|
29
35
|
this.manualInputGeneration = null
|
|
@@ -82,8 +88,8 @@ export class RealtimeTurnState {
|
|
|
82
88
|
return { context, supersededVoiceTurn }
|
|
83
89
|
}
|
|
84
90
|
|
|
85
|
-
resolveInput(itemId) {
|
|
86
|
-
return this.correlation.resolve(itemId, this.current())
|
|
91
|
+
resolveInput(itemId, { fallbackToCurrent = true } = {}) {
|
|
92
|
+
return this.correlation.resolve(itemId, fallbackToCurrent ? this.current() : null)
|
|
87
93
|
}
|
|
88
94
|
|
|
89
95
|
completeInput(itemId) {
|
|
@@ -123,9 +129,33 @@ export class RealtimeTurnState {
|
|
|
123
129
|
if (this.isStale(context)) return false
|
|
124
130
|
this.committedTurnId = context.turnId
|
|
125
131
|
this.committedTurnGeneration = context.turnGeneration
|
|
132
|
+
this.userTurns.set(context.turnId, context.turnGeneration)
|
|
133
|
+
if (this.userTurns.size > 100) this.userTurns.delete(this.userTurns.keys().next().value)
|
|
126
134
|
return true
|
|
127
135
|
}
|
|
128
136
|
|
|
137
|
+
// Later user turns may have superseded this one, but no boundary has.
|
|
138
|
+
isUserTurnSinceBoundary(context) {
|
|
139
|
+
const began = this.userTurns.get(context?.turnId)
|
|
140
|
+
return began === context?.turnGeneration && began > this.boundaryGeneration
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Whether user turn `laterId` began after user turn `turnId`.
|
|
144
|
+
beganAfterTurn(laterId, turnId) {
|
|
145
|
+
return this.userTurns.get(laterId) > this.userTurns.get(turnId)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
noteRequest(requestId) {
|
|
149
|
+
if (!requestId || this.requestTurns.has(requestId)) return
|
|
150
|
+
this.requestTurns.set(requestId, this.turnSequence)
|
|
151
|
+
if (this.requestTurns.size > 100) this.requestTurns.delete(this.requestTurns.keys().next().value)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Only a turn that began after the Gateway asked a request answers it.
|
|
155
|
+
beganAfterRequest(turnId, requestId) {
|
|
156
|
+
return this.userTurns.get(turnId) > this.requestTurns.get(requestId)
|
|
157
|
+
}
|
|
158
|
+
|
|
129
159
|
finishManualResponse(context, { automatic = false } = {}) {
|
|
130
160
|
if (
|
|
131
161
|
this.manualInputGeneration === null
|
|
@@ -145,6 +175,7 @@ export class RealtimeTurnState {
|
|
|
145
175
|
advanceBoundary() {
|
|
146
176
|
this.turnGeneration = ++this.turnSequence
|
|
147
177
|
this.committedTurnGeneration = this.turnGeneration
|
|
178
|
+
this.boundaryGeneration = this.turnGeneration
|
|
148
179
|
return this.current()
|
|
149
180
|
}
|
|
150
181
|
|
|
@@ -265,11 +265,21 @@ export class GatewayClient {
|
|
|
265
265
|
#connect() {
|
|
266
266
|
if (this.stopped) return
|
|
267
267
|
this.onStatus?.({ state: 'connecting' })
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
:
|
|
272
|
-
|
|
268
|
+
let socket
|
|
269
|
+
try {
|
|
270
|
+
socket = this.createSocket(this.url, {
|
|
271
|
+
headers: this.accessToken
|
|
272
|
+
? { Authorization: `Bearer ${this.accessToken}` }
|
|
273
|
+
: {},
|
|
274
|
+
})
|
|
275
|
+
} catch (error) {
|
|
276
|
+
this.onStatus?.({ state: 'unavailable', phase: 'connection', error })
|
|
277
|
+
// Callers that own reconnects need the same terminal status as a timeout.
|
|
278
|
+
if (this.stopped || this.socket !== null) return
|
|
279
|
+
this.onStatus?.({ state: 'disconnected' })
|
|
280
|
+
if (this.socket === null) this.#scheduleReconnect()
|
|
281
|
+
return
|
|
282
|
+
}
|
|
273
283
|
this.socket = socket
|
|
274
284
|
this.connectTimer = setTimeout(() => {
|
|
275
285
|
if (this.socket !== socket || this.stopped) return
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export const GATEWAY_WEBSOCKET_PROTOCOL = 'qwaudio.gcp.v6'
|
|
2
2
|
|
|
3
3
|
const GATEWAY_WEBSOCKET_BEARER_PREFIX = 'qwaudio.bearer.'
|
|
4
|
-
|
|
4
|
+
// Device tokens the Gateway issues are 128-bit base64url, i.e. 22 characters.
|
|
5
|
+
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{22,256}$/
|
|
5
6
|
|
|
6
7
|
function protocolValues(header = '') {
|
|
7
8
|
return String(header)
|