qwen-audio-agent 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +6 -3
  2. package/README_ZH.md +6 -3
  3. package/cli/package.json +1 -1
  4. package/cli/src/config-command.mjs +33 -2
  5. package/cli/src/gateway-service.mjs +7 -1
  6. package/config/frontend-agent/LIVE_PROMPT.md +64 -0
  7. package/desktop/src/i18n.mjs +1 -1
  8. package/desktop/src/settings-config.mjs +10 -24
  9. package/docs/configuration/frontend.md +29 -12
  10. package/docs/configuration/frontend.zh.md +28 -12
  11. package/docs/contract.md +2 -0
  12. package/docs/contract.zh.md +2 -0
  13. package/docs/extensions.md +14 -0
  14. package/docs/extensions.zh.md +11 -0
  15. package/docs/getting-started/install.md +3 -0
  16. package/docs/getting-started/install.zh.md +3 -0
  17. package/docs/getting-started/mobile.md +8 -2
  18. package/docs/getting-started/mobile.zh.md +5 -0
  19. package/docs/guides/web-search.md +17 -1
  20. package/docs/guides/web-search.zh.md +15 -1
  21. package/docs/operations/troubleshooting.md +30 -0
  22. package/docs/operations/troubleshooting.zh.md +26 -0
  23. package/docs/voice-frontends/custom-provider.md +18 -3
  24. package/docs/voice-frontends/custom-provider.zh.md +18 -3
  25. package/docs/voice-frontends/google-live.md +7 -3
  26. package/docs/voice-frontends/google-live.zh.md +6 -3
  27. package/docs/voice-frontends/gpt-live-1.md +149 -0
  28. package/docs/voice-frontends/gpt-live-1.zh.md +114 -0
  29. package/docs/voice-frontends/{gpt-live.md → openai-realtime.md} +12 -5
  30. package/docs/voice-frontends/{gpt-live.zh.md → openai-realtime.zh.md} +11 -5
  31. package/docs/voice-frontends/qwen-audio-live.md +164 -0
  32. package/docs/voice-frontends/qwen-audio-live.zh.md +122 -0
  33. package/docs/voice-frontends/qwen-audio-realtime.md +2 -1
  34. package/docs/voice-frontends/qwen-audio-realtime.zh.md +2 -1
  35. package/docs/voice-frontends/qwen-omni-realtime.md +1 -1
  36. package/docs/voice-frontends/qwen-omni-realtime.zh.md +1 -1
  37. package/package.json +13 -4
  38. package/scripts/patch-build-node-gyp.mjs +63 -0
  39. package/scripts/prepare-build.mjs +2 -0
  40. package/scripts/verify-package.mjs +3 -0
  41. package/server/package.json +2 -2
  42. package/server/src/conversation/frontend-agent-context.mjs +18 -5
  43. package/server/src/core/citation.mjs +8 -2
  44. package/server/src/core/config.mjs +16 -5
  45. package/server/src/core/request-security.mjs +7 -1
  46. package/server/src/frontend/frontend-tools.mjs +14 -1
  47. package/server/src/frontend/retrieval/providers/bing.mjs +23 -12
  48. package/server/src/frontend/retrieval/providers/factory.mjs +9 -1
  49. package/server/src/frontend/retrieval/providers/mcp.mjs +17 -9
  50. package/server/src/frontend/retrieval/providers/so360.mjs +23 -12
  51. package/server/src/frontend/tools/agent-task-runtime.mjs +22 -4
  52. package/server/src/frontend/tools/tool-call-handler.mjs +56 -20
  53. package/server/src/memory/providers/markdown/context-store.mjs +3 -1
  54. package/server/src/orchestration/session-task-coordinator.mjs +4 -1
  55. package/server/src/orchestration/task-operations.mjs +5 -3
  56. package/server/src/orchestration/task-updates.mjs +2 -1
  57. package/server/src/transport/gateway-client-transport.mjs +19 -0
  58. package/server/src/transport/webrtc/protocol.mjs +1 -1
  59. package/server/src/voice/audio-stream-diagnostics.mjs +139 -0
  60. package/server/src/voice/native-delegation-runtime.mjs +360 -0
  61. package/server/src/voice/providers/dashscope-live.mjs +93 -0
  62. package/server/src/voice/providers/dashscope.mjs +12 -4
  63. package/server/src/voice/providers/doubao-seeduplex-protocol.mjs +54 -0
  64. package/server/src/voice/providers/doubao-seeduplex.mjs +6 -5
  65. package/server/src/voice/providers/ga-protocol.mjs +7 -2
  66. package/server/src/voice/providers/google-live-protocol.mjs +124 -34
  67. package/server/src/voice/providers/google-live.mjs +6 -5
  68. package/server/src/voice/providers/gpt-live-1-protocol.mjs +597 -0
  69. package/server/src/voice/providers/gpt-live-1.mjs +3 -0
  70. package/server/src/voice/providers/gpt-live-client-context.mjs +182 -0
  71. package/server/src/voice/providers/openai-live.mjs +150 -0
  72. package/server/src/voice/providers/{gpt-live.mjs → openai-realtime.mjs} +15 -14
  73. package/server/src/voice/providers/provider-registry.mjs +11 -1
  74. package/server/src/voice/providers/qwen-live-protocol.mjs +399 -0
  75. package/server/src/voice/providers/registry.mjs +45 -10
  76. package/server/src/voice/providers/runtime-configuration.mjs +17 -6
  77. package/server/src/voice/providers/stepfun.mjs +1 -1
  78. package/server/src/voice/realtime-input-runtime.mjs +56 -20
  79. package/server/src/voice/realtime-presentation-runtime.mjs +21 -4
  80. package/server/src/voice/realtime-provider-session.mjs +59 -14
  81. package/server/src/voice/realtime-provider.mjs +332 -36
  82. package/server/src/voice/realtime-session-runtime.mjs +207 -16
  83. package/server/src/voice/realtime-task-presentation.mjs +6 -2
  84. package/server/src/voice/realtime-turn-state.mjs +33 -2
  85. package/shared/gateway/client-sdk.mjs +15 -5
  86. package/shared/gateway/websocket-auth.mjs +2 -1
  87. package/shared/protocol/gateway-events.mjs +31 -0
  88. package/shared/realtime-legacy-environment.mjs +37 -8
  89. package/shared/realtime-model-catalog.mjs +12 -10
  90. package/shared/realtime-models/README.md +10 -2
  91. package/shared/realtime-models/dashscope.mjs +11 -0
  92. package/shared/realtime-models/{google-live.mjs → google.mjs} +1 -1
  93. package/shared/realtime-models/openai.mjs +24 -0
  94. package/shared/realtime-models/profile.mjs +6 -3
  95. package/shared/realtime-models/{doubao-seeduplex.mjs → volcengine.mjs} +1 -1
  96. package/shared/realtime-provider-catalog.mjs +7 -6
  97. package/shared/realtime-provider-definitions.mjs +87 -22
  98. package/shared/runtime-environment.mjs +2 -2
  99. package/shared/web-search-configuration.mjs +14 -2
  100. package/tui/package.json +2 -2
  101. package/tui/src/index.mjs +14 -9
  102. package/tui/src/runtime-configuration.mjs +2 -0
  103. package/tui/src/terminal-commands.mjs +40 -0
  104. package/tui/src/text-cli.mjs +10 -1
  105. package/web/dist/assets/index-Bc2Q04J9.css +1 -0
  106. package/web/dist/assets/index-bY4DFXKT.js +96 -0
  107. package/web/dist/index.html +2 -2
  108. package/shared/realtime-models/gpt-live.mjs +0 -10
  109. package/web/dist/assets/index-8erKDCr2.css +0 -1
  110. package/web/dist/assets/index-Cs4hYWbS.js +0 -96
