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,106 @@
1
+ import {
2
+ mkdirSync,
3
+ readFileSync,
4
+ renameSync,
5
+ writeFileSync,
6
+ } from 'node:fs'
7
+ import { dirname } from 'node:path'
8
+
9
+ const VERSION = 1
10
+
11
+ export class AcpSessionRegistry {
12
+ constructor({ filePath = null } = {}) {
13
+ this.filePath = filePath
14
+ this.loaded = false
15
+ this.coordinators = {}
16
+ this.projects = {}
17
+ }
18
+
19
+ load() {
20
+ if (this.loaded) return
21
+ this.loaded = true
22
+ if (!this.filePath) return
23
+ try {
24
+ const parsed = JSON.parse(readFileSync(this.filePath, 'utf8'))
25
+ if (
26
+ parsed?.version === VERSION
27
+ && parsed.coordinators
28
+ && typeof parsed.coordinators === 'object'
29
+ ) {
30
+ this.coordinators = parsed.coordinators
31
+ this.projects = parsed.projects && typeof parsed.projects === 'object'
32
+ ? parsed.projects
33
+ : {}
34
+ }
35
+ } catch (error) {
36
+ if (error.code !== 'ENOENT') {
37
+ console.warn(`无法读取 ACP Session 索引:${error.message}`)
38
+ }
39
+ }
40
+ }
41
+
42
+ get(key) {
43
+ this.load()
44
+ const value = this.coordinators[String(key)]
45
+ return value && typeof value === 'object' ? { ...value } : null
46
+ }
47
+
48
+ set(key, session) {
49
+ this.load()
50
+ this.coordinators[String(key)] = {
51
+ sessionId: String(session.sessionId),
52
+ cwd: String(session.cwd),
53
+ updatedAt: Date.now(),
54
+ }
55
+ this.save()
56
+ }
57
+
58
+ delete(key) {
59
+ this.load()
60
+ delete this.coordinators[String(key)]
61
+ this.save()
62
+ }
63
+
64
+ getProject(key) {
65
+ this.load()
66
+ const value = this.projects[String(key)]
67
+ return value && typeof value === 'object' ? { ...value } : null
68
+ }
69
+
70
+ setProject(key, session) {
71
+ this.setProjects([[key, session]])
72
+ }
73
+
74
+ setProjects(entries) {
75
+ this.load()
76
+ let changed = false
77
+ for (const [key, session] of entries) {
78
+ const sessionId = String(session.sessionId || '')
79
+ const cwd = String(session.cwd || '')
80
+ if (!sessionId || !cwd) continue
81
+ this.projects[String(key)] = {
82
+ sessionId,
83
+ cwd,
84
+ title: String(session.title || ''),
85
+ updatedAt: Date.now(),
86
+ }
87
+ changed = true
88
+ }
89
+ if (changed) this.save()
90
+ }
91
+
92
+ save() {
93
+ if (!this.filePath) return
94
+ mkdirSync(dirname(this.filePath), { recursive: true })
95
+ const temporary = `${this.filePath}.${process.pid}.tmp`
96
+ writeFileSync(temporary, `${JSON.stringify({
97
+ version: VERSION,
98
+ coordinators: this.coordinators,
99
+ projects: this.projects,
100
+ }, null, 2)}\n`, {
101
+ encoding: 'utf8',
102
+ mode: 0o600,
103
+ })
104
+ renameSync(temporary, this.filePath)
105
+ }
106
+ }
@@ -0,0 +1,257 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { createServer as createHttpServer } from 'node:http'
3
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
4
+ import {
5
+ StreamableHTTPServerTransport,
6
+ } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
7
+ import { z } from 'zod'
8
+
9
+ export const ACP_SESSION_TOOL_SERVER = 'qwen_audio_agent'
10
+ export const ACP_SESSION_TOOL_NAMES = [
11
+ 'qwen_audio_agent_sessions_list',
12
+ 'qwen_audio_agent_session_start',
13
+ 'qwen_audio_agent_session_send',
14
+ 'qwen_audio_agent_session_status',
15
+ 'qwen_audio_agent_session_cancel',
16
+ ]
17
+
18
+ function jsonResult(value, isError = false) {
19
+ return {
20
+ content: [{ type: 'text', text: JSON.stringify(value) }],
21
+ ...(isError ? { isError: true } : {}),
22
+ }
23
+ }
24
+
25
+ function errorResult(error) {
26
+ return jsonResult({
27
+ status: 'failed',
28
+ error: error?.message || String(error),
29
+ }, true)
30
+ }
31
+
32
+ function registerTools(server, context) {
33
+ server.registerTool(
34
+ 'qwen_audio_agent_sessions_list',
35
+ {
36
+ title: 'List Agent Sessions',
37
+ description: 'List existing project Sessions. Use this to find the exact Session when the user asks to continue previous work.',
38
+ inputSchema: {
39
+ query: z.string().optional(),
40
+ directory: z.string().optional(),
41
+ limit: z.number().int().min(1).max(100).optional(),
42
+ },
43
+ annotations: {
44
+ readOnlyHint: true,
45
+ openWorldHint: false,
46
+ },
47
+ },
48
+ async input => {
49
+ try {
50
+ return jsonResult(await context.listSessions(input))
51
+ } catch (error) {
52
+ return errorResult(error)
53
+ }
54
+ },
55
+ )
56
+ server.registerTool(
57
+ 'qwen_audio_agent_session_start',
58
+ {
59
+ title: 'Start Agent Session',
60
+ description: 'Start a new project Session asynchronously. Send only the natural task text and an absolute project directory.',
61
+ inputSchema: {
62
+ prompt: z.string().min(1),
63
+ directory: z.string().min(1),
64
+ title: z.string().optional(),
65
+ },
66
+ },
67
+ async input => {
68
+ try {
69
+ return jsonResult(await context.startSession(input))
70
+ } catch (error) {
71
+ return errorResult(error)
72
+ }
73
+ },
74
+ )
75
+ server.registerTool(
76
+ 'qwen_audio_agent_session_send',
77
+ {
78
+ title: 'Continue Agent Session',
79
+ description: 'Continue an existing project Session asynchronously. Use the exact session_id and absolute project directory returned by the Session list.',
80
+ inputSchema: {
81
+ session_id: z.string().min(1),
82
+ prompt: z.string().min(1),
83
+ directory: z.string().min(1),
84
+ },
85
+ },
86
+ async input => {
87
+ try {
88
+ return jsonResult(await context.sendSession(input))
89
+ } catch (error) {
90
+ return errorResult(error)
91
+ }
92
+ },
93
+ )
94
+ server.registerTool(
95
+ 'qwen_audio_agent_session_status',
96
+ {
97
+ title: 'Query Agent Session',
98
+ description: 'Read the current status and latest known result of a delegated project Session.',
99
+ inputSchema: {
100
+ delegation_id: z.string().optional(),
101
+ session_id: z.string().optional(),
102
+ },
103
+ annotations: {
104
+ readOnlyHint: true,
105
+ openWorldHint: false,
106
+ },
107
+ },
108
+ async input => {
109
+ try {
110
+ return jsonResult(await context.sessionStatus(input))
111
+ } catch (error) {
112
+ return errorResult(error)
113
+ }
114
+ },
115
+ )
116
+ server.registerTool(
117
+ 'qwen_audio_agent_session_cancel',
118
+ {
119
+ title: 'Cancel Agent Session',
120
+ description: 'Cancel a delegated project Session.',
121
+ inputSchema: {
122
+ delegation_id: z.string().optional(),
123
+ session_id: z.string().optional(),
124
+ },
125
+ },
126
+ async input => {
127
+ try {
128
+ return jsonResult(await context.cancelSession(input))
129
+ } catch (error) {
130
+ return errorResult(error)
131
+ }
132
+ },
133
+ )
134
+ }
135
+
136
+ export class AcpSessionToolServer {
137
+ constructor({
138
+ host = '127.0.0.1',
139
+ createServer = createHttpServer,
140
+ } = {}) {
141
+ this.host = host
142
+ this.createServer = createServer
143
+ this.server = null
144
+ this.startPromise = null
145
+ this.port = null
146
+ this.contexts = new Map()
147
+ this.sockets = new Set()
148
+ }
149
+
150
+ async start() {
151
+ if (this.server?.listening) return
152
+ if (this.startPromise) return this.startPromise
153
+ this.startPromise = new Promise((resolve, reject) => {
154
+ const server = this.createServer((req, res) => {
155
+ this.handleRequest(req, res).catch(error => {
156
+ if (res.headersSent) return res.end()
157
+ res.writeHead(500, { 'Content-Type': 'application/json' })
158
+ res.end(JSON.stringify({
159
+ jsonrpc: '2.0',
160
+ id: null,
161
+ error: { code: -32603, message: error.message },
162
+ }))
163
+ })
164
+ })
165
+ server.once('error', reject)
166
+ server.on('connection', socket => {
167
+ this.sockets.add(socket)
168
+ socket.once('close', () => this.sockets.delete(socket))
169
+ })
170
+ server.listen(0, this.host, () => {
171
+ this.server = server
172
+ this.port = server.address().port
173
+ resolve()
174
+ })
175
+ }).finally(() => {
176
+ this.startPromise = null
177
+ })
178
+ return this.startPromise
179
+ }
180
+
181
+ async register(context) {
182
+ await this.start()
183
+ const token = randomUUID()
184
+ this.contexts.set(token, context)
185
+ return {
186
+ descriptor: {
187
+ type: 'http',
188
+ name: ACP_SESSION_TOOL_SERVER,
189
+ url: `http://${this.host}:${this.port}/mcp`,
190
+ headers: [{
191
+ name: 'Authorization',
192
+ value: `Bearer ${token}`,
193
+ }],
194
+ },
195
+ release: () => this.contexts.delete(token),
196
+ }
197
+ }
198
+
199
+ async handleRequest(req, res) {
200
+ const url = new URL(req.url || '/', `http://${this.host}`)
201
+ const authorization = String(req.headers.authorization || '')
202
+ const token = authorization.match(/^Bearer ([^\s]+)$/i)?.[1] || ''
203
+ const context = this.contexts.get(token)
204
+ if (
205
+ url.pathname !== '/mcp'
206
+ || !context
207
+ ) {
208
+ res.writeHead(404)
209
+ res.end()
210
+ return
211
+ }
212
+ if (req.method !== 'POST') {
213
+ res.writeHead(405, {
214
+ 'Content-Type': 'application/json',
215
+ Allow: 'POST',
216
+ })
217
+ res.end(JSON.stringify({
218
+ jsonrpc: '2.0',
219
+ id: null,
220
+ error: { code: -32000, message: 'Method not allowed.' },
221
+ }))
222
+ return
223
+ }
224
+ const server = new McpServer({
225
+ name: ACP_SESSION_TOOL_SERVER,
226
+ version: '1.0.0',
227
+ })
228
+ registerTools(server, context)
229
+ const transport = new StreamableHTTPServerTransport({
230
+ sessionIdGenerator: undefined,
231
+ })
232
+ await server.connect(transport)
233
+ const cleanup = () => {
234
+ transport.close().catch(() => {})
235
+ server.close().catch(() => {})
236
+ }
237
+ res.once('close', cleanup)
238
+ try {
239
+ await transport.handleRequest(req, res)
240
+ } finally {
241
+ if (res.writableEnded) cleanup()
242
+ }
243
+ }
244
+
245
+ async close() {
246
+ this.contexts.clear()
247
+ const server = this.server
248
+ this.server = null
249
+ this.port = null
250
+ if (!server?.listening) return
251
+ await new Promise(resolve => {
252
+ server.close(resolve)
253
+ for (const socket of this.sockets) socket.destroy()
254
+ this.sockets.clear()
255
+ })
256
+ }
257
+ }
@@ -0,0 +1,218 @@
1
+ import { config } from '../core/config.mjs'
2
+ import { AgentError } from './backend-adapter.mjs'
3
+ import { AcpBackendAdapter } from './acp-backend-adapter.mjs'
4
+ import { backendDriver } from './backends/registry.mjs'
5
+
6
+ export { AgentError }
7
+
8
+ export class AgentClient {
9
+ constructor({
10
+ protocol = config.agentProtocol,
11
+ mode = config.backendMode,
12
+ permissionMode = config.backendPermissionMode,
13
+ baseUrl = config.openCodeBaseUrl,
14
+ model,
15
+ timeoutMs = config.agentTimeoutMs,
16
+ directory = config.openCodeDirectory,
17
+ coordinatorAgent = config.openCodeCoordinatorAgent,
18
+ openClawBaseUrl = config.openClawBaseUrl,
19
+ openClawToken = config.openClawToken,
20
+ openClawTokenFile = config.openClawTokenFile,
21
+ openClawCoordinatorAgent = config.openClawCoordinatorAgent,
22
+ openClawDirectory = config.openClawDirectory,
23
+ qoderModel = config.qoderModel,
24
+ qoderDirectory = config.qoderDirectory,
25
+ qoderConfigDirectory = config.qoderConfigDirectory,
26
+ qoderCliPath = config.qoderCliPath,
27
+ hermesDirectory = config.hermesDirectory,
28
+ hermesCliPath = config.hermesCliPath,
29
+ codeBuddyModel = config.codeBuddyModel,
30
+ codeBuddyModelUrl = config.codeBuddyModelUrl,
31
+ codeBuddyDirectory = config.codeBuddyDirectory,
32
+ codeBuddyCliPath = config.codeBuddyCliPath,
33
+ codexModel = config.codexModel,
34
+ codexModelUrl = config.codexModelUrl,
35
+ codexDirectory = config.codexDirectory,
36
+ codexCliPath = config.codexCliPath,
37
+ acpCommand = config.acpCommand,
38
+ acpArgs = config.acpArgs,
39
+ acpLabel = config.acpLabel,
40
+ acpDirectory = config.acpDirectory,
41
+ acpModel = config.acpModel,
42
+ acpCoordinatorAgent = config.acpCoordinatorAgent,
43
+ sessionStatePath = config.backendSessionStatePath,
44
+ acpClient,
45
+ acpClientFactory,
46
+ sessionToolServer,
47
+ } = {}) {
48
+ const driver = backendDriver(protocol)
49
+ const options = driver.resolveOptions({
50
+ baseUrl,
51
+ model,
52
+ openCodeModel: config.openCodeModel,
53
+ openClawModel: config.openClawModel,
54
+ directory,
55
+ coordinatorAgent,
56
+ openClawBaseUrl,
57
+ openClawToken,
58
+ openClawTokenFile,
59
+ openClawCoordinatorAgent,
60
+ openClawDirectory,
61
+ qoderModel,
62
+ qoderDirectory,
63
+ qoderConfigDirectory,
64
+ qoderCliPath,
65
+ hermesDirectory,
66
+ hermesCliPath,
67
+ codeBuddyModel,
68
+ codeBuddyModelUrl,
69
+ codeBuddyDirectory,
70
+ codeBuddyCliPath,
71
+ codexModel,
72
+ codexModelUrl,
73
+ codexDirectory,
74
+ codexCliPath,
75
+ acpCommand,
76
+ acpArgs,
77
+ acpLabel,
78
+ acpDirectory,
79
+ acpModel,
80
+ acpCoordinatorAgent,
81
+ })
82
+ const profile = driver.createProfile({
83
+ protocol,
84
+ root: config.root,
85
+ permissionMode,
86
+ ...options,
87
+ })
88
+ this.adapter = new AcpBackendAdapter({
89
+ protocol,
90
+ root: config.root,
91
+ mode,
92
+ permissionMode,
93
+ timeoutMs,
94
+ ...options,
95
+ profile,
96
+ nativeDelegationAdapter:
97
+ driver.createNativeDelegationAdapter?.(options) || null,
98
+ sessionStatePath,
99
+ ...(acpClient ? { client: acpClient } : {}),
100
+ ...(acpClientFactory ? { clientFactory: acpClientFactory } : {}),
101
+ ...(sessionToolServer ? { sessionToolServer } : {}),
102
+ })
103
+ }
104
+
105
+ get protocol() {
106
+ return this.adapter.protocol
107
+ }
108
+
109
+ get label() {
110
+ return this.adapter.label
111
+ }
112
+
113
+ describe() {
114
+ return this.adapter.describe()
115
+ }
116
+
117
+ async health() {
118
+ try {
119
+ return await this.adapter.health()
120
+ } catch (error) {
121
+ return { ok: false, error: error.message, protocol: this.protocol }
122
+ }
123
+ }
124
+
125
+ runCoordinator(message, options = {}) {
126
+ return this.adapter.runCoordinator(message, options)
127
+ }
128
+
129
+ respondPermission(id, decision, options = {}) {
130
+ if (!this.adapter.respondPermission) {
131
+ throw new AgentError('当前后台 Agent 不支持权限确认', {
132
+ protocol: this.protocol,
133
+ })
134
+ }
135
+ return this.adapter.respondPermission(id, decision, options)
136
+ }
137
+
138
+ cancelDelegatedWork(workId, options = {}) {
139
+ if (!this.adapter.cancelDelegatedWork) {
140
+ throw new AgentError('当前后台 Agent 不支持取消第三层 Session', {
141
+ protocol: this.protocol,
142
+ })
143
+ }
144
+ return this.adapter.cancelDelegatedWork(workId, options)
145
+ }
146
+
147
+ queryDelegatedWork(workId, question, options = {}) {
148
+ if (!this.adapter.queryDelegatedWork) {
149
+ throw new AgentError('当前后台 Agent 不支持查询第三层 Session', {
150
+ protocol: this.protocol,
151
+ })
152
+ }
153
+ return this.adapter.queryDelegatedWork(workId, question, options)
154
+ }
155
+
156
+ canRecoverDelegatedWork(task) {
157
+ return this.adapter.canRecoverDelegatedWork?.(task) === true
158
+ }
159
+
160
+ recoverDelegatedWork(task, options = {}) {
161
+ if (!this.adapter.recoverDelegatedWork) {
162
+ throw new AgentError('当前后台 Agent 不支持恢复第三层 Session', {
163
+ protocol: this.protocol,
164
+ })
165
+ }
166
+ return this.adapter.recoverDelegatedWork(task, options)
167
+ }
168
+
169
+ uiUrl(options = {}) {
170
+ return this.adapter.uiUrl?.(options.ownerId) || Promise.resolve(null)
171
+ }
172
+
173
+ close() {
174
+ return this.adapter.close?.() || Promise.resolve()
175
+ }
176
+ }
177
+
178
+ // The shared client is created lazily so that importing this module never
179
+ // fails in environments without AGENT_PROTOCOL, such as unit tests. The
180
+ // Gateway itself fails fast in resolveManagedBackend before this point.
181
+ let sharedAgent = null
182
+
183
+ function requireAgent() {
184
+ if (!sharedAgent) {
185
+ if (!config.agentProtocol) {
186
+ throw new Error(
187
+ '必须指定后台 Agent:请在 config.env 中设置 AGENT_PROTOCOL',
188
+ )
189
+ }
190
+ sharedAgent = new AgentClient()
191
+ }
192
+ return sharedAgent
193
+ }
194
+
195
+ export const agent = {
196
+ get protocol() {
197
+ return requireAgent().protocol
198
+ },
199
+ get label() {
200
+ return requireAgent().label
201
+ },
202
+ describe: () => requireAgent().describe(),
203
+ health: () => requireAgent().health(),
204
+ runCoordinator: (message, options = {}) =>
205
+ requireAgent().runCoordinator(message, options),
206
+ respondPermission: (id, decision, options = {}) =>
207
+ requireAgent().respondPermission(id, decision, options),
208
+ cancelDelegatedWork: (workId, options = {}) =>
209
+ requireAgent().cancelDelegatedWork(workId, options),
210
+ queryDelegatedWork: (workId, question, options = {}) =>
211
+ requireAgent().queryDelegatedWork(workId, question, options),
212
+ canRecoverDelegatedWork: task =>
213
+ requireAgent().canRecoverDelegatedWork(task),
214
+ recoverDelegatedWork: (task, options = {}) =>
215
+ requireAgent().recoverDelegatedWork(task, options),
216
+ uiUrl: (options = {}) => requireAgent().uiUrl(options),
217
+ close: () => sharedAgent ? sharedAgent.close() : Promise.resolve(),
218
+ }
@@ -0,0 +1,15 @@
1
+ export class AgentError extends Error {
2
+ constructor(message, { status = 0, body = '', protocol = '' } = {}) {
3
+ super(message)
4
+ this.name = 'AgentError'
5
+ this.status = status
6
+ this.body = body
7
+ this.protocol = protocol
8
+ }
9
+ }
10
+
11
+ export function requestSignal(signal, timeoutMs) {
12
+ if (!timeoutMs) return signal
13
+ const timeout = AbortSignal.timeout(timeoutMs)
14
+ return signal ? AbortSignal.any([signal, timeout]) : timeout
15
+ }
@@ -0,0 +1,8 @@
1
+ export const BACKEND_AGENT_INSTRUCTIONS = [
2
+ 'You are the backend Agent for qwen-audio-agent.',
3
+ 'The user experiences the realtime voice frontend and your work as one assistant.',
4
+ 'Use the tools, project context, memory, and permissions already available to you.',
5
+ 'Treat the qwen-audio-agent request envelope as the current user request.',
6
+ 'Follow the response contract inside that envelope exactly.',
7
+ 'Do not expose backend routing, protocol fields, Agent IDs, or Session IDs.',
8
+ ].join('\n')
@@ -0,0 +1,47 @@
1
+ import { baseEnvironment, clean } from './shared.mjs'
2
+
3
+ export const codeBuddyBackendDriver = {
4
+ id: 'codebuddy',
5
+ label: 'CodeBuddy',
6
+
7
+ resolveOptions(options) {
8
+ return {
9
+ baseUrl: '',
10
+ model: options.codeBuddyModel,
11
+ modelUrl: options.codeBuddyModelUrl,
12
+ directory: options.codeBuddyDirectory,
13
+ cliPath: options.codeBuddyCliPath,
14
+ coordinatorAgent: options.coordinatorAgent,
15
+ }
16
+ },
17
+
18
+ createProfile({
19
+ directory,
20
+ cliPath,
21
+ model,
22
+ modelUrl,
23
+ permissionMode,
24
+ }) {
25
+ return {
26
+ label: this.label,
27
+ command: cliPath || 'codebuddy',
28
+ args: [
29
+ '--acp',
30
+ ...(clean(model) ? ['--model', clean(model)] : []),
31
+ ...(permissionMode === 'full'
32
+ ? ['--dangerously-skip-permissions']
33
+ : []),
34
+ ],
35
+ cwd: directory,
36
+ env: {
37
+ ...baseEnvironment(),
38
+ ...(clean(modelUrl)
39
+ ? { CODEBUDDY_MODEL_URL: clean(modelUrl) }
40
+ : {}),
41
+ },
42
+ externalMcp: true,
43
+ nativeDelegation: false,
44
+ backendUi: false,
45
+ }
46
+ },
47
+ }
@@ -0,0 +1,62 @@
1
+ import { resolve } from 'node:path'
2
+ import { baseEnvironment, clean } from './shared.mjs'
3
+
4
+ const CODEX_PROVIDER = 'qwen-audio-agent'
5
+
6
+ export const codexBackendDriver = {
7
+ id: 'codex',
8
+ label: 'Codex',
9
+
10
+ resolveOptions(options) {
11
+ return {
12
+ baseUrl: '',
13
+ model: options.codexModel,
14
+ modelUrl: options.codexModelUrl,
15
+ directory: options.codexDirectory,
16
+ cliPath: options.codexCliPath,
17
+ coordinatorAgent: options.coordinatorAgent,
18
+ }
19
+ },
20
+
21
+ createProfile({
22
+ root,
23
+ directory,
24
+ cliPath,
25
+ model,
26
+ modelUrl,
27
+ permissionMode,
28
+ }) {
29
+ return {
30
+ label: this.label,
31
+ command: cliPath || resolve(root, 'scripts/codex-acp'),
32
+ args: [],
33
+ cwd: directory,
34
+ env: {
35
+ ...baseEnvironment(),
36
+ ...(clean(modelUrl)
37
+ ? {
38
+ MODEL_PROVIDER: CODEX_PROVIDER,
39
+ CODEX_CONFIG: JSON.stringify({
40
+ ...(clean(model) ? { model: clean(model) } : {}),
41
+ model_provider: CODEX_PROVIDER,
42
+ model_providers: {
43
+ [CODEX_PROVIDER]: {
44
+ name: CODEX_PROVIDER,
45
+ base_url: clean(modelUrl),
46
+ env_key: 'DASHSCOPE_API_KEY',
47
+ wire_api: 'responses',
48
+ },
49
+ },
50
+ }),
51
+ }
52
+ : {}),
53
+ ...(permissionMode === 'full'
54
+ ? { INITIAL_AGENT_MODE: 'agent-full-access' }
55
+ : {}),
56
+ },
57
+ externalMcp: true,
58
+ nativeDelegation: false,
59
+ backendUi: false,
60
+ }
61
+ },
62
+ }