qwen-audio-agent 2.0.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +21 -10
  2. package/README_ZH.md +19 -10
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  4. package/cli/package.json +1 -1
  5. package/cli/src/arguments.mjs +4 -1
  6. package/cli/src/config-command.mjs +36 -6
  7. package/cli/src/gateway-service.mjs +7 -1
  8. package/cli/src/launcher.mjs +13 -0
  9. package/config/frontend-agent/LIVE_PROMPT.md +64 -0
  10. package/config/frontend-agent/PROMPT.md +29 -26
  11. package/desktop/src/i18n.mjs +6 -1
  12. package/desktop/src/settings-config.mjs +32 -40
  13. package/desktop/src/settings-store.mjs +19 -28
  14. package/docs/architecture/deep-dive.md +103 -66
  15. package/docs/architecture/deep-dive.zh.md +73 -50
  16. package/docs/backends/configuration.md +4 -4
  17. package/docs/backends/configuration.zh.md +4 -4
  18. package/docs/backends/overview.md +3 -0
  19. package/docs/backends/overview.zh.md +3 -0
  20. package/docs/configuration/backend.md +15 -1
  21. package/docs/configuration/backend.zh.md +15 -1
  22. package/docs/configuration/frontend.md +78 -28
  23. package/docs/configuration/frontend.zh.md +76 -28
  24. package/docs/configuration.md +1 -1
  25. package/docs/configuration.zh.md +1 -1
  26. package/docs/contract.md +24 -2
  27. package/docs/contract.zh.md +20 -2
  28. package/docs/extensions.md +14 -0
  29. package/docs/extensions.zh.md +11 -0
  30. package/docs/gateway-protocol.md +26 -0
  31. package/docs/gateway-protocol.zh.md +22 -0
  32. package/docs/gateway-webrtc-client.md +3 -3
  33. package/docs/gateway-webrtc-client.zh.md +3 -3
  34. package/docs/getting-started/install.md +4 -1
  35. package/docs/getting-started/install.zh.md +4 -1
  36. package/docs/getting-started/mobile.md +8 -2
  37. package/docs/getting-started/mobile.zh.md +5 -0
  38. package/docs/getting-started/quickstart.md +2 -2
  39. package/docs/getting-started/quickstart.zh.md +2 -2
  40. package/docs/getting-started/webui.md +2 -0
  41. package/docs/getting-started/webui.zh.md +2 -0
  42. package/docs/guides/knowledge.md +8 -5
  43. package/docs/guides/knowledge.zh.md +4 -3
  44. package/docs/guides/tasks.md +63 -2
  45. package/docs/guides/tasks.zh.md +45 -1
  46. package/docs/guides/web-search.md +32 -1
  47. package/docs/guides/web-search.zh.md +28 -1
  48. package/docs/operations/troubleshooting.md +30 -0
  49. package/docs/operations/troubleshooting.zh.md +26 -0
  50. package/docs/reference/backend-adapter-sdk.md +33 -2
  51. package/docs/reference/backend-adapter-sdk.zh.md +29 -2
  52. package/docs/reference/cli.md +3 -3
  53. package/docs/reference/cli.zh.md +3 -3
  54. package/docs/scenarios/lightrag.md +2 -2
  55. package/docs/scenarios/lightrag.zh.md +2 -2
  56. package/docs/scenarios/x-omni.md +5 -2
  57. package/docs/scenarios/x-omni.zh.md +5 -2
  58. package/docs/voice-agent-architecture-presentation.zh.md +34 -37
  59. package/docs/voice-frontends/custom-provider.md +22 -4
  60. package/docs/voice-frontends/custom-provider.zh.md +22 -4
  61. package/docs/voice-frontends/google-live.md +14 -8
  62. package/docs/voice-frontends/google-live.zh.md +13 -8
  63. package/docs/voice-frontends/gpt-live-1.md +149 -0
  64. package/docs/voice-frontends/gpt-live-1.zh.md +114 -0
  65. package/docs/voice-frontends/minicpm-o.md +8 -4
  66. package/docs/voice-frontends/minicpm-o.zh.md +7 -4
  67. package/docs/voice-frontends/{gpt-live.md → openai-realtime.md} +19 -10
  68. package/docs/voice-frontends/{gpt-live.zh.md → openai-realtime.zh.md} +18 -10
  69. package/docs/voice-frontends/qwen-audio-live.md +164 -0
  70. package/docs/voice-frontends/qwen-audio-live.zh.md +122 -0
  71. package/docs/voice-frontends/qwen-audio-realtime.md +41 -15
  72. package/docs/voice-frontends/qwen-audio-realtime.zh.md +34 -12
  73. package/docs/voice-frontends/qwen-omni-realtime.md +12 -9
  74. package/docs/voice-frontends/qwen-omni-realtime.zh.md +12 -9
  75. package/docs/voice-frontends/speech-to-speech.md +8 -4
  76. package/docs/voice-frontends/speech-to-speech.zh.md +7 -3
  77. package/docs/voice-frontends/stepfun.md +7 -4
  78. package/docs/voice-frontends/stepfun.zh.md +7 -4
  79. package/examples/webrtc/start.mjs +2 -1
  80. package/package.json +34 -16
  81. package/scripts/audit-dependencies.mjs +3 -25
  82. package/scripts/electron-smoke.mjs +5 -5
  83. package/scripts/patch-build-node-gyp.mjs +63 -0
  84. package/scripts/prepare-build.mjs +2 -0
  85. package/scripts/release-check +2 -2
  86. package/scripts/runtime/claude-code-acp.mjs +5 -5
  87. package/scripts/verify-package.mjs +3 -0
  88. package/server/package.json +5 -5
  89. package/server/src/app/gateway-application.mjs +3 -0
  90. package/server/src/app/gateway-http-routes.mjs +3 -0
  91. package/server/src/app/session-conversation-history.mjs +9 -1
  92. package/server/src/backend/adapters/a2a/backend-adapter.mjs +32 -26
  93. package/server/src/backend/adapters/acp/backend-adapter.mjs +703 -251
  94. package/server/src/backend/adapters/acp/coordinator-contract.mjs +2 -13
  95. package/server/src/backend/adapters/acp/coordinator-instructions.mjs +29 -8
  96. package/server/src/backend/adapters/acp/coordinator-queue.mjs +58 -0
  97. package/server/src/backend/adapters/acp/drivers/codex.mjs +1 -1
  98. package/server/src/backend/adapters/acp/drivers/openclaw.mjs +1 -2
  99. package/server/src/backend/adapters/acp/input-broker.mjs +2 -0
  100. package/server/src/backend/adapters/acp/process-client.mjs +111 -16
  101. package/server/src/backend/adapters/acp/session-configuration.mjs +2 -19
  102. package/server/src/backend/adapters/acp/session-registry.mjs +9 -0
  103. package/server/src/backend/adapters/acp/session-tools.mjs +1 -1
  104. package/server/src/backend/adapters/acp/turn-updates.mjs +188 -0
  105. package/server/src/backend/adapters/acp/work-continuation.mjs +48 -0
  106. package/server/src/backend/adapters/agent-client.mjs +24 -1
  107. package/server/src/backend/adapters/llm/backend-adapter.mjs +393 -0
  108. package/server/src/backend/adapters/muse/backend-adapter.mjs +2 -0
  109. package/server/src/backend/availability.mjs +12 -3
  110. package/server/src/backend/backend-adapter-sdk.mjs +3 -0
  111. package/server/src/backend/backend-port.mjs +13 -0
  112. package/server/src/backend/backend-work-runtime.mjs +23 -0
  113. package/server/src/client/client-command-runtime.mjs +14 -0
  114. package/server/src/conversation/conversation-sync.mjs +26 -2
  115. package/server/src/conversation/frontend-agent-context.mjs +18 -5
  116. package/server/src/conversation/frontend-notes.mjs +7 -5
  117. package/server/src/conversation/task-result-projector.mjs +1 -1
  118. package/server/src/core/backend-events.mjs +4 -0
  119. package/server/src/core/citation.mjs +8 -2
  120. package/server/src/core/config.mjs +46 -54
  121. package/server/src/core/gateway-protocol.mjs +4 -1
  122. package/server/src/core/request-security.mjs +7 -1
  123. package/server/src/core/work-conversation-context.mjs +138 -0
  124. package/server/src/core/work-input-request.mjs +1 -0
  125. package/server/src/frontend/frontend-tools.mjs +20 -7
  126. package/server/src/frontend/retrieval/providers/bing.mjs +23 -12
  127. package/server/src/frontend/retrieval/providers/factory.mjs +18 -1
  128. package/server/src/frontend/retrieval/providers/mcp.mjs +30 -11
  129. package/server/src/frontend/retrieval/providers/so360.mjs +23 -12
  130. package/server/src/frontend/tools/agent-task-runtime.mjs +119 -99
  131. package/server/src/frontend/tools/features/agent-task-tools.mjs +23 -42
  132. package/server/src/frontend/tools/frontend-tool-context.mjs +2 -2
  133. package/server/src/frontend/tools/spawn-thinking-tool.mjs +2 -2
  134. package/server/src/frontend/tools/tool-call-handler.mjs +166 -86
  135. package/server/src/knowledge/providers/local/library.mjs +26 -6
  136. package/server/src/knowledge/providers/local/provider.mjs +25 -6
  137. package/server/src/memory/providers/markdown/context-store.mjs +24 -11
  138. package/server/src/orchestration/session-task-coordinator.mjs +13 -3
  139. package/server/src/orchestration/task-operations.mjs +54 -12
  140. package/server/src/orchestration/task-updates.mjs +82 -0
  141. package/server/src/task/reminder-scheduler.mjs +5 -1
  142. package/server/src/task/task-manager.mjs +72 -15
  143. package/server/src/task/task-recovery.mjs +12 -2
  144. package/server/src/task/task-scheduler.mjs +5 -5
  145. package/server/src/task/task-state.mjs +13 -0
  146. package/server/src/transport/gateway-client-transport.mjs +35 -0
  147. package/server/src/transport/webrtc/protocol.mjs +1 -1
  148. package/server/src/voice/announcement/announcement-manager.mjs +3 -0
  149. package/server/src/voice/audio-stream-diagnostics.mjs +139 -0
  150. package/server/src/voice/native-delegation-runtime.mjs +360 -0
  151. package/server/src/voice/providers/dashscope-live.mjs +93 -0
  152. package/server/src/voice/providers/dashscope.mjs +45 -33
  153. package/server/src/voice/providers/doubao-seeduplex-protocol.mjs +54 -0
  154. package/server/src/voice/providers/doubao-seeduplex.mjs +16 -11
  155. package/server/src/voice/providers/ga-protocol.mjs +7 -2
  156. package/server/src/voice/providers/google-live-protocol.mjs +124 -34
  157. package/server/src/voice/providers/google-live.mjs +20 -14
  158. package/server/src/voice/providers/gpt-live-1-protocol.mjs +597 -0
  159. package/server/src/voice/providers/gpt-live-1.mjs +3 -0
  160. package/server/src/voice/providers/gpt-live-client-context.mjs +182 -0
  161. package/server/src/voice/providers/minicpm-o.mjs +9 -7
  162. package/server/src/voice/providers/openai-live.mjs +150 -0
  163. package/server/src/voice/providers/{gpt-live.mjs → openai-realtime.mjs} +23 -19
  164. package/server/src/voice/providers/provider-registry.mjs +11 -1
  165. package/server/src/voice/providers/qwen-live-protocol.mjs +399 -0
  166. package/server/src/voice/providers/registry.mjs +47 -12
  167. package/server/src/voice/providers/runtime-configuration.mjs +34 -0
  168. package/server/src/voice/providers/s2s.mjs +9 -7
  169. package/server/src/voice/providers/stepfun.mjs +14 -11
  170. package/server/src/voice/realtime-input-runtime.mjs +58 -20
  171. package/server/src/voice/realtime-presentation-runtime.mjs +111 -27
  172. package/server/src/voice/realtime-provider-session.mjs +59 -14
  173. package/server/src/voice/realtime-provider.mjs +358 -45
  174. package/server/src/voice/realtime-session-runtime.mjs +282 -35
  175. package/server/src/voice/realtime-task-presentation.mjs +8 -2
  176. package/server/src/voice/realtime-turn-state.mjs +33 -2
  177. package/shared/backend/catalog.mjs +26 -2
  178. package/shared/backend/install.mjs +3 -1
  179. package/shared/backend/setup.mjs +43 -0
  180. package/shared/gateway/client-sdk.mjs +21 -6
  181. package/shared/gateway/setup.mjs +13 -1
  182. package/shared/gateway/websocket-auth.mjs +2 -1
  183. package/shared/protocol/gateway-client-protocol.mjs +14 -0
  184. package/shared/protocol/gateway-events.mjs +39 -1
  185. package/shared/realtime-legacy-environment.mjs +81 -0
  186. package/shared/realtime-model-catalog.mjs +68 -194
  187. package/shared/realtime-models/README.md +33 -0
  188. package/shared/realtime-models/dashscope.mjs +57 -0
  189. package/shared/realtime-models/google.mjs +10 -0
  190. package/shared/realtime-models/openai.mjs +24 -0
  191. package/shared/realtime-models/profile.mjs +38 -0
  192. package/shared/realtime-models/stepfun.mjs +10 -0
  193. package/shared/realtime-models/volcengine.mjs +12 -0
  194. package/shared/realtime-provider-catalog.mjs +23 -11
  195. package/shared/realtime-provider-definitions.mjs +168 -235
  196. package/shared/runtime-environment.mjs +23 -30
  197. package/shared/skill-library.mjs +49 -13
  198. package/shared/web-search-configuration.mjs +25 -2
  199. package/tui/package.json +2 -2
  200. package/tui/src/index.mjs +14 -9
  201. package/tui/src/runtime-configuration.mjs +2 -0
  202. package/tui/src/terminal-commands.mjs +40 -0
  203. package/tui/src/text-cli.mjs +10 -1
  204. package/web/dist/assets/index-Bc2Q04J9.css +1 -0
  205. package/web/dist/assets/index-bY4DFXKT.js +96 -0
  206. package/web/dist/index.html +2 -2
  207. package/web/dist/assets/index-BRaiI-dW.js +0 -91
  208. package/web/dist/assets/index-D9k8R2JY.css +0 -1
