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
@@ -11,7 +11,12 @@ export function createWebSearchProvider(config, options = {}) {
11
11
  if (provider === 'so360') {
12
12
  return new So360WebSearchProvider(options)
13
13
  }
14
- if (provider === 'mcp' || provider === 'bailian') {
14
+ if (
15
+ provider === 'mcp'
16
+ || provider === 'bailian'
17
+ || provider === 'keenable'
18
+ || provider === 'parallel'
19
+ ) {
15
20
  return new McpWebSearchProvider({
16
21
  url: config.webSearchMcpUrl,
17
22
  token: config.webSearchMcpToken,
@@ -23,6 +28,18 @@ export function createWebSearchProvider(config, options = {}) {
23
28
  requiresToken: true,
24
29
  }
25
30
  : {}),
31
+ ...(provider === 'keenable'
32
+ ? {
33
+ key: 'keenable-mcp',
34
+ label: 'Keenable Web Search MCP',
35
+ // JSON keeps title, URL and snippet per result; snippets match
36
+ // the 1200-character citation bound.
37
+ toolArguments: { output_format: 'json', snippet_max_length: 1200 },
38
+ }
39
+ : {}),
40
+ ...(provider === 'parallel'
41
+ ? { key: 'parallel-mcp', label: 'Parallel Web Search MCP' }
42
+ : {}),
26
43
  ...options,
27
44
  })
28
45
  }
@@ -5,7 +5,9 @@ import {
5
5
  import { PACKAGE_VERSION } from '../../../core/package-version.mjs'
6
6
  import { listMcpTools } from '../../mcp-tool-discovery.mjs'
7
7
 
8
- const MAX_TOOL_TEXT_LENGTH = 24_000
8
+ // Search MCP responses can contain ~25,000 excerpt characters plus metadata.
9
+ // Keep JSON intact before the runtime bounds individual snippets and citations.
10
+ const MAX_TOOL_TEXT_LENGTH = 64 * 1024
9
11
  const QUERY_FIELDS = ['query', 'q', 'search_query']
10
12
  const LIMIT_FIELDS = ['limit', 'count', 'top_k', 'max_results']
11
13
  const RESULT_KEYS = [
@@ -90,7 +92,8 @@ function projectResult(item) {
90
92
  const url = clean(item.url || item.link || item.href)
91
93
  if (!url) return null
92
94
  const snippet = clean(
93
- item.snippet || item.description || item.content || item.text,
95
+ item.snippet || item.description || item.content || item.text
96
+ || (Array.isArray(item.excerpts) ? item.excerpts.join('\n') : ''),
94
97
  )
95
98
  const source = clean(
96
99
  item.source
@@ -100,7 +103,8 @@ function projectResult(item) {
100
103
  || item.domain,
101
104
  )
102
105
  const publishedAt = clean(
103
- item.publishedAt || item.published_at || item.published_date || item.date,
106
+ item.publishedAt || item.published_at || item.published_date
107
+ || item.publish_date || item.date,
104
108
  )
105
109
  return {
106
110
  title: clean(item.title || item.name),
@@ -154,12 +158,19 @@ function normalizeToolResult(result) {
154
158
  }
155
159
  }
156
160
 
157
- function callArguments(tool, query, limit) {
161
+ function callArguments(tool, query, limit, toolArguments = {}) {
158
162
  const properties = tool?.inputSchema?.properties || {}
159
- const queryField = QUERY_FIELDS.find(field => field in properties) || 'query'
160
- const args = { [queryField]: query }
163
+ const queryField = QUERY_FIELDS.find(field => field in properties)
164
+ // Keep existing single-query schemas preferred, including mixed schemas.
165
+ const args = !queryField && 'objective' in properties && 'search_queries' in properties
166
+ ? { objective: query, search_queries: [query] }
167
+ : { [queryField || 'query']: query }
161
168
  const limitField = LIMIT_FIELDS.find(field => field in properties)
162
169
  if (limitField) args[limitField] = limit
170
+ // Preset arguments are sent only when the tool declares them.
171
+ for (const [field, value] of Object.entries(toolArguments)) {
172
+ if (field in properties && !(field in args)) args[field] = value
173
+ }
163
174
  return args
164
175
  }
165
176
 
@@ -179,6 +190,7 @@ export class McpWebSearchProvider {
179
190
  key = 'mcp',
180
191
  label = 'MCP Web Search',
181
192
  requiresToken = false,
193
+ toolArguments = {},
182
194
  clientFactory = defaultClientFactory,
183
195
  transportFactory = defaultTransportFactory,
184
196
  } = {}) {
@@ -188,6 +200,7 @@ export class McpWebSearchProvider {
188
200
  this.key = clean(key) || 'mcp'
189
201
  this.label = clean(label) || 'MCP Web Search'
190
202
  this.requiresToken = Boolean(requiresToken)
203
+ this.toolArguments = { ...toolArguments }
191
204
  this.clientFactory = clientFactory
192
205
  this.transportFactory = transportFactory
193
206
  }
@@ -225,11 +238,12 @@ export class McpWebSearchProvider {
225
238
  const boundedLimit = Math.max(1, Math.min(8, Math.trunc(Number(limit) || 5)))
226
239
  const url = validateEndpoint(this.url, { hasToken: Boolean(this.token) })
227
240
  const client = this.clientFactory()
228
- const headers = this.token
229
- ? { authorization: `Bearer ${this.token}` }
230
- : undefined
241
+ const headers = {
242
+ 'User-Agent': `qwen-audio-agent/${PACKAGE_VERSION}`,
243
+ ...(this.token ? { authorization: `Bearer ${this.token}` } : {}),
244
+ }
231
245
  const transport = this.transportFactory(url, {
232
- ...(headers ? { requestInit: { headers } } : {}),
246
+ requestInit: { headers },
233
247
  })
234
248
  try {
235
249
  await client.connect(transport, { signal })
@@ -243,7 +257,12 @@ export class McpWebSearchProvider {
243
257
  }
244
258
  const result = await client.callTool({
245
259
  name: this.toolName,
246
- arguments: callArguments(tool, normalizedQuery, boundedLimit),
260
+ arguments: callArguments(
261
+ tool,
262
+ normalizedQuery,
263
+ boundedLimit,
264
+ this.toolArguments,
265
+ ),
247
266
  }, undefined, { signal })
248
267
  return normalizeToolResult(result)
249
268
  } catch (error) {
@@ -24,19 +24,30 @@ function decodedCodePoint(value, radix) {
24
24
  return String.fromCodePoint(codePoint)
25
25
  }
26
26
 
27
+ const NAMED_ENTITIES = {
28
+ amp: '&',
29
+ lt: '<',
30
+ gt: '>',
31
+ quot: '"',
32
+ apos: "'",
33
+ nbsp: ' ',
34
+ ensp: ' ',
35
+ emsp: ' ',
36
+ middot: '·',
37
+ }
38
+
39
+ // Decode in a single pass so text produced by one entity is never decoded
40
+ // again: `&amp;lt;` is the literal text `&lt;`, not `<`.
27
41
  function decodeEntities(value) {
28
- return String(value || '')
29
- .replace(/&amp;/giu, '&')
30
- .replace(/&lt;/giu, '<')
31
- .replace(/&gt;/giu, '>')
32
- .replace(/&quot;/giu, '"')
33
- .replace(/&(?:apos|#(?:39|x27));/giu, "'")
34
- .replace(/&nbsp;/giu, ' ')
35
- .replace(/&ensp;/giu, ' ')
36
- .replace(/&emsp;/giu, ' ')
37
- .replace(/&middot;/giu, '·')
38
- .replace(/&#(\d+);/gu, (_, code) => decodedCodePoint(code, 10))
39
- .replace(/&#x([0-9a-f]+);/giu, (_, code) => decodedCodePoint(code, 16))
42
+ return String(value || '').replace(
43
+ /&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/giu,
44
+ (entity, decimal, hex, name) => {
45
+ if (decimal !== undefined) return decodedCodePoint(decimal, 10)
46
+ if (hex !== undefined) return decodedCodePoint(hex, 16)
47
+ const key = name.toLowerCase()
48
+ return Object.hasOwn(NAMED_ENTITIES, key) ? NAMED_ENTITIES[key] : entity
49
+ },
50
+ )
40
51
  }
41
52
 
42
53
  function plainText(value) {
@@ -3,6 +3,7 @@ import { PERMISSION_DECISIONS } from '../../../../shared/permission-decisions.mj
3
3
  import { inputPartRef } from '../../../../shared/input-parts.mjs'
4
4
  import { isTaskCancellable } from '../../task/task-state.mjs'
5
5
  import { toolFailure as failure } from './tool-result.mjs'
6
+ import { RESPOND_PERMISSION_TOOL_NAME } from './features/agent-task-tools.mjs'
6
7
 
7
8
  const CANCEL_RECEIPT_INSTRUCTIONS = [
8
9
  '根据本次响应中的全部取消结果,只作一次简短自然的确认。',
@@ -10,6 +11,12 @@ const CANCEL_RECEIPT_INSTRUCTIONS = [
10
11
  ].join(' ')
11
12
 
12
13
  const STATUS_RESULT_MESSAGE = '请根据这次查询结果自然回答用户;不要再次调用状态工具,不要展示 task_id。'
14
+ const WORK_ACCEPTED_MESSAGE = '请求已受理,执行结果另行返回。本次只需自然确认受理。'
15
+ const WORK_DUPLICATE_MESSAGE = '请求此前已受理。本次只需自然确认受理。'
16
+
17
+ // Frontend handlers can be replaced on reconnect while their Tasks keep
18
+ // running. Keep bounded tool receipts with that TaskManager's lifetime.
19
+ const updateReceiptsByTaskManager = new WeakMap()
13
20
 
14
21
  function objectiveFingerprint(objective) {
15
22
  return createHash('sha256')
@@ -61,6 +68,9 @@ export class AgentTaskRuntime {
61
68
  constructor(host) {
62
69
  this.host = host
63
70
  this.permissionReceipts = new Map()
71
+ const manager = host.taskOperations?.taskManager || host.taskManager || host.taskOperations || host
72
+ if (!updateReceiptsByTaskManager.has(manager)) updateReceiptsByTaskManager.set(manager, new Map())
73
+ this.updateResponses = updateReceiptsByTaskManager.get(manager)
64
74
  }
65
75
 
66
76
  pendingPermissions() {
@@ -95,6 +105,68 @@ export class AgentTaskRuntime {
95
105
  })
96
106
  }
97
107
 
108
+ async executeUpdateToolCall({ callId, turnId, args, event, callContext = {} }) {
109
+ const responseId = String(callContext.responseId || event?.response_id || '')
110
+ const key = JSON.stringify([this.host.ownerId, this.host.sessionId, turnId || callId, args.task_id])
111
+ const previous = this.updateResponses.get(key)
112
+ let receipt
113
+ try {
114
+ // Keep the accepted receipt even after a pending input is resolved. A
115
+ // repeated answer must not fall through into steering or restart work.
116
+ if (previous) {
117
+ const prior = await previous
118
+ receipt = {
119
+ ...prior,
120
+ status: 'duplicate',
121
+ message: prior.input_request_id
122
+ ? '回答此前已受理,不代表操作已批准或执行完成。本次只需自然确认受理。'
123
+ : WORK_DUPLICATE_MESSAGE,
124
+ }
125
+ } else {
126
+ const pending = this.applyTaskUpdate({ callId, turnId, args })
127
+ this.updateResponses.set(key, pending)
128
+ if (this.updateResponses.size > 200) this.updateResponses.delete(this.updateResponses.keys().next().value)
129
+ receipt = await pending
130
+ }
131
+ } catch (error) {
132
+ if (!previous) this.updateResponses.delete(key)
133
+ await this.host.sendOutput(callId, failure(
134
+ error.code || 'work_update_failed', error.message, { retryable: false },
135
+ ), turnId, args.task_id)
136
+ return
137
+ }
138
+ if (previous) this.host.markTerminalToolResponse(responseId)
139
+ await this.host.sendOutput(callId, receipt, turnId, args.task_id,
140
+ previous ? { createResponse: false } : undefined)
141
+ }
142
+
143
+ async applyTaskUpdate({ callId, turnId, args }) {
144
+ const instruction = typeof args.instruction === 'string' ? args.instruction.trim() : ''
145
+ if (!instruction || instruction.length > 16_000) {
146
+ throw Object.assign(new Error('补充要求或回答不能为空或超过 16000 字符。'), { code: 'invalid_instruction' })
147
+ }
148
+ const task = this.host.taskOperations.get(args.task_id, this.host)
149
+ const request = task?.inputRequest
150
+ if (request?.status === 'pending'
151
+ || args.input_request_id !== undefined || args.values !== undefined) {
152
+ return this.replyToTaskInput(task, request, { ...args, instruction }, turnId)
153
+ }
154
+ const inputParts = mergeInputParts(
155
+ this.host.transcripts.parts(turnId),
156
+ this.host.inputAssets?.resolve({
157
+ ownerId: this.host.ownerId, sessionId: this.host.sessionId, refs: args.input_refs,
158
+ }) || [],
159
+ )
160
+ const receipt = this.host.taskOperations.update({
161
+ taskId: args.task_id, instruction, inputParts,
162
+ submissionKey: JSON.stringify(['update', this.host.sessionId, turnId || callId, args.task_id]),
163
+ }, this.host)
164
+ return {
165
+ status: receipt.status, task_id: receipt.taskId,
166
+ message: receipt.status === 'duplicate' ? WORK_DUPLICATE_MESSAGE : WORK_ACCEPTED_MESSAGE,
167
+ }
168
+ }
169
+
98
170
  async executeCancelToolCall({
99
171
  callId,
100
172
  turnId,
@@ -200,65 +272,9 @@ export class AgentTaskRuntime {
200
272
  event,
201
273
  callContext,
202
274
  }) {
203
- const pendingInputTasks = this.host.taskOperations.list({
204
- ownerId: this.host.ownerId,
205
- sessionId: this.host.sessionId,
206
- active: true,
207
- }).filter(task => task.status !== 'cancelling' && task.inputRequest?.status === 'pending')
208
- if (pendingInputTasks.length) {
209
- // A waiting task retains the serial backend lane. A new work item cannot
210
- // resume it and would remain queued indefinitely. Never infer approval
211
- // from a spawn objective: return the actual pending request.
212
- await this.host.sendOutput(callId, {
213
- status: 'input_pending', error: true, error_code: 'input_response_required',
214
- pending_inputs: pendingInputTasks.map(task => ({ task_id: task.id,
215
- kind: task.inputRequest.kind, prompt: task.inputRequest.prompt })),
216
- user_message: '当前有任务等待客户答复,未创建新任务。请回答或取消原任务后再派单。',
217
- retryable: true,
218
- }, turnId, pendingInputTasks.length === 1 ? pendingInputTasks[0].id : null, {
219
- response: { instructions: [
220
- 'No new task was created. The existing task is waiting for CUSTOMER input.',
221
- 'If the latest real customer reply answers the pending request, call respond_agent_input with that task_id and the customer reply.',
222
- 'Do not invent an answer or approve on behalf of the customer. If the customer has not answered, convey the pending question and wait.',
223
- 'Do not call spawn_thinking again or claim any operation completed. Multiple pending requests require clarification of which one the customer is answering.',
224
- ].join(' ') },
225
- })
226
- return
227
- }
228
- const pendingPermissionTask = this.host.taskOperations.list({
229
- ownerId: this.host.ownerId,
230
- sessionId: this.host.sessionId,
231
- active: true,
232
- }).find(task => task.authorization?.status === 'pending')
233
- if (pendingPermissionTask) {
234
- await this.host.sendOutput(
235
- callId,
236
- {
237
- status: 'authorization_pending',
238
- error: true,
239
- error_code: 'permission_decision_required',
240
- task_id: pendingPermissionTask.id,
241
- operation: pendingPermissionTask.authorization.summary,
242
- user_message: '当前有一项权限请求正在等待用户决定,不能把本轮回答提交成新工作。',
243
- retryable: true,
244
- },
245
- turnId,
246
- pendingPermissionTask.id,
247
- {
248
- response: {
249
- instructions: [
250
- '当前有一项权限请求正在等待决定,本轮不能调用 spawn_thinking。',
251
- '重新结合刚才提出的具体权限问题和本轮用户原话判断。',
252
- '若用户已自然表达同意或拒绝,立即调用 respond_permission;按语义判断,不要要求固定口令。',
253
- '若用户没有作出决定,只用一句自然的话继续确认。',
254
- '绝对不要代替用户同意,也不要声称权限已经生效。',
255
- ].join(' '),
256
- },
257
- },
258
- )
259
- return
260
- }
261
-
275
+ // A pending request belongs to its Task, not the entire conversation.
276
+ // Independent work can use another execution slot without approving or
277
+ // resolving that request. Replies use the explicit update/permission tools.
262
278
  // Receipt-based acceptance: this receipt only acknowledges intake, so it
263
279
  // must not wait on ASR timing or a live backend round trip. Availability
264
280
  // comes from the cached snapshot; a backend that looks healthy here but
@@ -421,12 +437,12 @@ export class AgentTaskRuntime {
421
437
  ? {
422
438
  status: 'duplicate',
423
439
  task_id: task.id,
424
- message: '同一工作此前已受理,请自然确认一次,不要再次调用工具。',
440
+ message: WORK_DUPLICATE_MESSAGE,
425
441
  }
426
442
  : {
427
443
  status: 'accepted',
428
444
  task_id: task.id,
429
- message: '工作已受理,请自然确认一次,不要再次调用工具。',
445
+ message: WORK_ACCEPTED_MESSAGE,
430
446
  },
431
447
  turnId,
432
448
  task.id,
@@ -496,6 +512,12 @@ export class AgentTaskRuntime {
496
512
  const pending = this.pendingPermissions()
497
513
  try {
498
514
  const transcript = String(await this.host.transcripts.transcript(turnId)).trim()
515
+ // A newer user turn or an explicit stop can supersede this decision
516
+ // while its transcript is pending. Check before submitting permission.
517
+ if (this.host.isStale(turnId, generation, RESPOND_PERMISSION_TOOL_NAME)) {
518
+ await this.host.closeStaleCall(callId, turnId)
519
+ return
520
+ }
499
521
  if (!response || !transcript) {
500
522
  await this.host.sendOutput(
501
523
  callId,
@@ -556,6 +578,12 @@ export class AgentTaskRuntime {
556
578
  )
557
579
  return
558
580
  }
581
+ if (this.host.answersRequest?.(turnId, authorizationId) === false) {
582
+ await this.host.sendOutput(callId, failure(
583
+ 'permission_not_answered', '用户还没有回答这个权限请求;请求仍待确认。', { retryable: false },
584
+ ), turnId, null, responseOptions('用户还没有回答这个权限请求。不要代替用户决定,简短询问是否允许,不要调用工具。'))
585
+ return
586
+ }
559
587
  if (!this.host.taskOperations.respondAuthorization) {
560
588
  await this.host.sendOutput(
561
589
  callId,
@@ -604,59 +632,49 @@ export class AgentTaskRuntime {
604
632
  }
605
633
  }
606
634
 
607
- async respondAgentInput({ callId, turnId, args }) {
608
- const taskId = String(args.task_id || '').trim()
609
- const action = ['accept', 'decline', 'cancel'].includes(args.action)
610
- ? args.action
611
- : ''
612
- const task = taskId ? this.host.taskOperations.get(taskId, {
613
- ownerId: this.host.ownerId,
614
- }) : null
615
- const request = task?.inputRequest
635
+ async replyToTaskInput(task, request, args, turnId) {
636
+ const fail = (code, message) => { throw Object.assign(new Error(message), { code }) }
616
637
  if (
617
638
  !task
618
639
  || task.sessionId !== this.host.sessionId
619
640
  || request?.status !== 'pending'
620
- || !action
641
+ || (args.input_request_id !== undefined && args.input_request_id !== request.id)
621
642
  ) {
622
- await this.host.sendOutput(callId, failure(
623
- 'input_not_pending',
624
- '当前没有仍在等待回答的后台输入请求。',
625
- ), turnId, null, {
626
- response: { instructions: '简短说明这次回答没有提交成功,不要声称后台已经继续。' },
627
- })
628
- return
643
+ fail('input_not_pending', '对应的后台问题已失效或不在当前会话,回答没有提交。')
644
+ }
645
+ if (this.host.answersRequest?.(turnId, request.id) === false) {
646
+ fail('input_not_answered', '用户还没有回答这个后台问题;请先向用户转述问题。')
629
647
  }
630
648
  if (!this.host.taskOperations.respondInput) {
631
- await this.host.sendOutput(callId, failure(
632
- 'input_unavailable',
633
- '当前后台无法接收补充输入。',
634
- ), turnId)
635
- return
649
+ fail('input_unavailable', '当前后台无法接收补充输入。')
650
+ }
651
+ if (args.values !== undefined && (!args.values || typeof args.values !== 'object' || Array.isArray(args.values))) {
652
+ fail('invalid_input_values', '表单回答必须是对象。')
636
653
  }
654
+ if (args.input_refs?.length || this.host.transcripts.parts(turnId)?.some(part => part?.type === 'file')) {
655
+ fail('input_attachments_unsupported', '当前后台追问仅支持文本或表单回答,尚未提交附件。')
656
+ }
657
+ // Deliver the user's answer, not an inferred approval. Its business meaning
658
+ // belongs to the backend holding the original question or operation preview.
637
659
  await this.host.taskOperations.respondToInput(task.id, request.id, {
638
- action,
639
- text: String(args.text || '').trim(),
660
+ text: args.instruction,
640
661
  values: args.values,
641
- }, { ownerId: this.host.ownerId })
642
- await this.host.sendOutput(callId, {
643
- status: 'submitted',
662
+ }, this.host)
663
+ return {
664
+ status: 'accepted',
644
665
  task_id: task.id,
645
- }, turnId, task.id, {
646
- response: {
647
- instructions: action === 'accept'
648
- ? '回答已交给原来的后台工作。只简短自然地说明会继续处理,不要新建工作或重复问题。'
649
- : '用户没有提供这次补充信息。只作简短自然确认,不要声称工作已经完成。',
650
- },
651
- })
666
+ input_request_id: request.id,
667
+ message: '回答已交回原来的工作,不代表操作已批准或执行完成。本次只需自然确认受理。',
668
+ }
652
669
  }
653
670
 
654
671
  async cancelAgentTask(callId, turnId, args, responseOptions) {
672
+ const reachable = task => !this.host.startedLater?.(task.turnId, turnId)
655
673
  if (args.all === true) {
656
674
  const targets = this.host.taskOperations.list({
657
675
  ownerId: this.host.ownerId,
658
676
  sessionId: this.host.sessionId,
659
- }).filter(task => isTaskCancellable(task.status))
677
+ }).filter(task => isTaskCancellable(task.status) && reachable(task))
660
678
  if (!targets.length) {
661
679
  await this.host.sendOutput(callId, {
662
680
  status: 'not_found',
@@ -684,7 +702,8 @@ export class AgentTaskRuntime {
684
702
  if (requestedSeriesId) {
685
703
  const existing = this.host.taskOperations.list({ ownerId: this.host.ownerId })
686
704
  .filter(task => task.seriesId === requestedSeriesId)
687
- if (!existing.length) {
705
+ // A series holding any task a later turn started is out of reach, as that task is.
706
+ if (!existing.length || !existing.every(reachable)) {
688
707
  await this.host.sendOutput(callId, {
689
708
  status: 'not_found',
690
709
  series_id: requestedSeriesId,
@@ -717,8 +736,8 @@ export class AgentTaskRuntime {
717
736
  : this.host.taskOperations.list({
718
737
  ownerId: this.host.ownerId,
719
738
  sessionId: this.host.sessionId,
720
- }).find(task => isTaskCancellable(task.status))
721
- if (!target) {
739
+ }).find(task => isTaskCancellable(task.status) && reachable(task))
740
+ if (!target || !reachable(target)) {
722
741
  await this.host.sendOutput(callId, {
723
742
  status: 'not_found',
724
743
  message: '当前没有仍在排队或执行的工作。',
@@ -811,6 +830,7 @@ export class AgentTaskRuntime {
811
830
  : null,
812
831
  authorization_pending: task.authorization?.status === 'pending',
813
832
  recent_updates: recentTaskUpdates(task.activity),
833
+ ...(task.updates?.length ? { instruction_updates: task.updates.slice(-5) } : {}),
814
834
  latest_update: task.message
815
835
  ? String(task.message).slice(0, 1_000)
816
836
  : null,
@@ -5,11 +5,10 @@ import {
5
5
 
6
6
  export { SPAWN_THINKING_TOOL_NAME } from '../spawn-thinking-tool.mjs'
7
7
  export const CANCEL_AGENT_TASK_TOOL_NAME = 'cancel_agent_task'
8
+ export const UPDATE_AGENT_TASK_TOOL_NAME = 'update_agent_task'
8
9
  export const GET_AGENT_TASK_STATUS_TOOL_NAME = 'get_agent_task_status'
9
10
  export const RESPOND_PERMISSION_TOOL_NAME = 'respond_permission'
10
11
  export const PERMISSION_RESPONSE_CAPABILITY = 'permission.respond'
11
- export const RESPOND_AGENT_INPUT_TOOL_NAME = 'respond_agent_input'
12
- export const BACKEND_INPUT_RESPONSE_CAPABILITY = 'backend.input.respond'
13
12
 
14
13
  const cancelAgentTaskTool = {
15
14
  type: 'function',
@@ -37,6 +36,26 @@ const cancelAgentTaskTool = {
37
36
  },
38
37
  }
39
38
 
39
+ const updateAgentTaskTool = {
40
+ type: 'function',
41
+ function: {
42
+ name: UPDATE_AGENT_TASK_TOOL_NAME,
43
+ description: '向已有工作补充要求、修改目标或回答追问,也可对已完成成果执行后续操作,保留原工作的关联上下文。',
44
+ parameters: {
45
+ type: 'object',
46
+ properties: {
47
+ task_id: { type: 'string', description: '系统提供的目标工作 ID;指代不明确时先查询或询问,不得猜造。' },
48
+ instruction: { type: 'string', description: '用户本次补充、修改的要求或对追问的回答。' },
49
+ input_request_id: { type: 'string', description: '回答后台追问时原样使用请求中的 ID,防止回答过期问题;普通工作调整必须省略此字段,不要传 null。' },
50
+ values: { type: 'object', description: '仅在回答后台追问的表单时填写对象,字段必须来自请求提供的 schema;普通工作调整或无需表单回答时必须省略此字段,不要传 null。', additionalProperties: true },
51
+ input_refs: spawnThinkingTool.function.parameters.properties.input_refs,
52
+ },
53
+ required: ['task_id', 'instruction'],
54
+ additionalProperties: false,
55
+ },
56
+ },
57
+ }
58
+
40
59
  const getAgentTaskStatusTool = {
41
60
  type: 'function',
42
61
  function: {
@@ -83,45 +102,13 @@ const respondPermissionTool = {
83
102
  },
84
103
  }
85
104
 
86
- const respondAgentInputTool = {
87
- type: 'function',
88
- function: {
89
- name: RESPOND_AGENT_INPUT_TOOL_NAME,
90
- description: '把用户对当前后台追问的回答交回同一项工作,使其继续执行,也可拒绝回答或取消这次交互。',
91
- parameters: {
92
- type: 'object',
93
- properties: {
94
- task_id: {
95
- type: 'string',
96
- description: '等待补充输入的工作 ID,必须来自当前后台输入请求。',
97
- },
98
- action: {
99
- type: 'string',
100
- enum: ['accept', 'decline', 'cancel'],
101
- description: 'accept 提交回答并继续;decline 拒绝提供;cancel 取消这次交互。',
102
- },
103
- text: {
104
- type: 'string',
105
- description: '用户要交给后台的自然语言回答。action=accept 时填写。',
106
- },
107
- values: {
108
- type: 'object',
109
- description: '可选的结构化表单回答;字段必须来自请求中提供的 schema。',
110
- additionalProperties: true,
111
- },
112
- },
113
- required: ['task_id', 'action'],
114
- additionalProperties: false,
115
- },
116
- },
117
- }
118
-
119
105
  export const agentTaskToolEntries = [
120
106
  {
121
107
  definition: spawnThinkingTool,
122
108
  policy: { repeatHandling: 'handler' },
123
109
  },
124
110
  { definition: cancelAgentTaskTool },
111
+ { definition: updateAgentTaskTool, policy: { repeatHandling: 'handler' } },
125
112
  { definition: getAgentTaskStatusTool },
126
113
  {
127
114
  definition: respondPermissionTool,
@@ -129,20 +116,14 @@ export const agentTaskToolEntries = [
129
116
  requiredCapabilities: [PERMISSION_RESPONSE_CAPABILITY],
130
117
  },
131
118
  },
132
- {
133
- definition: respondAgentInputTool,
134
- policy: {
135
- requiredCapabilities: [BACKEND_INPUT_RESPONSE_CAPABILITY],
136
- },
137
- },
138
119
  ]
139
120
 
140
121
  export function agentTaskToolHandlers(runtime) {
141
122
  return {
142
123
  spawn_thinking: context => runtime.executeSpawnThinkingToolCall(context),
124
+ [UPDATE_AGENT_TASK_TOOL_NAME]: context => runtime.executeUpdateToolCall(context),
143
125
  [CANCEL_AGENT_TASK_TOOL_NAME]: context => runtime.executeCancelToolCall(context),
144
126
  [GET_AGENT_TASK_STATUS_TOOL_NAME]: context => runtime.executeStatusToolCall(context),
145
127
  [RESPOND_PERMISSION_TOOL_NAME]: context => runtime.respondPermission(context),
146
- [RESPOND_AGENT_INPUT_TOOL_NAME]: context => runtime.respondAgentInput(context),
147
128
  }
148
129
  }
@@ -1,7 +1,7 @@
1
1
  import {
2
- BACKEND_INPUT_RESPONSE_CAPABILITY,
3
2
  PERMISSION_RESPONSE_CAPABILITY,
4
3
  SPAWN_THINKING_TOOL_NAME,
4
+ UPDATE_AGENT_TASK_TOOL_NAME,
5
5
  } from './features/agent-task-tools.mjs'
6
6
  import { FRONTEND_RECALL_CAPABILITY } from './features/retrieval-tools.mjs'
7
7
  import { optionalFrontendFeatures } from '../optional-features.mjs'
@@ -25,6 +25,7 @@ export function buildFrontendToolContext({
25
25
  disabledTools: [...new Set([
26
26
  ...disabledTools,
27
27
  ...(!backendConfigured ? [SPAWN_THINKING_TOOL_NAME] : []),
28
+ ...(!backendConfigured && !inputPending ? [UPDATE_AGENT_TASK_TOOL_NAME] : []),
28
29
  ])],
29
30
  capabilities: [...new Set([
30
31
  ...(frontendRetrieval?.capabilities?.() || []),
@@ -33,7 +34,6 @@ export function buildFrontendToolContext({
33
34
  )),
34
35
  ...(sessionDigests ? [FRONTEND_RECALL_CAPABILITY] : []),
35
36
  ...(permissionPending ? [PERMISSION_RESPONSE_CAPABILITY] : []),
36
- ...(inputPending ? [BACKEND_INPUT_RESPONSE_CAPABILITY] : []),
37
37
  ])],
38
38
  }
39
39
  }
@@ -6,13 +6,13 @@ export const spawnThinkingTool = {
6
6
  name: SPAWN_THINKING_TOOL_NAME,
7
7
  // 客户定制点:只修改后台 Agent 的能力描述。固定调用规则位于
8
8
  // PROMPT.md,参数协议由下方 schema 定义。
9
- description: '调用后台 Agent 访问或操作用户环境、设备、文件、屏幕、应用和代码,进行媒体创作、持续执行和制作交付物;也用于在用户补充信息、作出选择或确认后继续、修改已有工作。',
9
+ description: '新增一项后台工作,由后台 Agent 利用其工具与执行环境处理请求。新增工作不会替换或取消已有工作。',
10
10
  parameters: {
11
11
  type: 'object',
12
12
  properties: {
13
13
  objective: {
14
14
  type: 'string',
15
- description: '忠实、完整且自包含地转达用户要做什么及其明确约束,保留执行方式及与既有工作的关系。根据当前对话消解明确指代,只补充完成它所必需的事实或约束;不得遗漏、推断或改变用户语义,不要规定用户未要求的具体工具、Agent 或 Session,也不要提交占位目标。后台不会收到前台的完整对话、个性化偏好或长期记忆。',
15
+ description: '用户本次请求,必要时结合上下文补全指代;不添加用户未提出的要求。',
16
16
  },
17
17
  input_refs: {
18
18
  type: 'array',