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.
Files changed (122) hide show
  1. package/CONTRIBUTING.md +58 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +5 -0
  4. package/PRIVACY.md +34 -0
  5. package/README.md +282 -0
  6. package/README_EN.md +316 -0
  7. package/SECURITY.md +32 -0
  8. package/THIRD_PARTY_NOTICES.md +26 -0
  9. package/cli/bin/qwenaudio.mjs +10 -0
  10. package/cli/package.json +13 -0
  11. package/cli/src/arguments.mjs +247 -0
  12. package/cli/src/gateway-service.mjs +386 -0
  13. package/cli/src/instance-lock.mjs +65 -0
  14. package/cli/src/launcher.mjs +217 -0
  15. package/cli/src/runtime.mjs +356 -0
  16. package/cli/src/webui.mjs +61 -0
  17. package/config/acp/workspace/AGENTS.md +13 -0
  18. package/config/codebuddy/workspace/.codebuddy/models.json +19 -0
  19. package/config/codebuddy/workspace/AGENTS.md +13 -0
  20. package/config/codex/workspace/AGENTS.md +13 -0
  21. package/config/frontend-agent/PROMPT.md +127 -0
  22. package/config/hermes/workspace/AGENTS.md +13 -0
  23. package/config/openclaw/openclaw.json5 +50 -0
  24. package/config/openclaw/workspace/AGENTS.md +9 -0
  25. package/config/opencode/agents/qwen-audio-agent-backend.md +65 -0
  26. package/config/opencode/workspace/AGENTS.md +16 -0
  27. package/config/qoder/workspace/AGENTS.md +16 -0
  28. package/docs/architecture-overview-en.png +0 -0
  29. package/docs/architecture-overview.png +0 -0
  30. package/docs/architecture.md +332 -0
  31. package/docs/configuration.md +386 -0
  32. package/docs/desktop-fluid-orb-thinking.gif +0 -0
  33. package/docs/desktop-goo-orb-thinking.gif +0 -0
  34. package/docs/qwen-audio-agent-three-layer-architecture-en.png +0 -0
  35. package/docs/qwen-audio-agent-three-layer-architecture.png +0 -0
  36. package/package.json +126 -0
  37. package/scripts/audit-dependencies.mjs +109 -0
  38. package/scripts/check-desktop-release-env.mjs +41 -0
  39. package/scripts/codex-acp +58 -0
  40. package/scripts/install-global.mjs +66 -0
  41. package/scripts/openclaw +194 -0
  42. package/scripts/openclaw-gateway +8 -0
  43. package/scripts/opencode-acp +6 -0
  44. package/scripts/opencode-server +179 -0
  45. package/scripts/prepare-build.mjs +38 -0
  46. package/scripts/release-check +182 -0
  47. package/scripts/set-version.mjs +133 -0
  48. package/scripts/start.mjs +43 -0
  49. package/scripts/verify-package.mjs +109 -0
  50. package/server/package.json +18 -0
  51. package/server/src/agent/acp-backend-adapter.mjs +1138 -0
  52. package/server/src/agent/acp-backend-profile.mjs +35 -0
  53. package/server/src/agent/acp-backend-session-utils.mjs +139 -0
  54. package/server/src/agent/acp-process-client.mjs +447 -0
  55. package/server/src/agent/acp-session-registry.mjs +106 -0
  56. package/server/src/agent/acp-session-tools.mjs +257 -0
  57. package/server/src/agent/agent-client.mjs +218 -0
  58. package/server/src/agent/backend-adapter.mjs +15 -0
  59. package/server/src/agent/backend-agent-instructions.mjs +8 -0
  60. package/server/src/agent/backends/codebuddy.mjs +47 -0
  61. package/server/src/agent/backends/codex.mjs +62 -0
  62. package/server/src/agent/backends/generic-acp.mjs +46 -0
  63. package/server/src/agent/backends/hermes.mjs +29 -0
  64. package/server/src/agent/backends/openclaw.mjs +101 -0
  65. package/server/src/agent/backends/opencode.mjs +36 -0
  66. package/server/src/agent/backends/qoder.mjs +47 -0
  67. package/server/src/agent/backends/registry.mjs +32 -0
  68. package/server/src/agent/backends/shared.mjs +46 -0
  69. package/server/src/agent/coordinator.mjs +308 -0
  70. package/server/src/agent/openclaw-adapter.mjs +245 -0
  71. package/server/src/app/bootstrap.mjs +244 -0
  72. package/server/src/conversation/conversation-sync.mjs +183 -0
  73. package/server/src/conversation/frontend-agent-context.mjs +162 -0
  74. package/server/src/conversation/frontend-memory.mjs +328 -0
  75. package/server/src/conversation/profiled-memory-store.mjs +87 -0
  76. package/server/src/conversation/task-result-projector.mjs +18 -0
  77. package/server/src/conversation/user-profile.mjs +234 -0
  78. package/server/src/core/config.mjs +388 -0
  79. package/server/src/core/identity.mjs +93 -0
  80. package/server/src/core/install-paths.mjs +8 -0
  81. package/server/src/core/package-version.mjs +10 -0
  82. package/server/src/core/request-security.mjs +80 -0
  83. package/server/src/index.mjs +67 -0
  84. package/server/src/process/backend-drivers/codebuddy.mjs +15 -0
  85. package/server/src/process/backend-drivers/codex.mjs +15 -0
  86. package/server/src/process/backend-drivers/generic-acp.mjs +18 -0
  87. package/server/src/process/backend-drivers/hermes.mjs +15 -0
  88. package/server/src/process/backend-drivers/openclaw.mjs +35 -0
  89. package/server/src/process/backend-drivers/opencode.mjs +75 -0
  90. package/server/src/process/backend-drivers/qoder.mjs +15 -0
  91. package/server/src/process/backend-drivers/registry.mjs +24 -0
  92. package/server/src/process/backend-drivers/shared.mjs +46 -0
  93. package/server/src/process/managed-backend.mjs +188 -0
  94. package/server/src/task/task-manager.mjs +704 -0
  95. package/server/src/task/task-scheduler.mjs +44 -0
  96. package/server/src/task/task-store.mjs +167 -0
  97. package/server/src/voice/active-voice-clients.mjs +58 -0
  98. package/server/src/voice/announcement/announcement-manager.mjs +402 -0
  99. package/server/src/voice/announcement/announcement-window.mjs +89 -0
  100. package/server/src/voice/input-transcript.mjs +9 -0
  101. package/server/src/voice/realtime-errors.mjs +6 -0
  102. package/server/src/voice/realtime-gateway.mjs +1366 -0
  103. package/server/src/voice/realtime-provider.mjs +771 -0
  104. package/server/src/voice/reconnect-backoff.mjs +30 -0
  105. package/server/src/voice/response-context.mjs +41 -0
  106. package/server/src/voice/session-permission-policy.mjs +56 -0
  107. package/server/src/voice/tools/tool-call-handler.mjs +823 -0
  108. package/server/src/voice/tools/turn-transcripts.mjs +59 -0
  109. package/server/src/voice/turn-correlation.mjs +41 -0
  110. package/shared/backend-catalog.mjs +56 -0
  111. package/shared/gateway-client.mjs +13 -0
  112. package/shared/realtime-events.mjs +55 -0
  113. package/shared/runtime-environment.mjs +422 -0
  114. package/tui/native/macos-voice-io.swift +552 -0
  115. package/tui/native/portaudio-voice-io.py +240 -0
  116. package/tui/package.json +13 -0
  117. package/tui/src/index.mjs +1217 -0
  118. package/tui/src/macos-voice-io.mjs +186 -0
  119. package/tui/src/portaudio-voice-io.mjs +158 -0
  120. package/web/dist/assets/index-BeamDvsE.js +38 -0
  121. package/web/dist/assets/index-BuB0EFih.css +1 -0
  122. package/web/dist/index.html +14 -0