@@ -1,16 +1,5 @@
1
1
  import { backendInstructionFromWork } from '../../backend-work-input.mjs'
2
- import { COORDINATOR_STABLE_INSTRUCTIONS } from './coordinator-instructions.mjs'
3
2
 
4
- export function buildAcpCoordinatorInstruction({
5
- includeStableInstructions = true,
6
- ...work
7
- } = {}) {
8
- const instruction = backendInstructionFromWork(work)
9
-
10
- return [
11
- instruction,
12
- ...(includeStableInstructions
13
- ? ['', COORDINATOR_STABLE_INSTRUCTIONS]
14
- : []),
15
- ].filter(Boolean).join('\n')
3
+ export function buildAcpCoordinatorInstruction(work = {}) {
4
+ return backendInstructionFromWork(work)
16
5
  }
@@ -1,19 +1,40 @@
1
1
  // Claude Code has the strictest verified per-server budget.
2
2
  // Keeping one portable payload avoids host-specific instruction variants.
3
3
  export const COORDINATOR_MCP_INSTRUCTIONS_MAX_BYTES = 2 * 1024
4
+ export const COORDINATOR_PROMPT_REFRESH_INTERVAL = 20
4
5
 
5
- export const COORDINATOR_STABLE_INSTRUCTIONS = [
6
+ const COMMON_INSTRUCTIONS = [
6
7
  'Act as qwen-audio-agent\'s backend; the user sees one assistant. Use available capabilities and preserve requested action level.',
7
8
  'State that work succeeded only after it is confirmed. Keep routing, protocol, task state, and IDs out of user-facing output; send project Sessions only natural task text.',
8
9
  'Do not modify qwen-audio-agent unless explicitly requested.',
9
- 'Treat each incoming natural-language instruction as self-contained; attached ACP ContentBlocks are original user inputs.',
10
- 'Act only on the stated request. Do not infer additional goals from earlier coordinator-session history or transport metadata.',
11
- '',
10
+ 'Updates continue the referenced work using its history and completed actions; interruption does not undo actions. Attached ACP ContentBlocks are user inputs.',
11
+ 'Follow the current request. Recent conversation is reference context, not additional work; do not infer new goals from history or transport metadata.',
12
+ ].join('\n')
13
+
14
+ const PROJECT_INSTRUCTIONS = [
12
15
  'Project Session routing:',
13
- '- Start a new project Session only when the user explicitly asks to run this work as a separate independent task; never infer this from the objective.',
14
- '- Continue an existing project Session only when the user asks to resume or update that work; execute all other requests here.',
16
+ '- Use a project Session for work with a distinct goal that benefits from sustained, independent execution.',
17
+ '- Handle brief operations, clarification, and result synthesis in this Session.',
18
+ '- Continue related follow-ups in the original project Session rather than creating another.',
19
+ '- The user does not need to request a separate Session.',
15
20
  '- After a start or continue action succeeds, end the turn without querying, repeating, or claiming completion; its verified result will be supplied in a later turn.',
16
21
  '- Query status only for an existing independent task; report failure instead of substituting another tool.',
17
- '',
18
- 'For work handled in this Session, return the final user-facing answer as ordinary text and any supported ACP ContentBlocks.',
19
22
  ].join('\n')
23
+
24
+ export function stableCoordinatorInstructions(profile = {}) {
25
+ return [
26
+ COMMON_INSTRUCTIONS,
27
+ ...(profile.delegation !== false ? [PROJECT_INSTRUCTIONS] : []),
28
+ 'For work handled in this Session, return the final user-facing answer as ordinary text and any supported ACP ContentBlocks.',
29
+ String(profile.sessionInstructions || '').trim(),
30
+ ].filter(Boolean).join('\n\n')
31
+ }
32
+
33
+ export const COORDINATOR_STABLE_INSTRUCTIONS = stableCoordinatorInstructions()
34
+
35
+ export function coordinatorUsesMcpInstructions(profile) {
36
+ return profile.externalMcp === true
37
+ && profile.coordinatorMcpInstructions === true
38
+ && Buffer.byteLength(stableCoordinatorInstructions(profile), 'utf8')
39
+ <= COORDINATOR_MCP_INSTRUCTIONS_MAX_BYTES
40
+ }
@@ -0,0 +1,58 @@
1
+ /** Serializes coordinator turns per owner; delegated execution does not hold a lease. */
2
+ export class CoordinatorQueue {
3
+ constructor() {
4
+ this.owners = new Map()
5
+ this.closed = false
6
+ }
7
+
8
+ acquire(ownerKey, { signal } = {}) {
9
+ if (this.closed) return Promise.reject(new Error('Coordinator queue is closed'))
10
+ if (signal?.aborted) return Promise.reject(signal.reason ?? new Error('任务已取消'))
11
+ let state = this.owners.get(ownerKey)
12
+ if (!state) {
13
+ state = { busy: false, waiting: [] }
14
+ this.owners.set(ownerKey, state)
15
+ }
16
+ return new Promise((resolve, reject) => {
17
+ const waiter = { resolve, reject, signal }
18
+ waiter.abort = () => {
19
+ state.waiting = state.waiting.filter(item => item !== waiter)
20
+ signal?.removeEventListener('abort', waiter.abort)
21
+ reject(signal.reason ?? new Error('任务已取消'))
22
+ this.drain(ownerKey, state)
23
+ }
24
+ signal?.addEventListener('abort', waiter.abort, { once: true })
25
+ state.waiting.push(waiter)
26
+ this.drain(ownerKey, state)
27
+ })
28
+ }
29
+
30
+ drain(ownerKey, state) {
31
+ if (this.closed || state.busy) return
32
+ const waiter = state.waiting.shift()
33
+ if (!waiter) {
34
+ this.owners.delete(ownerKey)
35
+ return
36
+ }
37
+ waiter.signal?.removeEventListener('abort', waiter.abort)
38
+ state.busy = true
39
+ let released = false
40
+ waiter.resolve({ key: ownerKey, release: () => {
41
+ if (released) return
42
+ released = true
43
+ state.busy = false
44
+ this.drain(ownerKey, state)
45
+ } })
46
+ }
47
+
48
+ close() {
49
+ this.closed = true
50
+ for (const state of this.owners.values()) {
51
+ for (const waiter of state.waiting.splice(0)) {
52
+ waiter.signal?.removeEventListener('abort', waiter.abort)
53
+ waiter.reject(new Error('Coordinator queue is closed'))
54
+ }
55
+ }
56
+ this.owners.clear()
57
+ }
58
+ }
@@ -14,7 +14,7 @@ export const codexBackendDriver = {
14
14
  externalMcp: true,
15
15
  nativeDelegation: false,
16
16
  sessionMcp: true,
17
- coordinatorMcpInstructions: false,
17
+ coordinatorMcpInstructions: true,
18
18
  },
19
19
 
20
20
  createProfile({
@@ -122,8 +122,7 @@ export const openClawBackendDriver = {
122
122
  },
123
123
  defaultDelegationTitle: 'OpenClaw 项目任务',
124
124
  sessionInstructions: [
125
- 'When the current request explicitly requires a new or previous',
126
- 'project Session, use OpenClaw native Session tools:',
125
+ 'OpenClaw native Session tools:',
127
126
  'sessions_spawn to create work, sessions_list to locate prior Sessions,',
128
127
  'sessions_send to continue one, and sessions_history for status.',
129
128
  ].join(' '),
@@ -101,6 +101,8 @@ export class InputBroker {
101
101
  protocol: this.protocol,
102
102
  })
103
103
  }
104
+ // MCP elicitation's accept means submitting content, not approving an
105
+ // operation. Keep natural-language replies in content for the agent.
104
106
  const action = ['accept', 'decline', 'cancel'].includes(response.action)
105
107
  ? response.action
106
108
  : 'accept'
@@ -3,6 +3,7 @@ import { extname } from 'node:path'
3
3
  import { Readable, Writable } from 'node:stream'
4
4
  import { stripVTControlCharacters } from 'node:util'
5
5
  import * as acp from '@agentclientprotocol/sdk'
6
+ import { z } from 'zod'
6
7
  import { PACKAGE_VERSION } from '../../../core/package-version.mjs'
7
8
  import { AgentError } from '../../agent-error.mjs'
8
9
  import { requestSignal } from './request-signal.mjs'
@@ -19,6 +20,35 @@ const MAX_STDERR_CHARS = 12_000
19
20
  // logger cleanup after escalating an unresponsive process tree.
20
21
  const PROCESS_TREE_GRACE_MS = 750
21
22
  const PROCESS_TREE_POLL_MS = 25
23
+ // Keep cmd.exe quoting in sync with scripts/runtime/launcher.mjs. Carets
24
+ // inside quotes are literal, so metacharacters are escaped only outside them.
25
+ const CMD_META_CHARS = /["()%!^<>&|]/g
26
+
27
+ function escapeCmdValue(value) {
28
+ let quoted = false
29
+ return value.replace(CMD_META_CHARS, character => {
30
+ if (character === '"') {
31
+ quoted = !quoted
32
+ return character
33
+ }
34
+ return quoted ? character : `^${character}`
35
+ })
36
+ }
37
+
38
+ function quoteCmdArgument(value) {
39
+ const quoted = String(value)
40
+ .replace(/(\\*)"/g, '$1$1\\"')
41
+ .replace(/(\\*)$/g, '$1$1')
42
+ return escapeCmdValue(`"${quoted}"`)
43
+ }
44
+
45
+ function quoteCmdCommand(value) {
46
+ return escapeCmdValue(`"${String(value).replace(/"/g, '""')}"`)
47
+ }
48
+
49
+ function windowsComSpec(env) {
50
+ return clean(env?.ComSpec || env?.COMSPEC) || 'cmd.exe'
51
+ }
22
52
 
23
53
  function clean(value) {
24
54
  return String(value || '').trim()
@@ -136,6 +166,7 @@ export class AcpProcessClient {
136
166
  this.stderr = ''
137
167
  this.activePrompts = new Map()
138
168
  this.sessions = new Map()
169
+ this.midTurnPullSessions = new Set()
139
170
  this.processTreeCleanups = new WeakMap()
140
171
  }
141
172
 
@@ -183,23 +214,33 @@ export class AcpProcessClient {
183
214
  this.stderr = ''
184
215
  await this.prepare?.()
185
216
  const isWindows = this.platform === 'win32'
186
- // .exe 文件不需要 cmd.exe 包装;直接 spawn 避免路径含空格时
187
- // cmd.exe 将第一个空格前的内容误解析为命令名。
217
+ // .exe 不经 cmd.exe;.cmd/.bat 以及无扩展名的 Windows 命令必须走 cmd.exe,
218
+ // 否则 Node 无法启动批处理,PATHEXT 解析也会失败。
188
219
  const commandExt = isWindows ? extname(String(this.command)).toLowerCase() : ''
189
- const useShell = isWindows && commandExt !== '.exe'
190
- // cmd.exe 只把命令与参数按空格拼接:含空格的 .cmd/.bat 路径或参数需要加引号,
191
- // 否则命令会在第一个空格处被截断,参数也会被拆开。
192
- const shellArgument = value => {
193
- const text = String(value)
194
- return useShell && /\s/.test(text) && !/^".*"$/.test(text) ? `"${text}"` : text
220
+ const useCmd = isWindows && commandExt !== '.exe'
221
+ let spawnCommand = this.command
222
+ let spawnArgs = this.args
223
+ const spawnOptions = {
224
+ cwd: this.cwd,
225
+ env: this.env,
226
+ stdio: ['pipe', 'pipe', 'pipe'],
227
+ shell: false,
228
+ detached: !isWindows,
229
+ windowsHide: true,
195
230
  }
196
- const child = this.spawn(shellArgument(this.command), this.args.map(shellArgument), {
197
- cwd: this.cwd,
198
- env: this.env,
199
- stdio: ['pipe', 'pipe', 'pipe'],
200
- shell: useShell,
201
- detached: !isWindows,
202
- })
231
+ if (useCmd) {
232
+ // shell:true 只按空格拼接。C:\R&D\agent.cmd 或参数 a&b 即使没有空格
233
+ // 也会被 cmd.exe 拆成多条命令。这里与 runtime launcher 一样显式
234
+ // 调用 cmd.exe /d /s /c,并按 Windows 规则引用每个参数。
235
+ const commandLine = [
236
+ quoteCmdCommand(this.command),
237
+ ...this.args.map(quoteCmdArgument),
238
+ ].join(' ')
239
+ spawnCommand = windowsComSpec(this.env)
240
+ spawnArgs = ['/d', '/s', '/c', `"${commandLine}"`]
241
+ spawnOptions.windowsVerbatimArguments = true
242
+ }
243
+ const child = this.spawn(spawnCommand, spawnArgs, spawnOptions)
203
244
  const processLogger = logger.child({ subsystem: 'acp', backend: this.label })
204
245
  processLogger.info('acp.process_started', {
205
246
  pid: child.pid,
@@ -212,6 +253,8 @@ export class AcpProcessClient {
212
253
  Readable.toWeb(child.stdout),
213
254
  )
214
255
  const app = acp.client({ name: 'qwen-audio-agent' })
256
+ .onRequest('craft/drainMidTurnQueue', z.object({ sessionId: z.string() }).passthrough(),
257
+ context => this.drainMidTurnQueue(context.params))
215
258
  .onRequest(
216
259
  acp.methods.client.session.requestPermission,
217
260
  context => this.handlePermission(context.params, context.signal),
@@ -292,6 +335,7 @@ export class AcpProcessClient {
292
335
  this.connection = null
293
336
  this.context = null
294
337
  this.initializeResult = null
338
+ this.midTurnPullSessions.clear()
295
339
  }).catch(() => {})
296
340
  this.connectionGeneration += 1
297
341
  return this.initializeResult
@@ -370,17 +414,41 @@ export class AcpProcessClient {
370
414
  }
371
415
  }
372
416
 
417
+ drainMidTurnQueue({ sessionId }) {
418
+ if (!this.sessions.has(sessionId)) return { items: [], hasQueuedPrompt: false }
419
+ this.midTurnPullSessions.add(sessionId)
420
+ return this.activePrompts.get(sessionId)?.onMidTurnDrain?.()
421
+ || { items: [], hasQueuedPrompt: false }
422
+ }
423
+
424
+ steeringMode(sessionId) {
425
+ if (this.initializeResult?._meta?.steering?.supported === true) return 'extension'
426
+ if (this.midTurnPullSessions.has(sessionId)) return 'pull'
427
+ return 'restart'
428
+ }
429
+
430
+ steerSession(sessionId, prompt, { signal } = {}) {
431
+ const blocks = normalizeAcpPrompt(prompt)
432
+ assertPromptCapabilities(blocks, this.capabilities)
433
+ return this.request('_session/steering', {
434
+ sessionId, prompt: blocks,
435
+ _meta: { steering: { idleBehavior: 'promptRequired' } },
436
+ }, { timeoutMs: 15_000, ...(signal ? { signal } : {}) })
437
+ }
438
+
373
439
  requestSignal(signal, timeoutMs = this.timeoutMs) {
374
440
  return requestSignal(signal, timeoutMs)
375
441
  }
376
442
 
377
443
  async request(method, params, {
378
444
  signal,
445
+ guardSignal,
379
446
  timeoutMs = this.timeoutMs,
380
447
  } = {}) {
381
448
  let processOutputBefore = ''
382
449
  try {
383
450
  await this.start()
451
+ guardSignal?.throwIfAborted()
384
452
  processOutputBefore = cleanProcessOutput(
385
453
  this.stderr,
386
454
  this.sanitizeProcessOutput,
@@ -390,6 +458,7 @@ export class AcpProcessClient {
390
458
  })
391
459
  } catch (error) {
392
460
  if (signal?.aborted) throw signal.reason
461
+ if (guardSignal?.aborted) throw guardSignal.reason
393
462
  const isRequestError = error?.name === 'RequestError'
394
463
  const processOutput = cleanProcessOutput(
395
464
  this.stderr,
@@ -530,6 +599,8 @@ export class AcpProcessClient {
530
599
  signal,
531
600
  timeoutMs = this.timeoutMs,
532
601
  onUpdate,
602
+ onMidTurnDrain,
603
+ cancelTimeoutMs = 15_000,
533
604
  } = {}) {
534
605
  const id = String(sessionId)
535
606
  if (this.activePrompts.has(id)) {
@@ -539,10 +610,18 @@ export class AcpProcessClient {
539
610
  )
540
611
  }
541
612
  await this.start()
613
+ signal?.throwIfAborted()
614
+ if (this.activePrompts.has(id)) {
615
+ throw new AgentError(`${this.label} Session ${id} 已有正在执行的请求`, {
616
+ status: 409, protocol: 'acp',
617
+ })
618
+ }
542
619
  const promptBlocks = normalizeAcpPrompt(prompt)
543
620
  assertPromptCapabilities(promptBlocks, this.capabilities)
544
621
  const timeoutController = new AbortController()
622
+ const remoteController = new AbortController()
545
623
  let timeoutTimer = null
624
+ let cancellationTimer = null
546
625
  let permissionDepth = 0
547
626
  const armTimeout = () => {
548
627
  clearTimeout(timeoutTimer)
@@ -560,6 +639,7 @@ export class AcpProcessClient {
560
639
  text: [],
561
640
  contentBlocks: [],
562
641
  onUpdate,
642
+ onMidTurnDrain,
563
643
  pauseTimeout: () => {
564
644
  permissionDepth += 1
565
645
  clearTimeout(timeoutTimer)
@@ -579,6 +659,16 @@ export class AcpProcessClient {
579
659
  this.notify(acp.methods.agent.session.cancel, {
580
660
  sessionId: id,
581
661
  }).catch(() => {})
662
+ // Keep the prompt RPC alive until the Agent confirms its terminal result.
663
+ // Aborting the local RPC immediately would let the next pool tenant start
664
+ // a prompt while the old execution can still emit updates or permissions.
665
+ cancellationTimer = setTimeout(() => {
666
+ const error = new AgentError(`${this.label} 未确认 Session 已停止`, {
667
+ status: 504, protocol: 'acp',
668
+ })
669
+ error.contextUncertain = true
670
+ remoteController.abort(error)
671
+ }, cancelTimeoutMs)
582
672
  }
583
673
  combined?.addEventListener('abort', cancel, { once: true })
584
674
  if (combined?.aborted) cancel()
@@ -591,15 +681,18 @@ export class AcpProcessClient {
591
681
  sessionId: id,
592
682
  prompt: promptBlocks,
593
683
  },
594
- { signal: combined, timeoutMs: 0 },
684
+ { signal: remoteController.signal, guardSignal: combined, timeoutMs: 0 },
595
685
  )
596
686
  } catch (error) {
687
+ if (error.contextUncertain) throw error
597
688
  if (!timeoutController.signal.aborted || signal?.aborted) throw error
598
689
  throw new AgentError(
599
690
  `${this.label} ACP 请求超时(${timeoutDuration(timeoutMs)})`,
600
691
  { status: 504, protocol: 'acp' },
601
692
  )
602
693
  }
694
+ if (remoteController.signal.aborted) throw remoteController.signal.reason
695
+ signal?.throwIfAborted()
603
696
  if (timeoutController.signal.aborted && !signal?.aborted) {
604
697
  throw new AgentError(
605
698
  `${this.label} ACP 请求超时(${timeoutDuration(timeoutMs)})`,
@@ -614,6 +707,7 @@ export class AcpProcessClient {
614
707
  }
615
708
  } finally {
616
709
  clearTimeout(timeoutTimer)
710
+ clearTimeout(cancellationTimer)
617
711
  combined?.removeEventListener('abort', cancel)
618
712
  if (this.activePrompts.get(id) === active) {
619
713
  this.activePrompts.delete(id)
@@ -676,6 +770,7 @@ export class AcpProcessClient {
676
770
  this.context = null
677
771
  this.initializeResult = null
678
772
  connection?.close()
773
+ this.midTurnPullSessions.clear()
679
774
  if (child) await this.stopProcessTree(child)
680
775
  this.child = null
681
776
  }
@@ -1,8 +1,4 @@
1
1
  import { AgentError } from '../../agent-error.mjs'
2
- import {
3
- COORDINATOR_MCP_INSTRUCTIONS_MAX_BYTES,
4
- COORDINATOR_STABLE_INSTRUCTIONS,
5
- } from './coordinator-instructions.mjs'
6
2
 
7
3
  function clean(value) {
8
4
  return String(value || '').trim()
@@ -48,21 +44,8 @@ export function normalizeAcpModel(value) {
48
44
  return model.toLowerCase() === 'auto' ? '' : model
49
45
  }
50
46
 
51
- export function stableCoordinatorInstructions(profile) {
52
- return [
53
- COORDINATOR_STABLE_INSTRUCTIONS,
54
- clean(profile.sessionInstructions),
55
- ].filter(Boolean).join('\n\n')
56
- }
57
-
58
- export function coordinatorUsesMcpInstructions(profile) {
59
- return profile.coordinatorMcpInstructions === true
60
- && Buffer.byteLength(stableCoordinatorInstructions(profile), 'utf8')
61
- <= COORDINATOR_MCP_INSTRUCTIONS_MAX_BYTES
62
- }
63
-
64
- export function coordinatorMeta(profile, ownerId) {
65
- return profile.coordinatorMeta?.(ownerId) || null
47
+ export function coordinatorMeta(profile, ownerId, options = {}) {
48
+ return profile.coordinatorMeta?.(ownerId, options) || null
66
49
  }
67
50
 
68
51
  async function applyProfileSessionConfig({
@@ -61,6 +61,11 @@ export class AcpSessionRegistry {
61
61
  return value && typeof value === 'object' ? { ...value } : null
62
62
  }
63
63
 
64
+ coordinatorEntries() {
65
+ this.load()
66
+ return Object.entries(this.coordinators).map(([key, value]) => [key, { ...value }])
67
+ }
68
+
64
69
  set(key, session) {
65
70
  this.load()
66
71
  this.coordinators[String(key)] = {
@@ -69,6 +74,10 @@ export class AcpSessionRegistry {
69
74
  ...(Number.isInteger(session.contractVersion)
70
75
  ? { contractVersion: session.contractVersion }
71
76
  : {}),
77
+ ...(Number.isSafeInteger(session.coordinatorPromptTurns) && session.coordinatorPromptTurns >= 0
78
+ ? { coordinatorPromptTurns: session.coordinatorPromptTurns }
79
+ : {}),
80
+ ...(session.conversationCursors ? { conversationCursors: { ...session.conversationCursors } } : {}),
72
81
  updatedAt: Date.now(),
73
82
  }
74
83
  this.save()
@@ -75,7 +75,7 @@ function registerTools(server, context) {
75
75
  'qwen_audio_agent_session_send',
76
76
  {
77
77
  title: 'Continue Agent Session',
78
- description: 'Continue an existing project Session asynchronously. Use the exact session_id returned by the Session list; the Gateway restores its original project directory.',
78
+ description: 'Continue or update an existing project Session asynchronously using its exact session_id. The Gateway preserves its original project directory.',
79
79
  inputSchema: {
80
80
  session_id: z.string().min(1),
81
81
  prompt: z.string().min(1),
@@ -0,0 +1,188 @@
1
+ import { normalizeAcpPrompt } from './content.mjs'
2
+
3
+ function deferred() {
4
+ let resolve
5
+ let reject
6
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no })
7
+ promise.catch(() => {})
8
+ return { promise, resolve, reject }
9
+ }
10
+
11
+ export function updateError(code, message) {
12
+ return Object.assign(new Error(message), { code })
13
+ }
14
+
15
+ function bounded(promise, milliseconds) {
16
+ let timer
17
+ return Promise.race([
18
+ promise,
19
+ new Promise((_, reject) => {
20
+ timer = setTimeout(() => reject(updateError(
21
+ 'update_unconfirmed', '后台尚未确认结束当前执行,未发送新的执行请求。',
22
+ )), milliseconds)
23
+ }),
24
+ ]).finally(() => clearTimeout(timer))
25
+ }
26
+
27
+ /** One ACP prompt lifetime, including safe same-Session restarts. No Task or UI policy. */
28
+ export class AcpTurnUpdates {
29
+ constructor({ client, sessionId, signal, cancelTimeoutMs = 15_000, onRestart = () => {},
30
+ preparePrompt = prompt => ({ prompt, acknowledge() {} }) }) {
31
+ Object.assign(this, { client, sessionId, signal, cancelTimeoutMs, onRestart, preparePrompt })
32
+ this.pending = []
33
+ this.wake = deferred()
34
+ this.closed = false
35
+ this.hasUpdates = false
36
+ }
37
+
38
+ enqueue(prompt, { context } = {}) {
39
+ if (this.closed || this.signal?.aborted) throw updateError('task_not_running', '当前执行已结束。')
40
+ const entry = { prompt: normalizeAcpPrompt(prompt), context, ...deferred() }
41
+ this.hasUpdates = true
42
+ this.pending.push(entry)
43
+ this.wake.resolve()
44
+ return { completion: entry.promise }
45
+ }
46
+
47
+ take() {
48
+ this.wake = deferred()
49
+ return this.pending.splice(0)
50
+ }
51
+
52
+ // The Agent invokes this extension from its loop, not through an LLM tool.
53
+ drain() {
54
+ if (this.closed || this.signal?.aborted) return { items: [], hasQueuedPrompt: false }
55
+ const entries = this.take()
56
+ if (!entries.length) return { items: [], hasQueuedPrompt: false }
57
+ try {
58
+ // One pull boundary is one delivery: merge its context snapshots under
59
+ // the shared budget without truncating any of the update ContentBlocks.
60
+ const delivery = this.preparePrompt(
61
+ entries.flatMap(entry => entry.prompt), entries.map(entry => entry.context),
62
+ )
63
+ delivery.acknowledge()
64
+ entries.forEach(entry => entry.resolve({ status: 'delivered' }))
65
+ return { items: [{ content: delivery.prompt }], hasQueuedPrompt: false }
66
+ } catch (error) {
67
+ entries.forEach(entry => entry.reject(error))
68
+ throw error
69
+ }
70
+ }
71
+
72
+ followup(entries) {
73
+ return [
74
+ { type: 'text', text: '用户更新了当前工作的要求。请结合已有上下文和已执行的操作,按以下新要求继续:' },
75
+ ...entries.flatMap(entry => entry.prompt),
76
+ ]
77
+ }
78
+
79
+ async run(initialPrompt, { onAccepted = () => {}, ...options } = {}) {
80
+ let inFlightEntries = this.take()
81
+ let prompt = inFlightEntries.length
82
+ ? [...normalizeAcpPrompt(initialPrompt), ...this.followup(inFlightEntries)]
83
+ : initialPrompt
84
+ let activeExecution
85
+ let settled = true
86
+ try {
87
+ while (true) {
88
+ this.signal?.throwIfAborted()
89
+ settled = false
90
+ const submitted = inFlightEntries
91
+ inFlightEntries = []
92
+ const delivery = this.preparePrompt(prompt, submitted.map(entry => entry.context))
93
+ const acknowledge = () => {
94
+ delivery.acknowledge()
95
+ onAccepted()
96
+ submitted.forEach(entry => entry.resolve({ status: 'delivered' }))
97
+ }
98
+ const execution = this.client.prompt(this.sessionId, delivery.prompt, {
99
+ ...options, signal: this.signal, timeoutMs: 0,
100
+ onUpdate: update => { acknowledge(); options.onUpdate?.(update) },
101
+ onMidTurnDrain: () => this.drain(),
102
+ }).then(result => {
103
+ acknowledge()
104
+ return { result }
105
+ }, error => {
106
+ submitted.forEach(entry => entry.reject(error))
107
+ return { error }
108
+ }).then(outcome => {
109
+ settled = true
110
+ return outcome
111
+ })
112
+ activeExecution = execution
113
+ let restart = false
114
+ while (true) {
115
+ const outcome = await Promise.race([
116
+ execution,
117
+ this.wake.promise.then(() => ({ update: true })),
118
+ ])
119
+ // A local abort does not prove the remote prompt stopped. Preserve
120
+ // the client's uncertainty so the adapter can quarantine this Session.
121
+ if (outcome.error?.contextUncertain) throw outcome.error
122
+ this.signal?.throwIfAborted()
123
+ if (!outcome.update) {
124
+ if (outcome.error) throw outcome.error
125
+ if (!this.pending.length) return outcome.result
126
+ inFlightEntries = this.take()
127
+ prompt = this.followup(inFlightEntries)
128
+ restart = true
129
+ break
130
+ }
131
+ const mode = this.client.steeringMode?.(this.sessionId) || 'restart'
132
+ let promptRequired = false
133
+ if (mode === 'pull' && !settled) {
134
+ // Leave the entries for the Agent's next boundary. Reset only the wakeup.
135
+ this.wake = deferred()
136
+ continue
137
+ }
138
+ if (mode === 'extension' && !settled) {
139
+ inFlightEntries = this.take()
140
+ const delivery = this.preparePrompt(this.followup(inFlightEntries), inFlightEntries.map(entry => entry.context))
141
+ const reply = await this.client.steerSession(this.sessionId, delivery.prompt, { signal: this.signal })
142
+ if (reply?.outcome === 'injected') {
143
+ delivery.acknowledge()
144
+ inFlightEntries.forEach(entry => entry.resolve({ status: 'delivered' }))
145
+ inFlightEntries = []
146
+ continue
147
+ }
148
+ if (reply?.outcome !== 'promptRequired') {
149
+ // In particular, startedNewTurn may already be running remotely. Never replay it.
150
+ throw Object.assign(updateError('update_unconfirmed', '后台调整投递结果无法确认;没有自动重发。'), {
151
+ contextUncertain: true,
152
+ })
153
+ }
154
+ promptRequired = true
155
+ }
156
+ if (!settled && !promptRequired) {
157
+ await bounded(this.client.cancelSession(this.sessionId), this.cancelTimeoutMs)
158
+ }
159
+ const stopped = await bounded(execution, this.cancelTimeoutMs)
160
+ if (stopped.error) throw stopped.error
161
+ inFlightEntries.push(...this.take())
162
+ await this.onRestart()
163
+ prompt = this.followup(inFlightEntries)
164
+ restart = true
165
+ break
166
+ }
167
+ if (!restart) throw new Error('Unreachable ACP update state')
168
+ }
169
+ } catch (error) {
170
+ inFlightEntries.forEach(entry => entry.reject(error))
171
+ // Never allow generic prompt retries to replay an ambiguously delivered update.
172
+ if (this.hasUpdates) error.updateDeliveryFailed = true
173
+ if (this.hasUpdates && (!settled || error.contextUncertain)) {
174
+ try {
175
+ await bounded(this.client.cancelSession(this.sessionId), this.cancelTimeoutMs)
176
+ if (!settled) await bounded(activeExecution, this.cancelTimeoutMs)
177
+ } catch {
178
+ error.contextUncertain = true
179
+ }
180
+ }
181
+ throw error
182
+ } finally {
183
+ this.closed = true
184
+ const error = updateError('update_not_delivered', '执行已结束,追加要求未投递。')
185
+ this.take().forEach(entry => entry.reject(error))
186
+ }
187
+ }
188
+ }