@tencent-rtc/mcp 1.6.8 → 1.7.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 (75) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +53 -39
  3. package/knowledge/build-index.js +30 -6
  4. package/knowledge/chunker.js +82 -14
  5. package/knowledge/chunking-policy.js +100 -0
  6. package/knowledge/content-loader.js +3 -3
  7. package/knowledge/frontmatter-meta.js +167 -0
  8. package/knowledge/path-meta.js +28 -6
  9. package/knowledge/search/exact-lookup.js +9 -227
  10. package/knowledge/search/filter-pool.js +12 -29
  11. package/knowledge/search/framework-fallback.js +22 -0
  12. package/knowledge/search/intent-router.js +13 -0
  13. package/knowledge/search/query-normalizer.js +56 -3
  14. package/knowledge/search/search-core.js +391 -0
  15. package/knowledge/search/search-knowledge.js +292 -363
  16. package/knowledge/search/search-message.js +87 -0
  17. package/knowledge/search/search-pass.js +428 -0
  18. package/knowledge/search/search-types.js +1 -0
  19. package/knowledge/search/url-row-scorer.js +258 -0
  20. package/package.json +1 -1
  21. package/resource/_schema/feature-aliases.yaml +1 -1
  22. package/resource/index/manifest.json +1 -1
  23. package/resource/knowledge/callkit/best-practice/callkit-miniprogram/uniapp-shrink.md +60 -0
  24. package/resource/knowledge/callkit/best-practice/common/call-autoplay-blocked.md +77 -0
  25. package/resource/knowledge/callkit/best-practice/common/call-message-in-chat.md +78 -0
  26. package/resource/knowledge/callkit/best-practice/common/call-vs-calls.md +110 -0
  27. package/resource/knowledge/callkit/best-practice/common/callengine-call-flow.md +123 -0
  28. package/resource/knowledge/callkit/best-practice/common/callengine-log-level.md +67 -0
  29. package/resource/knowledge/callkit/best-practice/common/callkit-get-engine-instance.md +81 -0
  30. package/resource/knowledge/callkit/best-practice/common/callkit-get-roomid.md +78 -0
  31. package/resource/knowledge/callkit/best-practice/common/callkit-limitations.md +37 -0
  32. package/resource/knowledge/callkit/best-practice/common/callkit-user-register-and-kicked.md +98 -0
  33. package/resource/knowledge/chat/best-practice/common/avchatroom-message-loss-diagnosis.md +65 -0
  34. package/resource/knowledge/chat/best-practice/common/group-conversation-cleanup-on-system-notice.md +62 -0
  35. package/resource/knowledge/chat/best-practice/common/image-message-url-lifecycle.md +59 -0
  36. package/resource/knowledge/chat/best-practice/common/login-repeat-2025-diagnosis.md +61 -0
  37. package/resource/knowledge/chat/best-practice/common/message-read-report-and-receipt.md +64 -0
  38. package/resource/knowledge/chat/best-practice/common/message-receive-event.md +65 -0
  39. package/resource/knowledge/chat/best-practice/common/message-risk-error-and-render.md +65 -0
  40. package/resource/knowledge/chat/best-practice/common/message-unread-count.md +71 -0
  41. package/resource/knowledge/chat/best-practice/miniprogram/audio-message-send.md +113 -0
  42. package/resource/knowledge/chat/best-practice/miniprogram/login-timeout-2801-diagnosis.md +63 -0
  43. package/resource/knowledge/chat/best-practice/miniprogram/media-upload-fail-diagnosis.md +64 -0
  44. package/resource/knowledge/chat/best-practice/web/audio-message-send.md +118 -0
  45. package/resource/knowledge/chat/urls/sdk/web.md +1 -1
  46. package/resource/knowledge/livekit/best-practice/android/voice-room-anchor-start.md +120 -0
  47. package/resource/knowledge/livekit/best-practice/common/admin-take-seat.md +73 -0
  48. package/resource/knowledge/livekit/best-practice/common/audience-leave-live.md +81 -0
  49. package/resource/knowledge/livekit/best-practice/common/voice-room-no-audio-troubleshoot.md +100 -0
  50. package/resource/knowledge/livekit/best-practice/common/voice-room-seat-list-change.md +65 -0
  51. package/resource/knowledge/livekit/best-practice/flutter/voice-room-anchor-start.md +122 -0
  52. package/resource/knowledge/livekit/best-practice/ios/voice-room-anchor-start.md +126 -0
  53. package/resource/knowledge/roomkit/best-practice/common/room-ghost-member.md +70 -0
  54. package/resource/knowledge/roomkit/best-practice/common/room-limit-and-multi.md +83 -0
  55. package/resource/knowledge/roomkit/best-practice/common/room-screen-share-preview.md +83 -0
  56. package/resource/knowledge/roomkit/best-practice/common/room-status-after-all-leave.md +69 -0
  57. package/resource/knowledge/roomkit/best-practice/vue/room-uikit-vs-atomicx.md +111 -0
  58. package/resource/knowledge/rtcengine/web/plugin/30-advanced-cross-room-link.md +2 -0
  59. package/resource/knowledge/rtcengine/web/plugin/39-advanced-video-decoder.md +2 -0
  60. package/server.js +27 -22
  61. package/tools/common/finalize_answer.js +9 -1
  62. package/tools/common/search_trtc_knowledge.js +1 -1
  63. package/tools/definitions/finalize_answer_def.js +2 -2
  64. package/tools/definitions/integration-boundary.js +2 -1
  65. package/tools/definitions/search_trtc_knowledge_def.js +1 -1
  66. package/utils/report-cls-client.js +1 -1
  67. package/utils/report-es-client.js +1 -1
  68. package/cursor-setting.png +0 -0
  69. package/mcp-server-prompt.png +0 -0
  70. package/resource/knowledge/callkit/best-practice/web/callengine-invitation.md +0 -80
  71. package/resource/knowledge/callkit/best-practice/web/callengine-log-control.md +0 -24
  72. package/resource/knowledge/callkit/best-practice/web/callkit-call-vs-calls.md +0 -116
  73. package/resource/knowledge/callkit/preset/react/uikit-api-reference.md +0 -444
  74. package/resource/knowledge/callkit/preset/vue/uikit-api-reference.md +0 -464
  75. package/resource/knowledge/chat/best-practice/web/image-message-url-handling.md +0 -16
@@ -1,13 +1,15 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { fileURLToPath } from 'url';
4
- import { attachPoolContent, getSourceFileContent } from '../content-loader.js';
5
- import { buildReferences, resolveFragmentDocUrls } from '../doc-url-resolver.js';
6
- import { rankSubsetWithIndex } from '../bm25.js';
7
- import { getProductsBM25Index } from '../bm25-cache.js';
8
4
  import { filterPool, normalizeParams } from './filter-pool.js';