@@ -0,0 +1,597 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { GptLiveClientContext, GPT_LIVE_DELEGATION_READY_EVENT } from './gpt-live-client-context.mjs'
3
+
4
+ function id(prefix) {
5
+ return `${prefix}_${randomUUID().replaceAll('-', '')}`
6
+ }
7
+
8
+ const responseCreated = (id, extra) => ({ type: 'response.created', response: { id, status: 'in_progress' }, response_id: id, ...extra })
9
+ const responseDone = (id, status, extra) => ({ type: 'response.done', response: { id, status }, response_id: id, ...extra })
10
+ const PLAYBACK = { __voicePlayback: true }
11
+
12
+ export function messageItem(role, text) {
13
+ return { type: 'message', role, content: [{ type: role === 'assistant' ? 'output_text' : 'input_text', text }] }
14
+ }
15
+
16
+ function textFromItem(item) {
17
+ return (Array.isArray(item?.content) ? item.content : [])
18
+ .map(part => String(part?.text || '').trim())
19
+ .filter(Boolean)
20
+ .join('\n')
21
+ .trim()
22
+ }
23
+
24
+ // The Live API marks no turn or answer boundaries; these provisional defaults
25
+ // (ms), from live sessions, place them. See GPT_LIVE_1_*_MS.
26
+ export const GPT_LIVE_1_TIMING_DEFAULTS = Object.freeze({
27
+ // An answer ends after this long without its speech or words.
28
+ outputIdleMs: 1500,
29
+ // A gap this long in the model's words begins a new answer; pauses between words are shorter.
30
+ wordGapMs: 600,
31
+ // A gap this long in the user's speech begins a new utterance.
32
+ inputSegmentGapMs: 1200,
33
+ // An utterance completes after this much quiet.
34
+ inputIdleMs: 2000,
35
+ })
36
+ // Output audio streams silence between answers; quieter frames are not speech.
37
+ const OUTPUT_SPEECH_RMS = 100
38
+ const INPUT_IDLE_EVENT = 'gpt-live-1.input_idle'
39
+ const OUTPUT_IDLE_EVENT = 'gpt-live-1.output_idle'
40
+ // A sentence's closing punctuation can arrive with the next fragment.
41
+ const LEADING_PUNCTUATION_RE = /^[[\s\p{Pe}\p{Pf}\p{Po}]--[¡¿'"#%&*\/@\\]]+/v
42
+ // "[clear throat]"-style annotations are not speech; a short unclosed one waits.
43
+ const NON_SPEECH_TAG_RE = /\[[^[\]]*\]/g
44
+ const OPEN_TAG_RE = /\[[^[\]]{0,24}$/
45
+ // An appended instruction is how the Live API stops speech in progress. It stays in
46
+ // the session, so it names the cut reply only: the user can still ask for it again.
47
+ const STOP_SPEAKING = Object.freeze({
48
+ type: 'session.instructions.append',
49
+ delegation_id: null,
50
+ content: 'Stop speaking now and drop the reply you were giving. This applies to that reply only: if the user asks for it again, give it.',
51
+ })
52
+ // Punctuation and spaces are not speech.
53
+ const hasWords = text => /[\p{L}\p{N}]/u.test(String(text || ''))
54
+
55
+ function leadingPunctuation(text) {
56
+ return (String(text || '').match(LEADING_PUNCTUATION_RE)?.[0] || '').trim()
57
+ }
58
+
59
+ // What the user said, without annotations or the previous sentence's close.
60
+ function spokenInputText(raw) {
61
+ return String(raw || '')
62
+ .replace(NON_SPEECH_TAG_RE, '')
63
+ .replace(OPEN_TAG_RE, '')
64
+ .replace(LEADING_PUNCTUATION_RE, '')
65
+ }
66
+
67
+ // The caption keeps fragments as received, less the previous sentence's close.
68
+ function userCaption(raw) {
69
+ return String(raw || '').replace(LEADING_PUNCTUATION_RE, '')
70
+ }
71
+
72
+ // Append events accept at most 500 tokens. A UTF-8 byte bound is conservative
73
+ // for byte-based tokenizers even for emoji or punctuation-heavy tool output,
74
+ // unlike a characters-per-token estimate. Full results remain in the Task/UI.
75
+ const COMMENTARY_MAX_BYTES = 480
76
+
77
+ const tokenWeight = char => (char.codePointAt(0) > 0x7f ? 1 : 0.25)
78
+
79
+ export function estimateTokens(text) {
80
+ let tokens = 0
81
+ for (const char of String(text || '')) tokens += tokenWeight(char)
82
+ return Math.ceil(tokens)
83
+ }
84
+
85
+ export function clampCommentary(text) {
86
+ const value = String(text || '').trim()
87
+ if (Buffer.byteLength(value, 'utf8') <= COMMENTARY_MAX_BYTES) return value
88
+ let end = 0
89
+ let bytes = 0
90
+ for (const char of value) {
91
+ bytes += Buffer.byteLength(char, 'utf8')
92
+ if (bytes > COMMENTARY_MAX_BYTES - 3) break
93
+ end += char.length
94
+ }
95
+ return `${value.slice(0, end)}…`
96
+ }
97
+
98
+ // A form's envelope title may be generic (e.g. "Answer Questions"). Preserve
99
+ // the actual questions before that title within Live's short context budget.
100
+ // These are request facts; interaction rules belong in LIVE_PROMPT.md.
101
+ function inputRequestText(request) {
102
+ if (request.kind === 'permission') {
103
+ return `Permission pending; explicit client confirmation required.\n${String(request.prompt || '')}`
104
+ }
105
+ const properties = request.schema?.properties
106
+ const questions = properties && typeof properties === 'object'
107
+ ? Object.entries(properties).slice(0, 32).map(([name, field]) => {
108
+ const question = String(field?.description || field?.title || name).replace(/\s+/g, ' ').trim()
109
+ const choices = Array.isArray(field?.oneOf)
110
+ ? field.oneOf.map(option => option?.title ?? option?.const)
111
+ : Array.isArray(field?.enum) ? field.enum : []
112
+ const options = choices.filter(value => value != null).slice(0, 32).map(String)
113
+ return [question, ...(options.length ? [`Options: ${options.join(' / ')}`] : [])].join('\n')
114
+ })
115
+ : []
116
+ return [
117
+ 'User input pending; task not completed. Response via client controls required.',
118
+ ...questions,
119
+ String(request.prompt || ''),
120
+ ].filter(Boolean).join('\n')
121
+ }
122
+
123
+ // Maps the full-duplex Live API, which has no response or turn boundaries, onto
124
+ // Gateway playback segments. Native delegated work has its own task lifecycle.
125
+ export function createGptLive1Protocol({
126
+ emit,
127
+ outputIdleMs = GPT_LIVE_1_TIMING_DEFAULTS.outputIdleMs,
128
+ wordGapMs = GPT_LIVE_1_TIMING_DEFAULTS.wordGapMs,
129
+ inputSegmentGapMs = GPT_LIVE_1_TIMING_DEFAULTS.inputSegmentGapMs,
130
+ inputIdleMs = GPT_LIVE_1_TIMING_DEFAULTS.inputIdleMs,
131
+ onStartupError = null,
132
+ delegationSettleMs,
133
+ delegationWaitMs,
134
+ } = {}) {
135
+ const clientContext = new GptLiveClientContext({ emit, settleMs: delegationSettleMs, waitMs: delegationWaitMs })
136
+ let voiceResponseId = ''
137
+ // Session-timeline start of the current or last answer (output audio is untimed).
138
+ let answerStartMs = NaN
139
+ // Whether an answer began since the current user item opened.
140
+ let answeredSinceInput = false
141
+ // The user interrupted the playing answer, which plays out: the model yields,
142
+ // and only speech it had already generated follows.
143
+ let yielding = false
144
+ // An utterance began over an answer whose words have not come: their timing tells its question from a barge-in.
145
+ let undecided = false
146
+ let utteranceStartMs = NaN
147
+ // A stop waits for the playing answer to play out; then the voice stays silent until the user's next input.
148
+ let stopAfter = false
149
+ let stopped = false
150
+ // The model spoke while stopped and has not been quiet since: once the stop ends, that speech
151
+ // plays on as an interrupted answer.
152
+ let spokeWhileStopped = false
153
+ // Session-timeline end of the model's last words.
154
+ let lastCaptionEndMs = NaN
155
+ // The current answer's transcript so far.
156
+ let voiceTranscript = ''
157
+ let inputItemId = ''
158
+ let lastInputEndMs = -Infinity
159
+ // The current utterance's fragments as delivered.
160
+ let inputRaw = ''
161
+ // Fresh fragments with no spoken word yet; they open a turn once a word arrives.
162
+ let pendingInputRaw = ''
163
+ // The user turn commits when the answer starts or input goes idle.
164
+ let inputCommitted = false
165
+ // Set once session.started arrives; command errors before that fail startup.
166
+ let started = false
167
+ // The session.start payload, for onStartupError.
168
+ let lastStartSession = null
169
+
170
+ // Re-armed on every fragment; fires once the service has been quiet.
171
+ const idleTimer = (type, ms) => {
172
+ let timer = null
173
+ return {
174
+ clear: () => clearTimeout(timer),
175
+ arm: () => {
176
+ if (typeof emit !== 'function' || !(ms > 0)) return
177
+ clearTimeout(timer)
178
+ timer = setTimeout(() => emit({ type }), ms)
179
+ timer.unref?.()
180
+ },
181
+ }
182
+ }
183
+ const outputIdle = idleTimer(OUTPUT_IDLE_EVENT, outputIdleMs)
184
+ const inputIdle = idleTimer(INPUT_IDLE_EVENT, inputIdleMs)
185
+
186
+ const openVoiceResponse = (events, startMs = NaN) => {
187
+ if (voiceResponseId) {
188
+ if (!Number.isFinite(answerStartMs) && Number.isFinite(startMs)) answerStartMs = startMs
189
+ return voiceResponseId
190
+ }
191
+ voiceResponseId = id('voice')
192
+ voiceTranscript = ''
193
+ answerStartMs = Number.isFinite(startMs) ? startMs : NaN
194
+ answeredSinceInput = true
195
+ // The model's own speech, never the answer to a queued Gateway request.
196
+ events.push(responseCreated(voiceResponseId, { ...PLAYBACK, __voiceAutomatic: true }))
197
+ return voiceResponseId
198
+ }
199
+
200
+ // Transcript first, as on GA. A stop waiting on the answer takes effect as it closes.
201
+ const finishVoiceResponse = (events, status = 'completed') => {
202
+ outputIdle.clear()
203
+ if (!voiceResponseId) return events
204
+ const transcript = voiceTranscript.trim()
205
+ if (transcript) {
206
+ events.push({
207
+ type: 'response.output_audio_transcript.done',
208
+ response_id: voiceResponseId,
209
+ transcript,
210
+ })
211
+ }
212
+ events.push(responseDone(voiceResponseId, status, PLAYBACK))
213
+ if (stopAfter) stopped = true
214
+ voiceResponseId = ''
215
+ voiceTranscript = ''
216
+ yielding = stopAfter = undecided = false
217
+ return events
218
+ }
219
+
220
+ // A question whose words came after its answer began: from here on the answer is its reply,
221
+ // unless an interruption already has it playing out.
222
+ const answerLateQuestion = events => {
223
+ commitInput(events)
224
+ if (!yielding && !stopAfter) finishVoiceResponse(events)
225
+ }
226
+
227
+ // The user's next input ends a stop, and one still waiting on the playing answer.
228
+ const resume = () => {
229
+ stopped = stopAfter = false
230
+ }
231
+
232
+ // Speech under way when a stop ended plays on as an interrupted answer: it leaves
233
+ // the user's turn to the reply, and closes as the model's next words begin.
234
+ const resumeSpeech = () => {
235
+ if (!spokeWhileStopped || voiceResponseId) return
236
+ spokeWhileStopped = false
237
+ yielding = true
238
+ }
239
+
240
+ // Energy of one PCM16 frame (little-endian samples in the base64 delta).
241
+ const isSpeechFrame = delta => {
242
+ const bytes = Buffer.from(String(delta || ''), 'base64')
243
+ const samples = bytes.length >> 1
244
+ if (!samples) return false
245
+ let energy = 0
246
+ for (let i = 0; i < samples; i++) {
247
+ const sample = bytes.readInt16LE(i * 2)
248
+ energy += sample * sample
249
+ }
250
+ return Math.sqrt(energy / samples) >= OUTPUT_SPEECH_RMS
251
+ }
252
+
253
+ // Ends the user's turn (GA order: speech_stopped, committed); the transcript
254
+ // keeps streaming into the committed item.
255
+ const commitInput = events => {
256
+ if (!inputItemId || inputCommitted) return
257
+ inputCommitted = true
258
+ events.push({ type: 'input_audio_buffer.speech_stopped', item_id: inputItemId })
259
+ events.push({ type: 'input_audio_buffer.committed', item_id: inputItemId })
260
+ }
261
+
262
+ const completeInput = events => {
263
+ inputIdle.clear()
264
+ if (!inputItemId) return events
265
+ commitInput(events)
266
+ events.push({
267
+ type: 'conversation.item.input_audio_transcription.completed',
268
+ item_id: inputItemId,
269
+ transcript: userCaption(inputRaw).trim(),
270
+ })
271
+ inputItemId = ''
272
+ inputRaw = ''
273
+ inputCommitted = false
274
+ return events
275
+ }
276
+
277
+ // Only a rejected response command concerns the request waiting on it; any
278
+ // other error gets its own id and settles nothing else.
279
+ const commandError = (error, clientEventId, eventId) => {
280
+ if (!started) return { type: 'error', error }
281
+ return { type: 'error', error, requestId: clientEventId,
282
+ response_id: `gpt-live-1:command:${clientEventId || eventId || id('error')}` }
283
+ }
284
+
285
+ const normalizeEvent = event => {
286
+ switch (event?.type) {
287
+ case 'session.started':
288
+ started = true
289
+ clientContext.sessionId = event.session?.id || ''
290
+ return { type: 'session.created', session: { id: event.session?.id || null } }
291
+
292
+ // Acknowledgements only.
293
+ case 'session.updated':
294
+ case 'session.usage.updated':
295
+ case 'session.input_audio.muted':
296
+ case 'session.input_audio.unmuted':
297
+ return []
298
+
299
+ case 'session.thinking.appended':
300
+ case 'session.instructions.appended':
301
+ case 'session.commentary.appended':
302
+ return event.client_event_id
303
+ ? [{ type: 'delegation.update.acknowledged', requestId: event.client_event_id }] : []
304
+
305
+ case 'session.output_audio.delta': {
306
+ const events = []
307
+ const speech = isSpeechFrame(event.delta)
308
+ // Silence between answers is not output; inside an answer it is a pause that plays through.
309
+ if (!speech && !voiceResponseId) return events
310
+ if (stopped) {
311
+ if (speech) {
312
+ spokeWhileStopped = true
313
+ outputIdle.arm()
314
+ // Silent, yet the model answered: the user's next words start a turn.
315
+ if (!answeredSinceInput) {
316
+ answeredSinceInput = true
317
+ answerStartMs = NaN
318
+ }
319
+ }
320
+ return events
321
+ }
322
+ resumeSpeech()
323
+ // An answer starting ends the user's turn; one playing out after an
324
+ // interruption, or not yet known to answer it, leaves it to the reply.
325
+ if (speech && !yielding && !undecided) commitInput(events)
326
+ const responseId = openVoiceResponse(events)
327
+ events.push({
328
+ type: 'response.output_audio.delta',
329
+ response_id: responseId,
330
+ delta: event.delta || '',
331
+ })
332
+ if (speech) outputIdle.arm()
333
+ return events
334
+ }
335
+
336
+ case 'session.output_transcript.delta': {
337
+ const events = []
338
+ const fragment = String(event.delta || '')
339
+ const startMs = Number(event.start_ms)
340
+ const afterPause = Number.isFinite(startMs) && !(startMs - lastCaptionEndMs < wordGapMs)
341
+ lastCaptionEndMs = Number.isFinite(Number(event.end_ms)) ? Number(event.end_ms) : startMs
342
+ // The answer's first words date it: an utterance begun over it before them is its question.
343
+ if (undecided && voiceResponseId && !hasWords(voiceTranscript) && hasWords(fragment)) {
344
+ undecided = false
345
+ // Words the service did not time cannot tell: the answer replies to the utterance.
346
+ if (!(utteranceStartMs >= startMs)) answerLateQuestion(events)
347
+ else yielding = true
348
+ }
349
+ // After a spoken or typed interruption, words after a pause in the playing
350
+ // answer's words are the model's next answer, and that one closes; words
351
+ // running on are its own. A stopped answer plays out until the model is quiet.
352
+ if (yielding && !stopAfter && voiceTranscript.trim() && afterPause && hasWords(fragment)) finishVoiceResponse(events)
353
+ // After a stop, nothing the model says shows until the stop ends.
354
+ if (stopped) {
355
+ if (hasWords(fragment)) spokeWhileStopped = true
356
+ outputIdle.arm()
357
+ return events
358
+ }
359
+ // No answer begins with the previous one's closing punctuation.
360
+ const delta = voiceTranscript.trim() ? fragment : fragment.replace(LEADING_PUNCTUATION_RE, '')
361
+ if (!delta) return events
362
+ resumeSpeech()
363
+ if (!yielding && !undecided) commitInput(events)
364
+ const responseId = openVoiceResponse(events, startMs)
365
+ voiceTranscript += delta
366
+ events.push({
367
+ type: 'response.output_audio_transcript.delta',
368
+ response_id: responseId,
369
+ delta,
370
+ })
371
+ outputIdle.arm()
372
+ return events
373
+ }
374
+
375
+ case OUTPUT_IDLE_EVENT:
376
+ spokeWhileStopped = false
377
+ return finishVoiceResponse([])
378
+
379
+ case 'session.input_transcript.delta': {
380
+ const events = []
381
+ const startMs = Number(event.start_ms)
382
+ const endMs = Number(event.end_ms)
383
+ // A timeline jump is fresh speech; a late fragment continuing it is not.
384
+ const timelineGap = !Number.isFinite(lastInputEndMs)
385
+ || !Number.isFinite(startMs)
386
+ || startMs - lastInputEndMs > inputSegmentGapMs
387
+ // Speech after the answer began is a barge-in; a late fragment from before it belongs to the question.
388
+ const afterAnswer = Number.isFinite(answerStartMs) && Number.isFinite(startMs)
389
+ ? startMs > answerStartMs
390
+ : answeredSinceInput
391
+ // Fresh speech begins an utterance after an answer began, or with none open.
392
+ const freshTurn = timelineGap && (afterAnswer || !inputItemId)
393
+ let fragment = String(event.delta || '')
394
+ if (inputItemId && freshTurn) {
395
+ // The punctuation after the pause closes this utterance.
396
+ inputRaw += leadingPunctuation(fragment)
397
+ completeInput(events)
398
+ }
399
+ if (Number.isFinite(endMs)) lastInputEndMs = Math.max(lastInputEndMs, endMs)
400
+ else if (Number.isFinite(startMs)) lastInputEndMs = Math.max(lastInputEndMs, startMs)
401
+ const continuesPending = Boolean(pendingInputRaw) && !timelineGap
402
+ // Late words of a final utterance change nothing and start no turn.
403
+ if (!inputItemId && !continuesPending && !freshTurn) return events
404
+ // Any other words end a stop, even ones that continue the utterance.
405
+ if (spokenInputText(fragment)) resume()
406
+ // A question whose words all came after its answer began is already answered.
407
+ let answered = false
408
+ if (!inputItemId) {
409
+ // Only fresh speech holding a word opens a turn.
410
+ pendingInputRaw = (continuesPending ? pendingInputRaw : '') + fragment
411
+ if (!spokenInputText(pendingInputRaw)) return events
412
+ // Over an answer whose words have not come, they tell question from barge-in.
413
+ undecided = Boolean(voiceResponseId) && !Number.isFinite(answerStartMs) && Number.isFinite(startMs)
414
+ utteranceStartMs = startMs
415
+ // A barge-in: the model hears it and yields, what it already said playing out.
416
+ if (!undecided && afterAnswer && voiceResponseId) yielding = true
417
+ answered = !undecided && !afterAnswer && answeredSinceInput
418
+ inputItemId = id('input')
419
+ inputRaw = ''
420
+ inputCommitted = false
421
+ answeredSinceInput = false
422
+ fragment = pendingInputRaw
423
+ pendingInputRaw = ''
424
+ events.push({
425
+ type: 'input_audio_buffer.speech_started',
426
+ item_id: inputItemId,
427
+ })
428
+ }
429
+ const shown = userCaption(inputRaw)
430
+ inputRaw += fragment
431
+ const caption = userCaption(inputRaw)
432
+ // `text` is the whole caption so far, which the runtime shows live.
433
+ events.push({
434
+ type: 'conversation.item.input_audio_transcription.delta',
435
+ item_id: inputItemId,
436
+ delta: caption.startsWith(shown) ? caption.slice(shown.length) : fragment,
437
+ text: caption,
438
+ })
439
+ inputIdle.arm()
440
+ if (answered) answerLateQuestion(events)
441
+ return events
442
+ }
443
+
444
+ case INPUT_IDLE_EVENT:
445
+ return completeInput([])
446
+
447
+ // Wait briefly for transcript fragments that lag the delegation metadata.
448
+ case 'session.delegation.created': {
449
+ if (event.delegation?.target !== 'client') return []
450
+ const events = []
451
+ commitInput(events)
452
+ clientContext.receive(event)
453
+ return events
454
+ }
455
+
456
+ case GPT_LIVE_DELEGATION_READY_EVENT:
457
+ return clientContext.take(event)
458
+
459
+ // A Client session never invokes the hosted Responses tool loop.
460
+ case 'response.event':
461
+ return []
462
+
463
+ case 'session.closed': {
464
+ const events = []
465
+ pendingInputRaw = ''
466
+ clientContext.close()
467
+ completeInput(events)
468
+ // Closed for content (other moderation only cuts speech): the answer is
469
+ // not kept, and the runtime recovers without reseeding that history.
470
+ const content = String(event.reason || '') === 'content'
471
+ finishVoiceResponse(events, content ? 'incomplete' : 'completed')
472
+ if (content) {
473
+ events.push({
474
+ type: 'error',
475
+ error: { type: 'session_closed', code: 'content', message: 'GPT-Live 1 session closed by the service for content' },
476
+ })
477
+ }
478
+ return events
479
+ }
480
+
481
+ case 'error': {
482
+ const error = event.error || { message: 'GPT-Live 1 error' }
483
+ const clientEventId = String(error.client_event_id || event.client_event_id || '')
484
+ if (!started) onStartupError?.(error, { session: lastStartSession })
485
+ return commandError(error, clientEventId, event.event_id)
486
+ }
487
+
488
+ default:
489
+ // Only documented Live events become common Gateway events. In
490
+ // particular, raw response/function/delegation events cannot bypass
491
+ // this adapter's Client-mode ownership and transcript correlation.
492
+ return []
493
+ }
494
+ }
495
+
496
+ return Object.freeze({
497
+ encodeOutgoing: payload => {
498
+ if (payload == null) return null
499
+ const encoded = { event_id: id('event'), ...payload }
500
+ const { type } = payload
501
+ if (type.startsWith('response.')) return null
502
+ if (type === 'session.commentary.append') {
503
+ resume()
504
+ }
505
+ return encoded
506
+ },
507
+
508
+ normalizeIncoming: event => {
509
+ // The runtime's private markers (__voicePlayback, ...) are set by this adapter only.
510
+ for (const key of Object.keys(event ?? {})) if (key.startsWith('__')) delete event[key]
511
+ const normalized = normalizeEvent(event)
512
+ if (event?.type === 'session.input_transcript.delta') {
513
+ const input = [].concat(normalized ?? []).find(item => item.type === 'conversation.item.input_audio_transcription.delta')
514
+ clientContext.record(event, input?.item_id)
515
+ } else if (event?.type === 'session.output_transcript.delta') {
516
+ clientContext.record(event)
517
+ }
518
+ return normalized
519
+ },
520
+
521
+ // Sent before encodeOutgoing applies, so the id is stamped here.
522
+ connectionMessages: ({ session }) => {
523
+ lastStartSession = session ?? null
524
+ clientContext.seed(session?.input)
525
+ return [{ type: 'session.start', event_id: id('event'), session }]
526
+ },
527
+
528
+ sessionUpdate: () => null,
529
+
530
+ sessionClose: () => {
531
+ clientContext.close()
532
+ inputIdle.clear()
533
+ outputIdle.clear()
534
+ return { type: 'session.close' }
535
+ },
536
+
537
+ audioAppend: audio => ({ type: 'session.input_audio.append', audio }),
538
+
539
+ inputMute: () => ({ type: 'session.input_audio.mute' }),
540
+ inputUnmute: () => ({ type: 'session.input_audio.unmute' }),
541
+
542
+ imageAppend: () => null,
543
+
544
+ conversationItemId: () => id('item'),
545
+
546
+ // Typed work is executed locally; this is only a quiet context mirror.
547
+ conversationItemCreate: item => {
548
+ if (item?.type !== 'message') return null
549
+ const text = textFromItem(item)
550
+ if (text) clientContext.rememberContext(item.role === 'assistant' ? 'assistant' : 'user', text)
551
+ return text ? { type: 'session.thinking.append', delegation_id: null,
552
+ content: clampCommentary(`Application context (not a new delegation): ${text}`) } : null
553
+ },
554
+
555
+ responseInstructionsItem: () => null,
556
+
557
+ // Client mode has no response.create command or remotely hosted tool loop.
558
+ responseCreate: () => null,
559
+
560
+ delegationUpdate: ({ delegationId = null, kind, content, request } = {}) => {
561
+ const text = request ? inputRequestText(request) : String(content || '')
562
+ if (text) clientContext.rememberContext('application', text)
563
+ return { type: kind === 'progress' ? 'session.thinking.append' : 'session.commentary.append',
564
+ delegation_id: delegationId, content: clampCommentary(text) }
565
+ },
566
+
567
+ correlateResponseCreate: payload => payload,
568
+ responseCorrelationId: () => '',
569
+
570
+ // The Live API has no response cancel; backend responses keep running.
571
+ responseCancel: () => null,
572
+
573
+ // Every interruption lets the playing answer play out: the model yields, and
574
+ // only speech it had already generated follows. The model hears a spoken
575
+ // barge-in; typed input and a stop tell it to stop speaking. After a stop the
576
+ // voice stays silent until user input, an announcement or a commentary.
577
+ interruptPlayback: ({ stop = false, speech = false } = {}) => {
578
+ // The adapter saw the barge-in itself and let the answer play out.
579
+ if (speech && !stop) return null
580
+ const playing = Boolean(voiceResponseId)
581
+ if (playing) yielding = true
582
+ if (stop) {
583
+ if (playing) stopAfter = true
584
+ else stopped = true
585
+ return STOP_SPEAKING
586
+ }
587
+ // Typed input over speech, heard or kept silent by a stop, stops it too.
588
+ const speaking = playing || spokeWhileStopped
589
+ resume()
590
+ return speaking ? STOP_SPEAKING : null
591
+ },
592
+
593
+ userTextItem: text => messageItem('user', text),
594
+
595
+ functionOutputItem: () => null,
596
+ })
597
+ }
@@ -0,0 +1,3 @@
1
+ // Compatibility export for integrations importing the previous adapter name.
2
+ export { openaiLiveProvider as gptLive1Provider } from './openai-live.mjs'
3
+ export { sessionInputHistory } from './openai-live.mjs'