@tbox.cn/app-module-shopping-guide 0.2.1 → 0.8.3

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 (85) hide show
  1. package/AGENTS.md +16 -0
  2. package/README.md +96 -0
  3. package/dist/chunk-AYQZO2FV.js +1496 -0
  4. package/dist/chunk-VKDA6RXQ.js +1676 -0
  5. package/dist/client/index.d.ts +3 -3
  6. package/dist/client/index.js +1 -1
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +2 -8
  9. package/dist/server/index.d.ts +2512 -608
  10. package/dist/server/index.js +1 -7
  11. package/dist/shopping-guide-EGRHPEDA.css +2598 -0
  12. package/package.json +25 -16
  13. package/skills/shopping-guide/SKILL.md +127 -24
  14. package/src/client/cards/category-list/index.tsx +113 -0
  15. package/src/client/cards/human-guide-list/index.tsx +72 -0
  16. package/src/client/cards/index.ts +14 -0
  17. package/src/client/cards/location-handoff/index.tsx +52 -0
  18. package/src/client/cards/mall-directory/index.tsx +77 -0
  19. package/src/client/cards/nearby-mall-list/index.tsx +40 -0
  20. package/src/client/cards/product-comparison/index.tsx +100 -0
  21. package/src/client/cards/product-detail/index.tsx +97 -0
  22. package/src/client/cards/product-list/index.tsx +223 -0
  23. package/src/client/cards/recommend-merchants/index.tsx +147 -0
  24. package/src/client/cards/shop-detail/index.tsx +133 -0
  25. package/src/client/cards/shop-list/index.tsx +216 -0
  26. package/src/client/cards/view.ts +147 -0
  27. package/src/client/categories.ts +38 -0
  28. package/src/client/components/ImageWithFallback.tsx +34 -0
  29. package/src/client/components/MerchantRow.tsx +78 -0
  30. package/src/client/components/ShopDetailSheet.tsx +383 -0
  31. package/src/client/components/ShopGuideHeader.tsx +23 -0
  32. package/src/client/components/ShopGuideSectionLabel.tsx +10 -0
  33. package/src/client/components/ShopListSheet.tsx +293 -0
  34. package/src/client/index.ts +8 -6
  35. package/src/client/styles/shopping-guide.css +2598 -0
  36. package/src/client/types/css.d.ts +2 -0
  37. package/src/server/cards/category-list/meta.ts +0 -2
  38. package/src/server/cards/human-guide-list/meta.ts +0 -2
  39. package/src/server/cards/index.ts +10 -10
  40. package/src/server/cards/location-handoff/meta.ts +0 -2
  41. package/src/server/cards/mall-directory/meta.ts +0 -2
  42. package/src/server/cards/nearby-mall-list/meta.ts +1 -3
  43. package/src/server/cards/product-comparison/meta.ts +0 -2
  44. package/src/server/cards/product-detail/meta.ts +0 -2
  45. package/src/server/cards/product-list/meta.ts +0 -2
  46. package/src/server/cards/recommend-merchants/meta.ts +37 -0
  47. package/src/server/cards/recommend-merchants/samples.ts +189 -0
  48. package/src/server/cards/{merchant-detail → shop-detail}/meta.ts +6 -6
  49. package/src/server/cards/shop-detail/samples.ts +72 -0
  50. package/src/server/cards/{merchant-list → shop-list}/meta.ts +9 -9
  51. package/src/server/cards/shop-list/samples.ts +154 -0
  52. package/src/server/domain/value-objects.ts +1 -2
  53. package/src/server/handler.ts +63 -0
  54. package/src/server/index.ts +161 -101
  55. package/src/server/ports/index.ts +120 -91
  56. package/src/server/ports/local-adapters.ts +5 -55
  57. package/src/server/projections/index.ts +159 -41
  58. package/src/server/tools/index.ts +590 -315
  59. package/tbox.module.json +137 -0
  60. package/tests/cards-render.test.tsx +830 -0
  61. package/tests/floor-pretool.test.ts +275 -0
  62. package/tests/handler.test.ts +259 -0
  63. package/tests/merchant-list-limit.test.ts +53 -0
  64. package/tests/ports-resolve.test.ts +112 -0
  65. package/tests/samples.test.ts +71 -0
  66. package/tests/shopping-guide.test.ts +402 -234
  67. package/tests/skill.test.ts +86 -0
  68. package/tests/view.test.ts +42 -0
  69. package/tsup.config.ts +9 -1
  70. package/dist/chunk-AGBLC6XI.js +0 -1294
  71. package/dist/chunk-U4WDS5PQ.js +0 -173
  72. package/skills/shopping-guide/references/comparison-format.md +0 -5
  73. package/skills/shopping-guide/references/faq-answers.md +0 -5
  74. package/skills/shopping-guide/references/floor-directory.md +0 -4
  75. package/skills/shopping-guide/references/intent-patterns.md +0 -5
  76. package/skills/shopping-guide/references/location-format.md +0 -5
  77. package/skills/shopping-guide/references/policy-lookup.md +0 -5
  78. package/skills/shopping-guide/references/product-search-tips.md +0 -6
  79. package/skills/shopping-guide/references/recommendation-style.md +0 -5
  80. package/src/client/cards/index.tsx +0 -267
  81. package/src/server/cards/customer-service-faq/meta.ts +0 -18
  82. package/src/server/integrations/joycity/adapter.ts +0 -226
  83. package/src/server/integrations/joycity/auth-strategy.ts +0 -38
  84. package/src/server/integrations/joycity/gateway.ts +0 -128
  85. package/tbox.component.json +0 -48
@@ -1,51 +1,44 @@
1
1
  /**
2
2
  * 导购 15 工具(011 K5:D11 字符串化 inputSchema——仅 string / map<string,string>)。
3
3
  * 全部经 createTool;coerceStringifiedFields 首行转换(JSON 字符串化数值/数组还原)。
4
- * 输出 = 卡数据(allowedTools 绑定出卡)或 text 汇总(search-knowledge)。
4
+ * 出卡见文件头注释(v2 出参 cards 契约);product-facets 返回分面原始数据、search-knowledge 返回 text 汇总。
5
5
  */
6
- import { createTool, coerceStringifiedFields } from '@tbox.cn/app-sdk/server';
6
+ import { createTool, coerceStringifiedFields, requireToolRequestContext, withCardEmissionHint, internalTool } from '@tbox.cn/app-sdk/server';
7
7
  import { z } from 'zod';
8
- import type { ServerContext } from '@tbox.cn/app-sdk/server';
8
+ import type { ServerContext, ToolExecContextLike } from '@tbox.cn/app-sdk/server';
9
+ import { mallSubjectIdOf } from '@tbox.cn/app-contracts-mall';
9
10
  import type {
10
- MallRequestContext,
11
- ProductListCardData,
12
- ProductComparisonCardData,
11
+ CommercialCategoryQueryPort,
12
+ ShoppingPage,
13
13
  ShoppingQueryContext,
14
+ ShopRecord,
14
15
  } from '@tbox.cn/app-contracts-mall';
15
- import { parseMallScope } from '@tbox.cn/app-contracts-mall';
16
- import { toShoppingQueryContext } from '../domain/value-objects';
16
+ import type { MallOverviewSnapshot, ShopListCardData } from '@tbox.cn/app-contracts-mall';
17
+ import type { RequestContext } from '@tbox.cn/app-contracts';
18
+ import { toShoppingQueryContext, scopeFromMallId } from '../domain/value-objects';
17
19
  import { resolveShoppingGuidePorts, type ShoppingGuidePorts } from '../ports';
18
- import {
19
- projectCategoryList,
20
- projectCustomerServiceFaq,
21
- projectHumanGuideList,
22
- projectKnowledge,
23
- projectLocationHandoff,
24
- projectMallDirectory,
25
- projectMerchantDetail,
26
- projectMerchantList,
27
- projectNearbyMalls,
28
- projectProductComparison,
29
- projectProductDetail,
30
- projectProductList,
31
- } from '../projections';
20
+ import { projectShopDetail, projectShopList } from '../projections';
32
21
 
