qwen-audio-agent 2.1.0 → 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 (110) hide show
  1. package/README.md +6 -3
  2. package/README_ZH.md +6 -3
  3. package/cli/package.json +1 -1
  4. package/cli/src/config-command.mjs +33 -2
  5. package/cli/src/gateway-service.mjs +7 -1
  6. package/config/frontend-agent/LIVE_PROMPT.md +64 -0
  7. package/desktop/src/i18n.mjs +1 -1
  8. package/desktop/src/settings-config.mjs +10 -24
  9. package/docs/configuration/frontend.md +29 -12
  10. package/docs/configuration/frontend.zh.md +28 -12
  11. package/docs/contract.md +2 -0
  12. package/docs/contract.zh.md +2 -0
  13. package/docs/extensions.md +14 -0
  14. package/docs/extensions.zh.md +11 -0
  15. package/docs/getting-started/install.md +3 -0
  16. package/docs/getting-started/install.zh.md +3 -0
  17. package/docs/getting-started/mobile.md +8 -2
  18. package/docs/getting-started/mobile.zh.md +5 -0
  19. package/docs/guides/web-search.md +17 -1
  20. package/docs/guides/web-search.zh.md +15 -1
  21. package/docs/operations/troubleshooting.md +30 -0
  22. package/docs/operations/troubleshooting.zh.md +26 -0
  23. package/docs/voice-frontends/custom-provider.md +18 -3
  24. package/docs/voice-frontends/custom-provider.zh.md +18 -3
  25. package/docs/voice-frontends/google-live.md +7 -3
  26. package/docs/voice-frontends/google-live.zh.md +6 -3
  27. package/docs/voice-frontends/gpt-live-1.md +149 -0
  28. package/docs/voice-frontends/gpt-live-1.zh.md +114 -0
  29. package/docs/voice-frontends/{gpt-live.md → openai-realtime.md} +12 -5
  30. package/docs/voice-frontends/{gpt-live.zh.md → openai-realtime.zh.md} +11 -5
  31. package/docs/voice-frontends/qwen-audio-live.md +164 -0
  32. package/docs/voice-frontends/qwen-audio-live.zh.md +122 -0
  33. package/docs/voice-frontends/qwen-audio-realtime.md +2 -1
  34. package/docs/voice-frontends/qwen-audio-realtime.zh.md +2 -1
  35. package/docs/voice-frontends/qwen-omni-realtime.md +1 -1
  36. package/docs/voice-frontends/qwen-omni-realtime.zh.md +1 -1
  37. package/package.json +13 -4
  38. package/scripts/patch-build-node-gyp.mjs +63 -0
  39. package/scripts/prepare-build.mjs +2 -0
  40. package/scripts/verify-package.mjs +3 -0
  41. package/server/package.json +2 -2
  42. package/server/src/conversation/frontend-agent-context.mjs +18 -5
  43. package/server/src/core/citation.mjs +8 -2
  44. package/server/src/core/config.mjs +16 -5
  45. package/server/src/core/request-security.mjs +7 -1
  46. package/server/src/frontend/frontend-tools.mjs +14 -1
  47. package/server/src/frontend/retrieval/providers/bing.mjs +23 -12
  48. package/server/src/frontend/retrieval/providers/factory.mjs +9 -1
  49. package/server/src/frontend/retrieval/providers/mcp.mjs +17 -9
  50. package/server/src/frontend/retrieval/providers/so360.mjs +23 -12
  51. package/server/src/frontend/tools/agent-task-runtime.mjs +22 -4
  52. package/server/src/frontend/tools/tool-call-handler.mjs +56 -20
  53. package/server/src/memory/providers/markdown/context-store.mjs +3 -1
  54. package/server/src/orchestration/session-task-coordinator.mjs +4 -1
  55. package/server/src/orchestration/task-operations.mjs +5 -3
  56. package/server/src/orchestration/task-updates.mjs +2 -1
  57. package/server/src/transport/gateway-client-transport.mjs +19 -0
  58. package/server/src/transport/webrtc/protocol.mjs +1 -1
  59. package/server/src/voice/audio-stream-diagnostics.mjs +139 -0
  60. package/server/src/voice/native-delegation-runtime.mjs +360 -0
  61. package/server/src/voice/providers/dashscope-live.mjs +93 -0
  62. package/server/src/voice/providers/dashscope.mjs +12 -4
  63. package/server/src/voice/providers/doubao-seeduplex-protocol.mjs +54 -0
  64. package/server/src/voice/providers/doubao-seeduplex.mjs +6 -5
  65. package/server/src/voice/providers/ga-protocol.mjs +7 -2
  66. package/server/src/voice/providers/google-live-protocol.mjs +124 -34
  67. package/server/src/voice/providers/google-live.mjs +6 -5
  68. package/server/src/voice/providers/gpt-live-1-protocol.mjs +597 -0
  69. package/server/src/voice/providers/gpt-live-1.mjs +3 -0
  70. package/server/src/voice/providers/gpt-live-client-context.mjs +182 -0
  71. package/server/src/voice/providers/openai-live.mjs +150 -0
  72. package/server/src/voice/providers/{gpt-live.mjs → openai-realtime.mjs} +15 -14
  73. package/server/src/voice/providers/provider-registry.mjs +11 -1
  74. package/server/src/voice/providers/qwen-live-protocol.mjs +399 -0
  75. package/server/src/voice/providers/registry.mjs +45 -10
  76. package/server/src/voice/providers/runtime-configuration.mjs +17 -6
  77. package/server/src/voice/providers/stepfun.mjs +1 -1
  78. package/server/src/voice/realtime-input-runtime.mjs +56 -20
  79. package/server/src/voice/realtime-presentation-runtime.mjs +21 -4
  80. package/server/src/voice/realtime-provider-session.mjs +59 -14
  81. package/server/src/voice/realtime-provider.mjs +332 -36
  82. package/server/src/voice/realtime-session-runtime.mjs +207 -16
  83. package/server/src/voice/realtime-task-presentation.mjs +6 -2
  84. package/server/src/voice/realtime-turn-state.mjs +33 -2
  85. package/shared/gateway/client-sdk.mjs +15 -5
  86. package/shared/gateway/websocket-auth.mjs +2 -1
  87. package/shared/protocol/gateway-events.mjs +31 -0
  88. package/shared/realtime-legacy-environment.mjs +37 -8
  89. package/shared/realtime-model-catalog.mjs +12 -10
  90. package/shared/realtime-models/README.md +10 -2
  91. package/shared/realtime-models/dashscope.mjs +11 -0
  92. package/shared/realtime-models/{google-live.mjs → google.mjs} +1 -1
  93. package/shared/realtime-models/openai.mjs +24 -0
  94. package/shared/realtime-models/profile.mjs +6 -3
  95. package/shared/realtime-models/{doubao-seeduplex.mjs → volcengine.mjs} +1 -1
  96. package/shared/realtime-provider-catalog.mjs +7 -6
  97. package/shared/realtime-provider-definitions.mjs +87 -22
  98. package/shared/runtime-environment.mjs +2 -2
  99. package/shared/web-search-configuration.mjs +14 -2
  100. package/tui/package.json +2 -2
  101. package/tui/src/index.mjs +14 -9
  102. package/tui/src/runtime-configuration.mjs +2 -0
  103. package/tui/src/terminal-commands.mjs +40 -0
  104. package/tui/src/text-cli.mjs +10 -1
  105. package/web/dist/assets/index-Bc2Q04J9.css +1 -0
  106. package/web/dist/assets/index-bY4DFXKT.js +96 -0
  107. package/web/dist/index.html +2 -2
  108. package/shared/realtime-models/gpt-live.mjs +0 -10
  109. package/web/dist/assets/index-8erKDCr2.css +0 -1
  110. package/web/dist/assets/index-Cs4hYWbS.js +0 -96
