qwen-audio-agent 0.9.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/CONTRIBUTING.md +58 -0
- package/LICENSE +201 -0
- package/NOTICE +5 -0
- package/PRIVACY.md +34 -0
- package/README.md +282 -0
- package/README_EN.md +316 -0
- package/SECURITY.md +32 -0
- package/THIRD_PARTY_NOTICES.md +26 -0
- package/cli/bin/qwenaudio.mjs +10 -0
- package/cli/package.json +13 -0
- package/cli/src/arguments.mjs +247 -0
- package/cli/src/gateway-service.mjs +386 -0
- package/cli/src/instance-lock.mjs +65 -0
- package/cli/src/launcher.mjs +217 -0
- package/cli/src/runtime.mjs +356 -0
- package/cli/src/webui.mjs +61 -0
- package/config/acp/workspace/AGENTS.md +13 -0
- package/config/codebuddy/workspace/.codebuddy/models.json +19 -0
- package/config/codebuddy/workspace/AGENTS.md +13 -0
- package/config/codex/workspace/AGENTS.md +13 -0
- package/config/frontend-agent/PROMPT.md +127 -0
- package/config/hermes/workspace/AGENTS.md +13 -0
- package/config/openclaw/openclaw.json5 +50 -0
- package/config/openclaw/workspace/AGENTS.md +9 -0
- package/config/opencode/agents/qwen-audio-agent-backend.md +65 -0
- package/config/opencode/workspace/AGENTS.md +16 -0
- package/config/qoder/workspace/AGENTS.md +16 -0
- package/docs/architecture-overview-en.png +0 -0
- package/docs/architecture-overview.png +0 -0
- package/docs/architecture.md +332 -0
- package/docs/configuration.md +386 -0
- package/docs/desktop-fluid-orb-thinking.gif +0 -0
- package/docs/desktop-goo-orb-thinking.gif +0 -0
- package/docs/qwen-audio-agent-three-layer-architecture-en.png +0 -0
- package/docs/qwen-audio-agent-three-layer-architecture.png +0 -0
- package/package.json +126 -0
- package/scripts/audit-dependencies.mjs +109 -0
- package/scripts/check-desktop-release-env.mjs +41 -0
- package/scripts/codex-acp +58 -0
- package/scripts/install-global.mjs +66 -0
- package/scripts/openclaw +194 -0
- package/scripts/openclaw-gateway +8 -0
- package/scripts/opencode-acp +6 -0
- package/scripts/opencode-server +179 -0
- package/scripts/prepare-build.mjs +38 -0
- package/scripts/release-check +182 -0
- package/scripts/set-version.mjs +133 -0
- package/scripts/start.mjs +43 -0
- package/scripts/verify-package.mjs +109 -0
- package/server/package.json +18 -0
- package/server/src/agent/acp-backend-adapter.mjs +1138 -0
- package/server/src/agent/acp-backend-profile.mjs +35 -0
- package/server/src/agent/acp-backend-session-utils.mjs +139 -0
- package/server/src/agent/acp-process-client.mjs +447 -0
- package/server/src/agent/acp-session-registry.mjs +106 -0
- package/server/src/agent/acp-session-tools.mjs +257 -0
- package/server/src/agent/agent-client.mjs +218 -0
- package/server/src/agent/backend-adapter.mjs +15 -0
- package/server/src/agent/backend-agent-instructions.mjs +8 -0
- package/server/src/agent/backends/codebuddy.mjs +47 -0
- package/server/src/agent/backends/codex.mjs +62 -0
- package/server/src/agent/backends/generic-acp.mjs +46 -0
- package/server/src/agent/backends/hermes.mjs +29 -0
- package/server/src/agent/backends/openclaw.mjs +101 -0
- package/server/src/agent/backends/opencode.mjs +36 -0
- package/server/src/agent/backends/qoder.mjs +47 -0
- package/server/src/agent/backends/registry.mjs +32 -0
- package/server/src/agent/backends/shared.mjs +46 -0
- package/server/src/agent/coordinator.mjs +308 -0
- package/server/src/agent/openclaw-adapter.mjs +245 -0
- package/server/src/app/bootstrap.mjs +244 -0
- package/server/src/conversation/conversation-sync.mjs +183 -0
- package/server/src/conversation/frontend-agent-context.mjs +162 -0
- package/server/src/conversation/frontend-memory.mjs +328 -0
- package/server/src/conversation/profiled-memory-store.mjs +87 -0
- package/server/src/conversation/task-result-projector.mjs +18 -0
- package/server/src/conversation/user-profile.mjs +234 -0
- package/server/src/core/config.mjs +388 -0
- package/server/src/core/identity.mjs +93 -0
- package/server/src/core/install-paths.mjs +8 -0
- package/server/src/core/package-version.mjs +10 -0
- package/server/src/core/request-security.mjs +80 -0
- package/server/src/index.mjs +67 -0
- package/server/src/process/backend-drivers/codebuddy.mjs +15 -0
- package/server/src/process/backend-drivers/codex.mjs +15 -0
- package/server/src/process/backend-drivers/generic-acp.mjs +18 -0
- package/server/src/process/backend-drivers/hermes.mjs +15 -0
- package/server/src/process/backend-drivers/openclaw.mjs +35 -0
- package/server/src/process/backend-drivers/opencode.mjs +75 -0
- package/server/src/process/backend-drivers/qoder.mjs +15 -0
- package/server/src/process/backend-drivers/registry.mjs +24 -0
- package/server/src/process/backend-drivers/shared.mjs +46 -0
- package/server/src/process/managed-backend.mjs +188 -0
- package/server/src/task/task-manager.mjs +704 -0
- package/server/src/task/task-scheduler.mjs +44 -0
- package/server/src/task/task-store.mjs +167 -0
- package/server/src/voice/active-voice-clients.mjs +58 -0
- package/server/src/voice/announcement/announcement-manager.mjs +402 -0
- package/server/src/voice/announcement/announcement-window.mjs +89 -0
- package/server/src/voice/input-transcript.mjs +9 -0
- package/server/src/voice/realtime-errors.mjs +6 -0
- package/server/src/voice/realtime-gateway.mjs +1366 -0
- package/server/src/voice/realtime-provider.mjs +771 -0
- package/server/src/voice/reconnect-backoff.mjs +30 -0
- package/server/src/voice/response-context.mjs +41 -0
- package/server/src/voice/session-permission-policy.mjs +56 -0
- package/server/src/voice/tools/tool-call-handler.mjs +823 -0
- package/server/src/voice/tools/turn-transcripts.mjs +59 -0
- package/server/src/voice/turn-correlation.mjs +41 -0
- package/shared/backend-catalog.mjs +56 -0
- package/shared/gateway-client.mjs +13 -0
- package/shared/realtime-events.mjs +55 -0
- package/shared/runtime-environment.mjs +422 -0
- package/tui/native/macos-voice-io.swift +552 -0
- package/tui/native/portaudio-voice-io.py +240 -0
- package/tui/package.json +13 -0
- package/tui/src/index.mjs +1217 -0
- package/tui/src/macos-voice-io.mjs +186 -0
- package/tui/src/portaudio-voice-io.mjs +158 -0
- package/web/dist/assets/index-BeamDvsE.js +38 -0
- package/web/dist/assets/index-BuB0EFih.css +1 -0
- package/web/dist/index.html +14 -0
|
@@ -0,0 +1,1366 @@
|
|
|
1
|
+
import { WebSocket, WebSocketServer } from 'ws'
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import {
|
|
4
|
+
GatewayClientEvent,
|
|
5
|
+
GatewayServerEvent,
|
|
6
|
+
} from '../../../shared/realtime-events.mjs'
|
|
7
|
+
import { AnnouncementManager } from './announcement/announcement-manager.mjs'
|
|
8
|
+
import { AnnouncementWindow } from './announcement/announcement-window.mjs'
|
|
9
|
+
import { config } from '../core/config.mjs'
|
|
10
|
+
import { conversationSync } from '../conversation/conversation-sync.mjs'
|
|
11
|
+
import { normalizeClientContext } from '../conversation/frontend-agent-context.mjs'
|
|
12
|
+
import { createRealtimeFrontend } from './realtime-provider.mjs'
|
|
13
|
+
import { isAllowedOrigin } from '../core/request-security.mjs'
|
|
14
|
+
import { taskManager } from '../task/task-manager.mjs'
|
|
15
|
+
import { recordTaskResult } from '../conversation/task-result-projector.mjs'
|
|
16
|
+
import { ToolCallHandler } from './tools/tool-call-handler.mjs'
|
|
17
|
+
import { TurnTranscripts } from './tools/turn-transcripts.mjs'
|
|
18
|
+
import { TurnCorrelation } from './turn-correlation.mjs'
|
|
19
|
+
import { streamingInputTranscript } from './input-transcript.mjs'
|
|
20
|
+
import {
|
|
21
|
+
ensureResponseContext,
|
|
22
|
+
mergeResponseContext,
|
|
23
|
+
} from './response-context.mjs'
|
|
24
|
+
import {
|
|
25
|
+
ActiveVoiceClients,
|
|
26
|
+
clientVoiceCapabilities,
|
|
27
|
+
} from './active-voice-clients.mjs'
|
|
28
|
+
import { isRecoverableRealtimeInactivityError } from './realtime-errors.mjs'
|
|
29
|
+
import { ReconnectBackoff } from './reconnect-backoff.mjs'
|
|
30
|
+
|
|
31
|
+
const MAX_PENDING_AUDIO_CHUNKS = 30
|
|
32
|
+
const RESPONSE_START_WATCHDOG_MS = 12000
|
|
33
|
+
const PERMISSION_RESPONSE_GRACE_MS = 800
|
|
34
|
+
const RESPONSE_CONTEXT_CLEANUP_MS = 30000
|
|
35
|
+
const REALTIME_STABLE_CONNECTION_MS = 10000
|
|
36
|
+
|
|
37
|
+
function send(ws, event) {
|
|
38
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(event))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function responseId(event) {
|
|
42
|
+
return event.response_id || event.response?.id || event.item?.response_id || ''
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function rejectUpgrade(socket, status, message) {
|
|
46
|
+
socket.write(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Type: text/plain\r\n\r\n${message}`)
|
|
47
|
+
socket.destroy()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function rejectUnsupportedRealtimeUpgrade(socket, pathname) {
|
|
51
|
+
if (pathname === '/api/realtime') return false
|
|
52
|
+
socket.destroy()
|
|
53
|
+
return true
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function clientDescriptor(event = {}) {
|
|
57
|
+
const type = ['desktop', 'cli', 'web'].includes(event.clientType)
|
|
58
|
+
? event.clientType
|
|
59
|
+
: 'web'
|
|
60
|
+
const label = String(event.clientLabel || '').trim().slice(0, 40)
|
|
61
|
+
return {
|
|
62
|
+
type,
|
|
63
|
+
...(label ? { label } : {}),
|
|
64
|
+
instanceId: String(event.clientInstanceId || '').trim().slice(0, 80) || null,
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function attachRealtimeGateway(server, {
|
|
69
|
+
identityManager,
|
|
70
|
+
memoryStore,
|
|
71
|
+
coordinator,
|
|
72
|
+
coordinatorAvailable = async () => true,
|
|
73
|
+
respondPermission,
|
|
74
|
+
permissionPolicy,
|
|
75
|
+
}) {
|
|
76
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: 2 * 1024 * 1024 })
|
|
77
|
+
const activeVoiceClients = new ActiveVoiceClients()
|
|
78
|
+
const voiceConnections = new Map()
|
|
79
|
+
|
|
80
|
+
const broadcastVoiceOwnership = ownerId => {
|
|
81
|
+
const active = activeVoiceClients.active(ownerId)
|
|
82
|
+
const holder = active?.descriptor || null
|
|
83
|
+
for (const client of voiceConnections.get(ownerId) || []) {
|
|
84
|
+
send(client.ws, {
|
|
85
|
+
type: 'voice.ownership',
|
|
86
|
+
state: active === client
|
|
87
|
+
? 'active'
|
|
88
|
+
: holder ? 'busy' : 'available',
|
|
89
|
+
holder,
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
server.on('upgrade', (request, socket, head) => {
|
|
95
|
+
const url = new URL(request.url, 'http://localhost')
|
|
96
|
+
if (rejectUnsupportedRealtimeUpgrade(socket, url.pathname)) return
|
|
97
|
+
if (!isAllowedOrigin(request)) {
|
|
98
|
+
rejectUpgrade(socket, '403 Forbidden', 'origin not allowed')
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
const identity = identityManager.resolveUpgrade(request)
|
|
102
|
+
if (!identity) {
|
|
103
|
+
rejectUpgrade(socket, '401 Unauthorized', 'identity required')
|
|
104
|
+
return
|
|
105
|
+
}
|
|
106
|
+
wss.handleUpgrade(request, socket, head, ws => {
|
|
107
|
+
wss.emit('connection', ws, url, identity)
|
|
108
|
+
})
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
wss.on('connection', (ws, url, identity) => {
|
|
112
|
+
const ownerId = identity.ownerId
|
|
113
|
+
const sessionId = url.searchParams.get('sessionId') || 'main'
|
|
114
|
+
let frontend
|
|
115
|
+
let connectPromise
|
|
116
|
+
let pendingAudio = []
|
|
117
|
+
let turnId = ''
|
|
118
|
+
let turnGeneration = 0
|
|
119
|
+
let committedTurnId = ''
|
|
120
|
+
let committedTurnGeneration = 0
|
|
121
|
+
let userSpeaking = false
|
|
122
|
+
let inputEnabled = false
|
|
123
|
+
let outputEnabled = false
|
|
124
|
+
let textOnlySession = false
|
|
125
|
+
let descriptor = clientDescriptor()
|
|
126
|
+
let responseTurnCandidate = null
|
|
127
|
+
let responseStartWatchdog = null
|
|
128
|
+
let permissionResponseTimer = null
|
|
129
|
+
let realtimeReconnectTimer = null
|
|
130
|
+
let realtimeConnectedAt = 0
|
|
131
|
+
const realtimeReconnectBackoff = new ReconnectBackoff()
|
|
132
|
+
const announcementWindow = new AnnouncementWindow()
|
|
133
|
+
const playbackTurns = new Map()
|
|
134
|
+
const notificationClaimantId = `voice_${randomUUID()}`
|
|
135
|
+
let clientContext = normalizeClientContext()
|
|
136
|
+
const responseContexts = new Map()
|
|
137
|
+
const inputTurns = new TurnCorrelation()
|
|
138
|
+
const transcripts = new TurnTranscripts()
|
|
139
|
+
const announcedPermissions = new Set()
|
|
140
|
+
let permissionRetryTimer = null
|
|
141
|
+
const activeTaskContext = () => taskManager.list({
|
|
142
|
+
ownerId,
|
|
143
|
+
sessionId,
|
|
144
|
+
active: true,
|
|
145
|
+
}).slice(0, 5)
|
|
146
|
+
const activeTaskSignature = tasks => JSON.stringify(tasks.map(task => [
|
|
147
|
+
task.id,
|
|
148
|
+
task.status,
|
|
149
|
+
task.authorization?.id || null,
|
|
150
|
+
task.authorization?.status || null,
|
|
151
|
+
]))
|
|
152
|
+
let lastActiveTaskSignature = ''
|
|
153
|
+
const refreshActiveTaskContext = () => {
|
|
154
|
+
if (!frontend?.ready) return
|
|
155
|
+
const activeTasks = activeTaskContext()
|
|
156
|
+
const signature = activeTaskSignature(activeTasks)
|
|
157
|
+
if (signature === lastActiveTaskSignature) return
|
|
158
|
+
lastActiveTaskSignature = signature
|
|
159
|
+
frontend.updateAgentContext({ activeTasks })
|
|
160
|
+
}
|
|
161
|
+
const schedulePermissionRetry = () => {
|
|
162
|
+
if (permissionRetryTimer || !outputEnabled || !frontend?.ready) return
|
|
163
|
+
permissionRetryTimer = setTimeout(() => {
|
|
164
|
+
permissionRetryTimer = null
|
|
165
|
+
announcePendingPermissions()
|
|
166
|
+
}, Math.max(100, config.announcementQuietMs))
|
|
167
|
+
permissionRetryTimer.unref?.()
|
|
168
|
+
}
|
|
169
|
+
const announcePermission = task => {
|
|
170
|
+
const permission = task?.authorization
|
|
171
|
+
if (
|
|
172
|
+
!outputEnabled
|
|
173
|
+
|| !frontend?.ready
|
|
174
|
+
|| permission?.status !== 'pending'
|
|
175
|
+
|| announcedPermissions.has(permission.id)
|
|
176
|
+
) return
|
|
177
|
+
if (userSpeaking || announcementWindow.isBlocked()) {
|
|
178
|
+
schedulePermissionRetry()
|
|
179
|
+
return
|
|
180
|
+
}
|
|
181
|
+
announcedPermissions.add(permission.id)
|
|
182
|
+
frontend.injectPermission(permission, {
|
|
183
|
+
turnId: task.turnId,
|
|
184
|
+
taskId: task.id,
|
|
185
|
+
authorizationId: permission.id,
|
|
186
|
+
}, {
|
|
187
|
+
shouldSpeak: () => activeTaskContext().some(activeTask => (
|
|
188
|
+
activeTask.authorization?.id === permission.id
|
|
189
|
+
&& activeTask.authorization.status === 'pending'
|
|
190
|
+
)),
|
|
191
|
+
}).then(outcome => {
|
|
192
|
+
if (outcome?.completed) return
|
|
193
|
+
announcedPermissions.delete(permission.id)
|
|
194
|
+
schedulePermissionRetry()
|
|
195
|
+
}).catch(error => {
|
|
196
|
+
announcedPermissions.delete(permission.id)
|
|
197
|
+
schedulePermissionRetry()
|
|
198
|
+
send(ws, {
|
|
199
|
+
type: 'error',
|
|
200
|
+
message: `暂时无法询问权限:${error.message}`,
|
|
201
|
+
})
|
|
202
|
+
})
|
|
203
|
+
}
|
|
204
|
+
const announcePendingPermissions = () => {
|
|
205
|
+
const activeTasks = activeTaskContext()
|
|
206
|
+
const pendingIds = new Set(activeTasks
|
|
207
|
+
.filter(task => task.authorization?.status === 'pending')
|
|
208
|
+
.map(task => task.authorization.id))
|
|
209
|
+
for (const id of announcedPermissions) {
|
|
210
|
+
if (!pendingIds.has(id)) announcedPermissions.delete(id)
|
|
211
|
+
}
|
|
212
|
+
activeTasks.forEach(announcePermission)
|
|
213
|
+
}
|
|
214
|
+
const announcements = new AnnouncementManager({
|
|
215
|
+
getFrontend: () => frontend,
|
|
216
|
+
isDeliveryBlocked: () => !outputEnabled || announcementWindow.isBlocked(),
|
|
217
|
+
announceIntoContext: config.announceIntoContext,
|
|
218
|
+
resultContextMaxChars: config.resultContextMaxChars,
|
|
219
|
+
maxBatchItems: config.announcementMaxBatchItems,
|
|
220
|
+
batchWindowMs: config.announcementBatchMs,
|
|
221
|
+
acknowledgementTimeoutMs: config.announcementAcknowledgementTimeoutMs,
|
|
222
|
+
maxRetryAttempts: config.announcementMaxRetryAttempts,
|
|
223
|
+
leaseRenewIntervalMs: Math.max(
|
|
224
|
+
1000,
|
|
225
|
+
Math.floor(config.taskNotificationClaimTtlMs / 3),
|
|
226
|
+
),
|
|
227
|
+
onDelivered: taskIds => taskManager.markNotificationsDelivered(taskIds, {
|
|
228
|
+
claimantId: notificationClaimantId,
|
|
229
|
+
}),
|
|
230
|
+
onLeaseRenew: taskIds => taskManager.renewNotificationClaims(taskIds, {
|
|
231
|
+
claimantId: notificationClaimantId,
|
|
232
|
+
}),
|
|
233
|
+
onRelease: taskIds => taskManager.releaseNotificationClaims(taskIds, {
|
|
234
|
+
claimantId: notificationClaimantId,
|
|
235
|
+
}),
|
|
236
|
+
onError: error => send(ws, {
|
|
237
|
+
type: 'error',
|
|
238
|
+
message: `后台结果暂时无法播报,正在自动重试:${error.message}`,
|
|
239
|
+
}),
|
|
240
|
+
})
|
|
241
|
+
const voiceClient = {
|
|
242
|
+
ws,
|
|
243
|
+
descriptor,
|
|
244
|
+
deactivate: replacement => {
|
|
245
|
+
inputEnabled = false
|
|
246
|
+
outputEnabled = false
|
|
247
|
+
pendingAudio = []
|
|
248
|
+
announcementWindow.reset()
|
|
249
|
+
announcements.pause()
|
|
250
|
+
frontend?.cancel()
|
|
251
|
+
send(ws, { type: 'playback.clear' })
|
|
252
|
+
send(ws, {
|
|
253
|
+
type: 'voice.deactivated',
|
|
254
|
+
holder: replacement?.descriptor || null,
|
|
255
|
+
})
|
|
256
|
+
},
|
|
257
|
+
}
|
|
258
|
+
if (!voiceConnections.has(ownerId)) voiceConnections.set(ownerId, new Set())
|
|
259
|
+
voiceConnections.get(ownerId).add(voiceClient)
|
|
260
|
+
|
|
261
|
+
const activateVoiceClient = ({
|
|
262
|
+
takeover = false,
|
|
263
|
+
enableInput = true,
|
|
264
|
+
enableOutput = true,
|
|
265
|
+
} = {}) => {
|
|
266
|
+
const result = activeVoiceClients.activate(
|
|
267
|
+
ownerId,
|
|
268
|
+
voiceClient,
|
|
269
|
+
{ takeover },
|
|
270
|
+
)
|
|
271
|
+
inputEnabled = result.granted && enableInput
|
|
272
|
+
outputEnabled = result.granted && enableOutput
|
|
273
|
+
broadcastVoiceOwnership(ownerId)
|
|
274
|
+
return result.granted
|
|
275
|
+
}
|
|
276
|
+
const releaseVoiceClient = () => {
|
|
277
|
+
inputEnabled = false
|
|
278
|
+
outputEnabled = false
|
|
279
|
+
if (activeVoiceClients.release(ownerId, voiceClient)) {
|
|
280
|
+
broadcastVoiceOwnership(ownerId)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const toolCalls = new ToolCallHandler({
|
|
284
|
+
taskManager,
|
|
285
|
+
ownerId,
|
|
286
|
+
sessionId,
|
|
287
|
+
transcripts,
|
|
288
|
+
getFrontend: () => frontend,
|
|
289
|
+
getTurnId: () => committedTurnId,
|
|
290
|
+
getTurnGeneration: () => committedTurnGeneration,
|
|
291
|
+
memoryStore,
|
|
292
|
+
getClientContext: () => clientContext,
|
|
293
|
+
getConversationContext: () => conversationSync.frontendContext({
|
|
294
|
+
ownerId,
|
|
295
|
+
sessionId,
|
|
296
|
+
}),
|
|
297
|
+
onMemoryChanged: () => frontend?.updateAgentContext({
|
|
298
|
+
memories: memoryStore?.list(ownerId) || [],
|
|
299
|
+
}),
|
|
300
|
+
coordinator,
|
|
301
|
+
coordinatorAvailable,
|
|
302
|
+
respondPermission,
|
|
303
|
+
permissionPolicy,
|
|
304
|
+
})
|
|
305
|
+
const currentTurn = () => ({
|
|
306
|
+
turnId,
|
|
307
|
+
turnGeneration,
|
|
308
|
+
})
|
|
309
|
+
const rememberInputTurn = (itemId, context) => {
|
|
310
|
+
inputTurns.remember(itemId, context)
|
|
311
|
+
}
|
|
312
|
+
const inputTurn = event => (
|
|
313
|
+
inputTurns.resolve(event.item_id, currentTurn())
|
|
314
|
+
)
|
|
315
|
+
const commitTurn = context => {
|
|
316
|
+
if (!context?.turnId) return
|
|
317
|
+
if (
|
|
318
|
+
committedTurnId === context.turnId
|
|
319
|
+
&& committedTurnGeneration === context.turnGeneration
|
|
320
|
+
) return
|
|
321
|
+
if (context.turnGeneration < committedTurnGeneration) return
|
|
322
|
+
committedTurnId = context.turnId
|
|
323
|
+
committedTurnGeneration = context.turnGeneration
|
|
324
|
+
}
|
|
325
|
+
const clearResponseCandidate = () => {
|
|
326
|
+
clearTimeout(responseStartWatchdog)
|
|
327
|
+
clearTimeout(permissionResponseTimer)
|
|
328
|
+
responseStartWatchdog = null
|
|
329
|
+
permissionResponseTimer = null
|
|
330
|
+
responseTurnCandidate = null
|
|
331
|
+
}
|
|
332
|
+
const ensurePermissionResponseFor = context => {
|
|
333
|
+
clearTimeout(permissionResponseTimer)
|
|
334
|
+
const hasPendingPermission = () => activeTaskContext().some(task => (
|
|
335
|
+
task.authorization?.status === 'pending'
|
|
336
|
+
))
|
|
337
|
+
if (!hasPendingPermission()) return
|
|
338
|
+
permissionResponseTimer = setTimeout(() => {
|
|
339
|
+
permissionResponseTimer = null
|
|
340
|
+
frontend?.ensureResponse({
|
|
341
|
+
turnId: context.turnId,
|
|
342
|
+
turnGeneration: context.turnGeneration,
|
|
343
|
+
}, {
|
|
344
|
+
shouldCreate: () => {
|
|
345
|
+
if (
|
|
346
|
+
responseTurnCandidate !== context
|
|
347
|
+
|| !hasPendingPermission()
|
|
348
|
+
) return false
|
|
349
|
+
clearResponseCandidate()
|
|
350
|
+
return true
|
|
351
|
+
},
|
|
352
|
+
}).catch(error => send(ws, {
|
|
353
|
+
type: 'error',
|
|
354
|
+
message: `暂时无法处理权限回答:${error.message}`,
|
|
355
|
+
}))
|
|
356
|
+
}, PERMISSION_RESPONSE_GRACE_MS)
|
|
357
|
+
permissionResponseTimer.unref?.()
|
|
358
|
+
}
|
|
359
|
+
const expectResponseFor = context => {
|
|
360
|
+
clearResponseCandidate()
|
|
361
|
+
responseTurnCandidate = context
|
|
362
|
+
responseStartWatchdog = setTimeout(() => {
|
|
363
|
+
if (responseTurnCandidate !== context) return
|
|
364
|
+
clearResponseCandidate()
|
|
365
|
+
send(ws, {
|
|
366
|
+
type: 'error',
|
|
367
|
+
message: '实时模型没有开始回复,语音连接已自动恢复,请再说一次。',
|
|
368
|
+
})
|
|
369
|
+
send(ws, {
|
|
370
|
+
type: 'voice.state',
|
|
371
|
+
state: 'idle',
|
|
372
|
+
turnId: context.turnId,
|
|
373
|
+
origin: 'model',
|
|
374
|
+
})
|
|
375
|
+
const staleFrontend = frontend
|
|
376
|
+
frontend = null
|
|
377
|
+
staleFrontend?.close()
|
|
378
|
+
ensureFrontend().catch(error => send(ws, {
|
|
379
|
+
type: 'error',
|
|
380
|
+
message: error.message,
|
|
381
|
+
}))
|
|
382
|
+
}, RESPONSE_START_WATCHDOG_MS)
|
|
383
|
+
responseStartWatchdog.unref?.()
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const queueNotification = task => {
|
|
387
|
+
if (task.status === 'completed') {
|
|
388
|
+
announcements.completed(task)
|
|
389
|
+
}
|
|
390
|
+
if (task.status === 'failed') announcements.failed(task)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const recordResult = task => recordTaskResult({
|
|
394
|
+
conversationSync,
|
|
395
|
+
ownerId,
|
|
396
|
+
sessionId,
|
|
397
|
+
task,
|
|
398
|
+
})
|
|
399
|
+
|
|
400
|
+
const contextTaskIds = context => (
|
|
401
|
+
context?.taskIds?.length ? context.taskIds : [context?.taskId].filter(Boolean)
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
const publicResponseContext = context => ({
|
|
405
|
+
turnId: context.turnId,
|
|
406
|
+
taskId: context.taskId,
|
|
407
|
+
taskIds: context.taskIds,
|
|
408
|
+
turnIds: context.turnIds,
|
|
409
|
+
origin: context.origin,
|
|
410
|
+
turnGeneration: context.turnGeneration,
|
|
411
|
+
deliverySequence: context.deliverySequence,
|
|
412
|
+
})
|
|
413
|
+
|
|
414
|
+
const fallbackResponseContext = () => ({
|
|
415
|
+
turnId: committedTurnId || turnId,
|
|
416
|
+
taskId: null,
|
|
417
|
+
origin: 'model',
|
|
418
|
+
turnGeneration: committedTurnId
|
|
419
|
+
? committedTurnGeneration
|
|
420
|
+
: turnGeneration,
|
|
421
|
+
})
|
|
422
|
+
|
|
423
|
+
const emitAssistantTranscript = ({
|
|
424
|
+
id,
|
|
425
|
+
context,
|
|
426
|
+
content,
|
|
427
|
+
final,
|
|
428
|
+
}) => {
|
|
429
|
+
if (final) {
|
|
430
|
+
conversationSync.record({
|
|
431
|
+
ownerId,
|
|
432
|
+
sessionId,
|
|
433
|
+
id: `voice:assistant:${id}`,
|
|
434
|
+
role: 'assistant',
|
|
435
|
+
content,
|
|
436
|
+
source: context.origin === 'model' ? 'realtime-direct' : 'agent-presentation',
|
|
437
|
+
...context,
|
|
438
|
+
})
|
|
439
|
+
}
|
|
440
|
+
send(ws, {
|
|
441
|
+
type: final ? 'transcript.final' : 'transcript.delta',
|
|
442
|
+
role: 'assistant',
|
|
443
|
+
content: content || '',
|
|
444
|
+
responseId: id,
|
|
445
|
+
...publicResponseContext(context),
|
|
446
|
+
})
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const flushPendingTranscripts = (id, context) => {
|
|
450
|
+
for (const transcript of context?.pendingTranscripts || []) {
|
|
451
|
+
emitAssistantTranscript({
|
|
452
|
+
id,
|
|
453
|
+
context,
|
|
454
|
+
content: transcript.content,
|
|
455
|
+
final: transcript.final,
|
|
456
|
+
})
|
|
457
|
+
}
|
|
458
|
+
if (context) context.pendingTranscripts = []
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const finishResponseContextIfComplete = (id, context) => {
|
|
462
|
+
if (
|
|
463
|
+
context
|
|
464
|
+
&& context.playbackEnded
|
|
465
|
+
&& context.responseDone
|
|
466
|
+
&& context.transcriptDone
|
|
467
|
+
) {
|
|
468
|
+
responseContexts.delete(id)
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const scheduleResponseContextCleanup = (id, context) => {
|
|
473
|
+
const timer = setTimeout(() => {
|
|
474
|
+
if (responseContexts.get(id) !== context) return
|
|
475
|
+
responseContexts.delete(id)
|
|
476
|
+
playbackTurns.delete(id)
|
|
477
|
+
announcementWindow.finishPlayback(id, {
|
|
478
|
+
hasFunctionCall: Boolean(context?.hasFunctionCall),
|
|
479
|
+
})
|
|
480
|
+
}, RESPONSE_CONTEXT_CLEANUP_MS)
|
|
481
|
+
timer.unref?.()
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const startPlayback = id => {
|
|
485
|
+
const context = responseContexts.get(id)
|
|
486
|
+
// A cancelled response remains as a short-lived tombstone so late
|
|
487
|
+
// provider audio and client receipts cannot resurrect it.
|
|
488
|
+
if (context?.suppressed) return
|
|
489
|
+
announcementWindow.startPlayback(id)
|
|
490
|
+
const playbackTurnId = context?.turnId || playbackTurns.get(id) || turnId
|
|
491
|
+
send(ws, {
|
|
492
|
+
type: 'voice.state',
|
|
493
|
+
state: 'speaking',
|
|
494
|
+
turnId: playbackTurnId,
|
|
495
|
+
origin: context?.origin || 'model',
|
|
496
|
+
})
|
|
497
|
+
if (!context || context.playbackStarted) return
|
|
498
|
+
context.playbackStarted = true
|
|
499
|
+
flushPendingTranscripts(id, context)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const cancelQueuedPlayback = (id, { reason = '' } = {}) => {
|
|
503
|
+
const context = responseContexts.get(id)
|
|
504
|
+
announcementWindow.finishPlayback(id, {
|
|
505
|
+
hasFunctionCall: Boolean(context?.hasFunctionCall),
|
|
506
|
+
})
|
|
507
|
+
const playbackTurnId = playbackTurns.get(id) || turnId
|
|
508
|
+
playbackTurns.delete(id)
|
|
509
|
+
if (context?.origin === 'announcement') {
|
|
510
|
+
if (reason === 'user_interruption') {
|
|
511
|
+
announcements.confirmMany(contextTaskIds(context))
|
|
512
|
+
} else {
|
|
513
|
+
announcements.retryMany(contextTaskIds(context))
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
if (context?.playbackStarted && reason === 'user_interruption') {
|
|
517
|
+
send(ws, {
|
|
518
|
+
type: 'response.interrupted',
|
|
519
|
+
responseId: id,
|
|
520
|
+
...publicResponseContext(context),
|
|
521
|
+
})
|
|
522
|
+
}
|
|
523
|
+
if (context) {
|
|
524
|
+
context.suppressed = true
|
|
525
|
+
context.playbackEnded = true
|
|
526
|
+
context.pendingTranscripts = []
|
|
527
|
+
scheduleResponseContextCleanup(id, context)
|
|
528
|
+
}
|
|
529
|
+
send(ws, {
|
|
530
|
+
type: 'voice.state',
|
|
531
|
+
state: userSpeaking ? 'listening' : 'idle',
|
|
532
|
+
turnId: userSpeaking ? turnId : playbackTurnId,
|
|
533
|
+
origin: context?.origin || 'model',
|
|
534
|
+
})
|
|
535
|
+
const timer = setTimeout(
|
|
536
|
+
() => announcements.flush(),
|
|
537
|
+
config.announcementQuietMs,
|
|
538
|
+
)
|
|
539
|
+
timer.unref?.()
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
const finishPlayback = id => {
|
|
543
|
+
const playbackTurnId = playbackTurns.get(id) || turnId
|
|
544
|
+
const context = responseContexts.get(id)
|
|
545
|
+
if (context?.suppressed) {
|
|
546
|
+
playbackTurns.delete(id)
|
|
547
|
+
return
|
|
548
|
+
}
|
|
549
|
+
announcementWindow.finishPlayback(id, {
|
|
550
|
+
hasFunctionCall: Boolean(context?.hasFunctionCall),
|
|
551
|
+
})
|
|
552
|
+
playbackTurns.delete(id)
|
|
553
|
+
if (context) {
|
|
554
|
+
context.playbackEnded = true
|
|
555
|
+
if (
|
|
556
|
+
context.origin === 'announcement'
|
|
557
|
+
|| context.consumesTaskNotification
|
|
558
|
+
) {
|
|
559
|
+
announcements.confirmMany(contextTaskIds(context))
|
|
560
|
+
}
|
|
561
|
+
finishResponseContextIfComplete(id, context)
|
|
562
|
+
if (responseContexts.get(id) === context) {
|
|
563
|
+
scheduleResponseContextCleanup(id, context)
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
send(ws, {
|
|
567
|
+
type: 'voice.state',
|
|
568
|
+
state: userSpeaking ? 'listening' : 'idle',
|
|
569
|
+
turnId: userSpeaking ? turnId : playbackTurnId,
|
|
570
|
+
origin: context?.origin || 'model',
|
|
571
|
+
})
|
|
572
|
+
const timer = setTimeout(
|
|
573
|
+
() => announcements.flush(),
|
|
574
|
+
config.announcementQuietMs,
|
|
575
|
+
)
|
|
576
|
+
timer.unref?.()
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const claimPendingNotifications = (
|
|
580
|
+
taskIds,
|
|
581
|
+
{ includeOtherSessions = !taskIds?.length } = {},
|
|
582
|
+
) => {
|
|
583
|
+
if (!outputEnabled || !frontend?.ready) return
|
|
584
|
+
const claimed = taskManager.claimNotifications({
|
|
585
|
+
ownerId,
|
|
586
|
+
sessionId,
|
|
587
|
+
includeOtherSessions,
|
|
588
|
+
claimantId: notificationClaimantId,
|
|
589
|
+
taskIds,
|
|
590
|
+
})
|
|
591
|
+
claimed.forEach(task => {
|
|
592
|
+
recordResult(task)
|
|
593
|
+
queueNotification(task)
|
|
594
|
+
})
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const unsubscribeTasks = taskManager.subscribe(event => {
|
|
598
|
+
const task = event.task
|
|
599
|
+
if (event.ownerId !== ownerId) return
|
|
600
|
+
if (event.type === 'task.notification.pending') {
|
|
601
|
+
if (task.sessionId === sessionId) {
|
|
602
|
+
claimPendingNotifications([task.id])
|
|
603
|
+
}
|
|
604
|
+
return
|
|
605
|
+
}
|
|
606
|
+
if (task.sessionId !== sessionId) return
|
|
607
|
+
if (task.kind === 'control') return
|
|
608
|
+
send(ws, {
|
|
609
|
+
type: event.type,
|
|
610
|
+
task,
|
|
611
|
+
...(event.permission ? { permission: event.permission } : {}),
|
|
612
|
+
})
|
|
613
|
+
if (event.type === 'task.permission.requested') {
|
|
614
|
+
refreshActiveTaskContext()
|
|
615
|
+
announcePermission(task)
|
|
616
|
+
}
|
|
617
|
+
if (event.type === 'task.permission.resolved') {
|
|
618
|
+
const authorizationId = event.permission?.id
|
|
619
|
+
if (authorizationId) {
|
|
620
|
+
announcedPermissions.delete(authorizationId)
|
|
621
|
+
frontend?.cancelResponses((context, origin) => (
|
|
622
|
+
origin === 'permission'
|
|
623
|
+
&& context?.authorizationId === authorizationId
|
|
624
|
+
))
|
|
625
|
+
for (const [responseId, context] of responseContexts) {
|
|
626
|
+
if (
|
|
627
|
+
context.origin === 'permission'
|
|
628
|
+
&& context.authorizationId === authorizationId
|
|
629
|
+
&& !context.suppressed
|
|
630
|
+
) {
|
|
631
|
+
cancelQueuedPlayback(responseId, {
|
|
632
|
+
reason: 'permission_resolved',
|
|
633
|
+
})
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
refreshActiveTaskContext()
|
|
638
|
+
}
|
|
639
|
+
if (event.type === 'task.delegated') {
|
|
640
|
+
const presentation = task.delegation?.presentation
|
|
641
|
+
if (presentation?.inline?.content) {
|
|
642
|
+
send(ws, {
|
|
643
|
+
type: 'timeline.inline',
|
|
644
|
+
item: {
|
|
645
|
+
id: `inline_${task.id}_delegated`,
|
|
646
|
+
taskId: task.id,
|
|
647
|
+
turnId: task.turnId || null,
|
|
648
|
+
...presentation.inline,
|
|
649
|
+
},
|
|
650
|
+
})
|
|
651
|
+
}
|
|
652
|
+
if (outputEnabled && frontend?.ready && presentation?.speech) {
|
|
653
|
+
frontend.speak(presentation.speech, 'agent', {
|
|
654
|
+
turnId: task.turnId,
|
|
655
|
+
taskId: task.id,
|
|
656
|
+
}, {
|
|
657
|
+
// The accepted spawn_thinking follow-up is queued before the
|
|
658
|
+
// coordinator can delegate. Evaluate this only when the delegated
|
|
659
|
+
// confirmation reaches the front of the response queue, after the
|
|
660
|
+
// earlier acknowledgement transcript has been recorded.
|
|
661
|
+
shouldSpeak: () => !conversationSync.hasEquivalentAssistantSpeech({
|
|
662
|
+
ownerId,
|
|
663
|
+
sessionId,
|
|
664
|
+
turnId: task.turnId,
|
|
665
|
+
content: presentation.speech,
|
|
666
|
+
}),
|
|
667
|
+
}).catch(error => send(ws, {
|
|
668
|
+
type: 'error',
|
|
669
|
+
message: `暂时无法播报项目启动说明:${error.message}`,
|
|
670
|
+
}))
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
if (['task.completed', 'task.failed'].includes(event.type)) {
|
|
674
|
+
recordResult(task)
|
|
675
|
+
const inline = task.resultMetadata?.presentation?.inline
|
|
676
|
+
if (inline?.content) {
|
|
677
|
+
send(ws, {
|
|
678
|
+
type: 'timeline.inline',
|
|
679
|
+
item: {
|
|
680
|
+
id: `inline_${task.id}`,
|
|
681
|
+
taskId: task.id,
|
|
682
|
+
turnId: task.turnId || null,
|
|
683
|
+
...inline,
|
|
684
|
+
},
|
|
685
|
+
})
|
|
686
|
+
}
|
|
687
|
+
claimPendingNotifications([task.id])
|
|
688
|
+
}
|
|
689
|
+
if ([
|
|
690
|
+
'task.running',
|
|
691
|
+
'task.delegated',
|
|
692
|
+
'task.finalizing',
|
|
693
|
+
'task.cancelling',
|
|
694
|
+
'task.progress',
|
|
695
|
+
'task.completed',
|
|
696
|
+
'task.failed',
|
|
697
|
+
'task.cancelled',
|
|
698
|
+
'task.permission.requested',
|
|
699
|
+
'task.permission.resolved',
|
|
700
|
+
].includes(event.type)) {
|
|
701
|
+
refreshActiveTaskContext()
|
|
702
|
+
}
|
|
703
|
+
})
|
|
704
|
+
|
|
705
|
+
const handleEvent = event => {
|
|
706
|
+
if (event.type === 'input_audio_buffer.speech_started') {
|
|
707
|
+
userSpeaking = true
|
|
708
|
+
clearResponseCandidate()
|
|
709
|
+
turnGeneration += 1
|
|
710
|
+
turnId = `voice-${Date.now()}-${turnGeneration}`
|
|
711
|
+
rememberInputTurn(event.item_id, currentTurn())
|
|
712
|
+
announcementWindow.beginTurn(turnId)
|
|
713
|
+
announcements.dismissActive()
|
|
714
|
+
send(ws, {
|
|
715
|
+
type: 'playback.clear',
|
|
716
|
+
reason: 'user_interruption',
|
|
717
|
+
})
|
|
718
|
+
send(ws, { type: 'turn.started', turnId })
|
|
719
|
+
send(ws, { type: 'voice.state', state: 'listening', turnId })
|
|
720
|
+
frontend?.cancel()
|
|
721
|
+
} else if (event.type === 'input_audio_buffer.speech_stopped') {
|
|
722
|
+
const stoppedTurn = inputTurn(event)
|
|
723
|
+
userSpeaking = false
|
|
724
|
+
announcementWindow.endSpeech()
|
|
725
|
+
if (event.reason === 'turn_invalid') {
|
|
726
|
+
if (event.item_id) {
|
|
727
|
+
inputTurns.invalidate(event.item_id)
|
|
728
|
+
}
|
|
729
|
+
send(ws, {
|
|
730
|
+
type: 'transcript.discard',
|
|
731
|
+
role: 'user',
|
|
732
|
+
turnId: stoppedTurn.turnId,
|
|
733
|
+
reason: 'turn_invalid',
|
|
734
|
+
})
|
|
735
|
+
send(ws, {
|
|
736
|
+
type: 'voice.state',
|
|
737
|
+
state: 'idle',
|
|
738
|
+
turnId: stoppedTurn.turnId,
|
|
739
|
+
origin: 'model',
|
|
740
|
+
})
|
|
741
|
+
} else {
|
|
742
|
+
expectResponseFor(stoppedTurn)
|
|
743
|
+
send(ws, {
|
|
744
|
+
type: 'voice.state',
|
|
745
|
+
state: 'thinking',
|
|
746
|
+
turnId: stoppedTurn.turnId,
|
|
747
|
+
origin: 'model',
|
|
748
|
+
})
|
|
749
|
+
}
|
|
750
|
+
} else if (event.type === 'input_audio_buffer.committed') {
|
|
751
|
+
const committedInputTurn = inputTurn(event)
|
|
752
|
+
userSpeaking = false
|
|
753
|
+
announcementWindow.endSpeech()
|
|
754
|
+
if (!inputTurns.isInvalid(event.item_id)) {
|
|
755
|
+
send(ws, {
|
|
756
|
+
type: 'voice.state',
|
|
757
|
+
state: 'thinking',
|
|
758
|
+
turnId: committedInputTurn.turnId,
|
|
759
|
+
origin: 'model',
|
|
760
|
+
})
|
|
761
|
+
}
|
|
762
|
+
} else if (event.type === 'conversation.item.ambient_audio_transcription.completed') {
|
|
763
|
+
inputTurns.complete(event.item_id, currentTurn())
|
|
764
|
+
} else if (
|
|
765
|
+
event.type === 'conversation.item.input_audio_transcription.delta'
|
|
766
|
+
|| event.type === 'conversation.item.input_audio_transcription.text'
|
|
767
|
+
) {
|
|
768
|
+
if (inputTurns.isInvalid(event.item_id)) return
|
|
769
|
+
const transcriptTurn = inputTurns.resolve(event.item_id, currentTurn())
|
|
770
|
+
const transcript = streamingInputTranscript(event)
|
|
771
|
+
if (!transcriptTurn?.turnId || !transcript) return
|
|
772
|
+
send(ws, {
|
|
773
|
+
type: 'transcript.delta',
|
|
774
|
+
role: 'user',
|
|
775
|
+
content: transcript,
|
|
776
|
+
turnId: transcriptTurn.turnId,
|
|
777
|
+
replace: true,
|
|
778
|
+
})
|
|
779
|
+
} else if (event.type === 'conversation.item.input_audio_transcription.completed') {
|
|
780
|
+
const completedInput = inputTurns.complete(event.item_id, currentTurn())
|
|
781
|
+
const transcriptTurn = completedInput.context
|
|
782
|
+
if (completedInput.invalid) return
|
|
783
|
+
const transcript = String(event.transcript || '').trim()
|
|
784
|
+
if (!transcript) {
|
|
785
|
+
send(ws, {
|
|
786
|
+
type: 'transcript.discard',
|
|
787
|
+
role: 'user',
|
|
788
|
+
turnId: transcriptTurn.turnId,
|
|
789
|
+
})
|
|
790
|
+
return
|
|
791
|
+
}
|
|
792
|
+
commitTurn(transcriptTurn)
|
|
793
|
+
transcripts.record(transcriptTurn.turnId, transcript)
|
|
794
|
+
if (responseTurnCandidate === transcriptTurn) {
|
|
795
|
+
ensurePermissionResponseFor(transcriptTurn)
|
|
796
|
+
}
|
|
797
|
+
conversationSync.record({
|
|
798
|
+
ownerId,
|
|
799
|
+
sessionId,
|
|
800
|
+
id: `voice:user:${transcriptTurn.turnId}`,
|
|
801
|
+
role: 'user',
|
|
802
|
+
content: transcript,
|
|
803
|
+
source: 'voice-user',
|
|
804
|
+
turnId: transcriptTurn.turnId,
|
|
805
|
+
})
|
|
806
|
+
send(ws, {
|
|
807
|
+
type: 'transcript.final',
|
|
808
|
+
role: 'user',
|
|
809
|
+
content: transcript,
|
|
810
|
+
turnId: transcriptTurn.turnId,
|
|
811
|
+
})
|
|
812
|
+
} else if (event.type === 'conversation.item.input_audio_transcription.failed') {
|
|
813
|
+
const failedInput = inputTurns.complete(event.item_id, currentTurn())
|
|
814
|
+
send(ws, {
|
|
815
|
+
type: 'transcript.discard',
|
|
816
|
+
role: 'user',
|
|
817
|
+
turnId: failedInput.context?.turnId,
|
|
818
|
+
})
|
|
819
|
+
} else if (event.type === 'response.created') {
|
|
820
|
+
const id = responseId(event)
|
|
821
|
+
const automaticResponse = (
|
|
822
|
+
(event.__voiceOrigin || 'model') === 'model'
|
|
823
|
+
&& !event.__voiceContext?.turnId
|
|
824
|
+
)
|
|
825
|
+
const automaticTurn = automaticResponse
|
|
826
|
+
? responseTurnCandidate
|
|
827
|
+
: null
|
|
828
|
+
const context = mergeResponseContext(responseContexts, id, {
|
|
829
|
+
turnId: event.__voiceContext?.turnId
|
|
830
|
+
|| automaticTurn?.turnId
|
|
831
|
+
|| committedTurnId
|
|
832
|
+
|| turnId,
|
|
833
|
+
taskId: event.__voiceContext?.taskId || null,
|
|
834
|
+
origin: event.__voiceOrigin || 'model',
|
|
835
|
+
authorizationId: event.__voiceContext?.authorizationId || null,
|
|
836
|
+
turnGeneration: Number.isInteger(event.__voiceContext?.turnGeneration)
|
|
837
|
+
? event.__voiceContext.turnGeneration
|
|
838
|
+
: automaticTurn?.turnGeneration
|
|
839
|
+
?? (committedTurnId ? committedTurnGeneration : turnGeneration),
|
|
840
|
+
})
|
|
841
|
+
if (automaticTurn) {
|
|
842
|
+
// Qwen may begin inference and emit a function call before its final
|
|
843
|
+
// ASR event. response.created proves Smart Turn accepted this turn.
|
|
844
|
+
commitTurn(automaticTurn)
|
|
845
|
+
clearResponseCandidate()
|
|
846
|
+
}
|
|
847
|
+
if (Array.isArray(event.__voiceContext?.taskIds)) {
|
|
848
|
+
context.taskIds = event.__voiceContext.taskIds
|
|
849
|
+
}
|
|
850
|
+
if (Array.isArray(event.__voiceContext?.turnIds)) {
|
|
851
|
+
context.turnIds = event.__voiceContext.turnIds
|
|
852
|
+
}
|
|
853
|
+
if (event.__voiceContext?.deliverySequence) {
|
|
854
|
+
context.deliverySequence = event.__voiceContext.deliverySequence
|
|
855
|
+
}
|
|
856
|
+
send(ws, {
|
|
857
|
+
type: 'response.started',
|
|
858
|
+
responseId: id,
|
|
859
|
+
...publicResponseContext(context),
|
|
860
|
+
})
|
|
861
|
+
} else if (event.type === 'response.function_call_arguments.done') {
|
|
862
|
+
const id = responseId(event)
|
|
863
|
+
const callContext = responseContexts.get(id)
|
|
864
|
+
|| { turnId: '', turnGeneration: -1 }
|
|
865
|
+
if (responseContexts.has(id)) {
|
|
866
|
+
responseContexts.get(id).hasFunctionCall = true
|
|
867
|
+
}
|
|
868
|
+
toolCalls.handle(event, callContext).catch(error => {
|
|
869
|
+
send(ws, { type: 'error', message: error.message })
|
|
870
|
+
})
|
|
871
|
+
} else if (
|
|
872
|
+
event.type === 'response.audio.delta'
|
|
873
|
+
|| event.type === 'response.output_audio.delta'
|
|
874
|
+
) {
|
|
875
|
+
const id = responseId(event)
|
|
876
|
+
const responseContext = ensureResponseContext(
|
|
877
|
+
responseContexts,
|
|
878
|
+
id,
|
|
879
|
+
fallbackResponseContext(),
|
|
880
|
+
)
|
|
881
|
+
if (responseContext?.suppressed) return
|
|
882
|
+
const responseTurnId = responseContext.turnId || turnId
|
|
883
|
+
if (id) {
|
|
884
|
+
responseContext.hasAudio = true
|
|
885
|
+
playbackTurns.set(id, responseTurnId)
|
|
886
|
+
announcementWindow.queueAudio(id, {
|
|
887
|
+
turnId: responseTurnId,
|
|
888
|
+
origin: responseContext.origin || 'model',
|
|
889
|
+
})
|
|
890
|
+
}
|
|
891
|
+
send(ws, {
|
|
892
|
+
type: 'audio.delta',
|
|
893
|
+
audio: event.delta,
|
|
894
|
+
sampleRate: 24000,
|
|
895
|
+
responseId: id,
|
|
896
|
+
turnId: responseTurnId,
|
|
897
|
+
})
|
|
898
|
+
} else if (
|
|
899
|
+
event.type === 'response.audio_transcript.delta'
|
|
900
|
+
|| event.type === 'response.output_audio_transcript.delta'
|
|
901
|
+
) {
|
|
902
|
+
const id = responseId(event)
|
|
903
|
+
const context = ensureResponseContext(
|
|
904
|
+
responseContexts,
|
|
905
|
+
id,
|
|
906
|
+
fallbackResponseContext(),
|
|
907
|
+
)
|
|
908
|
+
if (context.suppressed) return
|
|
909
|
+
if (!context.playbackStarted) {
|
|
910
|
+
context.pendingTranscripts.push({
|
|
911
|
+
content: event.delta || '',
|
|
912
|
+
final: false,
|
|
913
|
+
})
|
|
914
|
+
} else {
|
|
915
|
+
emitAssistantTranscript({
|
|
916
|
+
id,
|
|
917
|
+
context,
|
|
918
|
+
content: event.delta || '',
|
|
919
|
+
final: false,
|
|
920
|
+
})
|
|
921
|
+
}
|
|
922
|
+
} else if (
|
|
923
|
+
event.type === 'response.audio_transcript.done'
|
|
924
|
+
|| event.type === 'response.output_audio_transcript.done'
|
|
925
|
+
) {
|
|
926
|
+
const id = responseId(event)
|
|
927
|
+
const context = ensureResponseContext(
|
|
928
|
+
responseContexts,
|
|
929
|
+
id,
|
|
930
|
+
fallbackResponseContext(),
|
|
931
|
+
)
|
|
932
|
+
if (context.suppressed) return
|
|
933
|
+
context.transcriptDone = true
|
|
934
|
+
if (!context.playbackStarted) {
|
|
935
|
+
context.pendingTranscripts.push({
|
|
936
|
+
content: event.transcript || '',
|
|
937
|
+
final: true,
|
|
938
|
+
})
|
|
939
|
+
} else {
|
|
940
|
+
emitAssistantTranscript({
|
|
941
|
+
id,
|
|
942
|
+
context,
|
|
943
|
+
content: event.transcript || '',
|
|
944
|
+
final: true,
|
|
945
|
+
})
|
|
946
|
+
}
|
|
947
|
+
finishResponseContextIfComplete(id, context)
|
|
948
|
+
} else if (event.type === 'response.text.delta') {
|
|
949
|
+
const id = responseId(event)
|
|
950
|
+
const context = ensureResponseContext(
|
|
951
|
+
responseContexts,
|
|
952
|
+
id,
|
|
953
|
+
fallbackResponseContext(),
|
|
954
|
+
)
|
|
955
|
+
if (context.suppressed) return
|
|
956
|
+
emitAssistantTranscript({
|
|
957
|
+
id,
|
|
958
|
+
context,
|
|
959
|
+
content: event.delta || '',
|
|
960
|
+
final: false,
|
|
961
|
+
})
|
|
962
|
+
} else if (event.type === 'response.text.done') {
|
|
963
|
+
const id = responseId(event)
|
|
964
|
+
const context = ensureResponseContext(
|
|
965
|
+
responseContexts,
|
|
966
|
+
id,
|
|
967
|
+
fallbackResponseContext(),
|
|
968
|
+
)
|
|
969
|
+
if (context.suppressed) return
|
|
970
|
+
context.transcriptDone = true
|
|
971
|
+
emitAssistantTranscript({
|
|
972
|
+
id,
|
|
973
|
+
context,
|
|
974
|
+
content: event.text || '',
|
|
975
|
+
final: true,
|
|
976
|
+
})
|
|
977
|
+
} else if (event.type === 'response.done') {
|
|
978
|
+
const id = responseId(event)
|
|
979
|
+
const responseContext = responseContexts.get(id)
|
|
980
|
+
const responseTurnId = responseContext?.turnId || turnId
|
|
981
|
+
const responseStatus = event.response?.status
|
|
982
|
+
const responseFailed = ['failed', 'cancelled', 'incomplete'].includes(
|
|
983
|
+
responseStatus,
|
|
984
|
+
)
|
|
985
|
+
if (!responseContext?.suppressed) {
|
|
986
|
+
send(ws, { type: 'audio.done', responseId: id, turnId: responseTurnId })
|
|
987
|
+
if (!responseContext?.hasAudio) {
|
|
988
|
+
send(ws, {
|
|
989
|
+
type: 'voice.state',
|
|
990
|
+
state: 'idle',
|
|
991
|
+
turnId: responseTurnId,
|
|
992
|
+
origin: responseContext?.origin || 'model',
|
|
993
|
+
})
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
if (responseContext?.hasAudio && !responseFailed) {
|
|
997
|
+
responseContext.responseDone = true
|
|
998
|
+
finishResponseContextIfComplete(id, responseContext)
|
|
999
|
+
} else {
|
|
1000
|
+
const completedTextAnnouncement = (
|
|
1001
|
+
responseContext?.origin === 'announcement'
|
|
1002
|
+
&& textOnlySession
|
|
1003
|
+
&& !responseFailed
|
|
1004
|
+
)
|
|
1005
|
+
const completedTextTaskNotification = (
|
|
1006
|
+
responseContext?.consumesTaskNotification
|
|
1007
|
+
&& textOnlySession
|
|
1008
|
+
&& !responseFailed
|
|
1009
|
+
)
|
|
1010
|
+
if (
|
|
1011
|
+
responseContext
|
|
1012
|
+
&& !responseFailed
|
|
1013
|
+
&& (
|
|
1014
|
+
responseContext.origin !== 'announcement'
|
|
1015
|
+
|| completedTextAnnouncement
|
|
1016
|
+
)
|
|
1017
|
+
) {
|
|
1018
|
+
flushPendingTranscripts(id, responseContext)
|
|
1019
|
+
}
|
|
1020
|
+
if (responseContext?.origin === 'announcement') {
|
|
1021
|
+
if (completedTextAnnouncement) {
|
|
1022
|
+
announcements.confirmMany(contextTaskIds(responseContext))
|
|
1023
|
+
} else {
|
|
1024
|
+
announcements.retryMany(contextTaskIds(responseContext))
|
|
1025
|
+
}
|
|
1026
|
+
} else if (completedTextTaskNotification) {
|
|
1027
|
+
announcements.confirmMany(contextTaskIds(responseContext))
|
|
1028
|
+
}
|
|
1029
|
+
responseContexts.delete(id)
|
|
1030
|
+
}
|
|
1031
|
+
if (responseFailed && id) {
|
|
1032
|
+
playbackTurns.delete(id)
|
|
1033
|
+
announcementWindow.finishPlayback(id, {
|
|
1034
|
+
hasFunctionCall: Boolean(responseContext?.hasFunctionCall),
|
|
1035
|
+
})
|
|
1036
|
+
}
|
|
1037
|
+
announcementWindow.responseDone({
|
|
1038
|
+
turnId: responseTurnId,
|
|
1039
|
+
origin: responseContext?.origin || 'model',
|
|
1040
|
+
hasAudio: Boolean(responseContext?.hasAudio),
|
|
1041
|
+
hasFunctionCall: Boolean(responseContext?.hasFunctionCall),
|
|
1042
|
+
suppressed: Boolean(responseContext?.suppressed),
|
|
1043
|
+
failed: responseFailed,
|
|
1044
|
+
})
|
|
1045
|
+
const timer = setTimeout(
|
|
1046
|
+
() => announcements.flush(),
|
|
1047
|
+
config.announcementQuietMs,
|
|
1048
|
+
)
|
|
1049
|
+
timer.unref?.()
|
|
1050
|
+
} else if (event.type === 'error') {
|
|
1051
|
+
const errorMessage = event.error?.message
|
|
1052
|
+
|| event.message
|
|
1053
|
+
|| '实时语音服务错误'
|
|
1054
|
+
const recoverableInactivity = isRecoverableRealtimeInactivityError(
|
|
1055
|
+
errorMessage,
|
|
1056
|
+
)
|
|
1057
|
+
const permissionSpeechCollision = (
|
|
1058
|
+
event.__voiceOrigin === 'permission'
|
|
1059
|
+
&& /user is speaking/i.test(
|
|
1060
|
+
errorMessage,
|
|
1061
|
+
)
|
|
1062
|
+
)
|
|
1063
|
+
if (permissionSpeechCollision) {
|
|
1064
|
+
schedulePermissionRetry()
|
|
1065
|
+
return
|
|
1066
|
+
}
|
|
1067
|
+
// 取消撞上已完成响应的良性竞态:提供方回"无进行中响应",对用户无意义,
|
|
1068
|
+
// 也不应触发失败簿记(此时本就没有响应在跑)。
|
|
1069
|
+
const benignCancelRace = /no active response/i.test(
|
|
1070
|
+
errorMessage,
|
|
1071
|
+
)
|
|
1072
|
+
if (benignCancelRace) return
|
|
1073
|
+
const id = responseId(event)
|
|
1074
|
+
const context = responseContexts.get(id)
|
|
1075
|
+
if (context?.origin === 'announcement') {
|
|
1076
|
+
send(ws, { type: 'playback.clear' })
|
|
1077
|
+
announcementWindow.finishPlayback(id)
|
|
1078
|
+
playbackTurns.delete(id)
|
|
1079
|
+
responseContexts.delete(id)
|
|
1080
|
+
announcements.retryMany(contextTaskIds(context))
|
|
1081
|
+
} else {
|
|
1082
|
+
if (id && context?.hasAudio) {
|
|
1083
|
+
send(ws, {
|
|
1084
|
+
type: 'audio.done',
|
|
1085
|
+
responseId: id,
|
|
1086
|
+
turnId: context.turnId || turnId,
|
|
1087
|
+
})
|
|
1088
|
+
}
|
|
1089
|
+
if (id && context?.hasAudio) {
|
|
1090
|
+
scheduleResponseContextCleanup(id, context)
|
|
1091
|
+
} else if (id) {
|
|
1092
|
+
responseContexts.delete(id)
|
|
1093
|
+
playbackTurns.delete(id)
|
|
1094
|
+
}
|
|
1095
|
+
announcementWindow.responseDone({
|
|
1096
|
+
turnId: context?.turnId || turnId,
|
|
1097
|
+
origin: context?.origin || 'model',
|
|
1098
|
+
hasAudio: Boolean(context?.hasAudio),
|
|
1099
|
+
hasFunctionCall: Boolean(context?.hasFunctionCall),
|
|
1100
|
+
failed: true,
|
|
1101
|
+
})
|
|
1102
|
+
}
|
|
1103
|
+
const timer = setTimeout(
|
|
1104
|
+
() => announcements.flush(),
|
|
1105
|
+
config.announcementQuietMs,
|
|
1106
|
+
)
|
|
1107
|
+
timer.unref?.()
|
|
1108
|
+
// Qwen may close an inactive response scope after 180 seconds while a
|
|
1109
|
+
// delegated backend task is still running. The task remains healthy,
|
|
1110
|
+
// and any pending announcement has already been returned to the retry
|
|
1111
|
+
// queue above, so this provider housekeeping event is not user-facing.
|
|
1112
|
+
if (!recoverableInactivity) {
|
|
1113
|
+
send(ws, { type: 'error', message: errorMessage })
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
const ensureFrontend = () => {
|
|
1119
|
+
if (frontend?.ready) return Promise.resolve()
|
|
1120
|
+
if (connectPromise) return connectPromise
|
|
1121
|
+
const activeTasks = activeTaskContext()
|
|
1122
|
+
lastActiveTaskSignature = activeTaskSignature(activeTasks)
|
|
1123
|
+
let createdFrontend
|
|
1124
|
+
createdFrontend = createRealtimeFrontend({
|
|
1125
|
+
agentContext: {
|
|
1126
|
+
client: clientContext,
|
|
1127
|
+
textOnly: textOnlySession,
|
|
1128
|
+
memories: memoryStore?.list(ownerId) || [],
|
|
1129
|
+
recentMessages: conversationSync.frontendContext({ ownerId, sessionId }),
|
|
1130
|
+
activeTasks,
|
|
1131
|
+
},
|
|
1132
|
+
onEvent: handleEvent,
|
|
1133
|
+
onError: error => {
|
|
1134
|
+
if (!isRecoverableRealtimeInactivityError(error.message)) {
|
|
1135
|
+
send(ws, { type: 'error', message: error.message })
|
|
1136
|
+
}
|
|
1137
|
+
},
|
|
1138
|
+
onClose: () => {
|
|
1139
|
+
send(ws, { type: 'voice.state', state: 'idle' })
|
|
1140
|
+
if (frontend !== createdFrontend) return
|
|
1141
|
+
frontend = null
|
|
1142
|
+
if (!inputEnabled && !outputEnabled) return
|
|
1143
|
+
if (
|
|
1144
|
+
realtimeConnectedAt
|
|
1145
|
+
&& Date.now() - realtimeConnectedAt >= REALTIME_STABLE_CONNECTION_MS
|
|
1146
|
+
) {
|
|
1147
|
+
realtimeReconnectBackoff.reset()
|
|
1148
|
+
}
|
|
1149
|
+
realtimeConnectedAt = 0
|
|
1150
|
+
clearTimeout(realtimeReconnectTimer)
|
|
1151
|
+
realtimeReconnectTimer = setTimeout(() => {
|
|
1152
|
+
realtimeReconnectTimer = null
|
|
1153
|
+
ensureFrontend()
|
|
1154
|
+
.then(() => announcements.flush())
|
|
1155
|
+
.catch(error => send(ws, {
|
|
1156
|
+
type: 'error',
|
|
1157
|
+
message: `实时语音连接恢复失败:${error.message}`,
|
|
1158
|
+
}))
|
|
1159
|
+
}, realtimeReconnectBackoff.next())
|
|
1160
|
+
realtimeReconnectTimer.unref?.()
|
|
1161
|
+
},
|
|
1162
|
+
})
|
|
1163
|
+
frontend = createdFrontend
|
|
1164
|
+
let createdConnectPromise
|
|
1165
|
+
createdConnectPromise = createdFrontend.connect()
|
|
1166
|
+
.then(() => {
|
|
1167
|
+
if (frontend !== createdFrontend) return
|
|
1168
|
+
realtimeConnectedAt = Date.now()
|
|
1169
|
+
refreshActiveTaskContext()
|
|
1170
|
+
announcePendingPermissions()
|
|
1171
|
+
pendingAudio.forEach(audio => createdFrontend.appendAudio(audio))
|
|
1172
|
+
pendingAudio = []
|
|
1173
|
+
if (outputEnabled) claimPendingNotifications()
|
|
1174
|
+
send(ws, {
|
|
1175
|
+
type: 'voice.ready',
|
|
1176
|
+
inputSampleRate: createdFrontend.provider.inputSampleRate,
|
|
1177
|
+
})
|
|
1178
|
+
})
|
|
1179
|
+
.finally(() => {
|
|
1180
|
+
if (connectPromise === createdConnectPromise) connectPromise = null
|
|
1181
|
+
})
|
|
1182
|
+
connectPromise = createdConnectPromise
|
|
1183
|
+
return createdConnectPromise
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
send(ws, { type: GatewayServerEvent.VOICE_STATE, state: 'idle' })
|
|
1187
|
+
ws.on('message', raw => {
|
|
1188
|
+
let event
|
|
1189
|
+
try {
|
|
1190
|
+
event = JSON.parse(raw.toString())
|
|
1191
|
+
} catch {
|
|
1192
|
+
return
|
|
1193
|
+
}
|
|
1194
|
+
if (event.type === GatewayClientEvent.CONNECT) {
|
|
1195
|
+
descriptor = clientDescriptor(event)
|
|
1196
|
+
voiceClient.descriptor = descriptor
|
|
1197
|
+
textOnlySession = event.textOnly === true
|
|
1198
|
+
const capabilities = clientVoiceCapabilities({
|
|
1199
|
+
voiceEnabled: event.voiceEnabled,
|
|
1200
|
+
inputEnabled: event.inputEnabled,
|
|
1201
|
+
outputEnabled: event.outputEnabled,
|
|
1202
|
+
textOnly: textOnlySession,
|
|
1203
|
+
})
|
|
1204
|
+
if (capabilities.participatesInVoiceArbitration) {
|
|
1205
|
+
activateVoiceClient({
|
|
1206
|
+
takeover: event.takeover === true,
|
|
1207
|
+
enableInput: capabilities.inputEnabled,
|
|
1208
|
+
enableOutput: capabilities.outputEnabled,
|
|
1209
|
+
})
|
|
1210
|
+
} else {
|
|
1211
|
+
releaseVoiceClient()
|
|
1212
|
+
inputEnabled = capabilities.inputEnabled
|
|
1213
|
+
outputEnabled = capabilities.outputEnabled
|
|
1214
|
+
broadcastVoiceOwnership(ownerId)
|
|
1215
|
+
}
|
|
1216
|
+
clientContext = normalizeClientContext({
|
|
1217
|
+
timeZone: event.timeZone,
|
|
1218
|
+
locale: event.locale,
|
|
1219
|
+
workingDirectory: event.workingDirectory,
|
|
1220
|
+
})
|
|
1221
|
+
frontend?.updateAgentContext({
|
|
1222
|
+
client: clientContext,
|
|
1223
|
+
textOnly: textOnlySession,
|
|
1224
|
+
})
|
|
1225
|
+
if (inputEnabled || outputEnabled) {
|
|
1226
|
+
ensureFrontend().catch(error => send(ws, {
|
|
1227
|
+
type: 'error',
|
|
1228
|
+
message: error.message,
|
|
1229
|
+
}))
|
|
1230
|
+
}
|
|
1231
|
+
} else if (event.type === GatewayClientEvent.UNMUTE) {
|
|
1232
|
+
if (textOnlySession) {
|
|
1233
|
+
inputEnabled = false
|
|
1234
|
+
outputEnabled = true
|
|
1235
|
+
broadcastVoiceOwnership(ownerId)
|
|
1236
|
+
} else {
|
|
1237
|
+
activateVoiceClient({ takeover: event.takeover === true })
|
|
1238
|
+
}
|
|
1239
|
+
ensureFrontend()
|
|
1240
|
+
.then(() => {
|
|
1241
|
+
announcePendingPermissions()
|
|
1242
|
+
claimPendingNotifications()
|
|
1243
|
+
announcements.flush()
|
|
1244
|
+
})
|
|
1245
|
+
.catch(error => send(ws, { type: 'error', message: error.message }))
|
|
1246
|
+
} else if (event.type === GatewayClientEvent.INPUT_UNMUTE) {
|
|
1247
|
+
if (textOnlySession) return
|
|
1248
|
+
if (activeVoiceClients.isActive(ownerId, voiceClient)) {
|
|
1249
|
+
inputEnabled = true
|
|
1250
|
+
outputEnabled = true
|
|
1251
|
+
broadcastVoiceOwnership(ownerId)
|
|
1252
|
+
} else {
|
|
1253
|
+
activateVoiceClient({ takeover: event.takeover === true })
|
|
1254
|
+
}
|
|
1255
|
+
ensureFrontend()
|
|
1256
|
+
.then(() => {
|
|
1257
|
+
announcePendingPermissions()
|
|
1258
|
+
claimPendingNotifications()
|
|
1259
|
+
announcements.flush()
|
|
1260
|
+
})
|
|
1261
|
+
.catch(error => send(ws, { type: 'error', message: error.message }))
|
|
1262
|
+
} else if (event.type === GatewayClientEvent.AUDIO_APPEND) {
|
|
1263
|
+
if (!inputEnabled || !activeVoiceClients.isActive(ownerId, voiceClient)) {
|
|
1264
|
+
return
|
|
1265
|
+
}
|
|
1266
|
+
if (frontend?.ready) frontend.appendAudio(event.audio)
|
|
1267
|
+
else {
|
|
1268
|
+
pendingAudio.push(event.audio)
|
|
1269
|
+
if (pendingAudio.length > MAX_PENDING_AUDIO_CHUNKS) {
|
|
1270
|
+
pendingAudio.splice(0, pendingAudio.length - MAX_PENDING_AUDIO_CHUNKS)
|
|
1271
|
+
}
|
|
1272
|
+
ensureFrontend().catch(error => send(ws, { type: 'error', message: error.message }))
|
|
1273
|
+
}
|
|
1274
|
+
} else if (event.type === GatewayClientEvent.TEXT_MESSAGE) {
|
|
1275
|
+
const text = String(event.text || '').trim()
|
|
1276
|
+
if (!text) return
|
|
1277
|
+
const turnId = `text_${randomUUID().replaceAll('-', '')}`
|
|
1278
|
+
conversationSync.record({
|
|
1279
|
+
ownerId,
|
|
1280
|
+
sessionId,
|
|
1281
|
+
id: `voice:user:${turnId}`,
|
|
1282
|
+
role: 'user',
|
|
1283
|
+
content: text,
|
|
1284
|
+
source: 'text-user',
|
|
1285
|
+
turnId,
|
|
1286
|
+
})
|
|
1287
|
+
send(ws, { type: 'transcript.final', role: 'user', content: text, turnId })
|
|
1288
|
+
ensureFrontend()
|
|
1289
|
+
.then(() => frontend.sendUserText(
|
|
1290
|
+
text,
|
|
1291
|
+
{ turnId },
|
|
1292
|
+
{
|
|
1293
|
+
modalities: textOnlySession && event.textOnly === true
|
|
1294
|
+
? ['text']
|
|
1295
|
+
: undefined,
|
|
1296
|
+
},
|
|
1297
|
+
))
|
|
1298
|
+
.catch(error => send(ws, { type: 'error', message: error.message }))
|
|
1299
|
+
} else if (event.type === GatewayClientEvent.INTERRUPT) {
|
|
1300
|
+
turnGeneration += 1
|
|
1301
|
+
committedTurnGeneration = turnGeneration
|
|
1302
|
+
announcementWindow.interrupt()
|
|
1303
|
+
announcements.dismissActive()
|
|
1304
|
+
frontend?.cancel()
|
|
1305
|
+
} else if (event.type === GatewayClientEvent.PLAYBACK_STARTED) {
|
|
1306
|
+
startPlayback(String(event.responseId || ''))
|
|
1307
|
+
} else if (event.type === GatewayClientEvent.PLAYBACK_ENDED) {
|
|
1308
|
+
finishPlayback(String(event.responseId || ''))
|
|
1309
|
+
} else if (event.type === GatewayClientEvent.PLAYBACK_CANCELLED) {
|
|
1310
|
+
cancelQueuedPlayback(String(event.responseId || ''), {
|
|
1311
|
+
reason: String(event.reason || ''),
|
|
1312
|
+
})
|
|
1313
|
+
} else if (event.type === GatewayClientEvent.MUTE) {
|
|
1314
|
+
releaseVoiceClient()
|
|
1315
|
+
turnGeneration += 1
|
|
1316
|
+
committedTurnGeneration = turnGeneration
|
|
1317
|
+
pendingAudio = []
|
|
1318
|
+
announcementWindow.reset()
|
|
1319
|
+
frontend?.cancel()
|
|
1320
|
+
} else if (event.type === GatewayClientEvent.INPUT_MUTE) {
|
|
1321
|
+
inputEnabled = false
|
|
1322
|
+
pendingAudio = []
|
|
1323
|
+
}
|
|
1324
|
+
})
|
|
1325
|
+
|
|
1326
|
+
ws.on('close', () => {
|
|
1327
|
+
releaseVoiceClient()
|
|
1328
|
+
const connections = voiceConnections.get(ownerId)
|
|
1329
|
+
connections?.delete(voiceClient)
|
|
1330
|
+
if (!connections?.size) voiceConnections.delete(ownerId)
|
|
1331
|
+
unsubscribeTasks()
|
|
1332
|
+
clearResponseCandidate()
|
|
1333
|
+
turnGeneration += 1
|
|
1334
|
+
committedTurnGeneration = turnGeneration
|
|
1335
|
+
transcripts.close()
|
|
1336
|
+
announcementWindow.reset()
|
|
1337
|
+
playbackTurns.clear()
|
|
1338
|
+
inputTurns.clear()
|
|
1339
|
+
announcements.close()
|
|
1340
|
+
clearTimeout(permissionRetryTimer)
|
|
1341
|
+
permissionRetryTimer = null
|
|
1342
|
+
clearTimeout(realtimeReconnectTimer)
|
|
1343
|
+
realtimeReconnectTimer = null
|
|
1344
|
+
frontend?.close()
|
|
1345
|
+
})
|
|
1346
|
+
})
|
|
1347
|
+
|
|
1348
|
+
return {
|
|
1349
|
+
status() {
|
|
1350
|
+
const byType = { desktop: 0, cli: 0, web: 0 }
|
|
1351
|
+
let connected = 0
|
|
1352
|
+
for (const clients of voiceConnections.values()) {
|
|
1353
|
+
for (const client of clients) {
|
|
1354
|
+
connected += 1
|
|
1355
|
+
const type = client.descriptor?.type || 'web'
|
|
1356
|
+
byType[type] = (byType[type] || 0) + 1
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
return {
|
|
1360
|
+
connected,
|
|
1361
|
+
activeOwners: activeVoiceClients.size,
|
|
1362
|
+
byType,
|
|
1363
|
+
}
|
|
1364
|
+
},
|
|
1365
|
+
}
|
|
1366
|
+
}
|