9
- import { runExactLookup } from './exact-lookup.js';
10
5
  import { requiresFramework } from './requires-framework.js';
6
+ import { classifyRetrievalMode } from './intent-router.js';
7
+ import { rankSubsetWithIndex } from '../bm25.js';
8
+ import { getProductsBM25Index } from '../bm25-cache.js';
9
+ import { hasExplicitFrameworkMatch } from './framework-fallback.js';
10
+ import { assessConfidence, assessNarrativeCompleteness, buildDiscoveryCatalog, buildNarrativeDocument, hasNativeClientFramework, hasNativeTrtcApiSignal, hasProductScopeIntent, inferQueryApiTokens, pickNarrativeSource, } from './search-core.js';
11
+ import { buildAnswerContract, buildAgentMessage } from './search-message.js';
12
+ import { runSearchPass } from './search-pass.js';
11
13
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
14
  let cachedManifest = null;
13
15
  function resolveResourcePath(...segments) {
@@ -18,313 +20,80 @@ function loadManifest() {
18
20
  return cachedManifest;
19
21
  const manifestPath = resolveResourcePath('index', 'manifest.json');
20
22
  if (!fs.existsSync(manifestPath)) {
21
- throw new Error('manifest.json not found. Run `npm run build` in zh/ first.');
23
+ throw new Error('manifest.json not found. Run `npm run build` first.');
22
24
  }
23
25
  cachedManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
24
26
  return cachedManifest;
25
27
  }
26
- function postProcess(ranked, chunksById, limit, opts) {
27
- const sourceCount = {};
28
- const urlMappingSourceCount = {};
29
- /** 已入选的 push config/android/{vendor} 文件,用于抑制其他厂商噪声 */
30
- let selectedVendorFile = null;
31
- const fragments = [];
32
- for (const item of ranked) {
33
- const chunk = chunksById.get(item.id);
34
- if (!chunk)
35
- continue;
36
- const isUrlMapping = Boolean(isUrlMappingSource(chunk.source));
37
- const isPinnedUrlRow = isUrlMapping && (opts?.pinnedUrlRowChunkIds?.has(chunk.id) ?? false);
38
- if (isUrlMapping) {
39
- const urlCount = urlMappingSourceCount[chunk.source] ?? 0;
40
- if (!isPinnedUrlRow && urlCount >= 1)
41
- continue;
42
- urlMappingSourceCount[chunk.source] = urlCount + 1;
43
- }
44
- else {
45
- const count = sourceCount[chunk.source] ?? 0;
46
- if (count >= 3)
47
- continue;
48
- sourceCount[chunk.source] = count + 1;
49
- }
50
- // 当用户明确问某厂商时,抑制同目录下其他厂商文档的噪声
51
- // 规则:如果已有 config/android/{vendor}.md 入选,
52
- // 后续其他 config/android/{other}.md 跳过
53
- const isVendorDoc = chunk.source.match(/^knowledge\/push\/config\/android\/[a-z]+\.md$/);
54
- if (isVendorDoc) {
55
- if (!selectedVendorFile) {
56
- selectedVendorFile = chunk.source;
57
- }
58
- else if (chunk.source !== selectedVendorFile) {
59
- continue; // 跳过其他厂商
60
- }
61
- }
62
- // 当已明确命中了厂商配置页后,后续的 push 通用文件(integration/、其他 config/)不再有意义
63
- // 只保留同厂商文件(已由 vendor dedup 处理)和 overview 综述,其他 push 通用文档视为噪声
64
- if (selectedVendorFile && chunk.source.startsWith('knowledge/push/') && !chunk.source.includes('/overview/')) {
65
- if (chunk.source !== selectedVendorFile)
66
- continue;
67
- }
68
- const firstPush = fragments.length === 0;
69
- if (firstPush) {
70
- // 首条不设分数截止,至少保证 1 条返回
71
- }
72
- else if (!isPinnedUrlRow) {
73
- // 分数衰减到 top 的 5% 以下时停止,不硬填到 limit
74
- // chat/urls 的行级精确命中(E7)不受该规则截断,保证多子主题可并行返回
75
- const topScore = fragments[0].score;
76
- if (topScore > 0 && item.score < topScore * 0.05)
77
- break;
78
- }
79
- const contentWithHint = chunk.contains_code
80
- ? `【代码示例,须与目标端一致】\n${chunk.content}`
81
- : chunk.content;
82
- fragments.push({
83
- rank: fragments.length + 1,
84
- score: item.score,
85
- title: chunk.title,
86
- content: contentWithHint,
87
- source: chunk.source,
88
- doc_urls: resolveFragmentDocUrls(chunk.source, chunk.content, getSourceFileContent(chunk.source)),
89
- product: chunk.product,
90
- framework: chunk.framework,
91
- types: chunk.types,
92
- variant: chunk.variant,
93
- scope: chunk.scope,
94
- doc_kind: chunk.doc_kind,
95
- capability_status: chunk.capability_status,
96
- api_names: chunk.api_names,
97
- contains_code: chunk.contains_code,
98
- citation: `[来源: ${chunk.id}]`,
99
- chunk_id: chunk.id,
100
- });
101
- if (fragments.length >= limit)
102
- break;
103
- }
104
- return fragments;
105
- }
106
- function isUrlMappingSource(source) {
107
- const normalized = source.replace(/\\/g, '/');
108
- const match = normalized.match(/knowledge\/chat\/urls\/(.+\.md)$/);
109
- if (!match)
110
- return null;
111
- return match[1].replace(/\.md$/, '').replace(/\/index$/, '');
112
- }
113
- function partitionFragments(fragments) {
114
- const urlMapping = [];
115
- const localDoc = [];
116
- for (const fragment of fragments) {
117
- if (isUrlMappingSource(fragment.source)) {
118
- urlMapping.push(fragment);
119
- }
120
- else {
121
- localDoc.push(fragment);
122
- }
123
- }
124
- const urlMappingKinds = [...new Set(urlMapping.map((f) => isUrlMappingSource(f.source)).filter(Boolean))];
125
- return { urlMapping, localDoc, urlMappingKinds };
126
- }
127
- function hasBestPracticeFragment(fragments) {
128
- return fragments.some((f) => /\/best-practice\//i.test(f.source));
129
- }
130
- function inferQueryApiTokens(prompt) {
131
- const tokens = new Set();
132
- // Keep API-shaped tokens only; exclude product/platform brand words to avoid false low-confidence downgrades.
133
- const upperNoise = new Set([
134
- 'SDK', 'API', 'HTTP', 'HTTPS', 'JSON', 'CALL', 'NAME', 'STATUS',
135
- 'TRTC', 'TENCENT', 'WEB', 'VUE', 'REACT', 'ROOMKIT', 'LIVEKIT', 'CALLKIT',
136
- ]);
137
- const platformNoise = new Set([
138
- 'ios', 'android', 'flutter', 'web', 'react', 'vue', 'miniprogram',
139
- 'harmonyos', 'react-native', 'unity', 'unreal', 'unreal-engine', 'donut', 'uni-app',
140
- 'pc', 'h5',
141
- ]);
142
- for (const match of prompt.matchAll(/\b([a-z]+[A-Z][A-Za-z0-9_]*)\b/g)) {
143
- tokens.add(match[1]);
144
- }
145
- for (const match of prompt.matchAll(/\b([A-Z][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*)\b/g)) {
146
- tokens.add(match[1]);
147
- }
148
- for (const match of prompt.matchAll(/\b(use[A-Z]\w*)\b/g)) {
149
- tokens.add(match[1]);
150
- }
151
- for (const match of prompt.matchAll(/\b(I[A-Z][A-Za-z0-9_]*)\b/g)) {
152
- tokens.add(match[1]);
153
- }
154
- for (const match of prompt.matchAll(/\b([A-Z][A-Za-z0-9_]*\.[A-Z_][A-Z0-9_]*)\b/g)) {
155
- tokens.add(match[1]);
156
- }
157
- for (const match of prompt.matchAll(/\b([A-Z_]{3,})\b/g)) {
158
- const token = match[1];
159
- if (!upperNoise.has(token))
160
- tokens.add(token);
161
- }
162
- return [...tokens].filter((token) => !platformNoise.has(token.toLowerCase()));
163
- }
164
- function tokenInChunk(token, chunk) {
165
- if (chunk.api_names?.some((name) => name.toLowerCase() === token.toLowerCase()))
166
- return true;
167
- if (chunk.symbols?.some((name) => name.toLowerCase() === token.toLowerCase()))
168
- return true;
169
- const low = token.toLowerCase();
170
- return chunk.title.toLowerCase().includes(low) || chunk.source.toLowerCase().includes(low);
171
- }
172
- function computeApiNameCoverage(tokens, candidates) {
173
- if (!tokens.length)
174
- return 1;
175
- const hit = tokens.filter((token) => candidates.some((chunk) => tokenInChunk(token, chunk))).length;
176
- return Number((hit / tokens.length).toFixed(2));
177
- }
178
- function computeMissingApiTokens(tokens, candidates) {
179
- if (!tokens.length)
180
- return [];
181
- return tokens.filter((token) => !candidates.some((chunk) => tokenInChunk(token, chunk)));
182
- }
183
- function hasProductScopeIntent(prompt) {
184
- return /控制台|开通|开通服务|计费|套餐|价格|pricing|billing|plan|console|activate|activation|service/i.test(prompt);
185
- }
186
- function hasNativeTrtcApiSignal(prompt, queryApiTokens) {
187
- if (/\bTRTCCloud\b|\bTRTCRenderParams\b|\bTXDeviceManager\b|setLocalRenderParams|startLocalPreview|stopLocalPreview/i.test(prompt)) {
188
- return true;
28
+ function buildCoverageReport(allChunks, fragments, preferredSource) {
29
+ if (!fragments.length) {
30
+ return {
31
+ files: [],
32
+ allow_pending_confirm: true,
33
+ retry_suggested: false,
34
+ };
189
35
  }
190
- return queryApiTokens.some((token) => /^(TRTC|TX)[A-Za-z0-9_]+$/.test(token)
191
- || /^(set|get|start|stop|enable|disable)[A-Z][A-Za-z0-9_]+$/.test(token));
192
- }
193
- function hasNativeClientFramework(frameworks) {
194
- if (!frameworks?.length)
195
- return false;
196
- return frameworks.some((fw) => ['android', 'ios', 'flutter', 'c++'].includes(fw));
197
- }
198
- function applyRankMultipliers(ranked, chunksById, opts) {
199
- const adjusted = ranked.map((item) => {
200
- const chunk = chunksById.get(item.id);
201
- if (!chunk)
202
- return item;
203
- let multiplier = 1;
204
- // A2: 传了 product 时,命中 scope 的通配语料允许召回但降权
205
- if (opts.product?.length && chunk.product === '*') {
206
- multiplier *= 0.2;
207
- }
208
- // F2: framework 软降权(保留硬过滤,处理 fallback/边界残留)
209
- if (opts.framework && opts.frameworks?.length && !chunk.framework.includes('*')) {
210
- const explicitMatch = opts.frameworks.some((fw) => chunk.framework.includes(fw));
211
- const callCoreWebFallback = Boolean(opts.product?.includes('call')
212
- && (opts.framework === 'react' || opts.framework === 'vue')
213
- && chunk.variant === 'core-sdk'
214
- && chunk.framework.includes('web'));
215
- const liveWebVueFallback = Boolean(opts.product?.includes('live')
216
- && opts.framework === 'web'
217
- && chunk.variant === 'core-sdk'
218
- && chunk.framework.includes('vue')
219
- && chunk.source.includes('/api-reference/'));
220
- const roomWebVueFallback = Boolean(opts.product?.includes('room')
221
- && opts.framework === 'web'
222
- && chunk.variant === 'core-sdk'
223
- && chunk.framework.includes('vue')
224
- && chunk.source.includes('knowledge/roomkit/core-sdk/vue/'));
225
- if (!explicitMatch && !callCoreWebFallback && !liveWebVueFallback && !roomWebVueFallback) {
226
- multiplier *= 0.2;
227
- }
228
- }
229
- return { ...item, score: item.score * multiplier };
36
+ const hitChunkIds = new Set(fragments.map((f) => f.chunk_id));
37
+ const sources = [...new Set(fragments.map((f) => f.source))];
38
+ const files = sources.map((source) => {
39
+ const sourceChunks = allChunks.filter((chunk) => chunk.source === source);
40
+ const fileToken = sourceChunks.reduce((sum, chunk) => sum + Math.max(0, chunk.char_end - chunk.char_start), 0);
41
+ const hitToken = sourceChunks
42
+ .filter((chunk) => hitChunkIds.has(chunk.id))
43
+ .reduce((sum, chunk) => sum + Math.max(0, chunk.char_end - chunk.char_start), 0);
44
+ const completeness = fileToken > 0 ? Number((hitToken / fileToken).toFixed(2)) : 0;
45
+ const missingChunkIds = sourceChunks.filter((chunk) => !hitChunkIds.has(chunk.id)).map((chunk) => chunk.id).slice(0, 12);
46
+ return {
47
+ source,
48
+ hit_token: hitToken,
49
+ file_token: fileToken,
50
+ completeness,
51
+ missing_chunk_ids: missingChunkIds,
52
+ };
230
53
  });
231
- return adjusted.sort((a, b) => b.score - a.score);
232
- }
233
- /**
234
- * 多因子置信度评估:exact 命中 + 分数梯度 + API 覆盖度。
235
- */
236
- function assessConfidence(fragments, exactHits, apiNameCoverage, queryApiTokens) {
237
- if (fragments.length === 0) {
238
- return { confidence: 'none', status: 'empty' };
239
- }
240
- const top = fragments[0].score;
241
- const second = fragments[1]?.score ?? 0;
242
- const ratio = second > 0 ? top / second : Infinity;
243
- let confidence;
244
- if (exactHits.length > 0 || top >= 50)
245
- confidence = 'high';
246
- else if (top >= 12 && ratio >= 1.25)
247
- confidence = 'medium';
248
- else if (top >= 6 && ratio >= 1.12)
249
- confidence = 'medium';
250
- else
251
- confidence = 'low';
252
- // D2: API 覆盖过低时,confidence 上限降为 low
253
- if (queryApiTokens.length > 0 && apiNameCoverage < 0.3) {
254
- confidence = 'low';
255
- }
256
- const status = confidence === 'low' ? 'low_confidence' : 'success';
257
- return { confidence, status };
258
- }
259
- function buildAnswerContract(status, confidence, opts) {
260
- const uncertaintyRule = status === 'low_confidence' || confidence === 'low'
261
- ? '当信息不足时必须显式写“待确认:”,只允许陈述缺口,不允许猜测补全。'
262
- : '除“待确认:”段落外,不得出现“可能/大概/应该/推测”等猜测措辞。';
263
- const riskRule = opts?.fabricationRisk
264
- ? 'fabrication_risk=true 时,若片段未覆盖该细节,必须输出“待确认:知识片段未覆盖此项”。'
265
- : '';
266
- return [
267
- '【输出模板(必须遵守)】',
268
- '使用“问题导向”标题组织答案,优先复用用户提问原句:一、<问题1> 二、<问题2> 三、<问题3> …',
269
- '每个小节先给直接结论,再补 1-2 句必要说明;避免模板化术语(如“依据/操作”字样)。',
270
- '信息缺口统一放在对应小节末尾,使用“待确认:xxx”;若全都确认则可省略“待确认”小节。',
271
- '末尾保留“参考文档”小节,仅列文档标题或 URL;正文不展示检索过程、证据链、打分细节。',
272
- '用户可见正文禁止出现系统检索话术(如“命中片段/检索结果/置信度/分数/召回/重排”)。',
273
- '硬约束:不得引入 fragments 未出现的 API 名、字段值、枚举项、事件名。',
274
- uncertaintyRule,
275
- riskRule,
276
- ].filter(Boolean).join(' ');
54
+ const primarySource = preferredSource ?? fragments[0]?.source;
55
+ const primaryCompleteness = primarySource
56
+ ? files.find((file) => file.source === primarySource)?.completeness ?? 0
57
+ : 0;
58
+ return {
59
+ files,
60
+ allow_pending_confirm: primaryCompleteness < 0.9,
61
+ primary_source: primarySource,
62
+ primary_completeness: primaryCompleteness,
63
+ retry_suggested: primaryCompleteness < 0.6,
64
+ };
277
65
  }
278
- function buildAgentMessage(status, fragments, confidence, _references, opts) {
279
- const platformRule = '端别硬规则:字段/API 描述前先标注【端别: framework】;禁止“部分版本也称 xxx”这类跨端混写;字段大小写必须与目标端文档一致;多端片段同时命中时主答案仅讲目标端,其他端差异放末尾简述;无片段覆盖的细节禁止补全。';
280
- const riskRule = opts?.fabricationRisk ? '当前检索存在幻觉风险(fabrication_risk=true):禁止补全未命中 API 细节。' : '';
281
- const answerContract = buildAnswerContract(status, confidence, opts);
282
- const tail = `${platformRule} ${riskRule} ${answerContract} Final answer drafted -> MUST call \`finalize_answer\` before replying. Explicit follow-up feedback -> call \`submit_feedback\`.`;
283
- if (status === 'needs_framework') {
284
- return '【硬规则】问题依赖具体平台实现,但未指定 frameworks,全平台混检信息密度低且被禁止。MUST 先调用 `present_framework_choice`(传入 product),等用户选定 web/miniprogram/android/ios/flutter/react/vue/uni-app 等后再调用本工具,并 MUST 带上 **product + frameworks**。禁止传空 frameworks 硬搜。';
285
- }
286
- const { urlMapping, localDoc, urlMappingKinds } = partitionFragments(fragments);
287
- const hasUrlMapping = urlMapping.length > 0;
288
- const hasLocalDoc = localDoc.length > 0;
289
- const hasBestPractice = hasBestPracticeFragment(fragments);
290
- const urlKindLabel = urlMappingKinds.join(' / ') || 'urls';
291
- if (status === 'success' && fragments.length > 0) {
292
- const topFragment = fragments[0];
293
- if (topFragment?.capability_status === 'unsupported') {
294
- const scopeLabel = topFragment.scope ? `(${topFragment.scope})` : '';
295
- return `当前问题在该平台 / 形态下 **不支持**${scopeLabel}。回答 MUST:① 第一段先明确写“**不支持**”;② 说明这是当前平台 Core 的能力边界,而不是缺少示例代码;③ 仅提供当前平台已支持的替代方案(如对应平台 preset 预制 UI);若当前知识库未给出明确替代形态,应直接说明暂无可执行替代路径;④ **禁止**输出当前平台 Core 的 API 调用步骤或集成步骤。${tail}`;
296
- }
297
- if (hasUrlMapping && !hasLocalDoc) {
298
- return `当前可用信息主要是文档入口链接(${urlKindLabel})。请先匹配用户问题对应的目标 URL,抓取官网文档后再合成答案;禁止仅复述映射表或臆造 API/错误码细节。${tail}`;
299
- }
300
- if (hasUrlMapping && hasLocalDoc) {
301
- if (hasBestPractice) {
302
- return `优先基于已命中的 best-practice 与本地片段直接作答;URL 映射仅作补充参考,不要再抓官网做二次求证。${tail}`;
303
- }
304
- return `本地文档片段可直接用于作答;若本地片段未覆盖关键细节,再从 URL 映射中提取目标 URL 抓取官网文档补齐。${tail}`;
305
- }
306
- return `请仅基于已返回 fragments 合成答案;不要并行 web_search 或额外抓取官网文档。${tail}`;
307
- }
308
- if (status === 'low_confidence') {
309
- if (hasUrlMapping) {
310
- if (hasBestPractice) {
311
- return `优先基于 best-practice 与本地片段给出可执行结论;未覆盖的内容统一写入“待确认”,不要默认抓官网二次求证。${tail}`;
312
- }
313
- return `请先从 URL 映射里提取目标 URL 并抓取官网文档补齐关键信息,再给出答案;仍无法确认的内容明确写“待确认”。${tail}`;
314
- }
315
- return `请基于已有 fragments 给出最可执行答案,并将未覆盖细节明确写为“待确认”;可引导用户补充组件名/API 名/错误码后重新检索。不要默认并行 web_search。${tail}`;
316
- }
317
- return `知识库未命中有效片段。请向用户说明并确认 product/framework 是否准确;若仍无 platform 信息且问题依赖具体客户端,应先 \`present_framework_choice\`。${tail}`;
66
+ /** 轻量覆盖度:仅算主文件完整度,用于非收敛场景的 allow_pending_confirm 判定,不产出逐文件明细 */
67
+ function computePrimaryCompleteness(allChunks, fragments, preferredSource) {
68
+ if (!fragments.length)
69
+ return { primary_completeness: 0 };
70
+ const primarySource = preferredSource ?? fragments[0]?.source;
71
+ if (!primarySource)
72
+ return { primary_completeness: 0 };
73
+ const hitChunkIds = new Set(fragments.map((f) => f.chunk_id));
74
+ const sourceChunks = allChunks.filter((chunk) => chunk.source === primarySource);
75
+ const fileToken = sourceChunks.reduce((sum, chunk) => sum + Math.max(0, chunk.char_end - chunk.char_start), 0);
76
+ const hitToken = sourceChunks
77
+ .filter((chunk) => hitChunkIds.has(chunk.id))
78
+ .reduce((sum, chunk) => sum + Math.max(0, chunk.char_end - chunk.char_start), 0);
79
+ return {
80
+ primary_source: primarySource,
81
+ primary_completeness: fileToken > 0 ? Number((hitToken / fileToken).toFixed(2)) : 0,
82
+ };
318
83
  }
319
84
  export function searchKnowledge(params) {
320
85
  const norm = normalizeParams(params);
86
+ const retrievalMode = classifyRetrievalMode(norm.prompt);
321
87
  if (requiresFramework(norm)) {
322
88
  const manifest = loadManifest();
323
89
  return {
324
90
  status: 'needs_framework',
325
91
  confidence: 'none',
326
- message: buildAgentMessage('needs_framework', [], 'none', undefined),
92
+ message: buildAgentMessage('needs_framework', retrievalMode, [], 'none', undefined),
327
93
  query: params,
94
+ retrieval_mode: retrievalMode,
95
+ documents: [],
96
+ catalog: [],
328
97
  meta: {
329
98
  pool_size: manifest.chunks.length,
330
99
  filtered_size: 0,
@@ -336,66 +105,63 @@ export function searchKnowledge(params) {
336
105
  const manifest = loadManifest();
337
106
  const allChunks = manifest.chunks;
338
107
  const queryApiTokens = inferQueryApiTokens(norm.prompt);
339
- const runSearchPass = (passNorm, opts) => {
340
- let pool = filterPool(allChunks, passNorm);
341
- // types 误传自愈:首轮保留,二次扩检也同样保留该能力
342
- if (pool.length === 0 && passNorm.types?.length) {
343
- pool = filterPool(allChunks, { ...passNorm, types: undefined });
344
- }
345
- const { boosts, exactHits, urlRowHitChunkIds } = runExactLookup(passNorm.prompt, pool, passNorm);
346
- // A2 补充正向路由:UserSig 问法下允许 share 命中且优先于无关 urls 噪声
347
- if (/usersig|sdkappid|secretkey|鉴权|签名|gentestusersig/i.test(passNorm.prompt)) {
348
- for (const chunk of pool) {
349
- if (chunk.product === '*' && chunk.source.includes('knowledge/share/userSig.md')) {
350
- boosts[chunk.id] = (boosts[chunk.id] ?? 0) + 220;
351
- }
108
+ let pass = runSearchPass({
109
+ allChunks,
110
+ passNorm: norm,
111
+ retrievalMode,
112
+ queryApiTokens,
113
+ });
114
+ // best-practice 懒补充:仅在主 pass 无本地片段(仅 URL 映射行或完全为空)时触发。
115
+ // 典型场景:Agent 传 types=['sdk'],filterPool 把 best-practice(type=faq)硬过滤掉,
116
+ // 只剩 URL 映射行(有 E7 boost 但内容只是一个 URL 链接)。
117
+ // 不侵入 runSearchPass 层,避免每次调用都执行重复检索。
118
+ const passRetryReasons = [];
119
+ const hasLocalContent = pass.fragments.some((f) => !f.source.includes('/urls/'));
120
+ if (!hasLocalContent && norm.product?.length && !norm.types?.includes('faq')) {
121
+ const primaryProduct = norm.product[0];
122
+ const bpCandidates = allChunks.filter((chunk) => {
123
+ if (!/\/best-practice\//i.test(chunk.source))
124
+ return false;
125
+ if (chunk.product !== primaryProduct && chunk.product !== '*')
126
+ return false;
127
+ if (norm.frameworks?.length) {
128
+ const explicitMatch = hasExplicitFrameworkMatch(chunk.framework, norm.frameworks);
129
+ const wildcardAllowed = chunk.framework.includes('*');
130
+ if (!explicitMatch && !wildcardAllowed)
131
+ return false;
352
132
  }
353
- }
354
- // B2: API 覆盖不足扩检时,对 api/integration 语料做轻量重排提权
355
- if (opts?.apiRetry) {
356
- for (const chunk of pool) {
357
- if (chunk.types.includes('api') || chunk.types.includes('integration')) {
358
- boosts[chunk.id] = (boosts[chunk.id] ?? 0) + 40;
133
+ return true;
134
+ });
135
+ if (bpCandidates.length > 0) {
136
+ const bpIndex = getProductsBM25Index(allChunks, [norm.product[0]]);
137
+ const bpRanked = rankSubsetWithIndex(norm.prompt, bpCandidates.map((c) => c.id), bpIndex, {});
138
+ if ((bpRanked[0]?.score ?? 0) >= 6) {
139
+ const bpPass = runSearchPass({
140
+ allChunks,
141
+ passNorm: { ...norm, types: undefined },
142
+ retrievalMode,
143
+ queryApiTokens,
144
+ });
145
+ if (bpPass.fragments.length > 0) {
146
+ pass = bpPass;
147
+ passRetryReasons.push('best_practice_supplement');
359
148
  }
360
149
  }
361
150
  }
362
- const productIndex = getProductsBM25Index(allChunks, passNorm.product);
363
- const poolWithContent = attachPoolContent(pool);
364
- const chunksById = new Map(poolWithContent.map((chunk) => [chunk.id, chunk]));
365
- const ranked = rankSubsetWithIndex(passNorm.prompt, pool.map((chunk) => chunk.id), productIndex, boosts);
366
- const rankedWithMultipliers = applyRankMultipliers(ranked, chunksById, {
367
- product: passNorm.product,
368
- framework: passNorm.framework,
369
- frameworks: passNorm.frameworks,
370
- });
371
- const pinnedUrlRowChunkIds = new Set(urlRowHitChunkIds);
372
- const fragments = postProcess(rankedWithMultipliers, chunksById, passNorm.limit, {
373
- pinnedUrlRowChunkIds,
374
- });
375
- const urlMappingSources = [...new Set(fragments.map((f) => f.source).filter((source) => isUrlMappingSource(source)))];
376
- const references = buildReferences(fragments);
377
- const apiNameCoverage = computeApiNameCoverage(queryApiTokens, poolWithContent);
378
- const missingApiTokens = computeMissingApiTokens(queryApiTokens, poolWithContent);
379
- return {
380
- pool,
381
- fragments,
382
- exactHits,
383
- urlMappingSources,
384
- references,
385
- apiNameCoverage,
386
- missingApiTokens,
387
- urlMapRelaxed: pinnedUrlRowChunkIds.size > 0,
388
- urlMapExactHitCount: pinnedUrlRowChunkIds.size,
389
- };
390
- };
391
- let pass = runSearchPass(norm);
392
- const retryReasons = [];
151
+ }
152
+ const retryReasons = [...passRetryReasons];
393
153
  // B2: API token 覆盖不足时触发一次扩检(去掉 types 约束 + api/integration 轻提权)
394
154
  const missingRatio = queryApiTokens.length > 0
395
155
  ? Number((pass.missingApiTokens.length / queryApiTokens.length).toFixed(2))
396
156
  : 0;
397
157
  if (queryApiTokens.length > 0 && (pass.apiNameCoverage === 0 || missingRatio >= 0.3)) {
398
- const retryPass = runSearchPass({ ...norm, types: undefined }, { apiRetry: true });
158
+ const retryPass = runSearchPass({
159
+ allChunks,
160
+ passNorm: { ...norm, types: undefined },
161
+ retrievalMode,
162
+ queryApiTokens,
163
+ opts: { apiRetry: true },
164
+ });
399
165
  const retryMissingRatio = queryApiTokens.length > 0
400
166
  ? Number((retryPass.missingApiTokens.length / queryApiTokens.length).toFixed(2))
401
167
  : 0;
@@ -406,10 +172,15 @@ export function searchKnowledge(params) {
406
172
  retryReasons.push(`api_gap_retry:coverage=${pass.apiNameCoverage},missing_ratio=${retryMissingRatio}`);
407
173
  }
408
174
  }
409
- // B3: Mixed “integration + product-scope” questions should include product docs, not just feature/integration.
175
+ // B3: 混合“集成 + 产品开通/计费/控制台”问法时,补充 product type,避免仅搜 integration/feature。
410
176
  if (norm.types?.length && !norm.types.includes('product') && hasProductScopeIntent(norm.prompt)) {
411
177
  const widenedTypes = [...new Set([...norm.types, 'product'])];
412
- const retryPass = runSearchPass({ ...norm, types: widenedTypes });
178
+ const retryPass = runSearchPass({
179
+ allChunks,
180
+ passNorm: { ...norm, types: widenedTypes },
181
+ retrievalMode,
182
+ queryApiTokens,
183
+ });
413
184
  const baseHasProduct = pass.fragments.some((f) => f.types.includes('product'));
414
185
  const retryHasProduct = retryPass.fragments.some((f) => f.types.includes('product'));
415
186
  if ((retryHasProduct && !baseHasProduct)
@@ -419,7 +190,7 @@ export function searchKnowledge(params) {
419
190
  retryReasons.push('product_scope_retry:types+=product');
420
191
  }
421
192
  }
422
- // B4: If query looks like Native TRTC APIs but routed to live/room/call, auto-append native_trtc_sdk and retry.
193
+ // B4: 若疑似 Native TRTC API 问法却路由到 live/room/call,自动补扩 native_trtc_sdk 产品重检。
423
194
  const shouldRetryNativeProduct = hasNativeClientFramework(norm.frameworks)
424
195
  && hasNativeTrtcApiSignal(norm.prompt, queryApiTokens)
425
196
  && norm.product?.some((p) => ['live', 'room', 'call'].includes(p))
@@ -428,7 +199,13 @@ export function searchKnowledge(params) {
428
199
  && pass.apiNameCoverage < 0.5;
429
200
  if (shouldRetryNativeProduct) {
430
201
  const expandedProducts = [...new Set([...(norm.product ?? []), 'native_trtc_sdk'])];
431
- const retryPass = runSearchPass({ ...norm, product: expandedProducts, types: undefined }, { apiRetry: true });
202
+ const retryPass = runSearchPass({
203
+ allChunks,
204
+ passNorm: { ...norm, product: expandedProducts, types: undefined },
205
+ retrievalMode,
206
+ queryApiTokens,
207
+ opts: { apiRetry: true },
208
+ });
432
209
  const retryMissingRatio = queryApiTokens.length > 0
433
210
  ? Number((retryPass.missingApiTokens.length / queryApiTokens.length).toFixed(2))
434
211
  : 0;
@@ -440,6 +217,85 @@ export function searchKnowledge(params) {
440
217
  retryReasons.push(`native_product_retry:products=${expandedProducts.join('+')},coverage=${retryPass.apiNameCoverage}`);
441
218
  }
442
219
  }
220
+ const resolveNarrativeState = (passSnapshot) => {
221
+ const source = retrievalMode === 'narrative'
222
+ ? pickNarrativeSource(passSnapshot.exactHits, passSnapshot.rankedWithMultipliers, passSnapshot.poolWithContent)
223
+ : null;
224
+ const document = source ? buildNarrativeDocument(source, allChunks) : null;
225
+ const quality = assessNarrativeCompleteness(document, norm.prompt);
226
+ return { source, document, quality };
227
+ };
228
+ let narrativeState = resolveNarrativeState(pass);
229
+ // P0: narrative 自动扩检(一次)——当“完整流程”候选文档缺失或完整度不足时,放宽 types 并提高 limit。
230
+ const shouldRetryNarrative = retrievalMode === 'narrative'
231
+ && (narrativeState.document === null || !narrativeState.quality.isComplete);
232
+ if (shouldRetryNarrative) {
233
+ const narrativeRetryNorm = {
234
+ ...norm,
235
+ types: undefined,
236
+ limit: Math.max(norm.limit ?? 8, 12),
237
+ };
238
+ const retryPass = runSearchPass({
239
+ allChunks,
240
+ passNorm: narrativeRetryNorm,
241
+ retrievalMode,
242
+ queryApiTokens,
243
+ opts: { apiRetry: true },
244
+ });
245
+ const retryNarrativeState = resolveNarrativeState(retryPass);
246
+ if (retryNarrativeState.quality.score > narrativeState.quality.score
247
+ || (narrativeState.document === null && retryNarrativeState.document !== null)
248
+ || (retryPass.exactHits.length > pass.exactHits.length && retryNarrativeState.document !== null)) {
249
+ pass = retryPass;
250
+ narrativeState = retryNarrativeState;
251
+ retryReasons.push(`narrative_retry:score=${retryNarrativeState.quality.score}`);
252
+ }
253
+ }
254
+ // 覆盖度深检(全量 files 明细 + 自动扩检)仅在收敛到单一 best-practice 时启用,
255
+ // 避免对普通点查场景做无差别二次检索与全量 coverage_report 外发。
256
+ const shouldDeepCoverageCheck = Boolean(pass.preferredSource || pass.fullDocumentMode) && pass.fragments.length > 0;
257
+ let coverageReport;
258
+ if (shouldDeepCoverageCheck) {
259
+ coverageReport = buildCoverageReport(allChunks, pass.fragments, pass.preferredSource);
260
+ if (coverageReport.retry_suggested) {
261
+ const coverageRetryPass = runSearchPass({
262
+ allChunks,
263
+ passNorm: { ...norm, types: undefined, limit: Math.max(norm.limit ?? 8, 12) },
264
+ retrievalMode,
265
+ queryApiTokens,
266
+ opts: { apiRetry: true },
267
+ });
268
+ const retriedCoverageReport = buildCoverageReport(allChunks, coverageRetryPass.fragments, coverageRetryPass.preferredSource);
269
+ const currentCoverage = coverageReport.primary_completeness ?? 0;
270
+ const retriedCoverage = retriedCoverageReport.primary_completeness ?? 0;
271
+ if (retriedCoverage > currentCoverage || coverageRetryPass.fragments.length > pass.fragments.length) {
272
+ pass = coverageRetryPass;
273
+ coverageReport = retriedCoverageReport;
274
+ retryReasons.push(`coverage_check_retry:primary=${retriedCoverage}`);
275
+ }
276
+ }
277
+ // 单 chunk 文档 completeness 恒为 1,不代表问题被完整覆盖;
278
+ // 仅在 fullDocumentMode 聚合多 chunk(>1)且覆盖度足够时才禁止“待确认”。
279
+ const primaryChunkCount = coverageReport.primary_source
280
+ ? allChunks.filter((chunk) => chunk.source === coverageReport.primary_source).length
281
+ : 0;
282
+ coverageReport = {
283
+ ...coverageReport,
284
+ allow_pending_confirm: !(pass.fullDocumentMode
285
+ && primaryChunkCount > 1
286
+ && (coverageReport.primary_completeness ?? 0) >= 0.9),
287
+ };
288
+ }
289
+ else {
290
+ const primary = computePrimaryCompleteness(allChunks, pass.fragments, pass.preferredSource);
291
+ coverageReport = {
292
+ allow_pending_confirm: true,
293
+ ...(primary.primary_source ? { primary_source: primary.primary_source } : {}),
294
+ primary_completeness: primary.primary_completeness,
295
+ retry_suggested: false,
296
+ };
297
+ }
298
+ narrativeState = resolveNarrativeState(pass);
443
299
  const retryReason = retryReasons.length ? retryReasons.join(';') : undefined;
444
300
  const routeInconsistencyWarning = pass.fragments.length > 0
445
301
  ? pass.fragments.filter((f) => f.product === '*').length / pass.fragments.length > 0.3
@@ -447,26 +303,73 @@ export function searchKnowledge(params) {
447
303
  const { confidence, status } = assessConfidence(pass.fragments, pass.exactHits, pass.apiNameCoverage, queryApiTokens);
448
304
  const fabricationRisk = (queryApiTokens.length > 0 && pass.apiNameCoverage < 0.3)
449
305
  || (confidence === 'low' && pass.fragments.length < 2);
306
+ // point 模式不再返回 documents:fullDocumentMode 下 fragments 已按 char_start 顺序返回完整章节,
307
+ // 再回 documents 会造成同一篇内容重复外发。
308
+ const documents = retrievalMode === 'narrative'
309
+ ? (narrativeState.document ? [narrativeState.document] : [])
310
+ : [];
311
+ const catalog = retrievalMode === 'discovery'
312
+ ? buildDiscoveryCatalog(pass.rankedWithMultipliers, pass.poolWithContent, norm.limit)
313
+ : [];
314
+ let finalStatus = status;
315
+ let finalConfidence = confidence;
316
+ if (retrievalMode === 'narrative' && documents.length > 0) {
317
+ if (narrativeState.quality.isComplete) {
318
+ finalStatus = 'success';
319
+ finalConfidence = 'high';
320
+ }
321
+ else {
322
+ finalStatus = 'low_confidence';
323
+ finalConfidence = 'low';
324
+ }
325
+ }
326
+ if (retrievalMode === 'discovery' && catalog.length > 0) {
327
+ finalStatus = 'success';
328
+ finalConfidence = finalConfidence === 'none' ? 'medium' : finalConfidence;
329
+ }
450
330
  const topScore = pass.fragments[0]?.score;
451
331
  const secondScore = pass.fragments[1]?.score;
452
- const answerContract = buildAnswerContract(status, confidence, { fabricationRisk });
332
+ const aggregatedFragments = pass.fragments
333
+ .filter((fragment) => fragment.aggregated || fragment.citation?.includes('[aggregated]'))
334
+ .map((fragment) => ({
335
+ chunk_id: fragment.chunk_id,
336
+ source: fragment.source,
337
+ citation: fragment.citation ?? `[来源: ${fragment.chunk_id}][aggregated]`,
338
+ }));
339
+ const fullDocumentRequired = retrievalMode === 'narrative'
340
+ && /完整的?\s*(接入|集成|教程|指南|流程)|完整\s*md|全文|原文|不要总结|含\s*(示例)?代码|全部步骤|完整步骤/i.test(norm.prompt);
341
+ const answerContract = buildAnswerContract(finalStatus, finalConfidence, retrievalMode, {
342
+ fabricationRisk,
343
+ fullDocumentRequired,
344
+ hasAggregatedFragments: aggregatedFragments.length > 0,
345
+ });
453
346
  const hasProductScope = hasProductScopeIntent(norm.prompt);
454
347
  const hasNativeSignal = hasNativeTrtcApiSignal(norm.prompt, queryApiTokens);
455
- const hasProductContent = pass.fragments.some((f) => f.types.includes('product') || /\/product\.md$/i.test(f.source));
348
+ const hasProductContent = pass.fragments.some((f) => f.types.includes('product') || /\/product\.md$/i.test(f.source) || /\/best-practice\//i.test(f.source));
456
349
  const hasIntegrationContent = pass.fragments.some((f) => f.types.includes('integration') || /\/integration\.md$/i.test(f.source) || /\/preset\//i.test(f.source));
457
350
  const hasApiQueryTokens = queryApiTokens.length > 0;
458
- const apiGapDetected = hasApiQueryTokens && (pass.apiNameCoverage === 0 || missingRatio >= 0.3);
351
+ const finalMissingRatio = hasApiQueryTokens
352
+ ? Number((pass.missingApiTokens.length / queryApiTokens.length).toFixed(2))
353
+ : 0;
354
+ const apiGapDetected = hasApiQueryTokens && (pass.apiNameCoverage === 0 || finalMissingRatio >= 0.3);
459
355
  const retryApiGapApplied = retryReasons.some((r) => r.startsWith('api_gap_retry:'));
460
356
  const retryProductScopeApplied = retryReasons.includes('product_scope_retry:types+=product');
461
357
  const retryNativeProductApplied = retryReasons.some((r) => r.startsWith('native_product_retry:'));
462
- const convergenceReached = status === 'success'
463
- && (confidence === 'high' || confidence === 'medium')
464
- && (!hasApiQueryTokens || pass.apiNameCoverage >= 0.5)
465
- && (!hasProductScope || hasProductContent || hasIntegrationContent);
358
+ const narrativeConverged = retrievalMode !== 'narrative'
359
+ || (documents.length > 0 && narrativeState.quality.isComplete);
360
+ const convergenceReached = (retrievalMode === 'narrative' && narrativeConverged)
361
+ || (retrievalMode === 'discovery' && catalog.length > 0)
362
+ || (finalStatus === 'success'
363
+ && (finalConfidence === 'high' || finalConfidence === 'medium')
364
+ && (!hasApiQueryTokens || pass.apiNameCoverage >= 0.5)
365
+ && (!hasProductScope || hasProductContent || hasIntegrationContent));
466
366
  const retryAdvice = (() => {
467
- if (status === 'needs_framework') {
367
+ if (finalStatus === 'needs_framework') {
468
368
  return { stop_retry: true, next_action: 'ask_framework', reason: 'missing_framework' };
469
369
  }
370
+ if (retrievalMode === 'narrative' && !narrativeConverged) {
371
+ return { stop_retry: false, next_action: 'retry_or_clarify', reason: 'narrative_incomplete' };
372
+ }
470
373
  if (convergenceReached) {
471
374
  return { stop_retry: true, next_action: 'answer', reason: 'converged' };
472
375
  }
@@ -479,16 +382,26 @@ export function searchKnowledge(params) {
479
382
  if (hasNativeSignal && hasNativeClientFramework(norm.frameworks) && !retryNativeProductApplied) {
480
383
  return { stop_retry: false, next_action: 'retry_add_native_trtc_sdk', reason: 'possible_native_product_misroute' };
481
384
  }
482
- if (status === 'empty' || confidence === 'low') {
385
+ if (finalStatus === 'empty' || finalConfidence === 'low') {
483
386
  return { stop_retry: false, next_action: 'retry_or_clarify', reason: 'insufficient_retrieval_signal' };
484
387
  }
485
388
  return { stop_retry: true, next_action: 'answer', reason: 'default_stop' };
486
389
  })();
487
390
  return {
488
- status,
489
- confidence,
490
- message: buildAgentMessage(status, pass.fragments, confidence, pass.references, { fabricationRisk }),
391
+ status: finalStatus,
392
+ confidence: finalConfidence,
393
+ message: buildAgentMessage(finalStatus, retrievalMode, pass.fragments, finalConfidence, pass.references, {
394
+ fabricationRisk,
395
+ hasDocuments: documents.length > 0,
396
+ hasCatalog: catalog.length > 0,
397
+ fullDocumentRequired,
398
+ preferDocuments: pass.fullDocumentMode,
399
+ hasAggregatedFragments: aggregatedFragments.length > 0,
400
+ }),
491
401
  query: params,
402
+ retrieval_mode: retrievalMode,
403
+ documents,
404
+ catalog,
492
405
  meta: {
493
406
  pool_size: allChunks.length,
494
407
  filtered_size: pass.pool.length,
@@ -502,6 +415,22 @@ export function searchKnowledge(params) {
502
415
  ...(queryApiTokens.length ? { query_api_tokens: queryApiTokens } : {}),
503
416
  ...(pass.missingApiTokens.length ? { missing_api_tokens: pass.missingApiTokens } : {}),
504
417
  ...(retryReason ? { retry_reason: retryReason } : {}),
418
+ ...(retrievalMode === 'narrative' && narrativeState.source ? { narrative_source: narrativeState.source } : {}),
419
+ ...(pass.preferredSource ? { preferred_source: pass.preferredSource } : {}),
420
+ ...(pass.fullDocumentMode ? { full_document_mode: pass.fullDocumentMode } : {}),
421
+ coverage_report: coverageReport,
422
+ ...(aggregatedFragments.length ? { aggregated_fragments: aggregatedFragments } : {}),
423
+ ...(retrievalMode === 'narrative'
424
+ ? {
425
+ narrative_completeness: {
426
+ is_complete: narrativeState.quality.isComplete,
427
+ score: narrativeState.quality.score,
428
+ section_count: narrativeState.quality.sectionCount,
429
+ total_chars: narrativeState.quality.totalChars,
430
+ reason: narrativeState.quality.reason,
431
+ },
432
+ }
433
+ : {}),
505
434
  answer_contract: answerContract,
506
435
  api_name_coverage: pass.apiNameCoverage,
507
436
  fabrication_risk: fabricationRisk,