@@ -0,0 +1,1138 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { AgentError } from './backend-adapter.mjs'
3
+ import { BACKEND_AGENT_INSTRUCTIONS } from './backend-agent-instructions.mjs'
4
+ import {
5
+ acpBackendProfile,
6
+ endpointAvailable,
7
+ } from './acp-backend-profile.mjs'
8
+ import {
9
+ activityFromUpdate,
10
+ coordinatorKey,
11
+ coordinatorPresentation,
12
+ nativeToolOutput,
13
+ normalizeCoordinatorContent,
14
+ projectSessionKey,
15
+ sessionSummary,
16
+ } from './acp-backend-session-utils.mjs'
17
+ import { AcpProcessClient } from './acp-process-client.mjs'
18
+ import { AcpSessionRegistry } from './acp-session-registry.mjs'
19
+ import {
20
+ ACP_SESSION_TOOL_NAMES,
21
+ AcpSessionToolServer,
22
+ } from './acp-session-tools.mjs'
23
+
24
+ const MAX_SESSION_RESULTS = 100
25
+ const MAX_DELEGATION_RESULT_CHARS = 12_000
26
+
27
+ export { acpBackendProfile } from './acp-backend-profile.mjs'
28
+
29
+ function clean(value) {
30
+ return String(value || '').trim()
31
+ }
32
+
33
+ function bounded(value, max = 300) {
34
+ return clean(value).replace(/\s+/g, ' ').slice(0, max)
35
+ }
36
+
37
+ function deferred() {
38
+ let resolvePromise
39
+ let rejectPromise
40
+ const promise = new Promise((resolve, reject) => {
41
+ resolvePromise = resolve
42
+ rejectPromise = reject
43
+ })
44
+ return { promise, resolve: resolvePromise, reject: rejectPromise }
45
+ }
46
+
47
+ export class AcpBackendAdapter {
48
+ constructor({
49
+ protocol = 'opencode',
50
+ root = process.cwd(),
51
+ mode = 'managed',
52
+ permissionMode = 'native',
53
+ model = '',
54
+ timeoutMs = 300_000,
55
+ directory = process.cwd(),
56
+ cliPath = '',
57
+ configDirectory = '',
58
+ baseUrl = '',
59
+ token = '',
60
+ tokenFile = '',
61
+ coordinatorAgent = '',
62
+ profile,
63
+ sessionStatePath = null,
64
+ client,
65
+ clientFactory = options => new AcpProcessClient(options),
66
+ backendAvailable = endpointAvailable,
67
+ sessionToolServer,
68
+ nativeDelegationAdapter,
69
+ } = {}) {
70
+ this.protocol = protocol
71
+ this.root = root
72
+ this.mode = mode === 'compatible' ? 'compatible' : 'managed'
73
+ this.permissionMode = permissionMode === 'full' ? 'full' : 'native'
74
+ this.model = clean(model)
75
+ this.timeoutMs = timeoutMs
76
+ this.directory = directory
77
+ this.baseUrl = clean(baseUrl) || null
78
+ this.coordinatorAgent = clean(coordinatorAgent)
79
+ this.profile = profile || acpBackendProfile({
80
+ protocol,
81
+ root,
82
+ directory,
83
+ cliPath,
84
+ baseUrl,
85
+ token,
86
+ tokenFile,
87
+ coordinatorAgent,
88
+ configDirectory,
89
+ permissionMode: this.permissionMode,
90
+ model: this.model,
91
+ })
92
+ this.registry = new AcpSessionRegistry({ filePath: sessionStatePath })
93
+ this.sessionToolServer = sessionToolServer || new AcpSessionToolServer()
94
+ this.pendingPermissions = new Map()
95
+ this.resolvedPermissions = new Map()
96
+ this.coordinatorSessions = new Map()
97
+ this.coordinatorSessionPromises = new Map()
98
+ this.sessionQueues = new Map()
99
+ this.activeCoordinatorTurns = new Set()
100
+ this.delegatedWorkRuns = new Map()
101
+ this.pendingCoordinatorFacts = new Map()
102
+ this.nativeDelegationAdapter = nativeDelegationAdapter || null
103
+ this.backendAvailable = client ? null : backendAvailable
104
+ this.client = client || clientFactory({
105
+ label: this.profile.label,
106
+ command: this.profile.command,
107
+ args: this.profile.args,
108
+ cwd: this.profile.cwd,
109
+ env: this.profile.env,
110
+ timeoutMs,
111
+ onPermission: (params, context) => (
112
+ this.handlePermission(params, context)
113
+ ),
114
+ })
115
+ }
116
+
117
+ get label() {
118
+ return this.profile.label
119
+ }
120
+
121
+ describe() {
122
+ return {
123
+ kind: this.protocol,
124
+ label: this.label,
125
+ baseUrl: this.baseUrl,
126
+ uiPath: null,
127
+ model: this.model || null,
128
+ directory: this.directory,
129
+ mode: this.mode,
130
+ permissionMode: this.permissionMode,
131
+ transport: 'acp',
132
+ backendAgent: this.coordinatorAgent || 'qwen-audio-agent-backend',
133
+ sessionModel: 'one-persistent-backend-agent',
134
+ capabilities: {
135
+ delegation: true,
136
+ permissions: true,
137
+ backendUi: Boolean(this.profile.backendUi),
138
+ nativeSessionHistory: true,
139
+ externalMcp: this.profile.externalMcp,
140
+ },
141
+ }
142
+ }
143
+
144
+ async health() {
145
+ try {
146
+ if (
147
+ this.profile.readinessMessage
148
+ && this.baseUrl
149
+ && this.backendAvailable
150
+ && !await this.backendAvailable(this.baseUrl)
151
+ ) {
152
+ return {
153
+ ok: false,
154
+ protocol: this.protocol,
155
+ mode: this.mode,
156
+ transport: 'acp',
157
+ error: this.profile.readinessMessage,
158
+ }
159
+ }
160
+ const initialized = await this.client.start()
161
+ return {
162
+ ok: true,
163
+ protocol: this.protocol,
164
+ mode: this.mode,
165
+ transport: 'acp',
166
+ agentInfo: initialized.agentInfo || null,
167
+ capabilities: initialized.agentCapabilities || {},
168
+ }
169
+ } catch (error) {
170
+ return {
171
+ ok: false,
172
+ protocol: this.protocol,
173
+ mode: this.mode,
174
+ transport: 'acp',
175
+ error: `${error.message}${
176
+ clean(this.client.stderr) ? `:${clean(this.client.stderr)}` : ''
177
+ }`,
178
+ }
179
+ }
180
+ }
181
+
182
+ serialize(key, operation) {
183
+ const previous = this.sessionQueues.get(key) || Promise.resolve()
184
+ const current = previous.catch(() => {}).then(operation)
185
+ this.sessionQueues.set(key, current)
186
+ return current.finally(() => {
187
+ if (this.sessionQueues.get(key) === current) {
188
+ this.sessionQueues.delete(key)
189
+ }
190
+ })
191
+ }
192
+
193
+ async ensureCoordinatorSession(ownerId, mcpServers = []) {
194
+ const key = coordinatorKey(ownerId, this.protocol)
195
+ if (this.coordinatorSessions.has(key)) {
196
+ return this.coordinatorSessions.get(key)
197
+ }
198
+ if (this.coordinatorSessionPromises.has(key)) {
199
+ return this.coordinatorSessionPromises.get(key)
200
+ }
201
+ const pending = (async () => {
202
+ const stored = this.registry.get(key)
203
+ let session
204
+ if (stored?.sessionId) {
205
+ try {
206
+ session = await this.client.resumeSession(stored.sessionId, {
207
+ cwd: stored.cwd || this.directory,
208
+ mcpServers,
209
+ meta: this.coordinatorMeta(ownerId),
210
+ ownerId,
211
+ role: 'coordinator',
212
+ })
213
+ session.isNew = false
214
+ } catch {
215
+ this.registry.delete(key)
216
+ }
217
+ }
218
+ if (!session) {
219
+ session = await this.client.newSession({
220
+ cwd: this.directory,
221
+ mcpServers,
222
+ meta: this.coordinatorMeta(ownerId),
223
+ ownerId,
224
+ role: 'coordinator',
225
+ })
226
+ session.isNew = true
227
+ }
228
+ await this.configureSession(session, 'coordinator')
229
+ this.coordinatorSessions.set(key, session)
230
+ this.registry.set(key, session)
231
+ return session
232
+ })().finally(() => this.coordinatorSessionPromises.delete(key))
233
+ this.coordinatorSessionPromises.set(key, pending)
234
+ return pending
235
+ }
236
+
237
+ coordinatorMeta(ownerId) {
238
+ return this.profile.coordinatorMeta?.(ownerId) || null
239
+ }
240
+
241
+ async configureSession(session, role) {
242
+ const options = Array.isArray(session?.response?.configOptions)
243
+ ? session.response.configOptions
244
+ : []
245
+ const desired = [
246
+ ...(role === 'coordinator' && this.coordinatorAgent
247
+ ? [['mode', this.coordinatorAgent]]
248
+ : []),
249
+ ...(this.model && this.model !== 'auto'
250
+ ? [['model', this.model]]
251
+ : []),
252
+ ]
253
+ for (const [configId, value] of desired) {
254
+ const option = options.find(item => item.id === configId)
255
+ const supported = option?.type !== 'select'
256
+ || option.options?.some(item => item.value === value)
257
+ if (!option || !supported || option.currentValue === value) continue
258
+ await this.client.setSessionConfigOption(
259
+ session.sessionId,
260
+ configId,
261
+ value,
262
+ )
263
+ option.currentValue = value
264
+ }
265
+ }
266
+
267
+ optionFor(params, decision) {
268
+ const options = Array.isArray(params?.options) ? params.options : []
269
+ const kinds = decision === 'always'
270
+ ? ['allow_once', 'allow_always']
271
+ : ['reject_always', 'reject_once']
272
+ for (const kind of kinds) {
273
+ const option = options.find(candidate => candidate.kind === kind)
274
+ if (option) return option
275
+ }
276
+ return null
277
+ }
278
+
279
+ async handlePermission(params, { signal, session } = {}) {
280
+ const name = clean(params?.toolCall?.name || params?.toolCall?.title)
281
+ const internal = ACP_SESSION_TOOL_NAMES.some(toolName => (
282
+ name === toolName
283
+ || name.endsWith(`__${toolName}`)
284
+ || name.startsWith(`${toolName} (`)
285
+ ))
286
+ if (
287
+ this.permissionMode === 'full'
288
+ || internal
289
+ ) {
290
+ const option = this.optionFor(params, 'always')
291
+ return option
292
+ ? { outcome: { outcome: 'selected', optionId: option.optionId } }
293
+ : { outcome: { outcome: 'cancelled' } }
294
+ }
295
+ const id = `auth_${randomUUID().replaceAll('-', '')}`
296
+ const pending = deferred()
297
+ const permission = {
298
+ id,
299
+ workId: session?.coordinationRunId || null,
300
+ status: 'pending',
301
+ category: bounded(name, 80) || 'unknown',
302
+ summary: [
303
+ bounded(name, 80),
304
+ bounded(
305
+ params?.toolCall?.rawInput?.description
306
+ || params?.toolCall?.rawInput?.command
307
+ || params?.toolCall?.rawInput?.path
308
+ || '',
309
+ ),
310
+ ].filter(Boolean).join(':'),
311
+ patterns: [],
312
+ }
313
+ const record = {
314
+ ...permission,
315
+ ownerId: clean(session?.ownerId),
316
+ sessionId: clean(session?.sessionId),
317
+ permissionScopeId: clean(session?.permissionScopeId),
318
+ params,
319
+ pending,
320
+ onEvent: session?.onEvent,
321
+ }
322
+ this.pendingPermissions.set(id, record)
323
+ record.onEvent?.({ type: 'backend.permission.requested', permission })
324
+ signal?.addEventListener('abort', () => {
325
+ this.cancelPermission(record)
326
+ }, { once: true })
327
+ return pending.promise
328
+ }
329
+
330
+ cancelPermission(record) {
331
+ if (!record || !this.pendingPermissions.delete(record.id)) return false
332
+ record.pending.resolve({ outcome: { outcome: 'cancelled' } })
333
+ const permission = {
334
+ id: record.id,
335
+ workId: record.workId,
336
+ status: 'cancelled',
337
+ category: record.category,
338
+ summary: record.summary,
339
+ }
340
+ record.onEvent?.({ type: 'backend.permission.resolved', permission })
341
+ return true
342
+ }
343
+
344
+ async respondPermission(id, decision, { ownerId } = {}) {
345
+ const record = this.pendingPermissions.get(String(id))
346
+ if (!record) {
347
+ const resolved = this.resolvedPermissions.get(String(id))
348
+ if (resolved?.ownerId === clean(ownerId)) return resolved.permission
349
+ }
350
+ if (!record || record.ownerId !== clean(ownerId)) {
351
+ throw new AgentError('权限请求不存在、已经失效或不属于当前用户', {
352
+ protocol: this.protocol,
353
+ })
354
+ }
355
+ this.pendingPermissions.delete(record.id)
356
+ const approved = decision === 'always'
357
+ const option = this.optionFor(
358
+ record.params,
359
+ approved ? 'always' : 'reject',
360
+ )
361
+ record.pending.resolve(option
362
+ ? { outcome: { outcome: 'selected', optionId: option.optionId } }
363
+ : { outcome: { outcome: 'cancelled' } })
364
+ const permission = {
365
+ id: record.id,
366
+ workId: record.workId,
367
+ status: approved ? 'approved' : 'denied',
368
+ category: record.category,
369
+ summary: record.summary,
370
+ }
371
+ record.onEvent?.({ type: 'backend.permission.resolved', permission })
372
+ this.resolvedPermissions.set(permission.id, {
373
+ ownerId: record.ownerId,
374
+ permission,
375
+ })
376
+ while (this.resolvedPermissions.size > 200) {
377
+ this.resolvedPermissions.delete(
378
+ this.resolvedPermissions.keys().next().value,
379
+ )
380
+ }
381
+ return permission
382
+ }
383
+
384
+ cancelPermissionsForScope(permissionScopeId) {
385
+ const scope = clean(permissionScopeId)
386
+ if (!scope) return
387
+ for (const record of this.pendingPermissions.values()) {
388
+ if (record.permissionScopeId !== scope) continue
389
+ this.cancelPermission(record)
390
+ }
391
+ }
392
+
393
+ onSessionUpdate(run, update) {
394
+ run.toolCalls ||= new Map()
395
+ const activity = activityFromUpdate(update, run.toolCalls)
396
+ if (activity) run.onEvent?.({ type: 'backend.activity', activity })
397
+ if (!this.profile.nativeDelegation) return
398
+ if (!['tool_call', 'tool_call_update'].includes(update?.sessionUpdate)) {
399
+ return
400
+ }
401
+ const id = clean(update.toolCallId)
402
+ const merged = {
403
+ ...(run.nativeToolCalls.get(id) || {}),
404
+ ...update,
405
+ }
406
+ run.nativeToolCalls.set(id, merged)
407
+ if (merged.status !== 'completed' || run.delegation) return
408
+ const name = clean(merged.name || merged.title).toLowerCase()
409
+ if (!/sessions_(spawn|send)/.test(name)) return
410
+ const output = nativeToolOutput(merged.rawOutput)
411
+ const sessionId = clean(
412
+ output.childSessionKey
413
+ || output.sessionKey
414
+ || output.session_id
415
+ || output.sessionId,
416
+ )
417
+ if (!sessionId) return
418
+ const delegationId = clean(output.runId)
419
+ if (!delegationId) return
420
+ run.delegation = this.createNativeDelegation(run, {
421
+ delegationId,
422
+ sessionId,
423
+ directory: clean(
424
+ merged.rawInput?.cwd
425
+ || merged.rawInput?.directory
426
+ || this.directory,
427
+ ),
428
+ title: bounded(
429
+ merged.rawInput?.label
430
+ || merged.rawInput?.task
431
+ || merged.rawInput?.message,
432
+ 160,
433
+ ) || this.profile.defaultDelegationTitle || `${this.label} 项目任务`,
434
+ })
435
+ }
436
+
437
+ async listProjectSessions({ query, directory, limit } = {}) {
438
+ const sessions = await this.client.listSessions({
439
+ cwd: clean(directory) || undefined,
440
+ limit: limit || 20,
441
+ })
442
+ this.registry.setProjects(sessions
443
+ .filter(session => clean(session?.sessionId) && clean(session?.cwd))
444
+ .map(session => [
445
+ projectSessionKey(this.protocol, session.sessionId),
446
+ session,
447
+ ]))
448
+ const coordinators = new Set(
449
+ [...this.coordinatorSessions.values()].map(item => item.sessionId),
450
+ )
451
+ const needle = clean(query).toLowerCase()
452
+ return {
453
+ sessions: sessions
454
+ .filter(session => !coordinators.has(clean(session.sessionId)))
455
+ .map(sessionSummary)
456
+ .filter(session => !needle || [
457
+ session.title,
458
+ session.directory,
459
+ ].join(' ').toLowerCase().includes(needle)),
460
+ }
461
+ }
462
+
463
+ rememberProjectSession(session) {
464
+ if (!clean(session?.sessionId) || !clean(session?.cwd)) return
465
+ this.registry.setProject(
466
+ projectSessionKey(this.protocol, session.sessionId),
467
+ session,
468
+ )
469
+ }
470
+
471
+ findDelegation({ delegation_id: delegationId, session_id: sessionId }) {
472
+ return [...this.delegatedWorkRuns.values()]
473
+ .map(run => run.delegation)
474
+ .find(record => (
475
+ (clean(delegationId) && record?.id === clean(delegationId))
476
+ || (clean(sessionId) && record?.sessionId === clean(sessionId))
477
+ ))
478
+ }
479
+
480
+ createDelegation(run, {
481
+ session,
482
+ prompt,
483
+ directory,
484
+ title,
485
+ }) {
486
+ if (run.delegation) {
487
+ throw new AgentError('当前协调轮次已经启动了一个第三层任务', {
488
+ protocol: this.protocol,
489
+ })
490
+ }
491
+ const controller = new AbortController()
492
+ const record = {
493
+ id: `${this.protocol}_run_${randomUUID()}`,
494
+ sessionId: session.sessionId,
495
+ directory,
496
+ title: bounded(title || prompt, 160) || `${this.label} 项目任务`,
497
+ ownerId: run.ownerId,
498
+ workId: run.coordinationRunId,
499
+ status: 'running',
500
+ controller,
501
+ result: null,
502
+ error: null,
503
+ }
504
+ run.delegation = record
505
+ this.delegatedWorkRuns.set(run.coordinationRunId, run)
506
+ record.promise = this.serialize(`target:${record.sessionId}`, async () => {
507
+ const permissionScopeId = `prompt_${randomUUID()}`
508
+ try {
509
+ session.ownerId = run.ownerId
510
+ session.coordinationRunId = run.coordinationRunId
511
+ session.onEvent = run.onEvent
512
+ session.permissionScopeId = permissionScopeId
513
+ const result = await this.client.prompt(record.sessionId, prompt, {
514
+ signal: controller.signal,
515
+ timeoutMs: 0,
516
+ onUpdate: update => this.onSessionUpdate(run, update),
517
+ })
518
+ record.status = 'completed'
519
+ record.result = result
520
+ return {
521
+ id: record.id,
522
+ sessionId: record.sessionId,
523
+ directory: record.directory,
524
+ title: record.title,
525
+ content: result.content,
526
+ }
527
+ } catch (error) {
528
+ record.status = controller.signal.aborted ? 'cancelled' : 'failed'
529
+ record.error = error
530
+ throw error
531
+ } finally {
532
+ this.cancelPermissionsForScope(permissionScopeId)
533
+ if (session.permissionScopeId === permissionScopeId) {
534
+ session.permissionScopeId = null
535
+ }
536
+ }
537
+ })
538
+ record.promise.catch(() => {})
539
+ return record
540
+ }
541
+
542
+ async startProjectSession(run, { prompt, directory, title }) {
543
+ const cwd = clean(directory)
544
+ const session = await this.client.newSession({
545
+ cwd,
546
+ ownerId: run.ownerId,
547
+ role: 'project',
548
+ })
549
+ this.rememberProjectSession({
550
+ ...session,
551
+ cwd,
552
+ title: clean(title || prompt),
553
+ })
554
+ await this.configureSession(session, 'project')
555
+ const record = this.createDelegation(run, {
556
+ session,
557
+ prompt: clean(prompt),
558
+ directory: cwd,
559
+ title,
560
+ })
561
+ return {
562
+ status: 'started',
563
+ delegation_id: record.id,
564
+ session_id: record.sessionId,
565
+ title: record.title,
566
+ directory: record.directory,
567
+ }
568
+ }
569
+
570
+ async continueProjectSession(
571
+ run,
572
+ { session_id: sessionId, prompt, directory },
573
+ ) {
574
+ const requestedDirectory = clean(directory)
575
+ const active = this.findDelegation({ session_id: sessionId })
576
+ const remembered = this.registry.getProject(
577
+ projectSessionKey(this.protocol, sessionId),
578
+ )
579
+ let existing = null
580
+ let cwd = clean(
581
+ requestedDirectory
582
+ || active?.directory
583
+ || remembered?.cwd,
584
+ )
585
+ if (!cwd) {
586
+ const sessions = await this.client.listSessions({
587
+ limit: MAX_SESSION_RESULTS,
588
+ })
589
+ existing = sessions.find(item => (
590
+ clean(item.sessionId) === clean(sessionId)
591
+ ))
592
+ cwd = clean(existing?.cwd)
593
+ }
594
+ if (!cwd) {
595
+ throw new AgentError(
596
+ `${this.label} Session 的项目目录未知,请先查询 Session 列表后再继续`,
597
+ { protocol: this.protocol },
598
+ )
599
+ }
600
+ const session = await this.client.resumeSession(clean(sessionId), {
601
+ cwd,
602
+ ownerId: run.ownerId,
603
+ role: 'project',
604
+ })
605
+ this.rememberProjectSession({
606
+ ...existing,
607
+ ...session,
608
+ cwd,
609
+ title: existing?.title || remembered?.title,
610
+ })
611
+ await this.configureSession(session, 'project')
612
+ const record = this.createDelegation(run, {
613
+ session,
614
+ prompt: clean(prompt),
615
+ directory: cwd,
616
+ title: clean(prompt),
617
+ })
618
+ return {
619
+ status: 'started',
620
+ delegation_id: record.id,
621
+ session_id: record.sessionId,
622
+ title: record.title,
623
+ directory: record.directory,
624
+ }
625
+ }
626
+
627
+ statusForDelegation(input) {
628
+ const record = this.findDelegation(input)
629
+ if (!record) return { status: 'not_found' }
630
+ return {
631
+ status: record.status,
632
+ delegation_id: record.id,
633
+ session_id: record.sessionId,
634
+ title: record.title,
635
+ directory: record.directory,
636
+ ...(record.status === 'completed'
637
+ ? { result: clean(record.result?.content).slice(0, 4000) }
638
+ : {}),
639
+ ...(record.status === 'failed'
640
+ ? { error: clean(record.error?.message || record.error) }
641
+ : {}),
642
+ }
643
+ }
644
+
645
+ async cancelDelegation(input) {
646
+ const record = this.findDelegation(input)
647
+ if (!record) return { status: 'not_found' }
648
+ if (!['completed', 'failed', 'cancelled'].includes(record.status)) {
649
+ record.status = 'cancelled'
650
+ if (this.nativeDelegationAdapter) {
651
+ await this.nativeDelegationAdapter.cancel({
652
+ runId: record.id,
653
+ sessionId: record.sessionId,
654
+ }).catch(() => {})
655
+ }
656
+ record.controller.abort(new Error('用户已取消这项项目任务'))
657
+ if (!this.nativeDelegationAdapter) {
658
+ await this.client.cancelSession(record.sessionId).catch(() => {})
659
+ }
660
+ }
661
+ return {
662
+ status: record.status,
663
+ delegation_id: record.id,
664
+ session_id: record.sessionId,
665
+ }
666
+ }
667
+
668
+ toolContext(run) {
669
+ return {
670
+ listSessions: input => this.listProjectSessions(input),
671
+ startSession: input => this.startProjectSession(run, input),
672
+ sendSession: input => this.continueProjectSession(run, input),
673
+ sessionStatus: input => this.statusForDelegation(input),
674
+ cancelSession: input => this.cancelDelegation(input),
675
+ }
676
+ }
677
+
678
+ coordinatorInstructions(message) {
679
+ const sessionInstructions = this.profile.sessionInstructions || [
680
+ 'The qwen_audio_agent MCP tools are the only interface for opening,',
681
+ 'continuing, querying, and cancelling third-layer project Sessions.',
682
+ 'session_start and session_send are asynchronous. After either returns',
683
+ 'status=started, return the delegated response required by the request',
684
+ 'envelope and stop this turn. Never poll it in the same turn.',
685
+ ].join(' ')
686
+ return [
687
+ '<qwen_audio_agent_backend_instructions>',
688
+ BACKEND_AGENT_INSTRUCTIONS,
689
+ sessionInstructions,
690
+ '</qwen_audio_agent_backend_instructions>',
691
+ '',
692
+ message,
693
+ ].join('\n')
694
+ }
695
+
696
+ async coordinatorTurn(message, {
697
+ ownerId,
698
+ coordinationRunId,
699
+ signal,
700
+ onEvent,
701
+ }) {
702
+ const run = {
703
+ ownerId: clean(ownerId),
704
+ coordinationRunId: clean(coordinationRunId),
705
+ onEvent,
706
+ delegation: null,
707
+ nativeToolCalls: new Map(),
708
+ toolCalls: new Map(),
709
+ initialPromptDone: false,
710
+ }
711
+ const ownerKey = clean(ownerId)
712
+ const pendingFacts = this.pendingCoordinatorFacts.get(ownerKey) || []
713
+ const prompt = pendingFacts.length
714
+ ? [
715
+ '<qwen_audio_agent_reconciliation>',
716
+ ...pendingFacts.map(fact => JSON.stringify(fact)),
717
+ '</qwen_audio_agent_reconciliation>',
718
+ '以上是 Gateway 已执行并验证的控制结果。请更新你的上下文,不要重复执行。',
719
+ '',
720
+ message,
721
+ ].join('\n')
722
+ : message
723
+ let registration = null
724
+ if (this.profile.externalMcp) {
725
+ registration = await this.sessionToolServer.register(
726
+ this.toolContext(run),
727
+ )
728
+ }
729
+ const mcpServers = registration ? [registration.descriptor] : []
730
+ const session = await this.ensureCoordinatorSession(ownerId, mcpServers)
731
+ const permissionScopeId = `prompt_${randomUUID()}`
732
+ run.sessionId = session.sessionId
733
+ session.ownerId = clean(ownerId)
734
+ session.coordinationRunId = clean(coordinationRunId)
735
+ session.onEvent = onEvent
736
+ session.permissionScopeId = permissionScopeId
737
+ this.activeCoordinatorTurns.add(session.sessionId)
738
+ try {
739
+ // Re-supply MCP definitions on resume: ACP Sessions do not require the
740
+ // agent to persist client-provided MCP connections across processes.
741
+ if (registration && !session.isNew) {
742
+ await this.client.resumeSession(session.sessionId, {
743
+ cwd: session.cwd || this.directory,
744
+ mcpServers,
745
+ meta: this.coordinatorMeta(ownerId),
746
+ ownerId,
747
+ role: 'coordinator',
748
+ })
749
+ }
750
+ const result = await this.client.prompt(
751
+ session.sessionId,
752
+ this.coordinatorInstructions(prompt),
753
+ {
754
+ signal,
755
+ timeoutMs: this.timeoutMs,
756
+ onUpdate: update => this.onSessionUpdate(run, update),
757
+ },
758
+ )
759
+ run.initialPromptDone = true
760
+ session.isNew = false
761
+ if (pendingFacts.length) this.pendingCoordinatorFacts.delete(ownerKey)
762
+ this.registry.set(
763
+ coordinatorKey(ownerId, this.protocol),
764
+ session,
765
+ )
766
+ return {
767
+ run,
768
+ session,
769
+ result: {
770
+ ...result,
771
+ content: normalizeCoordinatorContent(result.content),
772
+ },
773
+ }
774
+ } finally {
775
+ this.activeCoordinatorTurns.delete(session.sessionId)
776
+ registration?.release()
777
+ this.cancelPermissionsForScope(permissionScopeId)
778
+ if (session.permissionScopeId === permissionScopeId) {
779
+ session.permissionScopeId = null
780
+ }
781
+ }
782
+ }
783
+
784
+ createNativeDelegation(run, {
785
+ delegationId,
786
+ sessionId,
787
+ directory,
788
+ title,
789
+ }) {
790
+ const controller = new AbortController()
791
+ const record = {
792
+ id: delegationId,
793
+ sessionId,
794
+ directory,
795
+ title,
796
+ ownerId: run.ownerId,
797
+ workId: run.coordinationRunId,
798
+ status: 'running',
799
+ controller,
800
+ result: null,
801
+ error: null,
802
+ parentSessionId: run.sessionId,
803
+ nativeCompletion: deferred(),
804
+ }
805
+ this.delegatedWorkRuns.set(run.coordinationRunId, run)
806
+ record.promise = this.waitForNativeDelegation(record, run)
807
+ record.promise.catch(() => {})
808
+ return record
809
+ }
810
+
811
+ async waitForNativeDelegation(record) {
812
+ try {
813
+ const completed = this.nativeDelegationAdapter
814
+ ? await this.nativeDelegationAdapter.wait({
815
+ runId: record.id,
816
+ sessionId: record.sessionId,
817
+ signal: record.controller.signal,
818
+ })
819
+ : { content: await record.nativeCompletion.promise }
820
+ const content = clean(completed?.content)
821
+ record.status = 'completed'
822
+ record.result = { content }
823
+ return {
824
+ id: record.id,
825
+ sessionId: record.sessionId,
826
+ directory: record.directory,
827
+ title: record.title,
828
+ content,
829
+ }
830
+ } catch (error) {
831
+ record.status = record.controller.signal.aborted ? 'cancelled' : 'failed'
832
+ record.error = error
833
+ throw error
834
+ }
835
+ }
836
+
837
+ delegationResultPrompt(result, coordinationRunId) {
838
+ return [
839
+ '<qwen_audio_agent_delegation_result>',
840
+ JSON.stringify({
841
+ request_id: clean(coordinationRunId),
842
+ delegation_id: result.id,
843
+ target_session_id: result.sessionId,
844
+ directory: result.directory,
845
+ result: clean(result.content).slice(0, MAX_DELEGATION_RESULT_CHARS),
846
+ }, null, 2),
847
+ '</qwen_audio_agent_delegation_result>',
848
+ '这是由 Gateway 验证并关联到当前请求的第三层 Session 最终结果。',
849
+ '请只整理该可信结果并生成 presentation。',
850
+ '返回当前 request_id 的 completed 最终 presentation;',
851
+ '不要再次执行、委托或查询目标任务。',
852
+ ].join('\n')
853
+ }
854
+
855
+ resultEnvelope(initial, delegation = null) {
856
+ return {
857
+ content: initial.result.content,
858
+ raw: initial.result.response,
859
+ protocol: this.protocol,
860
+ metadata: {
861
+ backendRef: {
862
+ provider: this.protocol,
863
+ role: 'backend',
864
+ sessionId: initial.session.sessionId,
865
+ directory: initial.session.cwd || this.directory,
866
+ },
867
+ ...(delegation
868
+ ? {
869
+ delegation: {
870
+ id: delegation.id,
871
+ sessionId: delegation.sessionId,
872
+ title: delegation.title,
873
+ directory: delegation.directory,
874
+ },
875
+ }
876
+ : {}),
877
+ },
878
+ }
879
+ }
880
+
881
+ async runCoordinator(message, {
882
+ ownerId,
883
+ coordinationRunId,
884
+ signal,
885
+ onEvent,
886
+ } = {}) {
887
+ const key = coordinatorKey(ownerId, this.protocol)
888
+ const initial = await this.serialize(
889
+ `coordinator:${key}`,
890
+ () => this.coordinatorTurn(message, {
891
+ ownerId,
892
+ coordinationRunId,
893
+ signal,
894
+ onEvent,
895
+ }),
896
+ )
897
+ if (!initial.run.delegation) return this.resultEnvelope(initial)
898
+ const delegation = initial.run.delegation
899
+ onEvent?.({
900
+ type: 'backend.delegated',
901
+ delegation: {
902
+ id: delegation.id,
903
+ sessionId: delegation.sessionId,
904
+ title: delegation.title,
905
+ directory: delegation.directory,
906
+ presentation: coordinatorPresentation(initial.result.content),
907
+ },
908
+ })
909
+ try {
910
+ const target = await delegation.promise
911
+ onEvent?.({
912
+ type: 'backend.delegation.completed',
913
+ delegation: {
914
+ id: target.id,
915
+ sessionId: target.sessionId,
916
+ title: target.title,
917
+ directory: target.directory,
918
+ },
919
+ })
920
+ const final = await this.serialize(
921
+ `coordinator:${key}`,
922
+ () => this.coordinatorTurn(
923
+ this.delegationResultPrompt(target, coordinationRunId),
924
+ {
925
+ ownerId,
926
+ coordinationRunId,
927
+ signal,
928
+ onEvent,
929
+ },
930
+ ),
931
+ )
932
+ return this.resultEnvelope(final, target)
933
+ } finally {
934
+ this.delegatedWorkRuns.delete(clean(coordinationRunId))
935
+ }
936
+ }
937
+
938
+ canRecoverDelegatedWork(task) {
939
+ return Boolean(
940
+ this.nativeDelegationAdapter
941
+ && task?.delegation?.id
942
+ && task?.delegation?.sessionId,
943
+ )
944
+ }
945
+
946
+ async recoverDelegatedWork(task, {
947
+ signal,
948
+ onEvent,
949
+ } = {}) {
950
+ if (!this.canRecoverDelegatedWork(task)) {
951
+ throw new AgentError(`${this.label} 无法恢复这项第三层任务`, {
952
+ protocol: this.protocol,
953
+ })
954
+ }
955
+ const ownerId = clean(task.ownerId)
956
+ const coordinationRunId = clean(task.id)
957
+ const key = coordinatorKey(ownerId, this.protocol)
958
+ const session = await this.ensureCoordinatorSession(ownerId)
959
+ const run = {
960
+ ownerId,
961
+ coordinationRunId,
962
+ onEvent,
963
+ sessionId: session.sessionId,
964
+ nativeToolCalls: new Map(),
965
+ toolCalls: new Map(),
966
+ initialPromptDone: true,
967
+ delegation: null,
968
+ }
969
+ const saved = task.delegation
970
+ const delegation = this.createNativeDelegation(run, {
971
+ delegationId: clean(saved.id),
972
+ sessionId: clean(saved.sessionId),
973
+ directory: clean(saved.directory || this.directory),
974
+ title: bounded(saved.title || task.objective, 160)
975
+ || this.profile.defaultDelegationTitle
976
+ || `${this.label} 项目任务`,
977
+ })
978
+ signal?.addEventListener('abort', () => {
979
+ delegation.controller.abort(
980
+ signal.reason || new Error('用户已取消这项项目任务'),
981
+ )
982
+ }, { once: true })
983
+ onEvent?.({
984
+ type: 'backend.delegated',
985
+ delegation: {
986
+ id: delegation.id,
987
+ sessionId: delegation.sessionId,
988
+ title: delegation.title,
989
+ directory: delegation.directory,
990
+ presentation: saved.presentation || null,
991
+ },
992
+ })
993
+ try {
994
+ const target = await delegation.promise
995
+ onEvent?.({
996
+ type: 'backend.delegation.completed',
997
+ delegation: {
998
+ id: target.id,
999
+ sessionId: target.sessionId,
1000
+ title: target.title,
1001
+ directory: target.directory,
1002
+ },
1003
+ })
1004
+ const final = await this.serialize(
1005
+ `coordinator:${key}`,
1006
+ () => this.coordinatorTurn(
1007
+ this.delegationResultPrompt(target, coordinationRunId),
1008
+ {
1009
+ ownerId,
1010
+ coordinationRunId,
1011
+ signal,
1012
+ onEvent,
1013
+ },
1014
+ ),
1015
+ )
1016
+ return this.resultEnvelope(final, target)
1017
+ } finally {
1018
+ this.delegatedWorkRuns.delete(coordinationRunId)
1019
+ }
1020
+ }
1021
+
1022
+ async coordinatorControl(workId, prompt, {
1023
+ ownerId,
1024
+ signal,
1025
+ } = {}) {
1026
+ const key = coordinatorKey(ownerId, this.protocol)
1027
+ return this.serialize(
1028
+ `coordinator:${key}`,
1029
+ () => this.coordinatorTurn(prompt, {
1030
+ ownerId,
1031
+ coordinationRunId: workId,
1032
+ signal,
1033
+ onEvent: null,
1034
+ }),
1035
+ )
1036
+ }
1037
+
1038
+ async cancelDelegatedWork(workId, { ownerId, signal } = {}) {
1039
+ const run = this.delegatedWorkRuns.get(clean(workId))
1040
+ const record = run?.delegation
1041
+ if (!record || record.ownerId !== clean(ownerId)) {
1042
+ throw new AgentError(`没有找到可取消的 ${this.label} 项目任务`, {
1043
+ protocol: this.protocol,
1044
+ })
1045
+ }
1046
+ const coordinator = this.coordinatorSessions.get(
1047
+ coordinatorKey(ownerId, this.protocol),
1048
+ )
1049
+ const busy = coordinator
1050
+ && this.activeCoordinatorTurns.has(coordinator.sessionId)
1051
+ if (!busy) {
1052
+ try {
1053
+ const instruction = this.profile.cancelInstruction?.(record)
1054
+ || `请调用 qwen_audio_agent_session_cancel 取消 delegation_id=${record.id}。`
1055
+ await this.coordinatorControl(workId, [
1056
+ '<qwen_audio_agent_control kind="cancel">',
1057
+ instruction,
1058
+ '工具返回后只简短确认,不要做其他工作。',
1059
+ '</qwen_audio_agent_control>',
1060
+ ].join('\n'), { ownerId, signal })
1061
+ return {
1062
+ route: 'coordinator',
1063
+ layer: 'delegated',
1064
+ delegationId: record.id,
1065
+ sessionId: record.sessionId,
1066
+ }
1067
+ } catch {
1068
+ // Cancellation is urgent; fall through to the ACP transport.
1069
+ }
1070
+ }
1071
+ await this.cancelDelegation({ delegation_id: record.id })
1072
+ const ownerKey = clean(ownerId)
1073
+ const facts = this.pendingCoordinatorFacts.get(ownerKey) || []
1074
+ facts.push({
1075
+ kind: 'delegated_session_cancelled',
1076
+ work_id: clean(workId),
1077
+ delegation_id: record.id,
1078
+ target_session_id: record.sessionId,
1079
+ confirmed_at: new Date().toISOString(),
1080
+ })
1081
+ this.pendingCoordinatorFacts.set(ownerKey, facts.slice(-20))
1082
+ return {
1083
+ route: 'adapter',
1084
+ layer: 'delegated',
1085
+ delegationId: record.id,
1086
+ sessionId: record.sessionId,
1087
+ }
1088
+ }
1089
+
1090
+ async queryDelegatedWork(workId, question, { ownerId, signal } = {}) {
1091
+ const run = this.delegatedWorkRuns.get(clean(workId))
1092
+ const record = run?.delegation
1093
+ if (!record || record.ownerId !== clean(ownerId)) {
1094
+ throw new AgentError(`没有找到对应的 ${this.label} 项目任务`, {
1095
+ protocol: this.protocol,
1096
+ })
1097
+ }
1098
+ const instruction = this.profile.statusInstruction?.(record)
1099
+ || `请调用 qwen_audio_agent_session_status 查询 delegation_id=${record.id}。`
1100
+ const result = await this.coordinatorControl(workId, [
1101
+ '<qwen_audio_agent_control kind="status">',
1102
+ instruction,
1103
+ clean(question)
1104
+ ? `用户的具体问题:${clean(question)}`
1105
+ : '请自然地说明当前状态。',
1106
+ '只根据工具结果返回 completed/respond JSON,不要扫描项目或执行任务。',
1107
+ '</qwen_audio_agent_control>',
1108
+ ].join('\n'), { ownerId, signal })
1109
+ return this.resultEnvelope(result, record)
1110
+ }
1111
+
1112
+ async uiUrl(ownerId) {
1113
+ if (!this.profile.uiUrl) return null
1114
+ const key = coordinatorKey(ownerId, this.protocol)
1115
+ const session = this.coordinatorSessions.get(key) || this.registry.get(key)
1116
+ return this.profile.uiUrl({
1117
+ baseUrl: this.baseUrl,
1118
+ sessionId: session?.sessionId || null,
1119
+ ownerId,
1120
+ })
1121
+ }
1122
+
1123
+ async close() {
1124
+ for (const run of this.delegatedWorkRuns.values()) {
1125
+ run.delegation?.controller.abort(
1126
+ new Error(`${this.label} backend is shutting down`),
1127
+ )
1128
+ }
1129
+ for (const record of this.pendingPermissions.values()) {
1130
+ record.pending.resolve({ outcome: { outcome: 'cancelled' } })
1131
+ }
1132
+ this.pendingPermissions.clear()
1133
+ await Promise.allSettled([
1134
+ this.sessionToolServer.close(),
1135
+ this.client.close(),
1136
+ ])
1137
+ }
1138
+ }