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.
Files changed (208) hide show
  1. package/README.md +21 -10
  2. package/README_ZH.md +19 -10
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  4. package/cli/package.json +1 -1
  5. package/cli/src/arguments.mjs +4 -1
  6. package/cli/src/config-command.mjs +36 -6
  7. package/cli/src/gateway-service.mjs +7 -1
  8. package/cli/src/launcher.mjs +13 -0
  9. package/config/frontend-agent/LIVE_PROMPT.md +64 -0
  10. package/config/frontend-agent/PROMPT.md +29 -26
  11. package/desktop/src/i18n.mjs +6 -1
  12. package/desktop/src/settings-config.mjs +32 -40
  13. package/desktop/src/settings-store.mjs +19 -28
  14. package/docs/architecture/deep-dive.md +103 -66
  15. package/docs/architecture/deep-dive.zh.md +73 -50
  16. package/docs/backends/configuration.md +4 -4
  17. package/docs/backends/configuration.zh.md +4 -4
  18. package/docs/backends/overview.md +3 -0
  19. package/docs/backends/overview.zh.md +3 -0
  20. package/docs/configuration/backend.md +15 -1
  21. package/docs/configuration/backend.zh.md +15 -1
  22. package/docs/configuration/frontend.md +78 -28
  23. package/docs/configuration/frontend.zh.md +76 -28
  24. package/docs/configuration.md +1 -1
  25. package/docs/configuration.zh.md +1 -1
  26. package/docs/contract.md +24 -2
  27. package/docs/contract.zh.md +20 -2
  28. package/docs/extensions.md +14 -0
  29. package/docs/extensions.zh.md +11 -0
  30. package/docs/gateway-protocol.md +26 -0
  31. package/docs/gateway-protocol.zh.md +22 -0
  32. package/docs/gateway-webrtc-client.md +3 -3
  33. package/docs/gateway-webrtc-client.zh.md +3 -3
  34. package/docs/getting-started/install.md +4 -1
  35. package/docs/getting-started/install.zh.md +4 -1
  36. package/docs/getting-started/mobile.md +8 -2
  37. package/docs/getting-started/mobile.zh.md +5 -0
  38. package/docs/getting-started/quickstart.md +2 -2
  39. package/docs/getting-started/quickstart.zh.md +2 -2
  40. package/docs/getting-started/webui.md +2 -0
  41. package/docs/getting-started/webui.zh.md +2 -0
  42. package/docs/guides/knowledge.md +8 -5
  43. package/docs/guides/knowledge.zh.md +4 -3
  44. package/docs/guides/tasks.md +63 -2
  45. package/docs/guides/tasks.zh.md +45 -1
  46. package/docs/guides/web-search.md +32 -1
  47. package/docs/guides/web-search.zh.md +28 -1
  48. package/docs/operations/troubleshooting.md +30 -0
  49. package/docs/operations/troubleshooting.zh.md +26 -0
  50. package/docs/reference/backend-adapter-sdk.md +33 -2
  51. package/docs/reference/backend-adapter-sdk.zh.md +29 -2
  52. package/docs/reference/cli.md +3 -3
  53. package/docs/reference/cli.zh.md +3 -3
  54. package/docs/scenarios/lightrag.md +2 -2
  55. package/docs/scenarios/lightrag.zh.md +2 -2
  56. package/docs/scenarios/x-omni.md +5 -2
  57. package/docs/scenarios/x-omni.zh.md +5 -2
  58. package/docs/voice-agent-architecture-presentation.zh.md +34 -37
  59. package/docs/voice-frontends/custom-provider.md +22 -4
  60. package/docs/voice-frontends/custom-provider.zh.md +22 -4
  61. package/docs/voice-frontends/google-live.md +14 -8
  62. package/docs/voice-frontends/google-live.zh.md +13 -8
  63. package/docs/voice-frontends/gpt-live-1.md +149 -0
  64. package/docs/voice-frontends/gpt-live-1.zh.md +114 -0
  65. package/docs/voice-frontends/minicpm-o.md +8 -4
  66. package/docs/voice-frontends/minicpm-o.zh.md +7 -4
  67. package/docs/voice-frontends/{gpt-live.md → openai-realtime.md} +19 -10
  68. package/docs/voice-frontends/{gpt-live.zh.md → openai-realtime.zh.md} +18 -10
  69. package/docs/voice-frontends/qwen-audio-live.md +164 -0
  70. package/docs/voice-frontends/qwen-audio-live.zh.md +122 -0
  71. package/docs/voice-frontends/qwen-audio-realtime.md +41 -15
  72. package/docs/voice-frontends/qwen-audio-realtime.zh.md +34 -12
  73. package/docs/voice-frontends/qwen-omni-realtime.md +12 -9
  74. package/docs/voice-frontends/qwen-omni-realtime.zh.md +12 -9
  75. package/docs/voice-frontends/speech-to-speech.md +8 -4
  76. package/docs/voice-frontends/speech-to-speech.zh.md +7 -3
  77. package/docs/voice-frontends/stepfun.md +7 -4
  78. package/docs/voice-frontends/stepfun.zh.md +7 -4
  79. package/examples/webrtc/start.mjs +2 -1
  80. package/package.json +34 -16
  81. package/scripts/audit-dependencies.mjs +3 -25
  82. package/scripts/electron-smoke.mjs +5 -5
  83. package/scripts/patch-build-node-gyp.mjs +63 -0
  84. package/scripts/prepare-build.mjs +2 -0
  85. package/scripts/release-check +2 -2
  86. package/scripts/runtime/claude-code-acp.mjs +5 -5
  87. package/scripts/verify-package.mjs +3 -0
  88. package/server/package.json +5 -5
  89. package/server/src/app/gateway-application.mjs +3 -0
  90. package/server/src/app/gateway-http-routes.mjs +3 -0
  91. package/server/src/app/session-conversation-history.mjs +9 -1
  92. package/server/src/backend/adapters/a2a/backend-adapter.mjs +32 -26
  93. package/server/src/backend/adapters/acp/backend-adapter.mjs +703 -251
  94. package/server/src/backend/adapters/acp/coordinator-contract.mjs +2 -13
  95. package/server/src/backend/adapters/acp/coordinator-instructions.mjs +29 -8
  96. package/server/src/backend/adapters/acp/coordinator-queue.mjs +58 -0
  97. package/server/src/backend/adapters/acp/drivers/codex.mjs +1 -1
  98. package/server/src/backend/adapters/acp/drivers/openclaw.mjs +1 -2
  99. package/server/src/backend/adapters/acp/input-broker.mjs +2 -0
  100. package/server/src/backend/adapters/acp/process-client.mjs +111 -16
  101. package/server/src/backend/adapters/acp/session-configuration.mjs +2 -19
  102. package/server/src/backend/adapters/acp/session-registry.mjs +9 -0
  103. package/server/src/backend/adapters/acp/session-tools.mjs +1 -1
  104. package/server/src/backend/adapters/acp/turn-updates.mjs +188 -0
  105. package/server/src/backend/adapters/acp/work-continuation.mjs +48 -0
  106. package/server/src/backend/adapters/agent-client.mjs +24 -1
  107. package/server/src/backend/adapters/llm/backend-adapter.mjs +393 -0
  108. package/server/src/backend/adapters/muse/backend-adapter.mjs +2 -0
  109. package/server/src/backend/availability.mjs +12 -3
  110. package/server/src/backend/backend-adapter-sdk.mjs +3 -0
  111. package/server/src/backend/backend-port.mjs +13 -0
  112. package/server/src/backend/backend-work-runtime.mjs +23 -0
  113. package/server/src/client/client-command-runtime.mjs +14 -0
  114. package/server/src/conversation/conversation-sync.mjs +26 -2
  115. package/server/src/conversation/frontend-agent-context.mjs +18 -5
  116. package/server/src/conversation/frontend-notes.mjs +7 -5
  117. package/server/src/conversation/task-result-projector.mjs +1 -1
  118. package/server/src/core/backend-events.mjs +4 -0
  119. package/server/src/core/citation.mjs +8 -2
  120. package/server/src/core/config.mjs +46 -54
  121. package/server/src/core/gateway-protocol.mjs +4 -1
  122. package/server/src/core/request-security.mjs +7 -1
  123. package/server/src/core/work-conversation-context.mjs +138 -0
  124. package/server/src/core/work-input-request.mjs +1 -0
  125. package/server/src/frontend/frontend-tools.mjs +20 -7
  126. package/server/src/frontend/retrieval/providers/bing.mjs +23 -12
  127. package/server/src/frontend/retrieval/providers/factory.mjs +18 -1
  128. package/server/src/frontend/retrieval/providers/mcp.mjs +30 -11
  129. package/server/src/frontend/retrieval/providers/so360.mjs +23 -12
  130. package/server/src/frontend/tools/agent-task-runtime.mjs +119 -99
  131. package/server/src/frontend/tools/features/agent-task-tools.mjs +23 -42
  132. package/server/src/frontend/tools/frontend-tool-context.mjs +2 -2
  133. package/server/src/frontend/tools/spawn-thinking-tool.mjs +2 -2
  134. package/server/src/frontend/tools/tool-call-handler.mjs +166 -86
  135. package/server/src/knowledge/providers/local/library.mjs +26 -6
  136. package/server/src/knowledge/providers/local/provider.mjs +25 -6
  137. package/server/src/memory/providers/markdown/context-store.mjs +24 -11
  138. package/server/src/orchestration/session-task-coordinator.mjs +13 -3
  139. package/server/src/orchestration/task-operations.mjs +54 -12
  140. package/server/src/orchestration/task-updates.mjs +82 -0
  141. package/server/src/task/reminder-scheduler.mjs +5 -1
  142. package/server/src/task/task-manager.mjs +72 -15
  143. package/server/src/task/task-recovery.mjs +12 -2
  144. package/server/src/task/task-scheduler.mjs +5 -5
  145. package/server/src/task/task-state.mjs +13 -0
  146. package/server/src/transport/gateway-client-transport.mjs +35 -0
  147. package/server/src/transport/webrtc/protocol.mjs +1 -1
  148. package/server/src/voice/announcement/announcement-manager.mjs +3 -0
  149. package/server/src/voice/audio-stream-diagnostics.mjs +139 -0
  150. package/server/src/voice/native-delegation-runtime.mjs +360 -0
  151. package/server/src/voice/providers/dashscope-live.mjs +93 -0
  152. package/server/src/voice/providers/dashscope.mjs +45 -33
  153. package/server/src/voice/providers/doubao-seeduplex-protocol.mjs +54 -0
  154. package/server/src/voice/providers/doubao-seeduplex.mjs +16 -11
  155. package/server/src/voice/providers/ga-protocol.mjs +7 -2
  156. package/server/src/voice/providers/google-live-protocol.mjs +124 -34
  157. package/server/src/voice/providers/google-live.mjs +20 -14
  158. package/server/src/voice/providers/gpt-live-1-protocol.mjs +597 -0
  159. package/server/src/voice/providers/gpt-live-1.mjs +3 -0
  160. package/server/src/voice/providers/gpt-live-client-context.mjs +182 -0
  161. package/server/src/voice/providers/minicpm-o.mjs +9 -7
  162. package/server/src/voice/providers/openai-live.mjs +150 -0
  163. package/server/src/voice/providers/{gpt-live.mjs → openai-realtime.mjs} +23 -19
  164. package/server/src/voice/providers/provider-registry.mjs +11 -1
  165. package/server/src/voice/providers/qwen-live-protocol.mjs +399 -0
  166. package/server/src/voice/providers/registry.mjs +47 -12
  167. package/server/src/voice/providers/runtime-configuration.mjs +34 -0
  168. package/server/src/voice/providers/s2s.mjs +9 -7
  169. package/server/src/voice/providers/stepfun.mjs +14 -11
  170. package/server/src/voice/realtime-input-runtime.mjs +58 -20
  171. package/server/src/voice/realtime-presentation-runtime.mjs +111 -27
  172. package/server/src/voice/realtime-provider-session.mjs +59 -14
  173. package/server/src/voice/realtime-provider.mjs +358 -45
  174. package/server/src/voice/realtime-session-runtime.mjs +282 -35
  175. package/server/src/voice/realtime-task-presentation.mjs +8 -2
  176. package/server/src/voice/realtime-turn-state.mjs +33 -2
  177. package/shared/backend/catalog.mjs +26 -2
  178. package/shared/backend/install.mjs +3 -1
  179. package/shared/backend/setup.mjs +43 -0
  180. package/shared/gateway/client-sdk.mjs +21 -6
  181. package/shared/gateway/setup.mjs +13 -1
  182. package/shared/gateway/websocket-auth.mjs +2 -1
  183. package/shared/protocol/gateway-client-protocol.mjs +14 -0
  184. package/shared/protocol/gateway-events.mjs +39 -1
  185. package/shared/realtime-legacy-environment.mjs +81 -0
  186. package/shared/realtime-model-catalog.mjs +68 -194
  187. package/shared/realtime-models/README.md +33 -0
  188. package/shared/realtime-models/dashscope.mjs +57 -0
  189. package/shared/realtime-models/google.mjs +10 -0
  190. package/shared/realtime-models/openai.mjs +24 -0
  191. package/shared/realtime-models/profile.mjs +38 -0
  192. package/shared/realtime-models/stepfun.mjs +10 -0
  193. package/shared/realtime-models/volcengine.mjs +12 -0
  194. package/shared/realtime-provider-catalog.mjs +23 -11
  195. package/shared/realtime-provider-definitions.mjs +168 -235
  196. package/shared/runtime-environment.mjs +23 -30
  197. package/shared/skill-library.mjs +49 -13
  198. package/shared/web-search-configuration.mjs +25 -2
  199. package/tui/package.json +2 -2
  200. package/tui/src/index.mjs +14 -9
  201. package/tui/src/runtime-configuration.mjs +2 -0
  202. package/tui/src/terminal-commands.mjs +40 -0
  203. package/tui/src/text-cli.mjs +10 -1
  204. package/web/dist/assets/index-Bc2Q04J9.css +1 -0
  205. package/web/dist/assets/index-bY4DFXKT.js +96 -0
  206. package/web/dist/index.html +2 -2
  207. package/web/dist/assets/index-BRaiI-dW.js +0 -91
  208. package/web/dist/assets/index-D9k8R2JY.css +0 -1