@@ -1,5 +1,11 @@
1
+ // A budget is measured in UTF-16 code units, but never split a surrogate pair.
2
+ function cut(value, maxLength) {
3
+ const prefix = value.slice(0, maxLength)
4
+ return /[\uD800-\uDBFF]$/.test(prefix) ? prefix.slice(0, -1) : prefix
5
+ }
6
+
1
7
  function cleanText(value, maxLength) {
2
- return String(value || '').replace(/\s+/g, ' ').trim().slice(0, maxLength)
8
+ return cut(String(value || '').replace(/\s+/g, ' ').trim(), maxLength)
3
9
  }
4
10
 
5
11
  export function normalizePublicUrl(value) {
@@ -72,7 +78,7 @@ export function normalizeSearchResponse(response, { query, limit = 5 } = {}) {
72
78
  : {}),
73
79
  })
74
80
  }
75
- const summary = String(response?.summary || '').trim().slice(0, 8000)
81
+ const summary = cut(String(response?.summary || '').trim(), 8000)
76
82
  return {
77
83
  status: 'ok',
78
84
  query: cleanText(query, 500),
@@ -62,6 +62,21 @@ export function resolveDisabledFrontendTools(env = process.env) {
62
62
  ]
63
63
  }
64
64
 
65
+ // GPT-Live 1 timing overrides in milliseconds; a key left unset keeps the
66
+ // adapter's default. The floor keeps an idle timer from never ending a turn.
67
+ const GPT_LIVE_1_TIMING_SETTINGS = Object.freeze({
68
+ outputIdleMs: 'GPT_LIVE_1_OUTPUT_IDLE_MS',
69
+ wordGapMs: 'GPT_LIVE_1_WORD_GAP_MS',
70
+ inputSegmentGapMs: 'GPT_LIVE_1_INPUT_SEGMENT_GAP_MS',
71
+ inputIdleMs: 'GPT_LIVE_1_INPUT_IDLE_MS',
72
+ })
73
+
74
+ export function resolveGptLive1Timing(env = process.env) {
75
+ return Object.fromEntries(Object.entries(GPT_LIVE_1_TIMING_SETTINGS)
76
+ .map(([key, name]) => [key, numberSetting(env[name], undefined, { min: 100, max: 10_000 })])
77
+ .filter(([, value]) => value !== undefined))
78
+ }
79
+
65
80
  export function resolveBackendWorkspace(
66
81
  protocol,
67
82
  env = process.env,
@@ -252,6 +267,7 @@ export const config = {
252
267
  realtimeEndpoint: realtimeFrontend.active.endpoint,
253
268
  realtimeModel: realtimeFrontend.active.model,
254
269
  realtimeVoice: realtimeFrontend.active.voice,
270
+ gptLive1Timing: resolveGptLive1Timing(),
255
271
  webSearchProvider: webSearch.provider,
256
272
  webSearchMcpUrl: webSearch.mcpUrl,
257
273
  webSearchMcpToken: webSearch.mcpToken,
@@ -640,8 +656,3 @@ export const config = {
640
656
  { min: 0, max: 86_400 },
641
657
  ) * 1000,
642
658
  }
643
-
644
- export function realtimeUrl(baseUrl, model) {
645
- const separator = baseUrl.includes('?') ? '&' : '?'
646
- return `${baseUrl}${separator}model=${encodeURIComponent(model)}`
647
- }
@@ -2,10 +2,16 @@ import { config } from './config.mjs'
2
2
  import { isIP } from 'node:net'
3
3
 
4
4
  const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1'])
5
- const TRUSTED_NATIVE_CLIENT_ORIGINS = new Set(['https://qwaudio.local'])
5
+ const TRUSTED_NATIVE_CLIENT_ORIGINS = new Set([
6
+ 'https://qwaudio.local',
7
+ 'capacitor://qwaudio.local',
8
+ ])
6
9
 
7
10
  function normalizedOrigin(value) {
8
11
  if (typeof value !== 'string' || !value.trim()) return ''
12
+ // WKWebView uses a custom scheme for bundled iOS resources. Recognize only
13
+ // the fixed native app origins; arbitrary opaque origins remain invalid.
14
+ if (TRUSTED_NATIVE_CLIENT_ORIGINS.has(value.trim())) return value.trim()
9
15
  try {
10
16
  const url = new URL(value)
11
17
  return ['http:', 'https:'].includes(url.protocol) ? url.origin : ''
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  buildFrontendContext,
3
3
  loadFrontendPrompt,
4
+ loadLiveFrontendPrompt,
4
5
  resolveAssistantProfile,
5
6
  } from '../conversation/frontend-agent-context.mjs'
6
7
  import { FrontendToolRegistry } from './tools/frontend-tool-registry.mjs'
@@ -163,11 +164,23 @@ export const inputRequestResponseInstructions = [
163
164
  ].join(' ')
164
165
 
165
166
  export function buildFrontendInstructions(agentContext = {}) {
166
- return [
167
+ return composeFrontendInstructions(agentContext, [
167
168
  loadFrontendPrompt(),
168
169
  ...optionalFrontendFeatures.filter(feature => feature.entries.some(entry => (
169
170
  frontendToolRegistry.isEnabled(entry.definition.function.name, agentContext)
170
171
  ))).map(feature => feature.instructions).filter(Boolean),
172
+ ])
173
+ }
174
+
175
+ export function buildLiveFrontendInstructions(agentContext = {}) {
176
+ // Native delegation has no frontend function tools. Context remains shared,
177
+ // but rules for calling those tools must not enter the Live instructions.
178
+ return composeFrontendInstructions(agentContext, [loadLiveFrontendPrompt()])
179
+ }
180
+
181
+ function composeFrontendInstructions(agentContext, instructions) {
182
+ return [
183
+ ...instructions,
171
184
  '# Assistant Profile',
172
185
  '<assistant_profile authority="persona_only">',
173
186
  resolveAssistantProfile(agentContext),
@@ -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) {
@@ -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' || provider === 'keenable') {
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,
@@ -32,6 +37,9 @@ export function createWebSearchProvider(config, options = {}) {
32
37
  toolArguments: { output_format: 'json', snippet_max_length: 1200 },
33
38
  }
34
39
  : {}),
40
+ ...(provider === 'parallel'
41
+ ? { key: 'parallel-mcp', label: 'Parallel Web Search MCP' }
42
+ : {}),
35
43
  ...options,
36
44
  })
37
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),
@@ -156,8 +160,11 @@ function normalizeToolResult(result) {
156
160
 
157
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
163
170
  // Preset arguments are sent only when the tool declares them.
@@ -231,11 +238,12 @@ export class McpWebSearchProvider {
231
238
  const boundedLimit = Math.max(1, Math.min(8, Math.trunc(Number(limit) || 5)))
232
239
  const url = validateEndpoint(this.url, { hasToken: Boolean(this.token) })
233
240
  const client = this.clientFactory()
234
- const headers = this.token
235
- ? { authorization: `Bearer ${this.token}` }
236
- : undefined
241
+ const headers = {
242
+ 'User-Agent': `qwen-audio-agent/${PACKAGE_VERSION}`,
243
+ ...(this.token ? { authorization: `Bearer ${this.token}` } : {}),
244
+ }
237
245
  const transport = this.transportFactory(url, {
238
- ...(headers ? { requestInit: { headers } } : {}),
246
+ requestInit: { headers },
239
247
  })
240
248
  try {
241
249
  await client.connect(transport, { signal })
@@ -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
  '根据本次响应中的全部取消结果,只作一次简短自然的确认。',
@@ -511,6 +512,12 @@ export class AgentTaskRuntime {
511
512
  const pending = this.pendingPermissions()
512
513
  try {
513
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
+ }
514
521
  if (!response || !transcript) {
515
522
  await this.host.sendOutput(
516
523
  callId,
@@ -571,6 +578,12 @@ export class AgentTaskRuntime {
571
578
  )
572
579
  return
573
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
+ }
574
587
  if (!this.host.taskOperations.respondAuthorization) {
575
588
  await this.host.sendOutput(
576
589
  callId,
@@ -629,6 +642,9 @@ export class AgentTaskRuntime {
629
642
  ) {
630
643
  fail('input_not_pending', '对应的后台问题已失效或不在当前会话,回答没有提交。')
631
644
  }
645
+ if (this.host.answersRequest?.(turnId, request.id) === false) {
646
+ fail('input_not_answered', '用户还没有回答这个后台问题;请先向用户转述问题。')
647
+ }
632
648
  if (!this.host.taskOperations.respondInput) {
633
649
  fail('input_unavailable', '当前后台无法接收补充输入。')
634
650
  }
@@ -653,11 +669,12 @@ export class AgentTaskRuntime {
653
669
  }
654
670
 
655
671
  async cancelAgentTask(callId, turnId, args, responseOptions) {
672
+ const reachable = task => !this.host.startedLater?.(task.turnId, turnId)
656
673
  if (args.all === true) {
657
674
  const targets = this.host.taskOperations.list({
658
675
  ownerId: this.host.ownerId,
659
676
  sessionId: this.host.sessionId,
660
- }).filter(task => isTaskCancellable(task.status))
677
+ }).filter(task => isTaskCancellable(task.status) && reachable(task))
661
678
  if (!targets.length) {
662
679
  await this.host.sendOutput(callId, {
663
680
  status: 'not_found',
@@ -685,7 +702,8 @@ export class AgentTaskRuntime {
685
702
  if (requestedSeriesId) {
686
703
  const existing = this.host.taskOperations.list({ ownerId: this.host.ownerId })
687
704
  .filter(task => task.seriesId === requestedSeriesId)
688
- 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)) {
689
707
  await this.host.sendOutput(callId, {
690
708
  status: 'not_found',
691
709
  series_id: requestedSeriesId,
@@ -718,8 +736,8 @@ export class AgentTaskRuntime {
718
736
  : this.host.taskOperations.list({
719
737
  ownerId: this.host.ownerId,
720
738
  sessionId: this.host.sessionId,
721
- }).find(task => isTaskCancellable(task.status))
722
- if (!target) {
739
+ }).find(task => isTaskCancellable(task.status) && reachable(task))
740
+ if (!target || !reachable(target)) {
723
741
  await this.host.sendOutput(callId, {
724
742
  status: 'not_found',
725
743
  message: '当前没有仍在排队或执行的工作。',
@@ -23,6 +23,9 @@ import {
23
23
  FrontendToolLoop,
24
24
  } from './frontend-tool-loop.mjs'
25
25
 
26
+ // Calls that answer or update a pending request act for the latest user turn.
27
+ const LATEST_TURN_TOOLS = new Set([RESPOND_PERMISSION_TOOL_NAME, UPDATE_AGENT_TASK_TOOL_NAME])
28
+
26
29
  const MAX_DEBUG_RESULT_CHARS = 180
27
30
 
28
31
  function failure(errorCode, userMessage, {
@@ -86,6 +89,9 @@ export class ToolCallHandler {
86
89
  getFrontend,
87
90
  getTurnId,
88
91
  getTurnGeneration,
92
+ isUserTurnSinceBoundary = () => false,
93
+ userTurnBeganAfter = () => false,
94
+ answersRequest = () => true,
89
95
  backendRuntime,
90
96
  taskOperations,
91
97
  backendAvailability = null,
@@ -117,6 +123,9 @@ export class ToolCallHandler {
117
123
  this.getFrontend = getFrontend
118
124
  this.getTurnId = getTurnId
119
125
  this.getTurnGeneration = getTurnGeneration
126
+ this.isUserTurnSinceBoundary = isUserTurnSinceBoundary
127
+ this.userTurnBeganAfter = userTurnBeganAfter
128
+ this.answersRequest = answersRequest
120
129
  this.taskOperations = taskOperations || (taskManager ? new TaskOperations({
121
130
  taskManager, backendRuntime, respondAuthorization, respondInput, permissionPolicy,
122
131
  }) : null)
@@ -281,13 +290,23 @@ export class ToolCallHandler {
281
290
  return true
282
291
  }
283
292
 
284
- isStale(turnId, generation) {
285
- return (
286
- generation !== this.getTurnGeneration()
293
+ isStale(turnId, generation, toolName = '') {
294
+ const superseded = generation !== this.getTurnGeneration()
287
295
  || Boolean(turnId && this.getTurnId() && turnId !== this.getTurnId())
296
+ // Full duplex: later user turns alone do not supersede a turn's calls.
297
+ return superseded && !(
298
+ this.getFrontend?.()?.capabilities?.concurrentVoicePlayback
299
+ && !LATEST_TURN_TOOLS.has(toolName)
300
+ && this.isUserTurnSinceBoundary({ turnId, turnGeneration: generation })
288
301
  )
289
302
  }
290
303
 
304
+ // Full duplex: a call from an earlier turn does not act on work a later user turn started.
305
+ startedLater(taskTurnId, turnId) {
306
+ return Boolean(this.getFrontend?.()?.capabilities?.concurrentVoicePlayback
307
+ && this.userTurnBeganAfter(taskTurnId, turnId))
308
+ }
309
+
291
310
  async sendOutput(callId, output, turnId, taskId, options) {
292
311
  const {
293
312
  responseContext,
@@ -450,15 +469,16 @@ export class ToolCallHandler {
450
469
  async flushDeferredToolResponse(responseId, batch) {
451
470
  if (!batch.sourceDone || batch.pending > 0) return
452
471
  this.deferredToolResponses.delete(responseId)
472
+ const continuation = { turnId: batch.turnId, turnGeneration: batch.turnGeneration }
453
473
  if (batch.failed) {
454
474
  this.onToolResponseFailed({ responseId, turnId: batch.turnId })
455
- return
475
+ return this.continueToolResults(continuation)
456
476
  }
457
477
  if (
458
478
  batch.suppressResponse || !batch.responseRequested
459
479
  || (batch.sourceHasSpeech && !batch.requiresResultSummary)
460
480
  || this.isStale(batch.turnId, batch.turnGeneration)
461
- ) return
481
+ ) return this.continueToolResults(continuation)
462
482
  const instructions = [...batch.responseInstructions]
463
483
  if (batch.requiresResultSummary && instructions.length) {
464
484
  instructions.push(
@@ -466,7 +486,7 @@ export class ToolCallHandler {
466
486
  )
467
487
  }
468
488
  try {
469
- await this.getFrontend()?.ensureResponse?.(
489
+ const outcome = await this.getFrontend()?.ensureResponse?.(
470
490
  {
471
491
  turnId: batch.turnId,
472
492
  turnGeneration: batch.turnGeneration,
@@ -488,23 +508,37 @@ export class ToolCallHandler {
488
508
  } : {}),
489
509
  },
490
510
  )
511
+ if (outcome?.skipped) await this.continueToolResults(continuation)
491
512
  } catch (error) {
492
513
  this.onToolResponseFailed({ responseId, turnId: batch.turnId })
493
514
  throw error
494
515
  }
495
516
  }
496
517
 
497
- async closeStaleCall(callId, turnId) {
498
- await this.sendOutput(
499
- callId,
500
- {
501
- status: 'superseded',
502
- message: '用户已经开始了新一轮,这次尚未提交。',
503
- },
504
- turnId,
505
- null,
506
- { createResponse: false },
507
- )
518
+ // Continues a response the service resumes only after its tool results.
519
+ async continueToolResults(context) {
520
+ await this.getFrontend()?.continueToolResults?.(context)
521
+ }
522
+
523
+ async closeStaleCall(callId, turnId, { responseId = '', turnGeneration } = {}) {
524
+ // Joins its response's batch, which decides once how that response continues.
525
+ const deferred = this.getFrontend()?.capabilities?.toolOutputsBeforeResponse
526
+ ? this.beginDeferredToolResponse(responseId, { turnId, turnGeneration, requestResponse: false })
527
+ : null
528
+ try {
529
+ await this.sendOutput(
530
+ callId,
531
+ {
532
+ status: 'superseded',
533
+ message: '用户已经开始了新一轮,这次尚未提交。',
534
+ },
535
+ turnId,
536
+ null,
537
+ { createResponse: false },
538
+ )
539
+ } finally {
540
+ await this.completeDeferredToolResponse(deferred)
541
+ }
508
542
  }
509
543
 
510
544
  createWork(...args) {
@@ -558,15 +592,15 @@ export class ToolCallHandler {
558
592
  invalidArguments = true
559
593
  }
560
594
 
561
- if (this.isStale(turnId, generation)) {
562
- await this.closeStaleCall(callId, turnId)
595
+ const responseId = String(callContext.responseId || event.response_id || '').trim()
596
+ if (this.isStale(turnId, generation, toolName)) {
597
+ await this.closeStaleCall(callId, turnId, { responseId, turnGeneration: generation })
563
598
  return
564
599
  }
565
600
 
566
601
  const external = this.externalTool(toolName)
567
602
  const tool = frontendToolRegistry.get(toolName) || external?.tool
568
603
  if (tool) this.activeToolEntries.set(callId, tool)
569
- const responseId = String(callContext.responseId || event.response_id || '').trim()
570
604
  const debug = {
571
605
  callId,
572
606
  turnId,
@@ -652,6 +686,8 @@ export class ToolCallHandler {
652
686
  return execution
653
687
  } catch (error) {
654
688
  failed = true
689
+ // A frontend that still waits for this call's output gets a failure.
690
+ this.getFrontend()?.failCall?.(callId, failure('tool_failed', '工具执行失败。'))?.catch(() => {})
655
691
  throw error
656
692
  } finally {
657
693
  this.activeToolEntries.delete(callId)
@@ -48,7 +48,9 @@ function exactEditMatches(content, needle) {
48
48
  && !(offset <= comment.start && end >= comment.end)
49
49
  ))
50
50
  if (!partialComment) matches.push(offset)
51
- offset += needle.length
51
+ // Step by one, not by the needle: "- a\n- a" also starts on the second
52
+ // line of "- a\n- a\n- a", and that overlap makes the edit ambiguous.
53
+ offset += 1
52
54
  }
53
55
  return matches
54
56
  }
@@ -77,7 +77,7 @@ export class SessionTaskCoordinator {
77
77
  canDeliver() {
78
78
  const state = this.presentation.state()
79
79
  return !this.closed && state.ready && state.outputEnabled
80
- && !state.sleeping && !state.waking
80
+ && !state.sleeping && !state.waking && state.nativeTaskDelivery !== true
81
81
  }
82
82
 
83
83
  scheduleRetry() {
@@ -183,6 +183,9 @@ export class SessionTaskCoordinator {
183
183
  if (task.sessionId !== this.sessionId) return
184
184
  this.onTaskEvent(event)
185
185
  const state = this.presentation.state()
186
+ // Native delegation delivers task facts through its provider protocol.
187
+ // Keep the same UI events, but do not enqueue a second Realtime announcement.
188
+ if (state.nativeTaskDelivery === true) return
186
189
  if (event.type === TaskDomainEvent.UPDATED && event.message
187
190
  && task.authorization?.status !== 'pending' && task.inputRequest?.status !== 'pending'
188
191
  && state.outputEnabled && !state.sleeping && !state.waking) {
@@ -57,15 +57,17 @@ export class TaskOperations {
57
57
  return this.taskManager.list({ sessionId, active, ...filters, ownerId: owner(context) })
58
58
  }
59
59
 
60
- submit({ objective, inputParts = [], submissionKey }, context) {
60
+ submit({ objective, instruction, inputParts = [], submissionKey, notificationPolicy }, context) {
61
61
  const ownerId = owner(context)
62
62
  const { sessionId = 'main', turnId } = context
63
63
  const conversation = this.conversationSnapshot?.(context)
64
64
  return this.taskManager.create({
65
- objective, ownerId, sessionId, turnId, submissionKey,
65
+ objective, ownerId, sessionId, turnId, submissionKey, notificationPolicy,
66
66
  runner: (_objective, execution) => this.run(inputWithUpdates(
67
67
  this.taskManager.tasks.get(execution.taskId), {
68
- objective, inputParts, ...(conversation ? { conversation } : {}),
68
+ objective, inputParts,
69
+ ...(instruction === undefined ? {} : { instruction }),
70
+ ...(conversation ? { conversation } : {}),
69
71
  },
70
72
  ), {
71
73
  ...execution, ownerId, sessionId, turnId,
@@ -68,7 +68,8 @@ export function inputWithUpdates(task, input) {
68
68
  const queued = (task.updates || []).filter(entry => entry.status === 'queued')
69
69
  if (!queued.length) return input
70
70
  const instruction = [
71
- input.resumeContext ? `继续此前工作:${task.objective}` : task.objective,
71
+ // Native delegation context can differ from the concise card title.
72
+ input.instruction || (input.resumeContext ? `继续此前工作:${task.objective}` : task.objective),
72
73
  '以下是用户按时间顺序补充的要求;存在冲突时以较新的要求为准:',
73
74
  ...queued.map(entry => entry.instruction),
74
75
  ].join('\n\n')
@@ -190,6 +190,7 @@ export function attachGatewayClientTransport(server, {
190
190
  let admitted = false
191
191
  let clientLease = null
192
192
  let runtimeMessageChain = Promise.resolve()
193
+ const extensionCleanups = new Set()
193
194
  const voiceClient = {
194
195
  ws,
195
196
  descriptor,
@@ -329,6 +330,18 @@ export function attachGatewayClientTransport(server, {
329
330
  const result = await clientEventRouter.publish(message, {
330
331
  source: runtimeSource(),
331
332
  effects: {
333
+ setExternalInput(enabled, options) { sessionRuntime.setExternalInput(enabled, options) },
334
+ onRealtimeEvent(listener) { return sessionRuntime.onRealtimeEvent(listener) },
335
+ appendAudio(audio) { sessionRuntime.handleClientEvent({ type: GatewayClientEvent.AUDIO_APPEND, audio }) },
336
+ setInputCollecting(active) { sessionRuntime.setInputCollecting(active) },
337
+ submitInput(parts) { sessionRuntime.submitExternalInput(parts) },
338
+ publishClientState(state, data) {
339
+ send(ws, { type: GatewayServerEvent.CLIENT_STATE, state, data })
340
+ },
341
+ onDisconnect(cleanup) {
342
+ extensionCleanups.add(cleanup)
343
+ return () => extensionCleanups.delete(cleanup)
344
+ },
332
345
  setAssistantProfile(profile) {
333
346
  // Only a server-registered Client Event handler can reach this
334
347
  // effect. The Client supplies a schema-validated identifier,
@@ -465,6 +478,12 @@ export function attachGatewayClientTransport(server, {
465
478
  closeCode: Number(code),
466
479
  closeReason: reason?.toString() || undefined,
467
480
  })
481
+ for (const cleanup of extensionCleanups) {
482
+ try { cleanup() } catch (error) {
483
+ connectionLogger.warn('client_extension.cleanup_failed', { error: error.message })
484
+ }
485
+ }
486
+ extensionCleanups.clear()
468
487
  sessionRuntime.close()
469
488
  const connections = voiceConnections.get(ownerId)
470
489
  connections?.delete(voiceClient)
@@ -39,7 +39,7 @@ export class WebRtcConnection extends EventEmitter {
39
39
  ![GatewayClientCapability.SESSION_HEARTBEAT, GatewayClientCapability.CLIENT_ACTION_ENTER_SLEEP].includes(capability)
40
40
  && (this.video || capability !== GatewayClientCapability.INPUT_IMAGE_BUFFER)
41
41
  )), ...this.clientActions.map(name => `client.actions.${name}`)])],
42
- connection: { provider: this.provider.key, voice_enabled: true, input_enabled: true, output_enabled: true },
42
+ connection: { provider: this.provider.provider || this.provider.key, voice_enabled: true, input_enabled: true, output_enabled: true },
43
43
  takeover: this.takeover,
44
44
  }))
45
45
  }