33
22
  export type ShoppingGuideToolIds =
34
- | 'recommend'
35
- | 'search-products'
36
- | 'product-facets'
37
- | 'get-product'
38
- | 'compare-products'
39
- | 'search-merchants'
40
- | 'get-merchant'
41
- | 'mall-directory'
42
- | 'get-location'
43
- | 'list-human-guides'
44
- | 'list-browsing-history'
45
- | 'list-nearby-malls'
46
- | 'list-categories'
47
- | 'search-knowledge'
48
- | 'customer-service-faq';
23
+ // | 'recommend' // 知识库未接入,暂停
24
+ // | 'search-products' // provider 暂无商品目录接口,暂停
25
+ // | 'product-facets' // provider 暂无商品分面接口,暂停
26
+ // | 'get-product' // provider 暂无商品详情接口,暂停
27
+ // | 'compare-products' // provider 暂无商品接口,暂停
28
+ | 'search-shops'
29
+ | 'get-shop'
30
+ // | 'get-location' // provider 暂无导航接口,暂停
31
+ // | 'list-human-guides' // provider 暂无导购员接口,暂停
32
+ // | 'list-browsing-history' // provider 暂无浏览历史接口,暂停
33
+ // | 'list-nearby-malls' // 周边商场暂不涉及,暂停
34
+ // | 'list-categories' // 2026-09-02 下线:业态/楼层浏览统一 shop-list(类目 Tab),上下文数据走 mall-context preTool
35
+ // | 'mall-directory' // 2026-09-02 下线:楼层分布经 mall-context reminder 正文回答,楼层门店走 floor-shops
36
+ | 'mall-context'
37
+ | 'floor-shops'
38
+ | 'category-shops'
39
+ | 'mall-overview';
40
+ // | 'search-knowledge' // 知识库未接入,暂停
41
+ // | 'customer-service-faq' // 客服承接已拆分至 module-customer-service(2026-08-31)
49
42
 
50
43
  const str = (desc: string) => z.string().describe(desc);
51
44
  const optionalStr = (desc: string) => z.string().optional().describe(desc);
@@ -55,351 +48,633 @@ function coerce<T extends z.ZodTypeAny>(schema: T): T {
55
48
  return z.preprocess(coerceStringifiedFields, schema) as unknown as T;
56
49
  }
57
50
 
