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
|
@@ -15,6 +15,7 @@ import { frontendInputProjection } from '../../../shared/input-parts.mjs'
|
|
|
15
15
|
import { RealtimeConfigurationError } from './realtime-errors.mjs'
|
|
16
16
|
import { RealtimeResponseSlot } from './realtime-response-slot.mjs'
|
|
17
17
|
import { sendBoundedWebSocket } from '../core/websocket-send.mjs'
|
|
18
|
+
import { createAudioStreamDiagnostics } from './audio-stream-diagnostics.mjs'
|
|
18
19
|
|
|
19
20
|
// Re-export provider-agnostic tools and instructions so existing callers
|
|
20
21
|
// (tests, tool-call-handler, bootstrap) continue to work without changes.
|
|
@@ -55,7 +56,10 @@ function matchesConversationItem(expected, received) {
|
|
|
55
56
|
if (expected.type === 'function_call_output') return expected.call_id === received.call_id
|
|
56
57
|
if (expected.type !== 'message' || expected.role !== received.role) return false
|
|
57
58
|
// Ignore automatically created microphone/assistant items on the same socket.
|
|
58
|
-
|
|
59
|
+
// StepFun acknowledges text as audio/transcript; input_audio is microphone input.
|
|
60
|
+
const text = item => (item.content || []).map(part => (
|
|
61
|
+
part.text || (part.type === 'input_audio' ? '' : part.transcript) || ''
|
|
62
|
+
)).join('')
|
|
59
63
|
return text(expected) !== '' && text(expected) === text(received)
|
|
60
64
|
}
|
|
61
65
|
|
|
@@ -86,6 +90,8 @@ const DEFAULT_CAPABILITIES = Object.freeze({
|
|
|
86
90
|
acknowledgesSessionUpdate: true,
|
|
87
91
|
// Refuses concurrent response.create requests instead of queueing them.
|
|
88
92
|
singleResponseSlot: false,
|
|
93
|
+
// Require a formal start; a final transcript may still arrive after completion.
|
|
94
|
+
requiresResponseCreated: false,
|
|
89
95
|
// Echoes response metadata so client-created responses can be correlated
|
|
90
96
|
// without confusing them with automatic server-side responses.
|
|
91
97
|
responseMetadataCorrelation: false,
|
|
@@ -104,17 +110,45 @@ const DEFAULT_CAPABILITIES = Object.freeze({
|
|
|
104
110
|
restoreConversationContext: true,
|
|
105
111
|
// Accepts conversation.item.create and acknowledges created items.
|
|
106
112
|
conversationItems: true,
|
|
113
|
+
// User items can be appended without starting a new interaction.
|
|
114
|
+
contextOnlyItems: true,
|
|
107
115
|
// Tool receipts resume the service's current interaction without an explicit
|
|
108
116
|
// response request. They must be sent even while that interaction is active.
|
|
109
117
|
automaticToolResponses: false,
|
|
118
|
+
// A real user item starts native generation without response.create.
|
|
119
|
+
automaticUserResponses: false,
|
|
110
120
|
// Accepts response.create and response.cancel initiated by the client.
|
|
111
121
|
clientResponses: true,
|
|
122
|
+
// Native work requests and updates run independently of voice responses.
|
|
123
|
+
nativeDelegation: false,
|
|
124
|
+
// Native updates may carry session-wide state without a delegation ID.
|
|
125
|
+
nativeSessionContext: false,
|
|
112
126
|
// Allows session instructions to be refreshed after initial setup.
|
|
113
127
|
mutableSession: true,
|
|
114
128
|
// Requires an audio timeline before accepting the first visual frame.
|
|
115
129
|
imageRequiresAudioStart: false,
|
|
130
|
+
// Voice plays while the backend works; playback responses gate no Gateway request.
|
|
131
|
+
concurrentVoicePlayback: false,
|
|
132
|
+
// A response with calls resumes on a response.create after all their outputs.
|
|
133
|
+
toolOutputsBeforeResponse: false,
|
|
134
|
+
// The model finishes the speech it already generated when the user interrupts: playback is not cleared.
|
|
135
|
+
interruptionPlaysOut: false,
|
|
136
|
+
// Output audio arrives at playback speed, with no lead: clients buffer it even from a local Gateway.
|
|
137
|
+
pacedOutputAudio: false,
|
|
138
|
+
// Explicit input mute keeps the service running without client audio during sleep.
|
|
139
|
+
inputMuteOnSleep: false,
|
|
116
140
|
})
|
|
117
141
|
const DEFAULT_RESPONSE_CANCEL_GRACE_MS = 1_000
|
|
142
|
+
const DEFAULT_DELEGATION_UPDATE_TIMEOUT_MS = 5_000
|
|
143
|
+
const MAX_PENDING_DELEGATION_UPDATES = 64
|
|
144
|
+
const DELEGATION_UPDATE_REQUEST_PREFIX = 'delegation_update_'
|
|
145
|
+
const MAX_PENDING_FINAL_RESPONSES = 100
|
|
146
|
+
const FINAL_TEXT_EVENTS = new Set([
|
|
147
|
+
'response.audio_transcript.done',
|
|
148
|
+
'response.output_audio_transcript.done',
|
|
149
|
+
'response.text.done',
|
|
150
|
+
'response.output_text.done',
|
|
151
|
+
])
|
|
118
152
|
|
|
119
153
|
export class RealtimeFrontend {
|
|
120
154
|
constructor({
|
|
@@ -130,6 +164,7 @@ export class RealtimeFrontend {
|
|
|
130
164
|
responseInactivityTimeoutMs,
|
|
131
165
|
responseCompletionTimeoutMs,
|
|
132
166
|
responseCancelGraceMs = DEFAULT_RESPONSE_CANCEL_GRACE_MS,
|
|
167
|
+
delegationUpdateTimeoutMs = DEFAULT_DELEGATION_UPDATE_TIMEOUT_MS,
|
|
133
168
|
} = {}) {
|
|
134
169
|
this.provider = validateRealtimeProvider(provider)
|
|
135
170
|
this.connectionId = randomUUID()
|
|
@@ -137,6 +172,10 @@ export class RealtimeFrontend {
|
|
|
137
172
|
provider.createProtocol?.({
|
|
138
173
|
connectionId: this.connectionId,
|
|
139
174
|
provider,
|
|
175
|
+
// Protocol hook: a synthetic provider event, through normalizeIncoming.
|
|
176
|
+
emit: event => this.emitProviderEvent(event),
|
|
177
|
+
// Protocol hook: a wire event of its own; correlate: false skips requests.
|
|
178
|
+
send: (payload, options) => this.send(payload, options),
|
|
140
179
|
}) ?? provider.protocol,
|
|
141
180
|
provider.key || provider.label,
|
|
142
181
|
)
|
|
@@ -158,10 +197,24 @@ export class RealtimeFrontend {
|
|
|
158
197
|
this.restoringContext = false
|
|
159
198
|
this.audioInputStarted = false
|
|
160
199
|
this.activeResponses = new Set()
|
|
200
|
+
this.cancelledResponses = new Set()
|
|
201
|
+
// Only used by providers requiring response.created. false = awaiting final
|
|
202
|
+
// while active; true = successfully ended and awaiting one late final.
|
|
203
|
+
this.pendingFinalResponses = new Map()
|
|
204
|
+
// Voice-only playback responses (concurrentVoicePlayback).
|
|
205
|
+
this.playbackResponses = new Set()
|
|
206
|
+
// toolOutputsBeforeResponse: calls awaiting output; responses that made calls
|
|
207
|
+
// -> whether a response.create followed; whether a continuation is owed.
|
|
208
|
+
this.openCalls = new Set()
|
|
209
|
+
this.toolResponses = new Map()
|
|
210
|
+
this.continuationOwed = false
|
|
161
211
|
this.pendingResponses = []
|
|
162
212
|
this.retryingResponses = new Set()
|
|
163
213
|
this.responseWaiters = new Map()
|
|
164
214
|
this.conversationItemWaiters = new Map()
|
|
215
|
+
this.delegationUpdateWaiters = new Map()
|
|
216
|
+
this.delegationUpdateTimeoutMs = Number.isFinite(delegationUpdateTimeoutMs) && delegationUpdateTimeoutMs > 0
|
|
217
|
+
? delegationUpdateTimeoutMs : DEFAULT_DELEGATION_UPDATE_TIMEOUT_MS
|
|
165
218
|
this.conversationItemQueue = Promise.resolve()
|
|
166
219
|
this.conversationItemGeneration = 0
|
|
167
220
|
this.idleWaiters = []
|
|
@@ -194,6 +247,15 @@ export class RealtimeFrontend {
|
|
|
194
247
|
event: 'realtime.response_slot_recovery', provider: this.provider.key, phase,
|
|
195
248
|
}),
|
|
196
249
|
})
|
|
250
|
+
this.audioDiagnostics = this.capabilities.pacedOutputAudio && typeof onDiagnostic === 'function'
|
|
251
|
+
? createAudioStreamDiagnostics({
|
|
252
|
+
inputSampleRate: this.provider.inputSampleRate,
|
|
253
|
+
outputSampleRate: this.provider.outputSampleRate,
|
|
254
|
+
getBufferedAmount: () => this.ws?.bufferedAmount || 0,
|
|
255
|
+
onReport: fields => this.diagnose({ event: 'realtime.audio.transport',
|
|
256
|
+
provider: this.provider.key, connectionId: this.connectionId, ...fields }),
|
|
257
|
+
})
|
|
258
|
+
: null
|
|
197
259
|
}
|
|
198
260
|
|
|
199
261
|
diagnose(event) {
|
|
@@ -234,6 +296,7 @@ export class RealtimeFrontend {
|
|
|
234
296
|
else resolve()
|
|
235
297
|
}
|
|
236
298
|
ws.on('open', () => {
|
|
299
|
+
this.audioDiagnostics?.start()
|
|
237
300
|
try {
|
|
238
301
|
const messages = normalizedEvents(
|
|
239
302
|
this.protocol.connectionMessages?.({
|
|
@@ -262,6 +325,7 @@ export class RealtimeFrontend {
|
|
|
262
325
|
finish(error)
|
|
263
326
|
})
|
|
264
327
|
ws.on('close', (code, reason) => {
|
|
328
|
+
this.audioDiagnostics?.stop()
|
|
265
329
|
this.diagnose({
|
|
266
330
|
event: 'realtime.transport_closed',
|
|
267
331
|
provider: this.provider.key,
|
|
@@ -269,6 +333,7 @@ export class RealtimeFrontend {
|
|
|
269
333
|
reason: reason?.toString().slice(0, 512) || '',
|
|
270
334
|
})
|
|
271
335
|
this.ready = false
|
|
336
|
+
this.protocol.sessionClose?.('transport_closed')
|
|
272
337
|
this.sessionConfigured = false
|
|
273
338
|
this.recentContextInjected = false
|
|
274
339
|
this.resetResponses()
|
|
@@ -300,11 +365,39 @@ export class RealtimeFrontend {
|
|
|
300
365
|
})
|
|
301
366
|
}
|
|
302
367
|
|
|
368
|
+
emitProviderEvent(providerEvent) {
|
|
369
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return
|
|
370
|
+
try {
|
|
371
|
+
this.handleProviderEvent(providerEvent)
|
|
372
|
+
} catch (error) {
|
|
373
|
+
this.onError?.(error)
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
303
377
|
handleProviderEvent(providerEvent, { onSessionReady, onSessionError } = {}) {
|
|
304
|
-
const events =
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
378
|
+
const events = []
|
|
379
|
+
for (const event of normalizedEvents(this.protocol.normalizeIncoming(providerEvent))) {
|
|
380
|
+
if (event.type === 'response.audio.delta' || event.type === 'response.output_audio.delta') {
|
|
381
|
+
this.audioDiagnostics?.output(event.delta)
|
|
382
|
+
}
|
|
383
|
+
if (this.handleDelegationUpdateEvent(event)) continue
|
|
384
|
+
// Some providers replay early output after their formal response start.
|
|
385
|
+
// Late final text belongs to presentation, not to a new active response.
|
|
386
|
+
if (
|
|
387
|
+
this.capabilities.requiresResponseCreated
|
|
388
|
+
&& event.type !== 'response.created'
|
|
389
|
+
&& isResponseActivityEvent(event)
|
|
390
|
+
&& !this.activeResponses.has(realtimeResponseId(event))
|
|
391
|
+
&& !(event.type === 'response.done' && this.cancelledResponses.has(realtimeResponseId(event)))
|
|
392
|
+
) {
|
|
393
|
+
const id = realtimeResponseId(event)
|
|
394
|
+
if (!FINAL_TEXT_EVENTS.has(event.type) || this.pendingFinalResponses.get(id) !== true) continue
|
|
395
|
+
this.pendingFinalResponses.delete(id)
|
|
396
|
+
event.__voiceLateFinal = true
|
|
397
|
+
this.onEvent?.(event)
|
|
398
|
+
events.push(event)
|
|
399
|
+
continue
|
|
400
|
+
}
|
|
308
401
|
if (event.type === 'error' && this.restoringContext) {
|
|
309
402
|
event.__voiceOrigin = 'restore'
|
|
310
403
|
}
|
|
@@ -323,7 +416,9 @@ export class RealtimeFrontend {
|
|
|
323
416
|
this.completeSessionSetup(onSessionReady, onSessionError)
|
|
324
417
|
}
|
|
325
418
|
this.handleLifecycle(event)
|
|
419
|
+
if (event.type === 'response.done') this.cancelledResponses.delete(realtimeResponseId(event))
|
|
326
420
|
this.onEvent?.(event)
|
|
421
|
+
events.push(event)
|
|
327
422
|
}
|
|
328
423
|
return events
|
|
329
424
|
}
|
|
@@ -388,7 +483,8 @@ export class RealtimeFrontend {
|
|
|
388
483
|
}
|
|
389
484
|
|
|
390
485
|
appendAudio(audio) {
|
|
391
|
-
this.send(this.protocol.audioAppend(audio), { audio: true })
|
|
486
|
+
const sent = this.send(this.protocol.audioAppend(audio), { audio: true })
|
|
487
|
+
if (sent) this.audioDiagnostics?.clientInput(audio)
|
|
392
488
|
this.audioInputStarted = true
|
|
393
489
|
}
|
|
394
490
|
|
|
@@ -420,17 +516,7 @@ export class RealtimeFrontend {
|
|
|
420
516
|
sendUserText(text, context = {}, { modalities } = {}) {
|
|
421
517
|
const content = String(text || '').trim()
|
|
422
518
|
if (!content) return Promise.resolve()
|
|
423
|
-
|
|
424
|
-
return Promise.reject(new Error(
|
|
425
|
-
`${this.provider.label} 不支持文本输入`,
|
|
426
|
-
))
|
|
427
|
-
}
|
|
428
|
-
return this.enqueueResponse('model', context, async () => {
|
|
429
|
-
await this.createConversationItem(this.protocol.userTextItem(content), { contextOnly: false })
|
|
430
|
-
return this.sendResponse(
|
|
431
|
-
modalities ? { modalities } : undefined,
|
|
432
|
-
)
|
|
433
|
-
})
|
|
519
|
+
return this.sendUserInput([{ type: 'text', text: content }], context, { modalities })
|
|
434
520
|
}
|
|
435
521
|
|
|
436
522
|
projectUserInput(parts, options = {}) {
|
|
@@ -448,6 +534,75 @@ export class RealtimeFrontend {
|
|
|
448
534
|
: null
|
|
449
535
|
}
|
|
450
536
|
|
|
537
|
+
// A receipt confirms service acceptance, not speech or client playback.
|
|
538
|
+
// Never queue these updates behind a voice response or a waiting tool call.
|
|
539
|
+
async sendDelegationUpdate(update) {
|
|
540
|
+
if (!this.capabilities.nativeDelegation || typeof this.protocol.delegationUpdate !== 'function') {
|
|
541
|
+
throw new Error(`${this.provider.label} 不支持原生任务更新`)
|
|
542
|
+
}
|
|
543
|
+
if (!this.ready || this.ws?.readyState !== WebSocket.OPEN) {
|
|
544
|
+
throw new Error(`${this.provider.label} 连接未就绪,无法回传任务更新`)
|
|
545
|
+
}
|
|
546
|
+
if (this.delegationUpdateWaiters.size >= MAX_PENDING_DELEGATION_UPDATES) {
|
|
547
|
+
throw new Error('待确认的原生任务更新过多')
|
|
548
|
+
}
|
|
549
|
+
const payload = this.protocol.delegationUpdate(update)
|
|
550
|
+
if (!payload) throw new Error('Provider 未生成原生任务更新')
|
|
551
|
+
const requestId = `${DELEGATION_UPDATE_REQUEST_PREFIX}${randomUUID()}`
|
|
552
|
+
const startedAt = Date.now()
|
|
553
|
+
const fields = { provider: this.provider.key, connectionId: this.connectionId,
|
|
554
|
+
providerSessionId: update.providerSessionId ?? null, taskId: update.taskId ?? null,
|
|
555
|
+
delegationId: update.delegationId ?? null, updateKind: update.kind,
|
|
556
|
+
taskRequestId: update.request?.id ?? null, requestKind: update.request?.kind ?? null,
|
|
557
|
+
requestId, eventType: payload.type }
|
|
558
|
+
return new Promise((resolve, reject) => {
|
|
559
|
+
const settle = error => {
|
|
560
|
+
const waiter = this.delegationUpdateWaiters.get(requestId)
|
|
561
|
+
if (!waiter) return
|
|
562
|
+
clearTimeout(waiter.timer)
|
|
563
|
+
this.delegationUpdateWaiters.delete(requestId)
|
|
564
|
+
const elapsedMs = Math.max(0, Date.now() - startedAt)
|
|
565
|
+
if (error) {
|
|
566
|
+
// Preserve only locally generated receipt correlation on the error.
|
|
567
|
+
error.requestId = requestId
|
|
568
|
+
error.eventType = payload.type
|
|
569
|
+
error.elapsedMs = elapsedMs
|
|
570
|
+
reject(error)
|
|
571
|
+
} else {
|
|
572
|
+
this.diagnose({ event: 'realtime.delegation.update_acknowledged', ...fields, elapsedMs })
|
|
573
|
+
resolve({ accepted: true })
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
const timer = setTimeout(() => settle(new Error('原生任务更新确认超时')), this.delegationUpdateTimeoutMs)
|
|
577
|
+
this.delegationUpdateWaiters.set(requestId, { timer, settle })
|
|
578
|
+
try {
|
|
579
|
+
if (!this.send({ ...payload, event_id: requestId }, { correlate: false })) {
|
|
580
|
+
settle(new Error('原生任务更新发送失败'))
|
|
581
|
+
} else {
|
|
582
|
+
this.diagnose({ event: 'realtime.delegation.update_sent', ...fields })
|
|
583
|
+
}
|
|
584
|
+
} catch (error) {
|
|
585
|
+
settle(error)
|
|
586
|
+
}
|
|
587
|
+
})
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
handleDelegationUpdateEvent(event) {
|
|
591
|
+
if (!this.capabilities.nativeDelegation) return false
|
|
592
|
+
if (event.type === 'delegation.update.acknowledged') {
|
|
593
|
+
this.delegationUpdateWaiters.get(event.requestId)?.settle()
|
|
594
|
+
return true
|
|
595
|
+
}
|
|
596
|
+
const requestId = event.type === 'error' ? event.requestId : null
|
|
597
|
+
if (typeof requestId !== 'string' || !requestId.startsWith(DELEGATION_UPDATE_REQUEST_PREFIX)) return false
|
|
598
|
+
const error = new Error(realtimeEventErrorMessage(event, '原生任务更新被拒绝'))
|
|
599
|
+
if (typeof event.error?.code === 'string') error.code = event.error.code
|
|
600
|
+
error.realtimeEvent = true
|
|
601
|
+
this.delegationUpdateWaiters.get(requestId)?.settle(error)
|
|
602
|
+
// Late errors for expired updates must not fail an unrelated voice turn.
|
|
603
|
+
return true
|
|
604
|
+
}
|
|
605
|
+
|
|
451
606
|
async applyUserInput(parts, options = {}) {
|
|
452
607
|
const projection = this.projectUserInput(parts, options)
|
|
453
608
|
if (!projection) return false
|
|
@@ -462,11 +617,18 @@ export class RealtimeFrontend {
|
|
|
462
617
|
}
|
|
463
618
|
|
|
464
619
|
sendUserInput(parts, context = {}, { modalities } = {}) {
|
|
465
|
-
if (!this.capabilities.conversationItems
|
|
620
|
+
if (!this.capabilities.conversationItems
|
|
621
|
+
|| (!this.capabilities.clientResponses && !this.capabilities.automaticUserResponses)) {
|
|
466
622
|
return Promise.reject(new Error(
|
|
467
623
|
`${this.provider.label} 不支持离散文本或文件输入`,
|
|
468
624
|
))
|
|
469
625
|
}
|
|
626
|
+
if (this.capabilities.automaticUserResponses) {
|
|
627
|
+
// Native services own response scheduling; do not wait for an idle
|
|
628
|
+
// Realtime slot or create another response after accepting the input.
|
|
629
|
+
if (!this.ready) return Promise.reject(new Error(`${this.provider.label} 连接未就绪`))
|
|
630
|
+
return this.applyUserInput(parts, { contextOnly: false })
|
|
631
|
+
}
|
|
470
632
|
return this.enqueueResponse('model', context, async () => {
|
|
471
633
|
if (!await this.applyUserInput(parts, { contextOnly: false })) return false
|
|
472
634
|
return this.sendResponse(
|
|
@@ -476,14 +638,14 @@ export class RealtimeFrontend {
|
|
|
476
638
|
}
|
|
477
639
|
|
|
478
640
|
appendUserInputContext(parts, options = {}) {
|
|
479
|
-
if (!this.capabilities.conversationItems) return Promise.resolve(false)
|
|
641
|
+
if (!this.capabilities.conversationItems || !this.capabilities.contextOnlyItems) return Promise.resolve(false)
|
|
480
642
|
return this.enqueueAction(() => this.applyUserInput(parts, options))
|
|
481
643
|
}
|
|
482
644
|
|
|
483
645
|
appendUserContext(text) {
|
|
484
646
|
const content = String(text || '').trim()
|
|
485
647
|
if (!content) return Promise.resolve()
|
|
486
|
-
if (!this.capabilities.conversationItems) return Promise.resolve(false)
|
|
648
|
+
if (!this.capabilities.conversationItems || !this.capabilities.contextOnlyItems) return Promise.resolve(false)
|
|
487
649
|
return this.enqueueAction(() => this.createConversationItem(
|
|
488
650
|
this.protocol.userTextItem(content),
|
|
489
651
|
))
|
|
@@ -501,16 +663,25 @@ export class RealtimeFrontend {
|
|
|
501
663
|
return this.enqueueResponse('agent', context, pending => {
|
|
502
664
|
pending.isCurrent = shouldCreate
|
|
503
665
|
if (shouldCreate && !shouldCreate()) return false
|
|
666
|
+
// Tool results continue the response that made the calls once.
|
|
667
|
+
if (afterToolResults && this.capabilities.toolOutputsBeforeResponse && !this.continuationOwed) return false
|
|
504
668
|
return this.sendResponse(response)
|
|
505
669
|
})
|
|
506
670
|
}
|
|
507
671
|
|
|
672
|
+
// Unvoiced results still continue the response that made the calls.
|
|
673
|
+
continueToolResults(context = {}) {
|
|
674
|
+
if (!this.capabilities.toolOutputsBeforeResponse) return Promise.resolve({ skipped: true })
|
|
675
|
+
return this.ensureResponse(context, { afterToolResults: true })
|
|
676
|
+
}
|
|
677
|
+
|
|
508
678
|
sendFunctionOutput(callId, output, context = {}, {
|
|
509
679
|
createResponse = true,
|
|
510
680
|
response,
|
|
511
681
|
shouldRespond,
|
|
512
682
|
} = {}) {
|
|
513
|
-
if (!this.capabilities.conversationItems
|
|
683
|
+
if (!this.capabilities.conversationItems
|
|
684
|
+
|| (!this.capabilities.clientResponses && !this.capabilities.automaticToolResponses)) {
|
|
514
685
|
return Promise.reject(new Error(
|
|
515
686
|
`${this.provider.label} 不支持 Function Call 结果回注`,
|
|
516
687
|
))
|
|
@@ -525,20 +696,47 @@ export class RealtimeFrontend {
|
|
|
525
696
|
// This acknowledges delivery, not completion of the ensuing speech.
|
|
526
697
|
return sendOutput().then(() => ({ delivered: true, automatic: true }))
|
|
527
698
|
}
|
|
528
|
-
|
|
699
|
+
// Queued requests wait for this output, so it must not queue behind them.
|
|
700
|
+
const answered = this.capabilities.toolOutputsBeforeResponse
|
|
701
|
+
? this.answerCall(callId, sendOutput)
|
|
702
|
+
: null
|
|
703
|
+
if (!createResponse) return answered || this.enqueueAction(sendOutput)
|
|
704
|
+
// A failure is reported through the response request below.
|
|
705
|
+
answered?.catch(() => {})
|
|
529
706
|
return this.enqueueResponse('agent', context, async pending => {
|
|
530
707
|
pending.isCurrent = shouldRespond
|
|
531
|
-
await sendOutput()
|
|
708
|
+
await (answered || sendOutput())
|
|
532
709
|
return this.sendResponse(response)
|
|
533
710
|
})
|
|
534
711
|
}
|
|
535
712
|
|
|
713
|
+
// Sends a call's output once its response has ended; unknown calls get none.
|
|
714
|
+
async answerCall(callId, sendOutput) {
|
|
715
|
+
if (!this.openCalls.has(callId)) return
|
|
716
|
+
try {
|
|
717
|
+
await this.whenIdle()
|
|
718
|
+
if (this.ready) await sendOutput()
|
|
719
|
+
} finally {
|
|
720
|
+
if (this.openCalls.delete(callId)) this.resolveIdle()
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// A call that failed still gets an output: the service waits for one.
|
|
725
|
+
failCall(callId, output) {
|
|
726
|
+
return this.answerCall(callId, () => this.createConversationItem(
|
|
727
|
+
this.protocol.functionOutputItem(callId, output),
|
|
728
|
+
))
|
|
729
|
+
}
|
|
730
|
+
|
|
536
731
|
createConversationItem(item, { contextOnly = true } = {}) {
|
|
537
732
|
if (!this.capabilities.conversationItems) {
|
|
538
733
|
return Promise.reject(new Error(
|
|
539
734
|
`${this.provider.label} 不支持创建对话项`,
|
|
540
735
|
))
|
|
541
736
|
}
|
|
737
|
+
if (contextOnly && !this.capabilities.contextOnlyItems && item?.type === 'message') {
|
|
738
|
+
return Promise.reject(new Error(`${this.provider.label} 不支持静默写入对话项`))
|
|
739
|
+
}
|
|
542
740
|
if (this.capabilities.conversationItemIdEcho) return this.sendConversationItem(item, { contextOnly })
|
|
543
741
|
// Without echoed IDs, only one client-created item may await a receipt.
|
|
544
742
|
// This queue is independent of responses: permissions/environment context
|
|
@@ -720,18 +918,55 @@ export class RealtimeFrontend {
|
|
|
720
918
|
// A dialect may need a conversation item instead of transient response
|
|
721
919
|
// instructions. Wait for its acknowledgement before triggering inference.
|
|
722
920
|
const item = this.protocol.responseInstructionsItem?.(response)
|
|
921
|
+
// Outputs for open calls go first, then these instructions.
|
|
922
|
+
if (item && this.openCalls.size) {
|
|
923
|
+
await this.whenCallsAnswered(pending)
|
|
924
|
+
if (pending.settled) return false
|
|
925
|
+
}
|
|
723
926
|
if (item) await this.createConversationItem(item)
|
|
724
927
|
// An automatic response may have started while the input/context receipt
|
|
725
928
|
// was in flight. Recheck immediately before sending, not just on enqueue.
|
|
726
929
|
await this.whenIdle()
|
|
727
930
|
if (!this.ready || pending.settled || pending.isCurrent?.() === false) return false
|
|
931
|
+
const payload = this.protocol.responseCreate(response)
|
|
932
|
+
if (payload?.type === 'response.create' && this.openCalls.size) {
|
|
933
|
+
await this.whenCallsAnswered(pending)
|
|
934
|
+
// Held like a refused request, it never ran: let its gate re-check.
|
|
935
|
+
if (!this.ready || pending.settled || pending.isCurrent?.({ refused: true }) === false) return false
|
|
936
|
+
}
|
|
728
937
|
pending.responseRequested = true
|
|
729
|
-
|
|
938
|
+
pending.playbackRequest = Boolean(payload) && payload.type !== 'response.create'
|
|
939
|
+
this.send(payload)
|
|
730
940
|
}
|
|
731
941
|
|
|
732
|
-
|
|
942
|
+
// Holds a request until every open call has its output, or it settles.
|
|
943
|
+
async whenCallsAnswered(pending) {
|
|
944
|
+
while (!pending.settled && (this.openCalls.size || this.gatingResponsesActive())) {
|
|
945
|
+
await new Promise(resolve => {
|
|
946
|
+
pending.cancelCallWait = resolve
|
|
947
|
+
this.idleWaiters.push(resolve)
|
|
948
|
+
})
|
|
949
|
+
}
|
|
950
|
+
pending.cancelCallWait = null
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
cancel({ reason = '', speech = false } = {}) {
|
|
954
|
+
if (this.capabilities.concurrentVoicePlayback) {
|
|
955
|
+
// Only playback stops: user speech leaves backend work and queued requests
|
|
956
|
+
// running; any other cancel also drops them.
|
|
957
|
+
const userInterruption = reason === 'user_interruption'
|
|
958
|
+
// The protocol may return a frame that stops the model's speech; the model hears spoken interruptions.
|
|
959
|
+
this.send(this.protocol.interruptPlayback?.({ stop: !userInterruption, speech: userInterruption && speech }))
|
|
960
|
+
if (userInterruption) {
|
|
961
|
+
this.resolveIdle()
|
|
962
|
+
return
|
|
963
|
+
}
|
|
964
|
+
}
|
|
733
965
|
this.responseQueueGeneration += 1
|
|
734
966
|
const cancelledResponseIds = [...this.activeResponses]
|
|
967
|
+
for (const id of cancelledResponseIds) this.cancelledResponses.add(id)
|
|
968
|
+
while (this.cancelledResponses.size > 64) this.cancelledResponses.delete(this.cancelledResponses.values().next().value)
|
|
969
|
+
for (const id of cancelledResponseIds) this.pendingFinalResponses.delete(id)
|
|
735
970
|
const hasResponse = cancelledResponseIds.length
|
|
736
971
|
|| this.pendingResponses.some(pending => pending.responseRequested)
|
|
737
972
|
|| this.responseSlot.blocked
|
|
@@ -757,6 +992,8 @@ export class RealtimeFrontend {
|
|
|
757
992
|
}
|
|
758
993
|
const recoveryTimer = setTimeout(() => {
|
|
759
994
|
for (const responseId of cancelledResponseIds) {
|
|
995
|
+
// A playback response stays tracked until its own response.done.
|
|
996
|
+
if (this.playbackResponses.has(responseId)) continue
|
|
760
997
|
this.activeResponses.delete(responseId)
|
|
761
998
|
this.responseWaiters.delete(responseId)
|
|
762
999
|
}
|
|
@@ -788,9 +1025,10 @@ export class RealtimeFrontend {
|
|
|
788
1025
|
if (matches(pending)) this.settlePending(pending, { cancelled: true, phase: 'start' })
|
|
789
1026
|
}
|
|
790
1027
|
let cancelledActive = false
|
|
791
|
-
for (const pending of this.responseWaiters
|
|
1028
|
+
for (const [id, pending] of this.responseWaiters) {
|
|
792
1029
|
if (!matches(pending)) continue
|
|
793
1030
|
cancelledActive = true
|
|
1031
|
+
this.pendingFinalResponses.delete(id)
|
|
794
1032
|
this.settlePending(pending, {
|
|
795
1033
|
cancelled: true,
|
|
796
1034
|
phase: 'completion',
|
|
@@ -877,11 +1115,19 @@ export class RealtimeFrontend {
|
|
|
877
1115
|
}
|
|
878
1116
|
|
|
879
1117
|
handleLifecycle(event) {
|
|
1118
|
+
const callId = event.type === 'response.function_call_arguments.done'
|
|
1119
|
+
? event.call_id || event.item?.call_id : ''
|
|
1120
|
+
if (callId && this.capabilities.toolOutputsBeforeResponse) {
|
|
1121
|
+
this.openCalls.add(callId)
|
|
1122
|
+
this.toolResponses.set(realtimeResponseId(event), false)
|
|
1123
|
+
}
|
|
880
1124
|
if (event.type === 'error'
|
|
881
1125
|
&& this.provider.classifyError(realtimeEventErrorMessage(event)) === 'no_active_response') {
|
|
882
1126
|
// This acknowledges cancellation; it must not reject an unrelated item.
|
|
883
1127
|
if (this.responseSlot.phase === 'cancelling') {
|
|
1128
|
+
for (const id of this.activeResponses) this.pendingFinalResponses.delete(id)
|
|
884
1129
|
this.activeResponses.clear()
|
|
1130
|
+
this.playbackResponses.clear()
|
|
885
1131
|
this.responseWaiters.clear()
|
|
886
1132
|
this.responseSlot.release()
|
|
887
1133
|
this.resolveIdle()
|
|
@@ -926,6 +1172,7 @@ export class RealtimeFrontend {
|
|
|
926
1172
|
}
|
|
927
1173
|
if (isResponseActivityEvent(event)) {
|
|
928
1174
|
const responseId = realtimeResponseId(event)
|
|
1175
|
+
if (FINAL_TEXT_EVENTS.has(event.type)) this.pendingFinalResponses.delete(responseId)
|
|
929
1176
|
if (this.responseSlot.phase === 'cancelling') {
|
|
930
1177
|
event.__voiceContext = { suppressed: true }
|
|
931
1178
|
} else if (event.type !== 'response.done') {
|
|
@@ -958,8 +1205,12 @@ export class RealtimeFrontend {
|
|
|
958
1205
|
if (index >= 0) {
|
|
959
1206
|
pending = this.pendingResponses.splice(index, 1)[0]
|
|
960
1207
|
}
|
|
961
|
-
} else {
|
|
962
|
-
|
|
1208
|
+
} else if (!(this.capabilities.concurrentVoicePlayback && event.__voiceAutomatic)) {
|
|
1209
|
+
// The model's own speech answers no queued request; a speak request
|
|
1210
|
+
// is answered by playback only.
|
|
1211
|
+
const playback = this.capabilities.concurrentVoicePlayback && Boolean(event.__voicePlayback)
|
|
1212
|
+
const index = this.pendingResponses.findIndex(item => item.responseRequested
|
|
1213
|
+
&& (!this.capabilities.concurrentVoicePlayback || Boolean(item.playbackRequest) === playback))
|
|
963
1214
|
if (index >= 0) pending = this.pendingResponses.splice(index, 1)[0]
|
|
964
1215
|
}
|
|
965
1216
|
clearTimeout(pending?.timer)
|
|
@@ -968,6 +1219,15 @@ export class RealtimeFrontend {
|
|
|
968
1219
|
if (pending?.isCurrent?.() === false) event.__voiceContext = { ...pending.context, suppressed: true }
|
|
969
1220
|
if (id) {
|
|
970
1221
|
this.activeResponses.add(id)
|
|
1222
|
+
if (this.capabilities.requiresResponseCreated) {
|
|
1223
|
+
this.pendingFinalResponses.set(id, false)
|
|
1224
|
+
while (this.pendingFinalResponses.size > MAX_PENDING_FINAL_RESPONSES) {
|
|
1225
|
+
this.pendingFinalResponses.delete(this.pendingFinalResponses.keys().next().value)
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
if (this.capabilities.concurrentVoicePlayback && event.__voicePlayback) {
|
|
1229
|
+
this.playbackResponses.add(id)
|
|
1230
|
+
}
|
|
971
1231
|
if (pending) {
|
|
972
1232
|
this.responseWaiters.set(id, pending)
|
|
973
1233
|
pending.responseStartedAt = Date.now()
|
|
@@ -984,7 +1244,8 @@ export class RealtimeFrontend {
|
|
|
984
1244
|
event.type === 'response.done'
|
|
985
1245
|
|| event.type === 'error'
|
|
986
1246
|
) {
|
|
987
|
-
|
|
1247
|
+
const namedId = realtimeResponseId(event)
|
|
1248
|
+
let id = namedId
|
|
988
1249
|
let pending = this.responseWaiters.get(id)
|
|
989
1250
|
if (
|
|
990
1251
|
event.type === 'error'
|
|
@@ -1010,6 +1271,7 @@ export class RealtimeFrontend {
|
|
|
1010
1271
|
if (
|
|
1011
1272
|
event.type === 'error'
|
|
1012
1273
|
&& !id && this.activeResponses.size === 1
|
|
1274
|
+
&& !this.playbackResponses.has(this.activeResponses.values().next().value)
|
|
1013
1275
|
) {
|
|
1014
1276
|
id = this.activeResponses.values().next().value
|
|
1015
1277
|
event.response_id = id
|
|
@@ -1018,11 +1280,20 @@ export class RealtimeFrontend {
|
|
|
1018
1280
|
event.__voiceContext = { ...(pending?.context || {}), ...event.__voiceContext }
|
|
1019
1281
|
if (id) {
|
|
1020
1282
|
this.activeResponses.delete(id)
|
|
1283
|
+
this.playbackResponses.delete(id)
|
|
1021
1284
|
this.responseWaiters.delete(id)
|
|
1022
1285
|
}
|
|
1023
1286
|
const status = event.response?.status
|
|
1024
1287
|
const completed = event.type === 'response.done'
|
|
1025
1288
|
&& !['failed', 'cancelled', 'incomplete'].includes(status)
|
|
1289
|
+
if (completed && this.pendingFinalResponses.has(id)) {
|
|
1290
|
+
this.pendingFinalResponses.set(id, true)
|
|
1291
|
+
} else {
|
|
1292
|
+
this.pendingFinalResponses.delete(id)
|
|
1293
|
+
}
|
|
1294
|
+
// A response that made calls owes a response.create unless one went out.
|
|
1295
|
+
const continued = this.toolResponses.get(namedId)
|
|
1296
|
+
if (this.toolResponses.delete(namedId) && completed && !continued) this.continuationOwed = true
|
|
1026
1297
|
this.settlePending(pending, completed
|
|
1027
1298
|
? { completed: true, responseId: id }
|
|
1028
1299
|
: { failed: true, responseId: id, status })
|
|
@@ -1113,6 +1384,7 @@ export class RealtimeFrontend {
|
|
|
1113
1384
|
}
|
|
1114
1385
|
if (this.capabilities.singleResponseSlot) this.responseSlot.recover()
|
|
1115
1386
|
else this.send(this.protocol.responseCancel())
|
|
1387
|
+
this.pendingFinalResponses.delete(responseId)
|
|
1116
1388
|
this.settlePending(pending, {
|
|
1117
1389
|
timedOut: true,
|
|
1118
1390
|
phase: 'inactivity',
|
|
@@ -1122,6 +1394,7 @@ export class RealtimeFrontend {
|
|
|
1122
1394
|
if (this.responseWaiters.get(responseId) !== pending) return
|
|
1123
1395
|
this.responseWaiters.delete(responseId)
|
|
1124
1396
|
this.activeResponses.delete(responseId)
|
|
1397
|
+
this.playbackResponses.delete(responseId)
|
|
1125
1398
|
this.resolveIdle()
|
|
1126
1399
|
}, 1000)
|
|
1127
1400
|
recoveryTimer.unref?.()
|
|
@@ -1134,6 +1407,7 @@ export class RealtimeFrontend {
|
|
|
1134
1407
|
pending.settled = true
|
|
1135
1408
|
clearTimeout(pending.timer)
|
|
1136
1409
|
pending.cancelRetryDelay?.()
|
|
1410
|
+
pending.cancelCallWait?.()
|
|
1137
1411
|
this.retryingResponses.delete(pending)
|
|
1138
1412
|
pending.resolve(outcome)
|
|
1139
1413
|
try {
|
|
@@ -1190,21 +1464,35 @@ export class RealtimeFrontend {
|
|
|
1190
1464
|
})
|
|
1191
1465
|
}
|
|
1192
1466
|
|
|
1467
|
+
// Active responses that gate Gateway work: all but voice playback ones.
|
|
1468
|
+
gatingResponsesActive() {
|
|
1469
|
+
if (!this.capabilities.concurrentVoicePlayback) return this.activeResponses.size > 0
|
|
1470
|
+
for (const id of this.activeResponses) if (!this.playbackResponses.has(id)) return true
|
|
1471
|
+
return false
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1193
1474
|
async whenIdle() {
|
|
1194
|
-
while (this.responseSlot.blocked || this.
|
|
1475
|
+
while (this.responseSlot.blocked || this.gatingResponsesActive()) {
|
|
1195
1476
|
if (this.responseSlot.blocked) await this.responseSlot.wait()
|
|
1196
1477
|
else await new Promise(resolve => this.idleWaiters.push(resolve))
|
|
1197
1478
|
}
|
|
1198
1479
|
}
|
|
1199
1480
|
|
|
1200
1481
|
resolveIdle() {
|
|
1201
|
-
if (this.
|
|
1482
|
+
if (this.gatingResponsesActive()) return
|
|
1202
1483
|
while (this.idleWaiters.length) this.idleWaiters.shift()?.()
|
|
1203
1484
|
}
|
|
1204
1485
|
|
|
1205
1486
|
resetResponses() {
|
|
1487
|
+
for (const waiter of this.delegationUpdateWaiters.values()) waiter.settle(new Error('Realtime 会话已重置'))
|
|
1206
1488
|
this.responseQueueGeneration += 1
|
|
1207
1489
|
this.activeResponses.clear()
|
|
1490
|
+
this.cancelledResponses.clear()
|
|
1491
|
+
this.pendingFinalResponses.clear()
|
|
1492
|
+
this.playbackResponses.clear()
|
|
1493
|
+
this.openCalls.clear()
|
|
1494
|
+
this.toolResponses.clear()
|
|
1495
|
+
this.continuationOwed = false
|
|
1208
1496
|
this.responseSlot.release()
|
|
1209
1497
|
this.rejectConversationItemWaiters(new Error('Realtime 会话已重置'))
|
|
1210
1498
|
this.pendingResponses.forEach(item => this.settlePending(item, { cancelled: true }))
|
|
@@ -1225,9 +1513,9 @@ export class RealtimeFrontend {
|
|
|
1225
1513
|
}
|
|
1226
1514
|
|
|
1227
1515
|
close() {
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1516
|
+
this.audioDiagnostics?.stop()
|
|
1517
|
+
const closeEvent = this.protocol.sessionClose?.('client_closed')
|
|
1518
|
+
if (this.ws?.readyState === WebSocket.OPEN && closeEvent) this.send(closeEvent)
|
|
1231
1519
|
this.ws?.close(1000)
|
|
1232
1520
|
this.ws = null
|
|
1233
1521
|
this.ready = false
|
|
@@ -1240,6 +1528,7 @@ export class RealtimeFrontend {
|
|
|
1240
1528
|
return sendBoundedWebSocket(this.ws, JSON.stringify(body), {
|
|
1241
1529
|
...options,
|
|
1242
1530
|
onFailure: ({ code, bufferedBytes, messageBytes, limit }) => {
|
|
1531
|
+
this.audioDiagnostics?.sampleBuffer()
|
|
1243
1532
|
this.ready = false
|
|
1244
1533
|
this.resetResponses()
|
|
1245
1534
|
this.diagnose({
|
|
@@ -1254,7 +1543,11 @@ export class RealtimeFrontend {
|
|
|
1254
1543
|
if (!payload) return
|
|
1255
1544
|
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
1256
1545
|
let outgoing = payload
|
|
1257
|
-
if (payload.type === 'response.create'
|
|
1546
|
+
if (payload.type === 'response.create') {
|
|
1547
|
+
this.continuationOwed = false
|
|
1548
|
+
for (const id of this.toolResponses.keys()) this.toolResponses.set(id, true)
|
|
1549
|
+
}
|
|
1550
|
+
if (payload.type === 'response.create' && options.correlate !== false && this.pendingResponses.length) {
|
|
1258
1551
|
const pending = this.pendingResponses[this.pendingResponses.length - 1]
|
|
1259
1552
|
outgoing = this.protocol.correlateResponseCreate(
|
|
1260
1553
|
payload,
|
|
@@ -1273,7 +1566,10 @@ export class RealtimeFrontend {
|
|
|
1273
1566
|
}
|
|
1274
1567
|
const body = this.protocol.encodeOutgoing(outgoing)
|
|
1275
1568
|
if (body == null) return
|
|
1276
|
-
if (this.sendWireMessage(body, options))
|
|
1569
|
+
if (this.sendWireMessage(body, options)) {
|
|
1570
|
+
if (options.audio) this.audioDiagnostics?.input(outgoing.audio)
|
|
1571
|
+
return body
|
|
1572
|
+
}
|
|
1277
1573
|
}
|
|
1278
1574
|
}
|
|
1279
1575
|
}
|