@@ -1,10 +1,13 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import { normalizeInputParts } from '../../../shared/input-parts.mjs'
3
3
  import { GatewayClientEvent, GatewayServerEvent } from '../../../shared/protocol/realtime-events.mjs'
4
+ import { GatewayClientCapability } from '../../../shared/protocol/gateway-client-protocol.mjs'
5
+ import { normalizeAudioPlaybackDiagnostics } from '../../../shared/protocol/gateway-events.mjs'
4
6
  import { AnnouncementWindow } from './announcement/announcement-window.mjs'
5
7
  import { normalizeClientContext } from '../conversation/frontend-agent-context.mjs'
6
8
  import { realtimeEventErrorMessage } from './realtime-provider.mjs'
7
9
  import { SessionTaskCoordinator } from '../orchestration/session-task-coordinator.mjs'
10
+ import { NativeDelegationRuntime } from './native-delegation-runtime.mjs'
8
11
  import { createRealtimeTaskPresentation } from './realtime-task-presentation.mjs'
9
12
  import { recordTaskResult } from '../conversation/task-result-projector.mjs'
10
13
  import { ToolCallHandler } from '../frontend/tools/tool-call-handler.mjs'
@@ -34,6 +37,11 @@ const PERMISSION_RESPONSE_GRACE_MS = 800
34
37
  const RESPONSE_CONTEXT_CLEANUP_MS = 30000