58
- function toContext(ctx: ServerContext) {
59
- const requestContext = ctx.auth.getContext();
60
- // 011 I8 修复:显式防护——非对话窗口调用工具时给出结构化错误(模型可降级回答)
61
- if (!requestContext) {
62
- throw new Error('运行上下文未绑定(工具需在对话 run 窗口内调用)');
63
- }
64
- const subjectId =
65
- (requestContext.identity?.source === 'local' || requestContext.identity?.source === 'external')
66
- ? requestContext.identity.userId
67
- : undefined;
68
- return toShoppingQueryContext(requestContext, subjectId);
51
+ /** 上下文统一化:显式入参 reqCtx(工具 execute 第二参解析;require 已在上游完成)。
52
+ * 导出供 handler 复用(身份 → subjectId 归一经 mallSubjectIdOf 单源——
53
+ * 0.8.0 起 dev 身份与 local/external 同为登录主体,prod 零差异 dev 强制关断) */
54
+ export function toContext(reqCtx: RequestContext) {
55
+ return toShoppingQueryContext(reqCtx, mallSubjectIdOf(reqCtx));
69
56
  }
70
57
 
71
58
  /**
72
59
  * 宽松上下文:FAQ/知识库工具不依赖 mall scope——无 mall 时以空 scope 兜底(knowledge 不查 mall)。
73
60
  * 011 评审 6.1:scope 解析经 TIER1 parseMallScope(不手解 attributes 原始形状)。
74
61
  */
75
- function toLooseContext(ctx: ServerContext) {
76
- const requestContext = ctx.auth.getContext();
77
- if (!requestContext) {
78
- throw new Error('运行上下文未绑定(工具需在对话 run 窗口内调用)');
79
- }
80
- const scope = parseMallScope(requestContext.attributes) ?? { miniAppId: '', mallId: '' };
81
- return {
82
- scope,
83
- requestContext: requestContext as unknown as MallRequestContext,
84
- } as ShoppingQueryContext;
62
+
63
+ /** execute 第二参 → reqCtx(require 变体:缺失即 fail-visible 报错) */
64
+ function reqCtxOf(execCtx: ToolExecContextLike): RequestContext {
65
+ return requireToolRequestContext(execCtx);
66
+ }
67
+
68
+ /** B3:mallId 入参权威覆盖的查询上下文(args.mallId 由 preTool decide 注入;缺省回落 scope 解析)。
69
+ * 不变量(T3):args.mallId 权威——decide 侧 mallSlot.read 解析的 mallId 经入参传入,
70
+ * 「去重键由入参决定」由此成立(mallId 变更 → 键变更 → 自动重新执行);miniAppId 仍取 execCtx scope。 */
71
+ function contextWithMallId(reqCtx: RequestContext, mallId: unknown): ShoppingQueryContext {
72
+ const base = toContext(reqCtx);
73
+ const override = typeof mallId === 'string' && mallId.trim() ? mallId.trim() : undefined;
74
+ if (!override || override === base.scope.mallId) return base;
75
+ return { ...base, scope: scopeFromMallId(reqCtx, override) };
85
76
  }
86
77
 
87
78
  // D11:纯字符串字段不做 coerce(coerce 会把 "1" 还原成 number 反破坏 string 期望);
88
79
  // 仅结构字段(keywords/productIds 数组)走 coerce(LLM 可能传 JSON 编码字符串)。
89
80
  const pageFields = {
90
81
  page: z.string().optional().describe('页码(从 1 开始,字符串)'),
91
- pageSize: z.string().optional().describe('每页条数(字符串,缺省 10)'),
82
+ pageSize: z.string().optional().describe('每页条数(字符串,缺省 200)'),
92
83
  };
93
84
 
94
85
  function parsePage(page?: string, pageSize?: string): { page: number; pageSize: number } {
95
86
  const p = Math.max(1, Number(page) || 1);
96
- const s = Math.min(50, Math.max(1, Number(pageSize) || 10));
87
+ const s = Math.min(200, Math.max(1, Number(pageSize) || 200));
97
88
  return { page: p, pageSize: s };
98
89
  }
99
90
 
91
+ /** keywords 扇出并发预算(与 provider 层 FANOUT_MAX 约定同源;工具层统一截断——所有 provider 一致收敛,模型 ≤max(5) 不硬拒) */
92
+ const KEYWORD_FANOUT_MAX = 3;
93
+
94
+ /** 出卡出参组装(v2 契约,模式 B):summary 透传完整 JSON 数据 + cards 声明(data = 投影卡数据)。
95
+ * W7(2026-09-01):note 参数复活(原 _note 死参数完全丢弃 note → 全部回退 displayName 静态值)——
96
+ * note 是模型可见唯一卡片内容摘要,按契约传「主体+关键事实」。 */
97
+ function withCards<T extends Record<string, unknown>>(
98
+ data: T,
99
+ cardType: string,
100
+ note: string,
101
+ summary: string,
102
+ ): { summary: string; cards: unknown[] } {
103
+ return { summary, cards: [{ cardType, data, note }] };
104
+ }
105
+
106
+ /**
107
+ * shop-list 出卡 note(模型可见唯一卡片摘要,search-shops 与 floor-shops 共用单源):
108
+ * 店名(楼层)主体前置(至多 3 个——W7,模型凭 descriptor 区分同型候选、答话与卡内容对齐)+
109
+ * 计数恒由 total 派生(密度截断后 items.length 只是可见面,不是全量事实——
110
+ * 截断发生时以尾缀显式声明,对齐 merchant-list-limit 测试头注释「头部句由 pageInfo.total 派生」)。
111
+ * 120 字符预算由 SDK buildNote 统一截断,此处只组装内容。
112
+ */
113
+ export function shopListNote(data: ShopListCardData, total?: number): string {
114
+ const visible = data.items.length;
115
+ const all = total ?? visible;
116
+ const heads = data.items
117
+ .slice(0, 3)
118
+ .map((m) => (m.location.floorName ? `${m.name}(${m.location.floorName})` : m.name));
119
+ if (heads.length === 0) return `${all} 家门店`;
120
+ const countTail =
121
+ all > visible
122
+ ? `(共 ${all} 家门店,当前展示前 ${visible} 家)`
123
+ : visible > 3
124
+ ? ` 等 ${visible} 家门店`
125
+ : '';
126
+ return heads.join('、') + countTail;
127
+ }
128
+
129
+ /** 中文数字(楼层语境 1-10;更高楼层由阿拉伯数字形态覆盖) */
130
+ const CN_FLOOR_NUM: Record<string, number> = {
131
+ 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9, 十: 10,
132
+ };
133
+
134
+ /**
135
+ * 楼层引用归一键(跨 provider 格式归一):
136
+ * '2 楼'/'2F'/'第2层'/'二楼' → '2';'B1'/'b1 楼'/'负一楼'/'负1楼' → 'B1'。
137
+ * 无法解析 → undefined。
138
+ */
139
+ export function normalizeFloorKey(text: string): string | undefined {
140
+ const t = text.trim().toUpperCase().replace(/\s+/g, '');
141
+ if (!t) return undefined;
142
+ const neg = t.match(/^(?:B|负)(\d+)(?:楼|层|F)?$/);
143
+ if (neg) return `B${Number(neg[1])}`;
144
+ const negCn = t.match(/^负([一二三四五六七八九十])楼?$/);
145
+ if (negCn) return `B${CN_FLOOR_NUM[negCn[1]]}`;
146
+ const pos = t.match(/^(?:第)?(\d+)(?:楼|层|F)?$/);
147
+ if (pos) return `${Number(pos[1])}`;
148
+ const posCn = t.match(/^(?:第)?([一二三四五六七八九十])(?:楼|层)?$/);
149
+ if (posCn) return `${CN_FLOOR_NUM[posCn[1]]}`;
150
+ return undefined;
151
+ }
152
+
153
+ /** 楼层引用正则(export 供 preTool decide 剥离楼层引用用) */
154
+ export const FLOOR_MENTION_RE =
155
+ /B\s*\d+\s*(?:楼|层)?|负\s*[一二三四五六七八九十\d]+\s*(?:楼|层)?|第\s*[一二三四五六七八九十\d]+\s*[楼层]|[一二三四五六七八九十\d]+\s*(?:楼|层|F\b)/g;
156
+
157
+ export function extractFloorMentions(text: string): string[] {
158
+ const seen = new Set<string>();
159
+ const out: string[] = [];
160
+ for (const m of text.matchAll(FLOOR_MENTION_RE)) {
161
+ const raw = m[0].trim();
162
+ const key = normalizeFloorKey(raw);
163
+ if (key && !seen.has(key)) {
164
+ seen.add(key);
165
+ out.push(raw);
166
+ }
167
+ }
168
+ return out.slice(0, 3);
169
+ }
170
+
171
+ /**
172
+ * 类目词族(用户语言侧粗筛——preTool decide 门控用,跨商场稳定通用业态词)。
173
+ * 类目 code 真源 = provider listTags/listCategories(mall-context 注入同源);
174
+ * 归一对齐在 category-shops execute 侧数据驱动(词表漏新词 → 归一失败 → 无卡
175
+ * error summary → 模型经 reminder 自行降级调 search-shops,失败语义闭环)。
176
+ */
177
+ export const CATEGORY_WORDS = [
178
+ '购物', '餐饮', '美食', '生活', '娱乐', '儿童', '亲子', '服饰', '服装',
179
+ '运动', '美妆', '珠宝', '超市', '影院', '健身', '零售', '休闲',
180
+ ] as const;
181
+
182
+ /** 类目提及抽取(整句 → 命中词去重、截前 3;镜像 extractFloorMentions 形态) */
183
+ export function extractCategoryMentions(text: string): string[] {
184
+ const seen = new Set<string>();
185
+ const out: string[] = [];
186
+ for (const w of CATEGORY_WORDS) {
187
+ if (text.includes(w) && !seen.has(w)) {
188
+ seen.add(w);
189
+ out.push(w);
190
+ }
191
+ }
192
+ return out.slice(0, 3);
193
+ }
194
+
195
+ /** 类目同义词(词表词 → 常见规范类目名候选序;零子串关系词对的归一桥接,
196
+ * 候选缺席时自动落回原词子串双向——不做 provider 假设) */
197
+ const CATEGORY_SYNONYMS: Readonly<Record<string, readonly string[]>> = {
198
+ 美食: ['餐饮'],
199
+ 亲子: ['儿童'],
200
+ 服饰: ['服装'],
201
+ 零售: ['购物'],
202
+ 休闲: ['娱乐'],
203
+ };
204
+
205
+ /** summary 构建器:卡片数据 JSON 透传(LLM 依据 SKILL.md 提示词润色回复,summary 仅承载事实数据)。
206
+ * shopList 精简版:只含总数 + 每个门店的关键信息(名称/位置/类目/营业状态/优惠/电话),
207
+ * 不含 logo/cover/actions 等前端展示字段——减少模型上下文占用(200 条全量 card data 约 80KB+,精简版约 20KB)。 */
208
+ const summaries = {
209
+ shopList: (d: import('@tbox.cn/app-contracts-mall').ShopListCardData, allItems?: readonly ShopRecord[]): string => {
210
+ return JSON.stringify({
211
+ total: d.pageInfo?.total ?? d.items.length,
212
+ context: d.context,
213
+ ...(d.summary ? { summary: d.summary } : {}),
214
+ shops: (allItems ?? []).map((s) => ({
215
+ name: s.name,
216
+ ...(s.brand ? { brand: s.brand } : {}),
217
+ location: s.location?.displayText ?? s.location?.unitName,
218
+ categories: s.businessCategories,
219
+ ...(s.status?.label ? { status: s.status.label } : {}),
220
+ ...(s.promotionFacts?.length ? { promotions: s.promotionFacts } : {}),
221
+ ...(s.services?.length ? { services: s.services } : {}),
222
+ ...(s.description ? { description: s.description } : {}),
223
+ ...(s.contactInfo?.length ? { phone: s.contactInfo.map((c) => c.value).join(', ') } : {}),
224
+ ...(s.coupons?.length ? { coupons: s.coupons.map((c) => ({ name: c.name, ...(c.faceValue !== undefined ? { faceValue: c.faceValue } : {}), ...(c.salePrice !== undefined ? { salePrice: c.salePrice } : {}) })) } : {}),
225
+ })),
226
+ });
227
+ },
228
+ shopDetail: (d: import('@tbox.cn/app-contracts-mall').ShopDetailCardData): string => JSON.stringify(d),
229
+ };
230
+ /**
231
+ * 门店列表卡共享投影(search-shops 工具与品牌导览 intent handler 单源):
232
+ * projectShopList + 无过滤浏览态类目 Tab 聚合(Tab 与卡片可见门店值域严格一致)。
233
+ * 空结果语义归调用方(工具:summary 无卡;handler:固定文案无卡)。
234
+ * maxItems 缺省 G1 密度上限 200(单页 pageSize 顶格,投影层不二次截断——前端预览 3 条 +
235
+ * 浮层展示全量);零 LLM intent 通道(品牌导览 handler 卡数据直发前端不经模型)显式传全量。
236
+ */
237
+ export function buildShopListCard(
238
+ result: ShoppingPage<ShopRecord>,
239
+ q: ShoppingQueryContext,
240
+ noFilter: boolean,
241
+ maxItems?: number,
242
+ ): ShopListCardData {
243
+ const data = projectShopList(
244
+ 'search',
245
+ result,
246
+ result.items.length === 0 ? '未找到匹配的门店。' : undefined,
247
+ undefined,
248
+ q.scope.mallId || undefined,
249
+ q.scope.miniAppId || undefined,
250
+ maxItems,
251
+ );
252
+ if (noFilter && data.items.length > 0) {
253
+ const tabs = [...new Set(data.items.flatMap((m) => m.businessCategories))]
254
+ .filter((name) => name && !name.includes('测试') && !name.includes('erp') && !name.includes('未归类'))
255
+ .slice(0, 6)
256
+ .map((name) => ({ code: name, name }));
257
+ if (tabs.length > 0) data.categoryTabs = tabs;
258
+ }
259
+ return data;
260
+ }
261
+
100
262
  export function createShoppingGuideTools(opts: {
101
263
  /** 注册期绑定的 ServerContext 读取器(模块顶层单例持有;execute 内获取) */
102
264
  getCtx: () => ServerContext;
103
265
  }) {
104
- const portsOf = (): Promise<ShoppingGuidePorts> =>
105
- resolveShoppingGuidePorts(opts.getCtx());
266
+ /** 工具 execute 第二参 → 请求级 ports(require 变体 fail-visible) */
267
+ const portsOf = (execCtx: ToolExecContextLike): Promise<ShoppingGuidePorts> => {
268
+ const ctx = opts.getCtx();
269
+ return resolveShoppingGuidePorts(requireToolRequestContext(execCtx), ctx);
270
+ };
106
271
 
107
272
  const exec = <T>(
108
- fn: (ports: ShoppingGuidePorts, ctx: ServerContext, args: Record<string, unknown>) => Promise<T>,
273
+ fn: (
274
+ ports: ShoppingGuidePorts,
275
+ ctx: ServerContext,
276
+ args: Record<string, unknown>,
277
+ execCtx: ToolExecContextLike,
278
+ ) => Promise<T>,
109
279
  ) => {
110
- return async (args: Record<string, unknown>) => {
280
+ return async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
111
281
  const ctx = opts.getCtx();
112
- return fn(await portsOf(), ctx, args);
282
+ try {
283
+ return await fn(await portsOf(execCtx), ctx, args, execCtx);
284
+ } catch (err) {
285
+ const message = err instanceof Error ? err.message : String(err);
286
+ console.warn(`[shopping-guide] tool exec error: ${message}`);
287
+ return { found: false, message: '暂时无法查询,请稍后再试' } as unknown as T;
288
+ }
113
289
  };
114
290
  };
115
291
 
116
- const recommend = createTool({
117
- id: 'recommend',
292
+ // recommend:知识库未接入,暂停注册
293
+ // searchProducts:provider 暂无商品目录接口,暂停注册
294
+ // productFacets:provider 暂无商品分面接口,暂停注册
295
+ // getProduct:provider 暂无商品详情接口,暂停注册
296
+ // compareProducts:provider 暂无商品接口,暂停注册
297
+
298
+ const searchShops = createTool({
299
+ id: 'search-shops',
118
300
  description:
119
- '智能推荐:从权威商品数据中挑选最符合用户需求的结果。输出 product-list(context=recommendation)。' +
120
- '商户推荐请用 search-merchants。',
301
+ '门店搜索/列表:按品牌词、类目、楼层、楼栋搜索或浏览门店。输出 shop-list(卡片自带类目 Tab)。\n' +
302
+ '【零参数 = 探索性全量浏览】以下意图必须不传任何参数直接调用本工具:\n' +
303
+ ' "逛什么" / "有什么好逛的" / "随便逛逛" / "今天想逛逛" / "商场有什么" / "有哪些门店" / "有什么可逛的" / "帮我找找门店" / "看看有什么"\n' +
304
+ ' → 返回全量门店列表,卡片自带类目 Tab,用户可在卡片上自行筛选,无需先列类目再追问。\n' +
305
+ '结果已含门店名、品类、楼栋/楼层/铺位、营业状态、促销信息,无需再调 get-shop 补位置。\n' +
306
+ '【参数填充规则】businessCategory/floorCode/buildingCode 的合法值来自 mall-context 注入块(本轮或会话内历史轮均有效——楼栋/楼层/类目编码会话内不变):\n' +
307
+ ' - businessCategory = categories[].code(类目编码)\n' +
308
+ ' - floorCode = floors[].id(楼层 ID)\n' +
309
+ ' - buildingCode = blocks[].id(楼栋 ID)\n' +
310
+ '【路由逻辑】有品牌/店名关键词 → 填 keywords;纯按类目/楼层筛 → 只填对应编码;楼层+类目组合(如"3楼有餐饮吗")→ 同时填 floorCode + businessCategory,一次调用拿到该楼层指定类目门店。\n' +
311
+ '【检索引导】首次搜索:只填 keywords(行业通称并列同义词,如 ["美妆","彩妆"] 或 ["甜品","蛋糕"];' +
312
+ '品牌名必须中英文/别名并列多角度——["肯德基","KFC"]、["星巴克","Starbucks"]、["麦当劳","金拱门"],' +
313
+ '高频连锁品牌店名常只署英文名,只传中文名会漏召回),不要同时填 businessCategory——首次只用关键词搜。' +
314
+ '零结果后禁止再换同义词重试,按以下顺序降级(每次只用一个参数,不要混填):' +
315
+ '①将用户意图映射到 mall-context 类目编码(如"买鞋/买衣服"→ categories[].code "购物","吃饭/火锅/甜品"→ "餐饮"),仅传 businessCategory 重查(不加 keywords,让该类目下门店全量返回);' +
316
+ '②仍无结果改用无参数全量浏览(卡片自带类目 Tab 供用户自行筛选)。' +
317
+ '同一查询最多调用本工具 2 次(首次 + 1 次降级),禁止反复试参。',
318
+ // W2(2026-09-01):机制句(标签语法/出卡规则)归平台段单源——此处由 wrap 追加预告知句,删除【出卡规则】整段
121
319
  inputSchema: z.object({
122
- query: str('用户购物需求的自然语言描述'),
320
+ keywords: z.preprocess(
321
+ // LLM 有时输出裸字符串(如 "美妆")而非数组,统一包成数组再走 coerce
322
+ (val) => {
323
+ if (typeof val === 'string') {
324
+ try { return JSON.parse(val); } catch { return [val]; }
325
+ }
326
+ return val;
327
+ },
328
+ coerce(
329
+ // F5a:max 提至 10(模型偶尔列 4-5 个相关词,max(5) 会硬拒触发校验重试浪费整轮;
330
+ // describe 明写「最多 3 个超出取前 3」+ execute 软截 KEYWORD_FANOUT_MAX=3——接受面与硬限对齐)
331
+ z.array(z.string()).min(1).max(10)
332
+ .describe(
333
+ '品牌名/店名/业态关键词数组,最多 3 个(超出仅取前 3),如 ["美妆","彩妆"] 或 ["儿童服装","咖啡"]。' +
334
+ '【合并规则】用户一条请求提到的多个品类/品牌/店名并入同一次调用——结果合并为一张卡并自带品类 Tab;' +
335
+ '仅当不同诉求需要不同的楼层/楼栋/类目筛选时才拆分调用。' +
336
+ '【重要】必须是合法 JSON 字符串数组,每个元素加双引号,禁止写裸字符串(如 美妆)。' +
337
+ '纯按类目/楼层浏览时不填此字段。',
338
+ )
339
+ .optional(),
340
+ ).optional(),
341
+ ),
342
+ businessCategory: optionalStr('类目编码(来自 pre-tool 上下文 categories[].code);按类目浏览时填写'),
343
+ floorCode: optionalStr('楼层 ID(来自 pre-tool 上下文 floors[].id);按楼层筛选时填写'),
344
+ buildingCode: optionalStr('楼栋 ID(来自 pre-tool 上下文 blocks[].id);按楼栋筛选时填写'),
345
+ ...pageFields,
123
346
  }),
124
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
125
- const q = toContext(ctx);
126
- // 011 I6 修复:推荐 = 语义搜索的退化实现(joycity 无推荐 API),query 必须传给 keyword
347
+ execute: exec(async (ports, _ctx, args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
348
+ const q = toContext(reqCtxOf(execCtx));
349
+ const { page, pageSize } = parsePage(args.page as string, args.pageSize as string);
350
+ const rawKeywords = args.keywords as string[] | undefined;
351
+ // 软截断:超量词取前 KEYWORD_FANOUT_MAX 个(模型认知 ≤5 词即可,硬拒弱模型不偿失;describe 已明写截断行为)
352
+ const keywords = (rawKeywords ?? []).slice(0, KEYWORD_FANOUT_MAX);
353
+ if ((rawKeywords?.length ?? 0) > KEYWORD_FANOUT_MAX) {
354
+ console.warn(`[search-shops] keywords 超量(${rawKeywords!.length}),截断至前 ${KEYWORD_FANOUT_MAX}:丢弃 ${JSON.stringify(rawKeywords!.slice(KEYWORD_FANOUT_MAX))}`);
355
+ }
356
+ const hasFilter = keywords.length || args.businessCategory || args.floorCode || args.buildingCode;
127
357
  const criteria = {
128
358
  ctx: q,
129
- keyword: String(args.query ?? ''),
130
- page: 1,
131
- pageSize: 10,
132
- marketableOnly: true,
359
+ // keywords 数组为唯一真源(provider 逐词扇出/单值直通;不再 join 拼串——
360
+ // 厂商单值模糊匹配下拼串必不命中,契约注释已封堵)
361
+ keywords,
362
+ ...(args.businessCategory ? { businessCategory: String(args.businessCategory) } : {}),
363
+ ...(args.floorCode ? { floorCode: String(args.floorCode) } : {}),
364
+ ...(args.buildingCode ? { buildingCode: String(args.buildingCode) } : {}),
365
+ page,
366
+ pageSize,
133
367
  };
134
- const products = await ports.catalog.searchProducts(criteria);
135
- return projectProductList('recommendation', products) as ProductListCardData;
368
+ console.warn(`[search-shops] input keywords=${JSON.stringify(criteria.keywords)} businessCategory=${args.businessCategory ?? ''} floorCode=${args.floorCode ?? ''} buildingCode=${args.buildingCode ?? ''} page=${page}`);
369
+ const result = await ports.shop.searchShops(criteria);
370
+ console.warn(`[search-shops] output total=${result.total} items=${result.items.length} first=${result.items[0]?.name ?? '(empty)'}`);
371
+ const data = buildShopListCard(result, q, !hasFilter);
372
+ if (data.items.length === 0) return { summary: summaries.shopList(data) }; // 空结果不出卡
373
+ return withCards(data, 'shop-list', shopListNote(data, result.total), summaries.shopList(data, result.items));
136
374
  }),
137
375
  });
138
376
 
139
- const searchProducts = createTool({
140
- id: 'search-products',
377
+ const getShop = createTool({
378
+ id: 'get-shop',
141
379
  description:
142
- '商品搜索:按关键词/价格/品类搜索商品列表。输出 product-list(context=search)。',
143
- inputSchema: z.object({
144
- keywords: coerce(z.array(z.string()).min(1).max(5).describe('全部搜索角度,如 ["跑鞋","运动鞋"]')),
145
- minPriceMinor: optionalStr('最低价格(分,字符串)'),
146
- maxPriceMinor: optionalStr('最高价格(分,字符串)'),
147
- categoryCode: optionalStr('品类编码'),
148
- brandCode: optionalStr('品牌编码'),
149
- ...pageFields,
150
- }),
151
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
152
- const q = toContext(ctx);
153
- const { page, pageSize } = parsePage(args.page as string, args.pageSize as string);
154
- const result = await ports.catalog.searchProducts({
155
- ctx: q,
156
- keyword: (args.keywords as string[])?.join(' ') ?? '',
157
- keywords: args.keywords as string[],
158
- ...(args.minPriceMinor ? { minPriceMinor: Number(args.minPriceMinor) } : {}),
159
- ...(args.maxPriceMinor ? { maxPriceMinor: Number(args.maxPriceMinor) } : {}),
160
- ...(args.categoryCode ? { categoryCode: String(args.categoryCode) } : {}),
161
- ...(args.brandCode ? { brandCode: String(args.brandCode) } : {}),
162
- page,
163
- pageSize,
164
- marketableOnly: true,
165
- });
166
- return projectProductList(
167
- 'search',
168
- result,
169
- undefined,
170
- result.items.length === 0 ? '未找到匹配的商品,可尝试放宽关键词或换品类。' : undefined,
380
+ '门店详情:加载单个门店的完整快照(图片/简介/联系方式)。仅当用户点击门店卡片要看详情时调用。输出 shop-detail。',
381
+ inputSchema: z.object({ shopId: str('门店 ID(来自搜索结果卡)') }),
382
+ execute: exec(async (ports, _ctx, args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
383
+ console.warn(`[get-shop] input shopId="${args.shopId}"`);
384
+ const shop = await ports.shop.getShop(String(args.shopId), toContext(reqCtxOf(execCtx)));
385
+ console.warn(`[get-shop] output found=${!!shop} name="${shop?.name ?? ''}"`);
386
+ if (!shop) {
387
+ return { summary: JSON.stringify({ error: 'not_found' }) }; // 无 cards:不出卡
388
+ }
389
+ const shopCtx = toContext(reqCtxOf(execCtx));
390
+ const data = projectShopDetail(shop, shopCtx.scope.mallId || undefined, shopCtx.scope.miniAppId || undefined);
391
+ return withCards(
392
+ data,
393
+ 'shop-detail',
394
+ `${data.name}(${(data as { location?: { displayText?: string } }).location?.displayText ?? '门店详情'})`,
395
+ summaries.shopDetail(data),
171
396
  );
172
397
  }),
173
398
  });
174
399
 
175
- const productFacets = createTool({
176
- id: 'product-facets',
177
- description: '商品分面:查询当前品类/关键词下可用的筛选项(价格区间、品牌、品类树)。',
178
- inputSchema: z.object({
179
- keyword: optionalStr('关键词'),
180
- minPriceMinor: optionalStr('最低价格(分,字符串)'),
181
- maxPriceMinor: optionalStr('最高价格(分,字符串)'),
182
- }),
183
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
184
- const q = toContext(ctx);
185
- const facets = await ports.catalog.getFacets({
186
- ctx: q,
187
- ...(args.keyword ? { keyword: String(args.keyword) } : {}),
188
- ...(args.minPriceMinor ? { minPriceMinor: Number(args.minPriceMinor) } : {}),
189
- ...(args.maxPriceMinor ? { maxPriceMinor: Number(args.maxPriceMinor) } : {}),
190
- page: 1,
191
- pageSize: 10,
192
- });
193
- return facets;
194
- }),
195
- });
400
+ // mallDirectory:2026-09-02 下线(楼层分布经 mall-context reminder 正文回答,楼层门店走 floor-shops → shop-list)
401
+ // getLocation:provider 暂无导航接口,暂停注册
402
+ // listHumanGuides:provider 暂无导购员接口,暂停注册
403
+ // listBrowsingHistory:provider 暂无浏览历史接口,暂停注册
404
+ // listNearbyMalls:周边商场暂不涉及,暂停注册
196
405
 
197
- const getProduct = createTool({
198
- id: 'get-product',
199
- description: '商品详情:加载单个商品的完整快照(价格/库存/属性/商户归属)。输出 product-detail。',
200
- inputSchema: z.object({ productId: str('商品 ID(来自搜索结果卡)') }),
201
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
202
- const product = await ports.catalog.getProduct(String(args.productId), toContext(ctx));
203
- if (!product) {
204
- return { error: '未找到该商品,可能已下架。' };
205
- }
206
- return projectProductDetail(product);
207
- }),
208
- });
406
+ // listCategories:2026-09-02 下线(业态问句 = search-shops 零参出 shop-list 卡,类目 Tab 即业态清单;
407
+ // 类目/楼层数据面由 mall-context preTool 每轮 reminder 提供)
408
+ /**
409
+ * 商场上下文工具(mall-context pre-tool 专用):预加载楼栋+类目信息。
410
+ * 不由模型直接调用;由 mallContextPreTool 在每轮 silent 执行,结果注入 LLM 上下文。
411
+ * 模型可从 <system-reminder pre-tool="mall-context"> 数据块取到:
412
+ * - categories: [{code, name}] 类目列表(businessCategory 参数真源)
413
+ * - floors: [{id, name}] 楼层列表(floorCode 参数真源)
414
+ * - blocks: [{id, name}] 楼栋列表(buildingCode 参数真源)
415
+ */
416
+ const mallContext = createTool({
417
+ id: 'mall-context',
418
+ description: '【内部工具,模型勿调用】预加载商场楼栋+类目上下文,供 search-shops 参数填充。',
419
+ // B3:mallId 入参化——decide 自 mallSlot.read(attributes) 注入;去重键随 mallId 变更自动换键
420
+ inputSchema: z.object({ mallId: str('商圈 ID(pre-tool decide 注入)') }),
421
+ execute: exec(async (ports, _ctx, args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
422
+ const q = contextWithMallId(reqCtxOf(execCtx), args.mallId);
423
+ // brandTags 轻量预加载:adapter 有 listTags → 仅 1 次 API(不含 per-tag count);
424
+ // 无 → 降级 listCategories(含 count,6 次 API)
425
+ const categoryPort = ports.category as CommercialCategoryQueryPort & { listTags?: (ctx: ShoppingQueryContext) => Promise<readonly string[]> };
426
+ const [tagsResult, directory] = await Promise.allSettled([
427
+ categoryPort.listTags?.(q) ?? ports.category.listCategories(q).then((cs) => cs.map((c) => c.name)),
428
+ ports.directory.getDirectory(q),
429
+ ]);
430
+ const tagList = tagsResult.status === 'fulfilled' ? tagsResult.value : [];
431
+ const dir = directory.status === 'fulfilled' ? directory.value : null;
209
432
 
210
- const compareProducts = createTool({
211
- id: 'compare-products',
212
- description: '商品对比:并排对比 2-4 个商品的价格、属性、库存。输出 product-comparison。',
213
- inputSchema: z.object({
214
- productIds: coerce(z.array(z.string()).min(2).max(4).describe('待对比的商品 ID 数组')),
215
- }),
216
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
217
- const ids = (args.productIds as string[]).slice(0, 4);
218
- const q = toContext(ctx);
219
- const products = (await Promise.all(ids.map((id) => ports.catalog.getProduct(id, q)))).filter(
220
- (p): p is NonNullable<typeof p> => p !== null,
221
- );
222
- return projectProductComparison(products) as ProductComparisonCardData;
223
- }),
224
- });
433
+ const cats = tagList.map((name) => ({ code: name, name }));
434
+ const floors = dir?.buildings?.flatMap((b) =>
435
+ b.floors.map((f) => ({ id: f.floorCode ?? f.floorName, name: f.floorName, building: b.buildingName })),
436
+ ) ?? [];
437
+ const blocks = dir?.buildings?.map((b) => ({ id: b.buildingCode ?? b.buildingName, name: b.buildingName })) ?? [];
225
438
 
226
- const searchMerchants = createTool({
227
- id: 'search-merchants',
228
- description:
229
- '门店搜索:按关键词/楼层/品类搜索门店。结果已含门店名、品类、楼栋/楼层/铺位、营业状态、促销信息,' +
230
- '无需在同一轮再调 get-merchant 补位置。输出 merchant-list(context=search)。',
231
- inputSchema: z.object({
232
- keywords: coerce(z.array(z.string()).min(1).max(5).describe('多个搜索角度,如 ["酸奶","酸奶店"]')),
233
- businessCategory: optionalStr('业态分类编码;未知传 null/缺省'),
234
- floorCode: optionalStr('楼层编码;用户未指定时缺省'),
235
- buildingCode: optionalStr('楼栋编码;用户未指定时缺省'),
236
- ...pageFields,
237
- }),
238
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
239
- const q = toContext(ctx);
240
- const { page, pageSize } = parsePage(args.page as string, args.pageSize as string);
241
- const result = await ports.merchant.searchMerchants({
242
- ctx: q,
243
- keyword: (args.keywords as string[])?.join(' ') ?? '',
244
- keywords: args.keywords as string[],
245
- ...(args.businessCategory && args.businessCategory !== 'null' ? { businessCategory: String(args.businessCategory) } : {}),
246
- ...(args.floorCode && args.floorCode !== 'null' ? { floorCode: String(args.floorCode) } : {}),
247
- ...(args.buildingCode && args.buildingCode !== 'null' ? { buildingCode: String(args.buildingCode) } : {}),
248
- page,
249
- pageSize,
250
- });
251
- return projectMerchantList(
252
- 'search',
253
- result,
254
- result.items.length === 0 ? '未找到匹配的门店。' : undefined,
255
- );
439
+ console.warn(`[mall-context] preloaded categories=${cats.length} floors=${floors.length} blocks=${blocks.length}`);
440
+ return { categories: cats, floors, blocks };
256
441
  }),
257
442
  });
258
443
 
259
- const getMerchant = createTool({
260
- id: 'get-merchant',
261
- description:
262
- '门店详情:加载单个门店的完整快照(图片/简介/联系方式)。仅当用户点击门店卡片要看详情时调用。输出 merchant-detail。',
263
- inputSchema: z.object({ merchantId: str('门店 ID(来自搜索结果卡)') }),
264
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
265
- const merchant = await ports.merchant.getMerchant(String(args.merchantId), toContext(ctx));
266
- if (!merchant) {
267
- return { error: '未找到该门店。' };
268
- }
269
- return projectMerchantDetail(merchant);
270
- }),
271
- });
444
+ // searchKnowledge:知识库未接入,暂停注册
272
445
 
273
- const mallDirectory = createTool({
274
- id: 'mall-directory',
275
- description: '商场楼层目录:加载全商场楼栋-楼层结构(回答「几楼有什么」类问题)。输出 mall-directory。',
276
- inputSchema: z.object({}),
277
- execute: exec(async (ports, ctx, _args) => {
278
- const directory = await ports.directory.getDirectory(toContext(ctx));
446
+ /**
447
+ * 楼层问句确定性预执行工具(floor-shops pre-tool 专用):
448
+ * 不由模型直接调用;由 floorShopsPreTool 在楼层问句轮 silent 预执行。
449
+ * 楼层引用 → 目录归一解析(floorCode ?? floorName,与 mall-context 参数真源一致)
450
+ * → searchShops 端口按 floorCode 查询 → shop-list 出卡(capture 经 wrapped execute 入本轮候选池)。
451
+ * 解析/查询失败返回无卡 summary(模型经 reminder 自行降级调用 search-shops)。
452
+ */
453
+ const floorShops = createTool({
454
+ id: 'floor-shops',
455
+ description: '【内部工具,模型勿调用】楼层问句确定性预执行:按楼层引用预查门店,出 shop-list。',
456
+ inputSchema: z.object({ floorQuery: str('楼层引用文本(逗号分隔多楼层,如 "3楼,4楼")') }),
457
+ execute: exec(async (ports, _ctx, args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
458
+ const q = toContext(reqCtxOf(execCtx));
459
+ const floorQuery = String(args.floorQuery ?? '').trim();
460
+ if (!floorQuery) return { summary: JSON.stringify({ error: 'floor_query_empty' }) };
461
+ const directory = await ports.directory.getDirectory(q).catch(() => null);
279
462
  if (!directory) {
280
- return { error: '暂无商场目录数据。' };
463
+ return { summary: JSON.stringify({ error: 'directory_unavailable', floorQuery }) };
281
464
  }
282
- return projectMallDirectory(directory);
283
- }),
284
- });
285
-
286
- const getLocation = createTool({
287
- id: 'get-location',
288
- description:
289
- '位置导航:获取指定门店的位置信息及导航能力(仅在用户明确要求「导航/怎么走」时调用)。输出 location-handoff。',
290
- inputSchema: z.object({ merchantId: str('门店 ID') }),
291
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
292
- const merchant = await ports.merchant.getMerchant(String(args.merchantId), toContext(ctx));
293
- if (!merchant) {
294
- return { error: '未找到该门店。' };
465
+ const wantKeys = [
466
+ ...new Set(
467
+ floorQuery
468
+ .split(/[,,、/]/)
469
+ .map((s) => s.trim())
470
+ .filter(Boolean)
471
+ .map(normalizeFloorKey)
472
+ .filter((k): k is string => !!k),
473
+ ),
474
+ ];
475
+ if (wantKeys.length === 0) {
476
+ return { summary: JSON.stringify({ error: 'floor_query_unparsed', floorQuery }) };
295
477
  }
296
- return projectLocationHandoff(merchant);
297
- }),
298
- });
299
-
300
- const listHumanGuides = createTool({
301
- id: 'list-human-guides',
302
- description: '人工导购:列出指定门店的可联系导购员(仅在用户明确要求联系人工时调用)。输出 human-guide-list。',
303
- inputSchema: z.object({ merchantId: str('门店 ID') }),
304
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
305
- const merchant = await ports.merchant.getMerchant(String(args.merchantId), toContext(ctx));
306
- const guides = await ports.assistance.listHumanGuides(String(args.merchantId), toContext(ctx));
307
- return projectHumanGuideList(String(args.merchantId), merchant?.name ?? '门店', guides);
308
- }),
309
- });
310
-
311
- const listBrowsingHistory = createTool({
312
- id: 'list-browsing-history',
313
- description: '浏览历史:加载已登录用户的商品浏览记录。输出 product-list(context=history)。',
314
- inputSchema: z.object(pageFields),
315
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
316
- const { page, pageSize } = parsePage(args.page as string, args.pageSize as string);
317
- const result = await ports.navigation.listBrowsingHistory(toContext(ctx), page, pageSize);
318
- return projectProductList('history', result);
319
- }),
320
- });
321
-
322
- const listNearbyMalls = createTool({
323
- id: 'list-nearby-malls',
324
- description: '附近商场:查询附近可切换的大悦城门店列表。输出 nearby-mall-list。',
325
- inputSchema: z.object({ query: optionalStr('城市或位置提示;缺省使用默认位置') }),
326
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
327
- // 011 D10/评审 M4:feature 门控 = execute 内运行时护栏(navigation)
328
- if (!ctx.runtime.isFeatureEnabled('navigation')) {
329
- return { error: '导航功能未启用(部署未开启 navigation feature)' };
478
+ const resolved: { floorId: string; floorName: string; key: string }[] = [];
479
+ for (const b of directory.buildings ?? []) {
480
+ for (const f of b.floors ?? []) {
481
+ const floorId = f.floorCode ?? f.floorName;
482
+ const key = normalizeFloorKey(floorId) ?? normalizeFloorKey(f.floorName);
483
+ if (key && wantKeys.includes(key) && !resolved.some((r) => r.key === key)) {
484
+ resolved.push({ floorId, floorName: f.floorName, key });
485
+ }
486
+ }
330
487
  }
331
- const malls = await ports.navigation.listNearbyMalls(
332
- toContext(ctx),
333
- args.query ? String(args.query) : undefined,
488
+ if (resolved.length === 0) {
489
+ return { summary: JSON.stringify({ error: 'floor_not_found', floorQuery }) };
490
+ }
491
+ console.warn(`[floor-shops] input floorQuery="${floorQuery}" resolved=${resolved.map((r) => r.floorName).join('/')}`);
492
+ const results = await Promise.all(
493
+ resolved.map((r) =>
494
+ ports.shop.searchShops({
495
+ ctx: q,
496
+ keyword: '',
497
+ keywords: [],
498
+ floorCode: r.floorId,
499
+ page: 1,
500
+ pageSize: 200,
501
+ }),
502
+ ),
334
503
  );
335
- return projectNearbyMalls(malls, args.query ? String(args.query) : undefined);
336
- }),
337
- });
338
-
339
- const listCategories = createTool({
340
- id: 'list-categories',
341
- description:
342
- '商业品类目录:列出商场全部业态分类(餐饮/零售/娱乐等),回答「商场有哪些类型的店」类问题。输出 category-list。',
343
- inputSchema: z.object({}),
344
- execute: exec(async (ports, ctx, _args) => {
345
- return projectCategoryList(await ports.category.listCategories(toContext(ctx)));
504
+ const merged = {
505
+ items: results.flatMap((r) => r.items),
506
+ page: 1,
507
+ pageSize: 50,
508
+ total: results.reduce((s, r) => s + r.total, 0),
509
+ hasMore: results.some((r) => r.hasMore),
510
+ };
511
+ console.warn(`[floor-shops] output total=${merged.total} items=${merged.items.length}`);
512
+ const data = projectShopList(
513
+ 'search',
514
+ merged,
515
+ merged.items.length === 0 ? '该楼层暂无在营商户。' : undefined,
516
+ undefined,
517
+ q.scope.mallId || undefined,
518
+ q.scope.miniAppId || undefined,
519
+ );
520
+ if (data.items.length === 0) return { summary: JSON.stringify({ floors: resolved.map((r) => r.floorName), total: 0 }) };
521
+ return withCards(data, 'shop-list', shopListNote(data, merged.total), summaries.shopList(data, merged.items));
346
522
  }),
347
523
  });
348
524
 
349
- const searchKnowledge = createTool({
350
- id: 'search-knowledge',
351
- description:
352
- '知识库检索:语义搜索商场设施/政策/选购指南等稳定知识内容(不用于价格/库存/实时信息)。输出文本汇总。',
353
- inputSchema: z.object({
354
- query: str('检索查询文本'),
355
- topK: optionalStr('返回条数(字符串,1-5,缺省 3)'),
356
- }),
357
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
358
- const topK = Math.min(5, Math.max(1, Number(args.topK) || 3));
359
- const result = await ports.assistance.searchKnowledge(toLooseContext(ctx), String(args.query), topK);
360
- return projectKnowledge(result);
525
+ /**
526
+ * 类目问句确定性预执行工具(category-shops preTool 专用):不由模型直接调用。
527
+ * 类目词归一(对照本轮真实类目:精确 code/name 相等 → 子串双向,每词取首个匹配)
528
+ * → searchShops(businessCategory) → 多类目合并 shop-list 出卡(capture 入本轮候选池)。
529
+ * 归一/类目源失败返回无卡 summary(模型经 reminder 自行降级调 search-shops,
530
+ * 合法 code 来自 mall-context 注入)。
531
+ */
532
+ const categoryShops = createTool({
533
+ id: 'category-shops',
534
+ description: '【内部工具,模型勿调用】类目问句确定性预执行:类目词归一 → 该类目门店列表 → shop-list。',
535
+ inputSchema: z.object({ categoryQuery: str('类目词(逗号分隔多类目,如 "购物,餐饮")') }),
536
+ execute: exec(async (ports, _ctx, args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
537
+ const q = toContext(reqCtxOf(execCtx));
538
+ const categoryQuery = String(args.categoryQuery ?? '').trim();
539
+ if (!categoryQuery) return { summary: JSON.stringify({ error: 'category_query_empty' }) };
540
+ // 归一数据真源:listTags 优先(缺席/失败降级 listCategories,与 mall-context 同口径;
541
+ // 注意 ?.() 链式短路——显量控制流,防整链 undefined)
542
+ const categoryPort = ports.category as CommercialCategoryQueryPort & {
543
+ listTags?: (ctx: ShoppingQueryContext) => Promise<readonly string[]>;
544
+ };
545
+ let cats: { code: string; name: string }[] = [];
546
+ try {
547
+ const tags = await categoryPort.listTags?.(q);
548
+ if (tags && tags.length > 0) {
549
+ cats = tags.map((name) => ({ code: name, name }));
550
+ }
551
+ } catch { /* 降级 listCategories */ }
552
+ if (cats.length === 0) {
553
+ try {
554
+ cats = (await ports.category.listCategories(q)).map((c) => ({ code: c.code ?? c.name, name: c.name }));
555
+ } catch { /* 空表 → categories_unavailable */ }
556
+ }
557
+ if (cats.length === 0) return { summary: JSON.stringify({ error: 'categories_unavailable', categoryQuery }) };
558
+ const words = [...new Set(
559
+ categoryQuery
560
+ .split(/[,,、/]/)
561
+ .map((s) => s.trim())
562
+ .filter(Boolean),
563
+ )];
564
+ const matched: { code: string; name: string }[] = [];
565
+ for (const w of words) {
566
+ // 归一序:精确相等 → 同义词精确 → 子串双向;每词取首个匹配(同义词桥接「美食→餐饮」类零子串关系词对)
567
+ const candidates = [w, ...(CATEGORY_SYNONYMS[w] ?? [])];
568
+ let hit: { code: string; name: string } | undefined;
569
+ for (const c of candidates) {
570
+ hit = cats.find((x) => x.code === c || x.name === c);
571
+ if (hit) break;
572
+ }
573
+ if (!hit) {
574
+ for (const c of candidates) {
575
+ hit = cats.find((x) => x.name.includes(c) || c.includes(x.code) || c.includes(x.name));
576
+ if (hit) break;
577
+ }
578
+ }
579
+ if (hit && !matched.some((m) => m.code === hit.code)) matched.push(hit);
580
+ }
581
+ if (matched.length === 0) {
582
+ return { summary: JSON.stringify({ error: 'category_unresolved', categoryQuery, available: cats.map((c) => c.name) }) };
583
+ }
584
+ console.warn(`[category-shops] input categoryQuery="${categoryQuery}" resolved=${matched.map((m) => m.name).join('/')}`);
585
+ const results = await Promise.all(
586
+ matched.map((m) =>
587
+ ports.shop.searchShops({
588
+ ctx: q,
589
+ keyword: '',
590
+ keywords: [],
591
+ businessCategory: m.code,
592
+ page: 1,
593
+ pageSize: 200,
594
+ }),
595
+ ),
596
+ );
597
+ const merged = {
598
+ items: results.flatMap((r) => r.items),
599
+ page: 1,
600
+ pageSize: 50,
601
+ total: results.reduce((s, r) => s + r.total, 0),
602
+ hasMore: results.some((r) => r.hasMore),
603
+ };
604
+ console.warn(`[category-shops] output total=${merged.total} items=${merged.items.length}`);
605
+ const data = projectShopList(
606
+ 'search',
607
+ merged,
608
+ merged.items.length === 0 ? '该类目暂无在营商户。' : undefined,
609
+ undefined,
610
+ q.scope.mallId || undefined,
611
+ q.scope.miniAppId || undefined,
612
+ );
613
+ if (data.items.length === 0) return { summary: JSON.stringify({ categories: matched.map((m) => m.name), total: 0 }) };
614
+ return withCards(data, 'shop-list', shopListNote(data, merged.total), summaries.shopList(data, merged.items));
361
615
  }),
362
616
  });
363
617
 
364
- const customerServiceFaq = createTool({
365
- id: 'customer-service-faq',
366
- description:
367
- '客服FAQ:搜索常见问题答案(退换货、会员积分、停车等服务政策)。输出 customer-service-faq。',
368
- inputSchema: z.object({
369
- query: str('用户问题'),
370
- topK: optionalStr('返回条数(字符串,1-5,缺省 3)'),
371
- }),
372
- execute: exec(async (ports, ctx, args: Record<string, unknown>) => {
373
- // 011 D10/评审 M4:feature 门控 = execute 内运行时护栏(customer-service;FAQ silent preTool 同走本工具)
374
- if (!ctx.runtime.isFeatureEnabled('customer-service')) {
375
- return { error: '客服功能未启用(部署未开启 customer-service feature)' };
618
+ /**
619
+ * 商场概览(内部 preTool mall-overview 专用):结构问句(有哪些楼层/有啥类目/商场几层——
620
+ * 无可拆搜索参数)的品牌导览聚合承接:agg 数据 → shop-list 概览卡。
621
+ * note 携带权威数字(层数/业态计数)——模型引用数字作答,不自己数列表(计数幻觉免疫)。
622
+ * stores 为首页预览子集(非全量)——卡 summary 显式概览语义,全量浏览归 search-shops。
623
+ */
624
+ const mallOverview = createTool({
625
+ id: 'mall-overview',
626
+ description: '【内部工具,模型勿调用】商场概览(品牌导览聚合):楼层 + 业态(权威计数)+ 预览门店 → shop-list 概览卡。',
627
+ // B3:mallId 入参化(同 mall-context——dedup 键随 mallId 变更自动换键)
628
+ inputSchema: z.object({ mallId: str('商圈 ID(pre-tool decide 注入)') }),
629
+ execute: exec(async (ports, _ctx, args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
630
+ const q = contextWithMallId(reqCtxOf(execCtx), args.mallId);
631
+ // 可选能力口:provider 实现(概览聚合)→ 概览卡;未实现 → 降级 searchShops 零参全量(口径不变)
632
+ const overviewPort = ports.shop as ShoppingGuidePorts['shop'] & {
633
+ fetchStoreOverview?: (ctx: ShoppingQueryContext) => Promise<MallOverviewSnapshot | null>;
634
+ };
635
+ const overview = await overviewPort.fetchStoreOverview?.(q).catch(() => null);
636
+ if (overview && overview.stores.length > 0) {
637
+ const page = {
638
+ items: overview.stores,
639
+ page: 1,
640
+ pageSize: overview.stores.length,
641
+ total: overview.stores.length,
642
+ hasMore: false,
643
+ };
644
+ // 卡头不带概览数字(用户裁定:数字信息只在回答里)——note 仍携权威层数/业态计数供模型引用作答
645
+ const data = projectShopList(
646
+ 'search',
647
+ page,
648
+ '商场门店概览',
649
+ undefined,
650
+ q.scope.mallId || undefined,
651
+ q.scope.miniAppId || undefined,
652
+ );
653
+ const tagText = overview.categories.map((c) => `${c.name} ${c.merchantCount} 家`).join('、');
654
+ const note = `商场概览:${overview.floors.length} 层(${overview.floors.join('/')});业态:${tagText};当前展示其中 ${overview.stores.length} 家门店`;
655
+ return withCards(data, 'shop-list', note, summaries.shopList(data, overview.stores));
376
656
  }
377
- const topK = Math.min(5, Math.max(1, Number(args.topK) || 3));
378
- const faqs = await ports.assistance.searchFaq(toLooseContext(ctx), String(args.query), topK);
379
- return projectCustomerServiceFaq(
380
- String(args.query),
381
- faqs,
382
- faqs.length === 0 ? '未找到相关常见问题,请尝试人工客服。' : undefined,
383
- );
657
+ console.warn('[mall-overview] fetchStoreOverview 缺席/空 → 降级 searchShops 零参');
658
+ const result = await ports.shop.searchShops({ ctx: q, keyword: '', keywords: [], page: 1, pageSize: 50 });
659
+ const data = buildShopListCard(result, q, true);
660
+ if (data.items.length === 0) return { summary: summaries.shopList(data) };
661
+ return withCards(data, 'shop-list', shopListNote(data, result.total), summaries.shopList(data, result.items));
384
662
  }),
385
663
  });
386
664
 
665
+ // customerServiceFaq:客服承接已拆分至 module-customer-service(2026-08-31)
666
+
667
+ // W2(2026-09-01):出卡工具创建点单点 wrap(description 追加预告知句)——
668
+ // 注册与 preTool 声明均使用 wrapped 实例;mall-context/floor-shops 内部工具不 wrap。
669
+ // B3:四个内部工具 internalTool 原实例标记——Agent 模型面剔除(omitInternal),
670
+ // preTool 路径与 D9 实例一致性校验不受影响(标记不换实例)。
387
671
  return {
388
- recommend,
389
- searchProducts,
390
- productFacets,
391
- getProduct,
392
- compareProducts,
393
- searchMerchants,
394
- getMerchant,
395
- mallDirectory,
396
- getLocation,
397
- listHumanGuides,
398
- listBrowsingHistory,
399
- listNearbyMalls,
400
- listCategories,
401
- searchKnowledge,
402
- customerServiceFaq,
672
+ searchShops: withCardEmissionHint(searchShops),
673
+ getShop: withCardEmissionHint(getShop),
674
+ mallContext: internalTool(mallContext),
675
+ floorShops: internalTool(floorShops),
676
+ categoryShops: internalTool(categoryShops),
677
+ mallOverview: internalTool(mallOverview),
403
678
  } as const;
404
679
  }
405
680