qwen-audio-agent 2.0.1 → 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 +21 -10
- package/README_ZH.md +19 -10
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/cli/package.json +1 -1
- package/cli/src/arguments.mjs +4 -1
- package/cli/src/config-command.mjs +36 -6
- package/cli/src/gateway-service.mjs +7 -1
- package/cli/src/launcher.mjs +13 -0
- package/config/frontend-agent/LIVE_PROMPT.md +64 -0
- package/config/frontend-agent/PROMPT.md +29 -26
- package/desktop/src/i18n.mjs +6 -1
- package/desktop/src/settings-config.mjs +32 -40
- package/desktop/src/settings-store.mjs +19 -28
- package/docs/architecture/deep-dive.md +103 -66
- package/docs/architecture/deep-dive.zh.md +73 -50
- package/docs/backends/configuration.md +4 -4
- package/docs/backends/configuration.zh.md +4 -4
- package/docs/backends/overview.md +3 -0
- package/docs/backends/overview.zh.md +3 -0
- package/docs/configuration/backend.md +15 -1
- package/docs/configuration/backend.zh.md +15 -1
- package/docs/configuration/frontend.md +78 -28
- package/docs/configuration/frontend.zh.md +76 -28
- package/docs/configuration.md +1 -1
- package/docs/configuration.zh.md +1 -1
- package/docs/contract.md +24 -2
- package/docs/contract.zh.md +20 -2
- package/docs/extensions.md +14 -0
- package/docs/extensions.zh.md +11 -0
- package/docs/gateway-protocol.md +26 -0
- package/docs/gateway-protocol.zh.md +22 -0
- package/docs/gateway-webrtc-client.md +3 -3
- package/docs/gateway-webrtc-client.zh.md +3 -3
- package/docs/getting-started/install.md +4 -1
- package/docs/getting-started/install.zh.md +4 -1
- package/docs/getting-started/mobile.md +8 -2
- package/docs/getting-started/mobile.zh.md +5 -0
- package/docs/getting-started/quickstart.md +2 -2
- package/docs/getting-started/quickstart.zh.md +2 -2
- package/docs/getting-started/webui.md +2 -0
- package/docs/getting-started/webui.zh.md +2 -0
- package/docs/guides/knowledge.md +8 -5
- package/docs/guides/knowledge.zh.md +4 -3
- package/docs/guides/tasks.md +63 -2
- package/docs/guides/tasks.zh.md +45 -1
- package/docs/guides/web-search.md +32 -1
- package/docs/guides/web-search.zh.md +28 -1
- package/docs/operations/troubleshooting.md +30 -0
- package/docs/operations/troubleshooting.zh.md +26 -0
- package/docs/reference/backend-adapter-sdk.md +33 -2
- package/docs/reference/backend-adapter-sdk.zh.md +29 -2
- package/docs/reference/cli.md +3 -3
- package/docs/reference/cli.zh.md +3 -3
- package/docs/scenarios/lightrag.md +2 -2
- package/docs/scenarios/lightrag.zh.md +2 -2
- package/docs/scenarios/x-omni.md +5 -2
- package/docs/scenarios/x-omni.zh.md +5 -2
- package/docs/voice-agent-architecture-presentation.zh.md +34 -37
- package/docs/voice-frontends/custom-provider.md +22 -4
- package/docs/voice-frontends/custom-provider.zh.md +22 -4
- package/docs/voice-frontends/google-live.md +14 -8
- package/docs/voice-frontends/google-live.zh.md +13 -8
- 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/minicpm-o.md +8 -4
- package/docs/voice-frontends/minicpm-o.zh.md +7 -4
- package/docs/voice-frontends/{gpt-live.md → openai-realtime.md} +19 -10
- package/docs/voice-frontends/{gpt-live.zh.md → openai-realtime.zh.md} +18 -10
- 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 +41 -15
- package/docs/voice-frontends/qwen-audio-realtime.zh.md +34 -12
- package/docs/voice-frontends/qwen-omni-realtime.md +12 -9
- package/docs/voice-frontends/qwen-omni-realtime.zh.md +12 -9
- package/docs/voice-frontends/speech-to-speech.md +8 -4
- package/docs/voice-frontends/speech-to-speech.zh.md +7 -3
- package/docs/voice-frontends/stepfun.md +7 -4
- package/docs/voice-frontends/stepfun.zh.md +7 -4
- package/examples/webrtc/start.mjs +2 -1
- package/package.json +34 -16
- package/scripts/audit-dependencies.mjs +3 -25
- package/scripts/electron-smoke.mjs +5 -5
- package/scripts/patch-build-node-gyp.mjs +63 -0
- package/scripts/prepare-build.mjs +2 -0
- package/scripts/release-check +2 -2
- package/scripts/runtime/claude-code-acp.mjs +5 -5
- package/scripts/verify-package.mjs +3 -0
- package/server/package.json +5 -5
- package/server/src/app/gateway-application.mjs +3 -0
- package/server/src/app/gateway-http-routes.mjs +3 -0
- package/server/src/app/session-conversation-history.mjs +9 -1
- package/server/src/backend/adapters/a2a/backend-adapter.mjs +32 -26
- package/server/src/backend/adapters/acp/backend-adapter.mjs +703 -251
- package/server/src/backend/adapters/acp/coordinator-contract.mjs +2 -13
- package/server/src/backend/adapters/acp/coordinator-instructions.mjs +29 -8
- package/server/src/backend/adapters/acp/coordinator-queue.mjs +58 -0
- package/server/src/backend/adapters/acp/drivers/codex.mjs +1 -1
- package/server/src/backend/adapters/acp/drivers/openclaw.mjs +1 -2
- package/server/src/backend/adapters/acp/input-broker.mjs +2 -0
- package/server/src/backend/adapters/acp/process-client.mjs +111 -16
- package/server/src/backend/adapters/acp/session-configuration.mjs +2 -19
- package/server/src/backend/adapters/acp/session-registry.mjs +9 -0
- package/server/src/backend/adapters/acp/session-tools.mjs +1 -1
- package/server/src/backend/adapters/acp/turn-updates.mjs +188 -0
- package/server/src/backend/adapters/acp/work-continuation.mjs +48 -0
- package/server/src/backend/adapters/agent-client.mjs +24 -1
- package/server/src/backend/adapters/llm/backend-adapter.mjs +393 -0
- package/server/src/backend/adapters/muse/backend-adapter.mjs +2 -0
- package/server/src/backend/availability.mjs +12 -3
- package/server/src/backend/backend-adapter-sdk.mjs +3 -0
- package/server/src/backend/backend-port.mjs +13 -0
- package/server/src/backend/backend-work-runtime.mjs +23 -0
- package/server/src/client/client-command-runtime.mjs +14 -0
- package/server/src/conversation/conversation-sync.mjs +26 -2
- package/server/src/conversation/frontend-agent-context.mjs +18 -5
- package/server/src/conversation/frontend-notes.mjs +7 -5
- package/server/src/conversation/task-result-projector.mjs +1 -1
- package/server/src/core/backend-events.mjs +4 -0
- package/server/src/core/citation.mjs +8 -2
- package/server/src/core/config.mjs +46 -54
- package/server/src/core/gateway-protocol.mjs +4 -1
- package/server/src/core/request-security.mjs +7 -1
- package/server/src/core/work-conversation-context.mjs +138 -0
- package/server/src/core/work-input-request.mjs +1 -0
- package/server/src/frontend/frontend-tools.mjs +20 -7
- package/server/src/frontend/retrieval/providers/bing.mjs +23 -12
- package/server/src/frontend/retrieval/providers/factory.mjs +18 -1
- package/server/src/frontend/retrieval/providers/mcp.mjs +30 -11
- package/server/src/frontend/retrieval/providers/so360.mjs +23 -12
- package/server/src/frontend/tools/agent-task-runtime.mjs +119 -99
- package/server/src/frontend/tools/features/agent-task-tools.mjs +23 -42
- package/server/src/frontend/tools/frontend-tool-context.mjs +2 -2
- package/server/src/frontend/tools/spawn-thinking-tool.mjs +2 -2
- package/server/src/frontend/tools/tool-call-handler.mjs +166 -86
- package/server/src/knowledge/providers/local/library.mjs +26 -6
- package/server/src/knowledge/providers/local/provider.mjs +25 -6
- package/server/src/memory/providers/markdown/context-store.mjs +24 -11
- package/server/src/orchestration/session-task-coordinator.mjs +13 -3
- package/server/src/orchestration/task-operations.mjs +54 -12
- package/server/src/orchestration/task-updates.mjs +82 -0
- package/server/src/task/reminder-scheduler.mjs +5 -1
- package/server/src/task/task-manager.mjs +72 -15
- package/server/src/task/task-recovery.mjs +12 -2
- package/server/src/task/task-scheduler.mjs +5 -5
- package/server/src/task/task-state.mjs +13 -0
- package/server/src/transport/gateway-client-transport.mjs +35 -0
- package/server/src/transport/webrtc/protocol.mjs +1 -1
- package/server/src/voice/announcement/announcement-manager.mjs +3 -0
- 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 +45 -33
- package/server/src/voice/providers/doubao-seeduplex-protocol.mjs +54 -0
- package/server/src/voice/providers/doubao-seeduplex.mjs +16 -11
- 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 +20 -14
- 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/minicpm-o.mjs +9 -7
- package/server/src/voice/providers/openai-live.mjs +150 -0
- package/server/src/voice/providers/{gpt-live.mjs → openai-realtime.mjs} +23 -19
- 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 +47 -12
- package/server/src/voice/providers/runtime-configuration.mjs +34 -0
- package/server/src/voice/providers/s2s.mjs +9 -7
- package/server/src/voice/providers/stepfun.mjs +14 -11
- package/server/src/voice/realtime-input-runtime.mjs +58 -20
- package/server/src/voice/realtime-presentation-runtime.mjs +111 -27
- package/server/src/voice/realtime-provider-session.mjs +59 -14
- package/server/src/voice/realtime-provider.mjs +358 -45
- package/server/src/voice/realtime-session-runtime.mjs +282 -35
- package/server/src/voice/realtime-task-presentation.mjs +8 -2
- package/server/src/voice/realtime-turn-state.mjs +33 -2
- package/shared/backend/catalog.mjs +26 -2
- package/shared/backend/install.mjs +3 -1
- package/shared/backend/setup.mjs +43 -0
- package/shared/gateway/client-sdk.mjs +21 -6
- package/shared/gateway/setup.mjs +13 -1
- package/shared/gateway/websocket-auth.mjs +2 -1
- package/shared/protocol/gateway-client-protocol.mjs +14 -0
- package/shared/protocol/gateway-events.mjs +39 -1
- package/shared/realtime-legacy-environment.mjs +81 -0
- package/shared/realtime-model-catalog.mjs +68 -194
- package/shared/realtime-models/README.md +33 -0
- package/shared/realtime-models/dashscope.mjs +57 -0
- package/shared/realtime-models/google.mjs +10 -0
- package/shared/realtime-models/openai.mjs +24 -0
- package/shared/realtime-models/profile.mjs +38 -0
- package/shared/realtime-models/stepfun.mjs +10 -0
- package/shared/realtime-models/volcengine.mjs +12 -0
- package/shared/realtime-provider-catalog.mjs +23 -11
- package/shared/realtime-provider-definitions.mjs +168 -235
- package/shared/runtime-environment.mjs +23 -30
- package/shared/skill-library.mjs +49 -13
- package/shared/web-search-configuration.mjs +25 -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/web/dist/assets/index-BRaiI-dW.js +0 -91
- package/web/dist/assets/index-D9k8R2JY.css +0 -1
|
@@ -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,18 +56,29 @@ 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
|
|
|
62
66
|
export function realtimeEventErrorMessage(event, fallback = '实时语音服务错误') {
|
|
67
|
+
const failed = event?.type === 'response.done' && event.response?.status === 'failed'
|
|
68
|
+
const statusDetails = failed ? event.response.status_details : null
|
|
69
|
+
const error = event?.error ?? statusDetails?.error
|
|
63
70
|
const details = [
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
71
|
+
error?.code,
|
|
72
|
+
error?.type,
|
|
73
|
+
error?.message,
|
|
74
|
+
statusDetails?.code,
|
|
75
|
+
statusDetails?.message,
|
|
76
|
+
statusDetails?.reason,
|
|
77
|
+
typeof statusDetails === 'string' ? statusDetails : '',
|
|
67
78
|
event?.message,
|
|
68
79
|
].map(value => String(value || '').trim()).filter(Boolean)
|
|
69
|
-
return [...new Set(details)].join(': ')
|
|
80
|
+
return [...new Set(details)].join(': ')
|
|
81
|
+
|| (failed ? '实时语音服务生成回复失败' : fallback)
|
|
70
82
|
}
|
|
71
83
|
|
|
72
84
|
// Behavioural capabilities of a provider's Realtime implementation. Defaults
|
|
@@ -78,6 +90,8 @@ const DEFAULT_CAPABILITIES = Object.freeze({
|
|
|
78
90
|
acknowledgesSessionUpdate: true,
|
|
79
91
|
// Refuses concurrent response.create requests instead of queueing them.
|
|
80
92
|
singleResponseSlot: false,
|
|
93
|
+
// Require a formal start; a final transcript may still arrive after completion.
|
|
94
|
+
requiresResponseCreated: false,
|
|
81
95
|
// Echoes response metadata so client-created responses can be correlated
|
|
82
96
|
// without confusing them with automatic server-side responses.
|
|
83
97
|
responseMetadataCorrelation: false,
|
|
@@ -96,17 +110,45 @@ const DEFAULT_CAPABILITIES = Object.freeze({
|
|
|
96
110
|
restoreConversationContext: true,
|
|
97
111
|
// Accepts conversation.item.create and acknowledges created items.
|
|
98
112
|
conversationItems: true,
|
|
113
|
+
// User items can be appended without starting a new interaction.
|
|
114
|
+
contextOnlyItems: true,
|
|
99
115
|
// Tool receipts resume the service's current interaction without an explicit
|
|
100
116
|
// response request. They must be sent even while that interaction is active.
|
|
101
117
|
automaticToolResponses: false,
|
|
118
|
+
// A real user item starts native generation without response.create.
|
|
119
|
+
automaticUserResponses: false,
|
|
102
120
|
// Accepts response.create and response.cancel initiated by the client.
|
|
103
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,
|
|
104
126
|
// Allows session instructions to be refreshed after initial setup.
|
|
105
127
|
mutableSession: true,
|
|
106
128
|
// Requires an audio timeline before accepting the first visual frame.
|
|
107
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,
|
|
108
140
|
})
|
|
109
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
|
+
])
|
|
110
152
|
|
|
111
153
|
export class RealtimeFrontend {
|
|
112
154
|
constructor({
|
|
@@ -122,6 +164,7 @@ export class RealtimeFrontend {
|
|
|
122
164
|
responseInactivityTimeoutMs,
|
|
123
165
|
responseCompletionTimeoutMs,
|
|
124
166
|
responseCancelGraceMs = DEFAULT_RESPONSE_CANCEL_GRACE_MS,
|
|
167
|
+
delegationUpdateTimeoutMs = DEFAULT_DELEGATION_UPDATE_TIMEOUT_MS,
|
|
125
168
|
} = {}) {
|
|
126
169
|
this.provider = validateRealtimeProvider(provider)
|
|
127
170
|
this.connectionId = randomUUID()
|
|
@@ -129,6 +172,10 @@ export class RealtimeFrontend {
|
|
|
129
172
|
provider.createProtocol?.({
|
|
130
173
|
connectionId: this.connectionId,
|
|
131
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),
|
|
132
179
|
}) ?? provider.protocol,
|
|
133
180
|
provider.key || provider.label,
|
|
134
181
|
)
|
|
@@ -150,10 +197,24 @@ export class RealtimeFrontend {
|
|
|
150
197
|
this.restoringContext = false
|
|
151
198
|
this.audioInputStarted = false
|
|
152
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
|
|
153
211
|
this.pendingResponses = []
|
|
154
212
|
this.retryingResponses = new Set()
|
|
155
213
|
this.responseWaiters = new Map()
|
|
156
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
|
|
157
218
|
this.conversationItemQueue = Promise.resolve()
|
|
158
219
|
this.conversationItemGeneration = 0
|
|
159
220
|
this.idleWaiters = []
|
|
@@ -186,6 +247,15 @@ export class RealtimeFrontend {
|
|
|
186
247
|
event: 'realtime.response_slot_recovery', provider: this.provider.key, phase,
|
|
187
248
|
}),
|
|
188
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
|
|
189
259
|
}
|
|
190
260
|
|
|
191
261
|
diagnose(event) {
|
|
@@ -196,7 +266,7 @@ export class RealtimeFrontend {
|
|
|
196
266
|
if (this.modelProfile?.family === 'unknown') {
|
|
197
267
|
return Promise.reject(new RealtimeConfigurationError(
|
|
198
268
|
`不支持的 Realtime 模型:${this.modelProfile.id}`
|
|
199
|
-
+ `(${this.provider.label}
|
|
269
|
+
+ `(${this.provider.label});请选择受支持的模型,或升级框架以获取新增模型支持`,
|
|
200
270
|
))
|
|
201
271
|
}
|
|
202
272
|
if (!this.provider.isConfigured()) {
|
|
@@ -226,6 +296,7 @@ export class RealtimeFrontend {
|
|
|
226
296
|
else resolve()
|
|
227
297
|
}
|
|
228
298
|
ws.on('open', () => {
|
|
299
|
+
this.audioDiagnostics?.start()
|
|
229
300
|
try {
|
|
230
301
|
const messages = normalizedEvents(
|
|
231
302
|
this.protocol.connectionMessages?.({
|
|
@@ -253,8 +324,16 @@ export class RealtimeFrontend {
|
|
|
253
324
|
this.onError?.(error)
|
|
254
325
|
finish(error)
|
|
255
326
|
})
|
|
256
|
-
ws.on('close', () => {
|
|
327
|
+
ws.on('close', (code, reason) => {
|
|
328
|
+
this.audioDiagnostics?.stop()
|
|
329
|
+
this.diagnose({
|
|
330
|
+
event: 'realtime.transport_closed',
|
|
331
|
+
provider: this.provider.key,
|
|
332
|
+
code,
|
|
333
|
+
reason: reason?.toString().slice(0, 512) || '',
|
|
334
|
+
})
|
|
257
335
|
this.ready = false
|
|
336
|
+
this.protocol.sessionClose?.('transport_closed')
|
|
258
337
|
this.sessionConfigured = false
|
|
259
338
|
this.recentContextInjected = false
|
|
260
339
|
this.resetResponses()
|
|
@@ -286,11 +365,39 @@ export class RealtimeFrontend {
|
|
|
286
365
|
})
|
|
287
366
|
}
|
|
288
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
|
+
|
|
289
377
|
handleProviderEvent(providerEvent, { onSessionReady, onSessionError } = {}) {
|
|
290
|
-
const events =
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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
|
+
}
|
|
294
401
|
if (event.type === 'error' && this.restoringContext) {
|
|
295
402
|
event.__voiceOrigin = 'restore'
|
|
296
403
|
}
|
|
@@ -309,7 +416,9 @@ export class RealtimeFrontend {
|
|
|
309
416
|
this.completeSessionSetup(onSessionReady, onSessionError)
|
|
310
417
|
}
|
|
311
418
|
this.handleLifecycle(event)
|
|
419
|
+
if (event.type === 'response.done') this.cancelledResponses.delete(realtimeResponseId(event))
|
|
312
420
|
this.onEvent?.(event)
|
|
421
|
+
events.push(event)
|
|
313
422
|
}
|
|
314
423
|
return events
|
|
315
424
|
}
|
|
@@ -374,7 +483,8 @@ export class RealtimeFrontend {
|
|
|
374
483
|
}
|
|
375
484
|
|
|
376
485
|
appendAudio(audio) {
|
|
377
|
-
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)
|
|
378
488
|
this.audioInputStarted = true
|
|
379
489
|
}
|
|
380
490
|
|
|
@@ -406,17 +516,7 @@ export class RealtimeFrontend {
|
|
|
406
516
|
sendUserText(text, context = {}, { modalities } = {}) {
|
|
407
517
|
const content = String(text || '').trim()
|
|
408
518
|
if (!content) return Promise.resolve()
|
|
409
|
-
|
|
410
|
-
return Promise.reject(new Error(
|
|
411
|
-
`${this.provider.label} 不支持文本输入`,
|
|
412
|
-
))
|
|
413
|
-
}
|
|
414
|
-
return this.enqueueResponse('model', context, async () => {
|
|
415
|
-
await this.createConversationItem(this.protocol.userTextItem(content), { contextOnly: false })
|
|
416
|
-
return this.sendResponse(
|
|
417
|
-
modalities ? { modalities } : undefined,
|
|
418
|
-
)
|
|
419
|
-
})
|
|
519
|
+
return this.sendUserInput([{ type: 'text', text: content }], context, { modalities })
|
|
420
520
|
}
|
|
421
521
|
|
|
422
522
|
projectUserInput(parts, options = {}) {
|
|
@@ -434,6 +534,75 @@ export class RealtimeFrontend {
|
|
|
434
534
|
: null
|
|
435
535
|
}
|
|
436
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
|
+
|
|
437
606
|
async applyUserInput(parts, options = {}) {
|
|
438
607
|
const projection = this.projectUserInput(parts, options)
|
|
439
608
|
if (!projection) return false
|
|
@@ -448,11 +617,18 @@ export class RealtimeFrontend {
|
|
|
448
617
|
}
|
|
449
618
|
|
|
450
619
|
sendUserInput(parts, context = {}, { modalities } = {}) {
|
|
451
|
-
if (!this.capabilities.conversationItems
|
|
620
|
+
if (!this.capabilities.conversationItems
|
|
621
|
+
|| (!this.capabilities.clientResponses && !this.capabilities.automaticUserResponses)) {
|
|
452
622
|
return Promise.reject(new Error(
|
|
453
623
|
`${this.provider.label} 不支持离散文本或文件输入`,
|
|
454
624
|
))
|
|
455
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
|
+
}
|
|
456
632
|
return this.enqueueResponse('model', context, async () => {
|
|
457
633
|
if (!await this.applyUserInput(parts, { contextOnly: false })) return false
|
|
458
634
|
return this.sendResponse(
|
|
@@ -462,14 +638,14 @@ export class RealtimeFrontend {
|
|
|
462
638
|
}
|
|
463
639
|
|
|
464
640
|
appendUserInputContext(parts, options = {}) {
|
|
465
|
-
if (!this.capabilities.conversationItems) return Promise.resolve(false)
|
|
641
|
+
if (!this.capabilities.conversationItems || !this.capabilities.contextOnlyItems) return Promise.resolve(false)
|
|
466
642
|
return this.enqueueAction(() => this.applyUserInput(parts, options))
|
|
467
643
|
}
|
|
468
644
|
|
|
469
645
|
appendUserContext(text) {
|
|
470
646
|
const content = String(text || '').trim()
|
|
471
647
|
if (!content) return Promise.resolve()
|
|
472
|
-
if (!this.capabilities.conversationItems) return Promise.resolve(false)
|
|
648
|
+
if (!this.capabilities.conversationItems || !this.capabilities.contextOnlyItems) return Promise.resolve(false)
|
|
473
649
|
return this.enqueueAction(() => this.createConversationItem(
|
|
474
650
|
this.protocol.userTextItem(content),
|
|
475
651
|
))
|
|
@@ -487,16 +663,25 @@ export class RealtimeFrontend {
|
|
|
487
663
|
return this.enqueueResponse('agent', context, pending => {
|
|
488
664
|
pending.isCurrent = shouldCreate
|
|
489
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
|
|
490
668
|
return this.sendResponse(response)
|
|
491
669
|
})
|
|
492
670
|
}
|
|
493
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
|
+
|
|
494
678
|
sendFunctionOutput(callId, output, context = {}, {
|
|
495
679
|
createResponse = true,
|
|
496
680
|
response,
|
|
497
681
|
shouldRespond,
|
|
498
682
|
} = {}) {
|
|
499
|
-
if (!this.capabilities.conversationItems
|
|
683
|
+
if (!this.capabilities.conversationItems
|
|
684
|
+
|| (!this.capabilities.clientResponses && !this.capabilities.automaticToolResponses)) {
|
|
500
685
|
return Promise.reject(new Error(
|
|
501
686
|
`${this.provider.label} 不支持 Function Call 结果回注`,
|
|
502
687
|
))
|
|
@@ -511,20 +696,47 @@ export class RealtimeFrontend {
|
|
|
511
696
|
// This acknowledges delivery, not completion of the ensuing speech.
|
|
512
697
|
return sendOutput().then(() => ({ delivered: true, automatic: true }))
|
|
513
698
|
}
|
|
514
|
-
|
|
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(() => {})
|
|
515
706
|
return this.enqueueResponse('agent', context, async pending => {
|
|
516
707
|
pending.isCurrent = shouldRespond
|
|
517
|
-
await sendOutput()
|
|
708
|
+
await (answered || sendOutput())
|
|
518
709
|
return this.sendResponse(response)
|
|
519
710
|
})
|
|
520
711
|
}
|
|
521
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
|
+
|
|
522
731
|
createConversationItem(item, { contextOnly = true } = {}) {
|
|
523
732
|
if (!this.capabilities.conversationItems) {
|
|
524
733
|
return Promise.reject(new Error(
|
|
525
734
|
`${this.provider.label} 不支持创建对话项`,
|
|
526
735
|
))
|
|
527
736
|
}
|
|
737
|
+
if (contextOnly && !this.capabilities.contextOnlyItems && item?.type === 'message') {
|
|
738
|
+
return Promise.reject(new Error(`${this.provider.label} 不支持静默写入对话项`))
|
|
739
|
+
}
|
|
528
740
|
if (this.capabilities.conversationItemIdEcho) return this.sendConversationItem(item, { contextOnly })
|
|
529
741
|
// Without echoed IDs, only one client-created item may await a receipt.
|
|
530
742
|
// This queue is independent of responses: permissions/environment context
|
|
@@ -706,18 +918,55 @@ export class RealtimeFrontend {
|
|
|
706
918
|
// A dialect may need a conversation item instead of transient response
|
|
707
919
|
// instructions. Wait for its acknowledgement before triggering inference.
|
|
708
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
|
+
}
|
|
709
926
|
if (item) await this.createConversationItem(item)
|
|
710
927
|
// An automatic response may have started while the input/context receipt
|
|
711
928
|
// was in flight. Recheck immediately before sending, not just on enqueue.
|
|
712
929
|
await this.whenIdle()
|
|
713
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
|
+
}
|
|
714
937
|
pending.responseRequested = true
|
|
715
|
-
|
|
938
|
+
pending.playbackRequest = Boolean(payload) && payload.type !== 'response.create'
|
|
939
|
+
this.send(payload)
|
|
716
940
|
}
|
|
717
941
|
|
|
718
|
-
|
|
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
|
+
}
|
|
719
965
|
this.responseQueueGeneration += 1
|
|
720
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)
|
|
721
970
|
const hasResponse = cancelledResponseIds.length
|
|
722
971
|
|| this.pendingResponses.some(pending => pending.responseRequested)
|
|
723
972
|
|| this.responseSlot.blocked
|
|
@@ -743,6 +992,8 @@ export class RealtimeFrontend {
|
|
|
743
992
|
}
|
|
744
993
|
const recoveryTimer = setTimeout(() => {
|
|
745
994
|
for (const responseId of cancelledResponseIds) {
|
|
995
|
+
// A playback response stays tracked until its own response.done.
|
|
996
|
+
if (this.playbackResponses.has(responseId)) continue
|
|
746
997
|
this.activeResponses.delete(responseId)
|
|
747
998
|
this.responseWaiters.delete(responseId)
|
|
748
999
|
}
|
|
@@ -774,9 +1025,10 @@ export class RealtimeFrontend {
|
|
|
774
1025
|
if (matches(pending)) this.settlePending(pending, { cancelled: true, phase: 'start' })
|
|
775
1026
|
}
|
|
776
1027
|
let cancelledActive = false
|
|
777
|
-
for (const pending of this.responseWaiters
|
|
1028
|
+
for (const [id, pending] of this.responseWaiters) {
|
|
778
1029
|
if (!matches(pending)) continue
|
|
779
1030
|
cancelledActive = true
|
|
1031
|
+
this.pendingFinalResponses.delete(id)
|
|
780
1032
|
this.settlePending(pending, {
|
|
781
1033
|
cancelled: true,
|
|
782
1034
|
phase: 'completion',
|
|
@@ -863,11 +1115,19 @@ export class RealtimeFrontend {
|
|
|
863
1115
|
}
|
|
864
1116
|
|
|
865
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
|
+
}
|
|
866
1124
|
if (event.type === 'error'
|
|
867
1125
|
&& this.provider.classifyError(realtimeEventErrorMessage(event)) === 'no_active_response') {
|
|
868
1126
|
// This acknowledges cancellation; it must not reject an unrelated item.
|
|
869
1127
|
if (this.responseSlot.phase === 'cancelling') {
|
|
1128
|
+
for (const id of this.activeResponses) this.pendingFinalResponses.delete(id)
|
|
870
1129
|
this.activeResponses.clear()
|
|
1130
|
+
this.playbackResponses.clear()
|
|
871
1131
|
this.responseWaiters.clear()
|
|
872
1132
|
this.responseSlot.release()
|
|
873
1133
|
this.resolveIdle()
|
|
@@ -912,6 +1172,7 @@ export class RealtimeFrontend {
|
|
|
912
1172
|
}
|
|
913
1173
|
if (isResponseActivityEvent(event)) {
|
|
914
1174
|
const responseId = realtimeResponseId(event)
|
|
1175
|
+
if (FINAL_TEXT_EVENTS.has(event.type)) this.pendingFinalResponses.delete(responseId)
|
|
915
1176
|
if (this.responseSlot.phase === 'cancelling') {
|
|
916
1177
|
event.__voiceContext = { suppressed: true }
|
|
917
1178
|
} else if (event.type !== 'response.done') {
|
|
@@ -944,8 +1205,12 @@ export class RealtimeFrontend {
|
|
|
944
1205
|
if (index >= 0) {
|
|
945
1206
|
pending = this.pendingResponses.splice(index, 1)[0]
|
|
946
1207
|
}
|
|
947
|
-
} else {
|
|
948
|
-
|
|
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))
|
|
949
1214
|
if (index >= 0) pending = this.pendingResponses.splice(index, 1)[0]
|
|
950
1215
|
}
|
|
951
1216
|
clearTimeout(pending?.timer)
|
|
@@ -954,6 +1219,15 @@ export class RealtimeFrontend {
|
|
|
954
1219
|
if (pending?.isCurrent?.() === false) event.__voiceContext = { ...pending.context, suppressed: true }
|
|
955
1220
|
if (id) {
|
|
956
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
|
+
}
|
|
957
1231
|
if (pending) {
|
|
958
1232
|
this.responseWaiters.set(id, pending)
|
|
959
1233
|
pending.responseStartedAt = Date.now()
|
|
@@ -970,7 +1244,8 @@ export class RealtimeFrontend {
|
|
|
970
1244
|
event.type === 'response.done'
|
|
971
1245
|
|| event.type === 'error'
|
|
972
1246
|
) {
|
|
973
|
-
|
|
1247
|
+
const namedId = realtimeResponseId(event)
|
|
1248
|
+
let id = namedId
|
|
974
1249
|
let pending = this.responseWaiters.get(id)
|
|
975
1250
|
if (
|
|
976
1251
|
event.type === 'error'
|
|
@@ -978,9 +1253,11 @@ export class RealtimeFrontend {
|
|
|
978
1253
|
) {
|
|
979
1254
|
pending = this.pendingResponses.shift()
|
|
980
1255
|
}
|
|
1256
|
+
// An error that names a response belongs to it; only an id-less error
|
|
1257
|
+
// falls back to the sole waiter.
|
|
981
1258
|
if (
|
|
982
1259
|
event.type === 'error'
|
|
983
|
-
&& !pending && this.responseWaiters.size === 1
|
|
1260
|
+
&& !pending && !id && this.responseWaiters.size === 1
|
|
984
1261
|
) {
|
|
985
1262
|
const first = this.responseWaiters.entries().next().value
|
|
986
1263
|
id = first[0]
|
|
@@ -994,6 +1271,7 @@ export class RealtimeFrontend {
|
|
|
994
1271
|
if (
|
|
995
1272
|
event.type === 'error'
|
|
996
1273
|
&& !id && this.activeResponses.size === 1
|
|
1274
|
+
&& !this.playbackResponses.has(this.activeResponses.values().next().value)
|
|
997
1275
|
) {
|
|
998
1276
|
id = this.activeResponses.values().next().value
|
|
999
1277
|
event.response_id = id
|
|
@@ -1002,11 +1280,20 @@ export class RealtimeFrontend {
|
|
|
1002
1280
|
event.__voiceContext = { ...(pending?.context || {}), ...event.__voiceContext }
|
|
1003
1281
|
if (id) {
|
|
1004
1282
|
this.activeResponses.delete(id)
|
|
1283
|
+
this.playbackResponses.delete(id)
|
|
1005
1284
|
this.responseWaiters.delete(id)
|
|
1006
1285
|
}
|
|
1007
1286
|
const status = event.response?.status
|
|
1008
1287
|
const completed = event.type === 'response.done'
|
|
1009
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
|
|
1010
1297
|
this.settlePending(pending, completed
|
|
1011
1298
|
? { completed: true, responseId: id }
|
|
1012
1299
|
: { failed: true, responseId: id, status })
|
|
@@ -1097,6 +1384,7 @@ export class RealtimeFrontend {
|
|
|
1097
1384
|
}
|
|
1098
1385
|
if (this.capabilities.singleResponseSlot) this.responseSlot.recover()
|
|
1099
1386
|
else this.send(this.protocol.responseCancel())
|
|
1387
|
+
this.pendingFinalResponses.delete(responseId)
|
|
1100
1388
|
this.settlePending(pending, {
|
|
1101
1389
|
timedOut: true,
|
|
1102
1390
|
phase: 'inactivity',
|
|
@@ -1106,6 +1394,7 @@ export class RealtimeFrontend {
|
|
|
1106
1394
|
if (this.responseWaiters.get(responseId) !== pending) return
|
|
1107
1395
|
this.responseWaiters.delete(responseId)
|
|
1108
1396
|
this.activeResponses.delete(responseId)
|
|
1397
|
+
this.playbackResponses.delete(responseId)
|
|
1109
1398
|
this.resolveIdle()
|
|
1110
1399
|
}, 1000)
|
|
1111
1400
|
recoveryTimer.unref?.()
|
|
@@ -1118,6 +1407,7 @@ export class RealtimeFrontend {
|
|
|
1118
1407
|
pending.settled = true
|
|
1119
1408
|
clearTimeout(pending.timer)
|
|
1120
1409
|
pending.cancelRetryDelay?.()
|
|
1410
|
+
pending.cancelCallWait?.()
|
|
1121
1411
|
this.retryingResponses.delete(pending)
|
|
1122
1412
|
pending.resolve(outcome)
|
|
1123
1413
|
try {
|
|
@@ -1152,7 +1442,8 @@ export class RealtimeFrontend {
|
|
|
1152
1442
|
this.settlePending(pending, { cancelled: true, phase: 'start' })
|
|
1153
1443
|
return
|
|
1154
1444
|
}
|
|
1155
|
-
|
|
1445
|
+
// A refused request never ran: let its gate re-check.
|
|
1446
|
+
if (pending.isCurrent?.({ refused: true }) === false) {
|
|
1156
1447
|
this.settlePending(pending, { skipped: true, phase: 'superseded' })
|
|
1157
1448
|
return
|
|
1158
1449
|
}
|
|
@@ -1173,21 +1464,35 @@ export class RealtimeFrontend {
|
|
|
1173
1464
|
})
|
|
1174
1465
|
}
|
|
1175
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
|
+
|
|
1176
1474
|
async whenIdle() {
|
|
1177
|
-
while (this.responseSlot.blocked || this.
|
|
1475
|
+
while (this.responseSlot.blocked || this.gatingResponsesActive()) {
|
|
1178
1476
|
if (this.responseSlot.blocked) await this.responseSlot.wait()
|
|
1179
1477
|
else await new Promise(resolve => this.idleWaiters.push(resolve))
|
|
1180
1478
|
}
|
|
1181
1479
|
}
|
|
1182
1480
|
|
|
1183
1481
|
resolveIdle() {
|
|
1184
|
-
if (this.
|
|
1482
|
+
if (this.gatingResponsesActive()) return
|
|
1185
1483
|
while (this.idleWaiters.length) this.idleWaiters.shift()?.()
|
|
1186
1484
|
}
|
|
1187
1485
|
|
|
1188
1486
|
resetResponses() {
|
|
1487
|
+
for (const waiter of this.delegationUpdateWaiters.values()) waiter.settle(new Error('Realtime 会话已重置'))
|
|
1189
1488
|
this.responseQueueGeneration += 1
|
|
1190
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
|
|
1191
1496
|
this.responseSlot.release()
|
|
1192
1497
|
this.rejectConversationItemWaiters(new Error('Realtime 会话已重置'))
|
|
1193
1498
|
this.pendingResponses.forEach(item => this.settlePending(item, { cancelled: true }))
|
|
@@ -1208,10 +1513,10 @@ export class RealtimeFrontend {
|
|
|
1208
1513
|
}
|
|
1209
1514
|
|
|
1210
1515
|
close() {
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
this.ws?.close()
|
|
1516
|
+
this.audioDiagnostics?.stop()
|
|
1517
|
+
const closeEvent = this.protocol.sessionClose?.('client_closed')
|
|
1518
|
+
if (this.ws?.readyState === WebSocket.OPEN && closeEvent) this.send(closeEvent)
|
|
1519
|
+
this.ws?.close(1000)
|
|
1215
1520
|
this.ws = null
|
|
1216
1521
|
this.ready = false
|
|
1217
1522
|
this.sessionConfigured = false
|
|
@@ -1223,6 +1528,7 @@ export class RealtimeFrontend {
|
|
|
1223
1528
|
return sendBoundedWebSocket(this.ws, JSON.stringify(body), {
|
|
1224
1529
|
...options,
|
|
1225
1530
|
onFailure: ({ code, bufferedBytes, messageBytes, limit }) => {
|
|
1531
|
+
this.audioDiagnostics?.sampleBuffer()
|
|
1226
1532
|
this.ready = false
|
|
1227
1533
|
this.resetResponses()
|
|
1228
1534
|
this.diagnose({
|
|
@@ -1237,7 +1543,11 @@ export class RealtimeFrontend {
|
|
|
1237
1543
|
if (!payload) return
|
|
1238
1544
|
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
1239
1545
|
let outgoing = payload
|
|
1240
|
-
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) {
|
|
1241
1551
|
const pending = this.pendingResponses[this.pendingResponses.length - 1]
|
|
1242
1552
|
outgoing = this.protocol.correlateResponseCreate(
|
|
1243
1553
|
payload,
|
|
@@ -1256,7 +1566,10 @@ export class RealtimeFrontend {
|
|
|
1256
1566
|
}
|
|
1257
1567
|
const body = this.protocol.encodeOutgoing(outgoing)
|
|
1258
1568
|
if (body == null) return
|
|
1259
|
-
if (this.sendWireMessage(body, options))
|
|
1569
|
+
if (this.sendWireMessage(body, options)) {
|
|
1570
|
+
if (options.audio) this.audioDiagnostics?.input(outgoing.audio)
|
|
1571
|
+
return body
|
|
1572
|
+
}
|
|
1260
1573
|
}
|
|
1261
1574
|
}
|
|
1262
1575
|
}
|