35
38
  const REALTIME_STABLE_CONNECTION_MS = 10000
36
39
 
40
+ function playbackDiagnosticFields(event) {
41
+ const audioDiagnostics = normalizeAudioPlaybackDiagnostics(event.audioDiagnostics)
42
+ return audioDiagnostics ? { audioDiagnostics } : {}
43
+ }
44
+
37
45
  function gatewayTurnId() {
38
46
  return `gateway_${randomUUID().replaceAll('-', '')}`
39
47
  }
@@ -47,6 +55,20 @@ export function isSleepActivityEvent(event = {}) {
47
55
  ].includes(event.type)
48
56
  }
49
57
 
58
+ // The frontend checks shouldCreate on enqueue and again before sending: decide
59
+ // once. A busy-refused request never ran, so retry it only while the
60
+ // permission is still pending.
61
+ export function permissionResponseGate({ isCandidate, hasPendingPermission, claim }) {
62
+ let decided = null
63
+ return ({ refused = false } = {}) => {
64
+ if (decided === null) {
65
+ decided = isCandidate() && hasPendingPermission()
66
+ if (decided) claim()
67
+ }
68
+ return refused ? decided && hasPendingPermission() : decided
69
+ }
70
+ }
71
+
50
72
  /**
51
73
  * One frontend conversation runtime per client connection.
52
74
  * Receives decoded semantic input plus trusted identity; emits internal events.
@@ -68,14 +90,27 @@ export function createRealtimeSessionRuntime({
68
90
  }) {
69
91
  let closed = false
70
92
  let started = false
71
- const emit = event => { if (!closed) send(event) }
93
+ let presentationRuntime
94
+ const emit = event => {
95
+ if (closed) return
96
+ if (event.type === GatewayServerEvent.PLAYBACK_CLEAR) {
97
+ presentationRuntime?.clearPlayback({ reason: event.reason })
98
+ }
99
+ send(event)
100
+ }
72
101
  let inputEnabled = false
102
+ let externalInput = false
103
+ let externalAudioInput = false
104
+ let inputCollecting = false
105
+ const realtimeEventListeners = new Set()
106
+ const pendingProviderInputs = new Map()
73
107
  let outputEnabled = false
74
108
  // Set only by host arbitration. Unlike inputEnabled (which the client
75
109
  // declares about itself) this means the client has been ordered to stop
76
110
  // capturing, so nothing here may re-enable audio on its own.
77
111
  let inputSuspended = initialInputSuspension?.suspended === true
78
112
  let nonVoiceClient = false
113
+ let playbackReceipts = true
79
114
  let descriptor = { type: 'unknown', instanceId: null }
80
115
  let responseTurnCandidate = null
81
116
  let responseStartWatchdog = null
@@ -105,6 +140,7 @@ export function createRealtimeSessionRuntime({
105
140
  beforeSleep: async () => {
106
141
  inputEnabled = false
107
142
  realtimeSession.clearPendingAudio()
143
+ syncProviderInputMute()
108
144
  },
109
145
  onSleeping: () => enterSleep(),
110
146
  onFailure: ({ error }) => connectionLogger.warn('presence.sleep_failed', {
@@ -120,6 +156,15 @@ export function createRealtimeSessionRuntime({
120
156
  const transcripts = new TurnTranscripts()
121
157
  const turnCitations = new TurnCitations()
122
158
  let realtimeSession
159
+ let nativeDelegations
160
+ // Only opted-in protocols need a cloud mute for client sleep. Derive their
161
+ // state from all input gates so wake/unmute event ordering cannot reopen it.
162
+ const syncProviderInputMute = requestedMuted => {
163
+ const sleepAware = realtimeSession.provider()?.capabilities?.inputMuteOnSleep === true
164
+ if (!sleepAware && requestedMuted === undefined) return
165
+ const muted = sleepAware ? sleeping || inputSuspended || !inputEnabled : requestedMuted
166
+ if (!sleepAware || muted !== realtimeSession.inputMuted) realtimeSession.setInputMuted(muted)
167
+ }
123
168
  let visualInput
124
169
  const clearVisualInput = () => {
125
170
  realtimeSession?.clearPendingImage?.()
@@ -129,6 +174,7 @@ export function createRealtimeSessionRuntime({
129
174
  getFrontend: () => realtimeSession?.frontend,
130
175
  isDeliveryBlocked: delivery => (
131
176
  closed
177
+ || inputCollecting
132
178
  || !realtimeSession?.ready
133
179
  || (delivery.mode !== 'context' && (sleeping || waking || !outputEnabled))
134
180
  ),
@@ -174,6 +220,9 @@ export function createRealtimeSessionRuntime({
174
220
  getState: () => ({
175
221
  ready: realtimeSession?.ready === true,
176
222
  outputEnabled, sleeping, waking,
223
+ nativeTaskDelivery: realtimeSession?.provider()?.capabilities?.nativeDelegation === true,
224
+ notificationDeliverySupported: realtimeSession?.frontend?.capabilities?.clientResponses !== false
225
+ && (nonVoiceClient || playbackReceipts),
177
226
  windowBlocked: announcementWindow.isBlocked(),
178
227
  busy: turns.userSpeaking || announcementWindow.isBlocked(),
179
228
  }),
@@ -187,6 +236,9 @@ export function createRealtimeSessionRuntime({
187
236
  onProgressError: error => connectionLogger.warn('progress.injection_failed', {
188
237
  error: error.message,
189
238
  }),
239
+ onPresentRequest: requestId => {
240
+ if (realtimeSession.frontend?.capabilities?.concurrentVoicePlayback) turns.noteRequest(requestId)
241
+ },
190
242
  }),
191
243
  onTaskEvent,
192
244
  onResult: task => recordTaskResult({ conversationSync, ownerId, sessionId, task }),
@@ -209,7 +261,15 @@ export function createRealtimeSessionRuntime({
209
261
  onEvent: event => handleEvent(event),
210
262
  onDiagnostic: diagnostic => {
211
263
  const { event, ...fields } = diagnostic
212
- if (['realtime.response_requested', 'realtime.response_started'].includes(event)) connectionLogger.info(event, fields)
264
+ const delegationUpdate = ['realtime.delegation.update_sent', 'realtime.delegation.update_acknowledged'].includes(event)
265
+ if (delegationUpdate && fields.updateKind === 'progress') {
266
+ connectionLogger.debug(event, fields)
267
+ return
268
+ }
269
+ const informational = ['realtime.response_requested', 'realtime.response_started', 'realtime.audio.transport'].includes(event)
270
+ || delegationUpdate
271
+ || (event === 'realtime.transport_closed' && fields.code === 1000)
272
+ if (informational) connectionLogger.info(event, fields)
213
273
  else connectionLogger.warn(event, fields)
214
274
  },
215
275
  onResponseSettled: ({ origin, context, outcome }) => {
@@ -222,6 +282,7 @@ export function createRealtimeSessionRuntime({
222
282
  announcements.flush()
223
283
  },
224
284
  onConnected: () => {
285
+ nativeDelegations?.syncTaskState()
225
286
  taskCoordinator.announcePendingPermissions()
226
287
  taskCoordinator.announcePendingInputs()
227
288
  },
@@ -232,8 +293,10 @@ export function createRealtimeSessionRuntime({
232
293
  emit({
233
294
  type: GatewayServerEvent.VOICE_READY,
234
295
  inputSampleRate: createdFrontend.provider.inputSampleRate,
235
- provider: createdFrontend.provider.key,
296
+ provider: createdFrontend.provider.provider || createdFrontend.provider.key,
236
297
  providerLabel: createdFrontend.provider.label,
298
+ ...(createdFrontend.capabilities?.interruptionPlaysOut ? { interruptionPlaysOut: true } : {}),
299
+ ...(createdFrontend.capabilities?.pacedOutputAudio ? { pacedOutputAudio: true } : {}),
237
300
  })
238
301
  sleepController.recordActivity()
239
302
  progressAnnouncements.flush()
@@ -249,6 +312,9 @@ export function createRealtimeSessionRuntime({
249
312
  }
250
313
  },
251
314
  onDisconnected: () => {
315
+ nativeDelegations?.detach()
316
+ pendingProviderInputs.clear()
317
+ for (const listener of realtimeEventListeners) listener({ type: 'session.disconnected' })
252
318
  taskCoordinator.resetPresentation()
253
319
  clearVisualInput()
254
320
  clearResponseCandidate()
@@ -278,6 +344,23 @@ export function createRealtimeSessionRuntime({
278
344
  ? { createFrontend: realtimeFrontendFactory }
279
345
  : {}),
280
346
  })
347
+ nativeDelegations = new NativeDelegationRuntime({
348
+ taskManager, taskOperations, ownerId, sessionId, backendAvailability, inputAssets,
349
+ getFrontend: () => realtimeSession.frontend,
350
+ getTurn: () => turns.committed(),
351
+ getInputContext: itemId => turns.resolveInput(itemId, { fallbackToCurrent: false }),
352
+ onResult: task => recordTaskResult({ conversationSync, ownerId, sessionId, task }),
353
+ onPresentRequest: requestId => turns.noteRequest(requestId),
354
+ onError: (error, fields = {}) => {
355
+ connectionLogger.warn('realtime.delegation.delivery_failed', { ...fields,
356
+ ...(typeof error.requestId === 'string' ? { requestId: error.requestId } : {}),
357
+ ...(typeof error.eventType === 'string' ? { eventType: error.eventType } : {}),
358
+ ...(typeof error.code === 'string' ? { errorCode: error.code } : {}),
359
+ ...(Number.isFinite(error.elapsedMs) ? { elapsedMs: error.elapsedMs } : {}),
360
+ error: error.message })
361
+ emit({ type: GatewayServerEvent.ERROR, message: `Live 任务消息未确认送达:${error.message}` })
362
+ },
363
+ })
281
364
  visualInput = new VisualInputBuffer({
282
365
  onFrame: image => realtimeSession.appendImage(image),
283
366
  })
@@ -289,7 +372,7 @@ export function createRealtimeSessionRuntime({
289
372
  if (suspend) {
290
373
  // Buffered audio predates the suspension and is no longer wanted.
291
374
  realtimeSession.clearPendingAudio()
292
- realtimeSession.setInputMuted(true)
375
+ syncProviderInputMute(true)
293
376
  clearVisualInput()
294
377
  sleepController?.disable()
295
378
  realtimeSession.cancelResponse()
@@ -302,7 +385,7 @@ export function createRealtimeSessionRuntime({
302
385
  })
303
386
  return
304
387
  }
305
- if (inputEnabled) realtimeSession.setInputMuted(false)
388
+ if (inputEnabled) syncProviderInputMute(false)
306
389
  emit({ type: GatewayServerEvent.INPUT_RESUME })
307
390
  }
308
391
  const deactivate = holder => {
@@ -358,6 +441,11 @@ export function createRealtimeSessionRuntime({
358
441
  })
359
442
  })
360
443
  : () => {}
444
+ // Full duplex: only a turn that began after the Gateway asked answers a request.
445
+ const answersRequest = (turnId, requestId) => (
446
+ !realtimeSession.frontend?.capabilities?.concurrentVoicePlayback
447
+ || turns.beganAfterRequest(turnId, requestId)
448
+ )
361
449
  const toolCalls = new ToolCallHandler({
362
450
  taskManager,
363
451
  taskOperations,
@@ -367,6 +455,9 @@ export function createRealtimeSessionRuntime({
367
455
  getFrontend: () => realtimeSession.frontend,
368
456
  getTurnId: () => turns.committedTurnId,
369
457
  getTurnGeneration: () => turns.committedTurnGeneration,
458
+ isUserTurnSinceBoundary: context => turns.isUserTurnSinceBoundary(context),
459
+ userTurnBeganAfter: (laterId, turnId) => turns.beganAfterTurn(laterId, turnId),
460
+ answersRequest,
370
461
  memoryService,
371
462
  notesStore,
372
463
  getClientContext: () => clientContext,
@@ -398,7 +489,8 @@ export function createRealtimeSessionRuntime({
398
489
  authorizationId,
399
490
  error,
400
491
  })
401
- taskCoordinator.retryPermission(authorizationId)
492
+ if (realtimeSession.frontend?.capabilities?.nativeDelegation) nativeDelegations.retryPermission(authorizationId)
493
+ else taskCoordinator.retryPermission(authorizationId)
402
494
  },
403
495
  onToolResultReady: ({ callId, turnId, toolName, failed, errorCode }) => {
404
496
  const timing = toolCallTimings.get(callId)
@@ -413,6 +505,10 @@ export function createRealtimeSessionRuntime({
413
505
  durationMs: Math.max(0, Date.now() - timing.startedAt),
414
506
  })
415
507
  },
508
+ onToolResponseFailed: context => {
509
+ connectionLogger.warn('realtime.tool_follow_up.failed', context)
510
+ presentationRuntime.failToolResponse(context)
511
+ },
416
512
  onToolCallDebug: event => {
417
513
  const { startedAt: _startedAt, ...publicEvent } = event || {}
418
514
  emit({
@@ -446,17 +542,24 @@ export function createRealtimeSessionRuntime({
446
542
  turnCitations,
447
543
  sessionDigests,
448
544
  })
449
- const clearResponseCandidate = () => {
545
+ const clearResponseWatchdog = () => {
450
546
  clearTimeout(responseStartWatchdog)
451
- clearTimeout(permissionResponseTimer)
452
547
  responseStartWatchdog = null
548
+ }
549
+ const clearResponseCandidate = () => {
550
+ clearResponseWatchdog()
551
+ clearTimeout(permissionResponseTimer)
453
552
  permissionResponseTimer = null
454
553
  responseTurnCandidate = null
455
554
  }
456
555
 
457
556
  const ensurePermissionResponseFor = context => {
458
557
  clearTimeout(permissionResponseTimer)
459
- const hasPendingPermission = () => taskCoordinator.hasPendingPermission()
558
+ const hasPendingPermission = () => (realtimeSession.frontend?.capabilities?.concurrentVoicePlayback
559
+ ? taskCoordinator.activeTasks().some(({ authorization }) => (
560
+ authorization?.status === 'pending' && turns.beganAfterRequest(context.turnId, authorization.id)
561
+ ))
562
+ : taskCoordinator.hasPendingPermission())
460
563
  if (!hasPendingPermission()) return
461
564
  permissionResponseTimer = setTimeout(() => {
462
565
  permissionResponseTimer = null
@@ -464,14 +567,11 @@ export function createRealtimeSessionRuntime({
464
567
  turnId: context.turnId,
465
568
  turnGeneration: context.turnGeneration,
466
569
  }, {
467
- shouldCreate: () => {
468
- if (
469
- responseTurnCandidate !== context
470
- || !hasPendingPermission()
471
- ) return false
472
- clearResponseCandidate()
473
- return true
474
- },
570
+ shouldCreate: permissionResponseGate({
571
+ isCandidate: () => responseTurnCandidate === context,
572
+ hasPendingPermission,
573
+ claim: clearResponseCandidate,
574
+ }),
475
575
  }).catch(error => emit({
476
576
  type: 'error',
477
577
  message: `暂时无法处理权限回答:${error.message}`,
@@ -485,6 +585,13 @@ export function createRealtimeSessionRuntime({
485
585
  responseStartWatchdog = setTimeout(() => {
486
586
  if (responseTurnCandidate !== context) return
487
587
  clearResponseCandidate()
588
+ // The turn is given up: Gateway requests no longer wait for its reply.
589
+ announcementWindow.responseDone({ turnId: context.turnId, failed: true })
590
+ // A full-duplex model may leave a turn unanswered: not a stall.
591
+ if (realtimeSession.frontend?.capabilities?.concurrentVoicePlayback) {
592
+ if (!turns.userSpeaking) emit({ type: 'voice.state', state: 'idle', turnId: context.turnId, origin: 'model' })
593
+ return
594
+ }
488
595
  emit({
489
596
  type: 'error',
490
597
  message: '实时模型没有开始回复,语音连接已自动恢复,请再说一次。',
@@ -516,6 +623,20 @@ export function createRealtimeSessionRuntime({
516
623
  send: event => emit(event),
517
624
  getFrontend: () => realtimeSession.frontend,
518
625
  ensureFrontend: () => realtimeSession.ensure(),
626
+ submitUserInput: async (parts, context) => {
627
+ const frontend = realtimeSession.frontend
628
+ if (!frontend?.capabilities?.nativeDelegation || frontend.capabilities.automaticUserResponses) {
629
+ return frontend.sendUserInput(parts, context)
630
+ }
631
+ // Services without native typed requests leave execution to the local
632
+ // backend. Mirror context without creating a second cloud delegation.
633
+ await frontend.appendUserInputContext(parts)
634
+ if (!nativeDelegations.handleUserInput({ parts, context })) {
635
+ throw new Error('未受理本次输入,请检查后台任务或连接状态。')
636
+ }
637
+ expectResponseFor(context)
638
+ return { delegated: true }
639
+ },
519
640
  clearResponseCandidate,
520
641
  expectResponseFor,
521
642
  shouldEnsurePermissionResponse: context => responseTurnCandidate === context,
@@ -531,7 +652,7 @@ export function createRealtimeSessionRuntime({
531
652
  },
532
653
  })
533
654
 
534
- const presentationRuntime = new RealtimePresentationRuntime({
655
+ presentationRuntime = new RealtimePresentationRuntime({
535
656
  ownerId,
536
657
  sessionId,
537
658
  turns,
@@ -543,8 +664,10 @@ export function createRealtimeSessionRuntime({
543
664
  getFrontend: () => realtimeSession.frontend,
544
665
  getOutputEnabled: () => outputEnabled,
545
666
  getNonVoiceClient: () => nonVoiceClient,
667
+ getPlaybackReceipts: () => playbackReceipts && outputEnabled,
546
668
  getResponseTurnCandidate: () => responseTurnCandidate,
547
669
  clearResponseCandidate,
670
+ clearResponseWatchdog,
548
671
  announcementQuietMs: config.announcementQuietMs,
549
672
  responseContextCleanupMs: RESPONSE_CONTEXT_CLEANUP_MS,
550
673
  turnCitations,
@@ -554,9 +677,51 @@ export function createRealtimeSessionRuntime({
554
677
 
555
678
  const handleEvent = event => {
556
679
  if (closed) return
680
+ if (event.type === 'input_audio_buffer.speech_started') {
681
+ pendingProviderInputs.set(event.item_id, { events: [event], suppressed: externalInput, ended: false })
682
+ } else if (inputs.handles(event)) {
683
+ const pending = pendingProviderInputs.get(event.item_id)
684
+ if (pending) {
685
+ pending.events = pending.events.filter(previous => previous.type !== event.type)
686
+ pending.events.push(event)
687
+ if (event.type === 'input_audio_buffer.speech_stopped') {
688
+ pending.ended = true
689
+ if (event.reason === 'turn_invalid') pendingProviderInputs.delete(event.item_id)
690
+ }
691
+ }
692
+ }
693
+ let cancelAutomaticResponse = false
694
+ if (event.type === 'response.created' && !event.__voiceContext?.turnId) {
695
+ for (const [id, pending] of pendingProviderInputs) {
696
+ if (!pending.ended) continue
697
+ cancelAutomaticResponse ||= pending.suppressed
698
+ pendingProviderInputs.delete(id)
699
+ }
700
+ cancelAutomaticResponse ||= externalInput
701
+ if (cancelAutomaticResponse) event.__voiceContext = { ...event.__voiceContext, suppressed: true }
702
+ }
703
+ for (const listener of realtimeEventListeners) listener(event)
704
+ if (event.type === 'delegation.created') {
705
+ if (!inputCollecting && !externalInput) nativeDelegations.handle(event)
706
+ return
707
+ }
708
+ if (externalInput && inputs.handles(event)) return
709
+ if ((inputCollecting && isResponseActivityEvent(event))
710
+ || (externalInput && event.type === 'response.created' && !event.__voiceContext?.turnId)) {
711
+ event.__voiceContext = { ...event.__voiceContext, suppressed: true }
712
+ }
713
+ // A late final may finish an existing presentation, never create a new turn
714
+ // after its original response context has already expired or been removed.
715
+ if (event.__voiceLateFinal && !presentationRuntime.has(realtimeResponseId(event))) return
557
716
  if (isSleepActivityEvent(event)) sleepController?.recordActivity()
558
717
  if (isResponseActivityEvent(event)) presentationRuntime.begin(event)
718
+ if (cancelAutomaticResponse) realtimeSession.cancelResponse()
559
719
  if (inputs.handleProviderEvent(event)) return
720
+ const responseFailed = event.type === 'response.done' && event.response?.status === 'failed'
721
+ // Terminal handling may remove or suppress the context; retain its original
722
+ // identity for error reporting and content-safety recovery afterwards.
723
+ const responseContext = responseFailed ? presentationRuntime.get(realtimeResponseId(event)) : null
724
+ const failedContext = responseContext ? { ...responseContext } : null
560
725
  if (event.type === 'response.done') {
561
726
  const responseId = realtimeResponseId(event)
562
727
  const context = presentationRuntime.get(responseId)
@@ -571,6 +736,14 @@ export function createRealtimeSessionRuntime({
571
736
  hasFunctionCall: Boolean(context?.hasFunctionCall),
572
737
  suppressed: Boolean(context?.suppressed),
573
738
  })
739
+ if (responseFailed) {
740
+ connectionLogger.warn('realtime.response.failed', {
741
+ provider: realtimeSession.providerKey,
742
+ responseId,
743
+ turnId: context?.turnId || '',
744
+ errorMessage: realtimeEventErrorMessage(event),
745
+ })
746
+ }
574
747
  }
575
748
  if (event.type === 'response.function_call_arguments.done') {
576
749
  const id = realtimeResponseId(event)
@@ -590,7 +763,10 @@ export function createRealtimeSessionRuntime({
590
763
  startedAt,
591
764
  resultReady: false,
592
765
  })
593
- toolCalls.handle(event, { ...callContext, responseId: id })
766
+ toolCalls.handle(event, {
767
+ ...callContext, responseId: id,
768
+ ...(inputCollecting || callContext.suppressed ? { turnGeneration: -1 } : {}),
769
+ })
594
770
  .catch(error => {
595
771
  connectionLogger.warn('realtime.tool_call.failed', {
596
772
  ...callFields,
@@ -609,21 +785,25 @@ export function createRealtimeSessionRuntime({
609
785
  status: event.response?.status || 'unknown',
610
786
  })
611
787
  }
612
- return
613
- } else if (event.type === 'error') {
788
+ // A failed response is also an error, not only a playback terminal.
789
+ // Cancelled/incomplete and superseded responses remain silent.
790
+ if (!responseFailed || failedContext?.suppressed) return
791
+ }
792
+ if (event.type === 'error' || responseFailed) {
614
793
  // A response refused by a busy single-slot provider is retried by the
615
794
  // frontend transparently; nothing user-facing happened.
616
795
  if (event.__voiceRetried) return
617
796
  const errorMessage = realtimeEventErrorMessage(event)
618
797
  const providerError = realtimeSession.classifyError(errorMessage)
619
798
  const recoverableInactivity = providerError === 'inactivity'
799
+ const errorOrigin = event.__voiceOrigin || failedContext?.origin
620
800
  // A local or otherwise capacity-bounded provider can still be draining
621
801
  // the previous Session. Its close event drives the shared reconnect
622
802
  // backoff, so this transient refusal is neither a response failure nor
623
803
  // a user-facing error.
624
804
  if (providerError === 'capacity_busy') return
625
805
  const permissionSpeechCollision = (
626
- event.__voiceOrigin === 'permission'
806
+ errorOrigin === 'permission'
627
807
  && providerError === 'input_busy'
628
808
  )
629
809
  if (permissionSpeechCollision) {
@@ -636,16 +816,16 @@ export function createRealtimeSessionRuntime({
636
816
  if (benignCancelRace) return
637
817
  if (providerError === 'content_safety') {
638
818
  const recentMessages = conversationSync.frontendContext({ ownerId, sessionId })
639
- const restoring = ['restore', 'session'].includes(event.__voiceOrigin)
640
- const failedContext = restoring ? {} : (
641
- presentationRuntime.get(realtimeResponseId(event)) || {
819
+ const restoring = ['restore', 'session'].includes(errorOrigin)
820
+ const rejectedContext = restoring ? {} : (
821
+ failedContext || presentationRuntime.get(realtimeResponseId(event)) || {
642
822
  turnId: turns.committedTurnId || turns.turnId,
643
823
  }
644
824
  )
645
825
  const generation = ++contentRecoveryGeneration
646
- const canRecover = realtimeRecoveryContext.beginRecovery(failedContext, recentMessages)
826
+ const canRecover = realtimeRecoveryContext.beginRecovery(rejectedContext, recentMessages)
647
827
  clearResponseCandidate()
648
- presentationRuntime.failResponse(event)
828
+ if (!responseFailed) presentationRuntime.failResponse(event)
649
829
  emit({
650
830
  type: GatewayServerEvent.PLAYBACK_CLEAR,
651
831
  reason: 'provider_content_safety',
@@ -657,8 +837,8 @@ export function createRealtimeSessionRuntime({
657
837
  })
658
838
  connectionLogger.warn('realtime.content_safety_recovery', {
659
839
  provider: realtimeSession.providerKey,
660
- excludedTurnId: failedContext.turnId || '',
661
- origin: event.__voiceOrigin || 'response',
840
+ excludedTurnId: rejectedContext.turnId || '',
841
+ origin: errorOrigin || 'response',
662
842
  errorMessage,
663
843
  responseId: realtimeResponseId(event),
664
844
  attempt: realtimeRecoveryContext.attempts,
@@ -728,7 +908,7 @@ export function createRealtimeSessionRuntime({
728
908
  message: errorMessage,
729
909
  })
730
910
  }
731
- presentationRuntime.failResponse(event)
911
+ if (!responseFailed) presentationRuntime.failResponse(event)
732
912
  // A provider may close an inactive response scope while a delegated
733
913
  // backend task is still running. The task remains healthy, and any
734
914
  // pending announcement has already returned to the retry queue, so this
@@ -744,6 +924,7 @@ export function createRealtimeSessionRuntime({
744
924
  clearVisualInput()
745
925
  sleeping = true
746
926
  waking = false
927
+ syncProviderInputMute()
747
928
  announcementWindow.reset()
748
929
  progressAnnouncements.clear()
749
930
  emit({
@@ -770,8 +951,12 @@ export function createRealtimeSessionRuntime({
770
951
  if (!sleeping || waking) return
771
952
  sleeping = false
772
953
  waking = false
954
+ syncProviderInputMute()
773
955
  presenceController.wake()
774
956
  sleepController.wake()
957
+ if (realtimeSession.provider()?.capabilities?.inputMuteOnSleep && (inputEnabled || outputEnabled)) {
958
+ realtimeSession.ensure().catch(reportFrontendError)
959
+ }
775
960
  emit({
776
961
  type: GatewayServerEvent.VOICE_SLEEP,
777
962
  state: 'awake',
@@ -860,7 +1045,7 @@ export function createRealtimeSessionRuntime({
860
1045
  }
861
1046
  }
862
1047
 
863
- const handleClientEvent = (event, { descriptor: nextDescriptor = descriptor, capabilities: negotiatedCapabilities = [] } = {}) => {
1048
+ const handleClientEvent = (event, { descriptor: nextDescriptor = descriptor, capabilities: negotiatedCapabilities = [], capabilitiesNegotiated = false } = {}) => {
864
1049
  if (closed) return
865
1050
  if (event.type === GatewayClientEvent.CONNECT) {
866
1051
  descriptor = nextDescriptor
@@ -873,6 +1058,9 @@ export function createRealtimeSessionRuntime({
873
1058
  textOnly: event.textOnly === true,
874
1059
  })
875
1060
  nonVoiceClient = event.textOnly === true
1061
+ // Legacy clients predate negotiation and already send playback receipts.
1062
+ playbackReceipts = !capabilitiesNegotiated
1063
+ || negotiatedCapabilities.includes(GatewayClientCapability.PLAYBACK_RECEIPTS)
876
1064
  sessionOutputVoice = String(event.outputVoice || '').trim()
877
1065
  // The client may pick a realtime front end per session. An unknown
878
1066
  // name is reported instead of silently falling back, so a typo does
@@ -968,6 +1156,7 @@ export function createRealtimeSessionRuntime({
968
1156
  if (negotiatedCapabilities.includes('client.presence')) enterSleep()
969
1157
  else requestExplicitSleep()
970
1158
  } else if (inputEnabled || outputEnabled) {
1159
+ syncProviderInputMute()
971
1160
  realtimeSession.ensure().catch(reportFrontendError)
972
1161
  }
973
1162
  }).catch(reportFrontendError)
@@ -979,7 +1168,7 @@ export function createRealtimeSessionRuntime({
979
1168
  } else {
980
1169
  activateVoiceClient()
981
1170
  }
982
- realtimeSession.setInputMuted(false)
1171
+ syncProviderInputMute(false)
983
1172
  realtimeSession.ensure()
984
1173
  .then(() => {
985
1174
  taskCoordinator.announcePendingPermissions()
@@ -997,7 +1186,7 @@ export function createRealtimeSessionRuntime({
997
1186
  } else {
998
1187
  activateVoiceClient()
999
1188
  }
1000
- realtimeSession.setInputMuted(false)
1189
+ syncProviderInputMute(false)
1001
1190
  if (sleeping) {
1002
1191
  return
1003
1192
  }
@@ -1016,6 +1205,7 @@ export function createRealtimeSessionRuntime({
1016
1205
  // Defence in depth: a client that has not yet acted on the suspension
1017
1206
  // must not be able to feed audio through it.
1018
1207
  || inputSuspended
1208
+ || (externalInput && !externalAudioInput)
1019
1209
  || !voiceAccess.isActive()
1020
1210
  ) {
1021
1211
  return
@@ -1052,6 +1242,7 @@ export function createRealtimeSessionRuntime({
1052
1242
  event.type === GatewayClientEvent.TEXT_MESSAGE
1053
1243
  || event.type === GatewayClientEvent.INPUT_MESSAGE
1054
1244
  ) {
1245
+ if (externalInput) return
1055
1246
  if (sleeping || waking) {
1056
1247
  emit({
1057
1248
  type: 'error',
@@ -1067,6 +1258,10 @@ export function createRealtimeSessionRuntime({
1067
1258
  announcementWindow.interrupt()
1068
1259
  announcements.dismissActive()
1069
1260
  realtimeSession.cancelResponse()
1261
+ // A frontend whose model finishes the speech it already generated plays it out, then stops.
1262
+ if (!realtimeSession.frontend?.capabilities?.interruptionPlaysOut) {
1263
+ emit({ type: GatewayServerEvent.PLAYBACK_CLEAR, reason: 'user_interruption' })
1264
+ }
1070
1265
  } else if (event.type === GatewayClientEvent.PLAYBACK_STARTED) {
1071
1266
  const id = String(event.responseId || '')
1072
1267
  const playbackContext = presentationRuntime.get(id)
@@ -1079,6 +1274,7 @@ export function createRealtimeSessionRuntime({
1079
1274
  responseId: id,
1080
1275
  turnId: playbackContext?.turnId || '',
1081
1276
  origin: playbackContext?.origin || 'model',
1277
+ ...playbackDiagnosticFields(event),
1082
1278
  })
1083
1279
  presentationRuntime.startPlayback(id)
1084
1280
  }
@@ -1089,7 +1285,7 @@ export function createRealtimeSessionRuntime({
1089
1285
  active: voiceAccess.isActive(),
1090
1286
  responseKnown: presentationRuntime.has(id),
1091
1287
  })
1092
- connectionLogger.info('realtime.playback.ended', { responseId: id, accepted })
1288
+ connectionLogger.info('realtime.playback.ended', { responseId: id, accepted, ...playbackDiagnosticFields(event) })
1093
1289
  if (accepted) presentationRuntime.finishPlayback(id)
1094
1290
  } else if (event.type === GatewayClientEvent.PLAYBACK_CANCELLED) {
1095
1291
  const id = String(event.responseId || '')
@@ -1100,6 +1296,7 @@ export function createRealtimeSessionRuntime({
1100
1296
  })
1101
1297
  connectionLogger.info('realtime.playback.cancelled', {
1102
1298
  responseId: id, accepted, reason: String(event.reason || ''),
1299
+ ...playbackDiagnosticFields(event),
1103
1300
  })
1104
1301
  if (accepted) {
1105
1302
  presentationRuntime.cancelPlayback(id, {
@@ -1120,7 +1317,7 @@ export function createRealtimeSessionRuntime({
1120
1317
  } else if (event.type === GatewayClientEvent.INPUT_MUTE) {
1121
1318
  inputEnabled = false
1122
1319
  realtimeSession.clearPendingAudio()
1123
- realtimeSession.setInputMuted(true)
1320
+ syncProviderInputMute(true)
1124
1321
  } else if (event.type === GatewayClientEvent.SLEEP) {
1125
1322
  requestExplicitSleep('client')
1126
1323
  } else if (event.type === GatewayClientEvent.WAKE) {
@@ -1152,7 +1349,54 @@ export function createRealtimeSessionRuntime({
1152
1349
  applyInputSuspension,
1153
1350
  deactivate,
1154
1351
  status: () => realtimeSession.status({ sleeping, waking }),
1352
+ inputState: () => ({
1353
+ inputEnabled,
1354
+ inputSuspended,
1355
+ inputActive: inputEnabled && !inputSuspended && !sleeping && !closed && voiceAccess.isActive(),
1356
+ }),
1155
1357
  updateOutputVoice: updateSessionOutputVoice,
1358
+ // Trusted extensions observe native input or collect external turns.
1359
+ // Business batching stays outside the framework; submission reuses the
1360
+ // ordinary user-turn lifecycle without replacing provider turn detection.
1361
+ setExternalInput(enabled, { audioInput = false } = {}) {
1362
+ const next = enabled === true
1363
+ if (closed) return
1364
+ externalAudioInput = next && audioInput === true
1365
+ if (next === externalInput) return
1366
+ externalInput = next
1367
+ if (!externalAudioInput) realtimeSession.clearPendingAudio()
1368
+ if (externalInput) {
1369
+ for (const pending of pendingProviderInputs.values()) pending.suppressed = true
1370
+ handleClientEvent({ type: GatewayClientEvent.INTERRUPT })
1371
+ }
1372
+ connectionLogger.info('realtime.input_mode.changed', {
1373
+ externalInput, audioInput: externalAudioInput, rebuild: false, provider: realtimeSession.providerKey,
1374
+ })
1375
+ },
1376
+ onRealtimeEvent(listener) {
1377
+ realtimeEventListeners.add(listener)
1378
+ for (const pending of pendingProviderInputs.values()) {
1379
+ for (const event of pending.events) listener(event)
1380
+ }
1381
+ return () => realtimeEventListeners.delete(listener)
1382
+ },
1383
+ setInputCollecting(active) {
1384
+ if (closed || inputCollecting === (active === true)) return
1385
+ inputCollecting = active === true
1386
+ if (inputCollecting) {
1387
+ if (sleeping) wakeFromSleep()
1388
+ handleClientEvent({ type: GatewayClientEvent.INTERRUPT })
1389
+ announcementWindow.beginTurn(gatewayTurnId())
1390
+ } else {
1391
+ announcementWindow.reset()
1392
+ }
1393
+ },
1394
+ submitExternalInput(parts) {
1395
+ if (closed || sleeping || waking) throw new Error('Frontend session is unavailable')
1396
+ if (inputCollecting) throw new Error('External input is not ready')
1397
+ sleepController.recordActivity()
1398
+ inputs.submit({ parts })
1399
+ },
1156
1400
  setAssistantProfile(profile) {
1157
1401
  if (closed) return
1158
1402
  sessionAssistantProfile = String(profile || '').trim()
@@ -1172,9 +1416,12 @@ export function createRealtimeSessionRuntime({
1172
1416
  close() {
1173
1417
  if (closed) return
1174
1418
  closed = true
1419
+ realtimeEventListeners.clear()
1420
+ pendingProviderInputs.clear()
1175
1421
  toolScope.abort(new Error('Client disconnected'))
1176
1422
  releaseVoiceClient()
1177
1423
  taskCoordinator.close()
1424
+ nativeDelegations.close()
1178
1425
  unsubscribeMemory()
1179
1426
  clearResponseCandidate()
1180
1427
  turns.close()