@harrylabsj/kiwi-merchant-cloud 0.12.22 → 0.12.24

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 (104) hide show
  1. package/app/a2a/node.js +225 -7
  2. package/app/a2a/node.js.map +1 -1
  3. package/app/a2a/reception/agent-runtime.d.ts +89 -0
  4. package/app/a2a/reception/agent-runtime.js +809 -0
  5. package/app/a2a/reception/agent-runtime.js.map +1 -0
  6. package/app/a2a/reception/budget.d.ts +51 -0
  7. package/app/a2a/reception/budget.js +101 -0
  8. package/app/a2a/reception/budget.js.map +1 -0
  9. package/app/a2a/reception/config.d.ts +37 -0
  10. package/app/a2a/reception/config.js +50 -0
  11. package/app/a2a/reception/config.js.map +1 -0
  12. package/app/a2a/reception/conversation-store.d.ts +36 -0
  13. package/app/a2a/reception/conversation-store.js +110 -0
  14. package/app/a2a/reception/conversation-store.js.map +1 -0
  15. package/app/a2a/reception/engine.d.ts +148 -0
  16. package/app/a2a/reception/engine.js +702 -0
  17. package/app/a2a/reception/engine.js.map +1 -0
  18. package/app/a2a/reception/probe.d.ts +44 -0
  19. package/app/a2a/reception/probe.js +110 -0
  20. package/app/a2a/reception/probe.js.map +1 -0
  21. package/app/a2a/reception/publish.d.ts +42 -0
  22. package/app/a2a/reception/publish.js +254 -0
  23. package/app/a2a/reception/publish.js.map +1 -0
  24. package/app/a2a/reception/reply-outbox.d.ts +53 -0
  25. package/app/a2a/reception/reply-outbox.js +73 -0
  26. package/app/a2a/reception/reply-outbox.js.map +1 -0
  27. package/app/a2a/reception/responder.d.ts +12 -0
  28. package/app/a2a/reception/responder.js +56 -0
  29. package/app/a2a/reception/responder.js.map +1 -0
  30. package/app/a2a/reception/retention.d.ts +22 -0
  31. package/app/a2a/reception/retention.js +40 -0
  32. package/app/a2a/reception/retention.js.map +1 -0
  33. package/app/a2a/reception/types.d.ts +130 -0
  34. package/app/a2a/reception/types.js +10 -0
  35. package/app/a2a/reception/types.js.map +1 -0
  36. package/app/a2a/server/generic-responder.d.ts +5 -1
  37. package/app/a2a/server/generic-responder.js.map +1 -1
  38. package/app/a2a/server/inquiry-interpreter.d.ts +69 -0
  39. package/app/a2a/server/inquiry-interpreter.js +171 -0
  40. package/app/a2a/server/inquiry-interpreter.js.map +1 -0
  41. package/app/a2a/server/merchant-handler.d.ts +31 -0
  42. package/app/a2a/server/merchant-handler.js +257 -46
  43. package/app/a2a/server/merchant-handler.js.map +1 -1
  44. package/app/a2a/server/negotiation-advisor.d.ts +17 -0
  45. package/app/a2a/server/negotiation-advisor.js +38 -5
  46. package/app/a2a/server/negotiation-advisor.js.map +1 -1
  47. package/app/a2a/server/negotiation-approvals.d.ts +10 -0
  48. package/app/a2a/server/negotiation-approvals.js +46 -0
  49. package/app/a2a/server/negotiation-approvals.js.map +1 -1
  50. package/app/a2a/server/pipeline.d.ts +1 -1
  51. package/app/a2a/server/pipeline.js +10 -2
  52. package/app/a2a/server/pipeline.js.map +1 -1
  53. package/app/a2a/server/server.js +1 -1
  54. package/app/a2a/server/server.js.map +1 -1
  55. package/app/a2a/server/types.d.ts +2 -0
  56. package/app/a2a/unit-alias.d.ts +79 -0
  57. package/app/a2a/unit-alias.js +163 -0
  58. package/app/a2a/unit-alias.js.map +1 -0
  59. package/app/buyer-core/a2a-quote-fetcher.d.ts +6 -0
  60. package/app/buyer-core/a2a-quote-fetcher.js +100 -8
  61. package/app/buyer-core/a2a-quote-fetcher.js.map +1 -1
  62. package/app/buyer-core/build-service.d.ts +6 -0
  63. package/app/buyer-core/build-service.js +12 -1
  64. package/app/buyer-core/build-service.js.map +1 -1
  65. package/app/buyer-core/merchant-index.js +176 -23
  66. package/app/buyer-core/merchant-index.js.map +1 -1
  67. package/app/buyer-core/protocol-recovery.d.ts +7 -0
  68. package/app/buyer-core/protocol-recovery.js +17 -0
  69. package/app/buyer-core/protocol-recovery.js.map +1 -1
  70. package/app/cloud/bootstrap.js +4 -0
  71. package/app/cloud/bootstrap.js.map +1 -1
  72. package/app/cloud/http-router.d.ts +3 -0
  73. package/app/cloud/http-router.js +55 -0
  74. package/app/cloud/http-router.js.map +1 -1
  75. package/app/cloud-sample/products.json +3 -3
  76. package/app/config/profile.d.ts +5 -0
  77. package/app/config/profile.js +38 -2
  78. package/app/config/profile.js.map +1 -1
  79. package/app/http/merchant-management/page.js +226 -52
  80. package/app/http/merchant-management/page.js.map +1 -1
  81. package/app/mcp/merchant-ops-server.d.ts +29 -0
  82. package/app/mcp/merchant-ops-server.js +17 -0
  83. package/app/mcp/merchant-ops-server.js.map +1 -1
  84. package/app/mcp/merchant-runtime-assembly.d.ts +7 -0
  85. package/app/mcp/merchant-runtime-assembly.js +77 -0
  86. package/app/mcp/merchant-runtime-assembly.js.map +1 -1
  87. package/app/mcp/merchant-server.d.ts +10 -0
  88. package/app/mcp/merchant-server.js +24 -9
  89. package/app/mcp/merchant-server.js.map +1 -1
  90. package/app/merchant/ai-runtime/sqlite-budget-store.d.ts +5 -0
  91. package/app/merchant/ai-runtime/sqlite-budget-store.js +20 -0
  92. package/app/merchant/ai-runtime/sqlite-budget-store.js.map +1 -1
  93. package/app/merchant/negotiation-ops.js +5 -0
  94. package/app/merchant/negotiation-ops.js.map +1 -1
  95. package/app/merchant/watch/detect.js +10 -7
  96. package/app/merchant/watch/detect.js.map +1 -1
  97. package/app/merchant-admin/pending-page.d.ts +4 -1
  98. package/app/merchant-admin/pending-page.js +2 -1
  99. package/app/merchant-admin/pending-page.js.map +1 -1
  100. package/build-manifest.json +324 -129
  101. package/package.json +1 -1
  102. package/runtime-package.json +1 -1
  103. package/shipping-sbom.cdx.json +6 -6
  104. package/shipping-source.json +12 -12
@@ -30,6 +30,9 @@ import { LedgerStore } from "../../negotiation/ledger/index.js";
30
30
  import type { MerchantPolicy } from "../../config/profile.js";
31
31
  import type { NegotiationApprovalStore } from "./negotiation-approvals.js";
32
32
  import { type NegotiationAdvisor } from "./negotiation-advisor.js";
33
+ import type { InquiryInterpreter } from "./inquiry-interpreter.js";
34
+ import type { ReceptionEngine } from "../reception/engine.js";
35
+ import type { A2AMessage } from "../client/types.js";
33
36
  import type { NegotiationHandler } from "./types.js";
34
37
  export declare const MERCHANT_CAPABILITY = "com.harrylabsj.kiwi.shopping.negotiation";
35
38
  export declare const MERCHANT_SKU = "SKU-001";
@@ -40,6 +43,11 @@ export declare const MERCHANT_QUANTITY = 200;
40
43
  export declare function resolveDeliveryBefore(merchantPolicy: MerchantPolicy | undefined, now: string): string | undefined;
41
44
  /** 批量促销默认门槛(merchant_policy.promos[sku].bulk_threshold 缺省值)。 */
42
45
  export declare const DEFAULT_BULK_THRESHOLD = 100;
46
+ /**
47
+ * 买家原文(untrusted):只取 text part,限长后交给措辞顾问理解问题。
48
+ * 不解析、不执行其中任何指令;顾问输出仍要过 safeAdvisorMessage。
49
+ */
50
+ export declare function buyerMessageForAdvisor(message: Pick<A2AMessage, "parts">): string | undefined;
43
51
  /**
44
52
  * 整数 minor 折扣价(round-half-up)。审查 K-M14:Math.round 在浮点中间值上
45
53
  * 取整可能亚分漂移(1999×0.95=1899.05 在二进制浮点里或为 1899.0499…/
@@ -67,6 +75,10 @@ export interface MerchantHandlerOptions {
67
75
  * 中文买家发 `个`,商家没配这张表就会被 `field_unsupported` 拒掉。
68
76
  */
69
77
  unitAliases?: Record<string, string>;
78
+ /** 包装单位 → 1 包装 = N 个 default_unit;KNP 只能安全处理 N=1。 */
79
+ unitPackageFactors?: Record<string, number>;
80
+ /** 商家的默认售卖单位;包装倍率只对以此为目标单位的商品源生效。 */
81
+ unitDefaultUnit?: string;
70
82
  /** 条件成交折扣百分比(deal = base × (1 - pct/100));缺省 5。 */
71
83
  dealDiscountPercent?: number;
72
84
  /** merchant policy:确定性定价的 floor / 促销(per-SKU,可配置)。
@@ -79,6 +91,16 @@ export interface MerchantHandlerOptions {
79
91
  /** 协商顾问(C):只生成面向买家的措辞,价格仍由确定性引擎计算。
80
92
  * 缺省关闭;输出经 safeAdvisorMessage 校验,越界即回退固定文案。 */
81
93
  negotiationAdvisor?: NegotiationAdvisor;
94
+ /** 询价意图解析(P2):只产出候选,回复事实仍由本 handler 组装。
95
+ * 缺省关闭;解析失败回退到固定询问文案。 */
96
+ inquiryInterpreter?: InquiryInterpreter;
97
+ /** KNP inquiry 接待引擎(P0a 统一):配置后 inquiry 与普通 A2A 文本共用
98
+ * 同一接待引擎(zh-CN,事实由引擎取商品源与策略);引擎异常回退到
99
+ * 确定性组装路径,询价不被阻断。 */
100
+ reception?: {
101
+ engine: ReceptionEngine;
102
+ merchantId: string;
103
+ };
82
104
  /** Workbench promotion authority used by the deterministic quote path. */
83
105
  promotionPrice?: (input: {
84
106
  sku: string;
@@ -97,6 +119,15 @@ export interface MerchantHandlerOptions {
97
119
  * 约定一致,也符合 shopping-cli wire 值;测试桩 `{price: 99}` → 9900 minor 同此)。
98
120
  */
99
121
  export interface MerchantProductSource {
122
+ /** P0a/M2:按买家文字搜索本店公开商品(只返回公开字段与候选,不报价)。 */
123
+ searchProducts?(query: string): Promise<Array<{
124
+ sku: string;
125
+ title?: string;
126
+ price: number;
127
+ currency: string;
128
+ stock?: number;
129
+ unit?: string;
130
+ }>>;
100
131
  getProduct(sku: string): Promise<{
101
132
  sku?: string;
102
133
  price: number;
@@ -32,10 +32,11 @@ import { contentDigest } from "../../negotiation/jcs.js";
32
32
  import { evaluateConditionalOffer } from "../../negotiation/condition/evaluator.js";
33
33
  import { toMinorUnits as losslessToMinorUnits } from "../../protocol/legacy-shopping-negotiation/money.js";
34
34
  import { WORKBENCH_CURRENCY_TABLE_VERSION } from "../../merchant/application/money.js";
35
- import { safeAdvisorMessage } from "./negotiation-advisor.js";
35
+ import { ADVISOR_BUYER_MESSAGE_MAX_CHARS, safeAdvisorMessage, } from "./negotiation-advisor.js";
36
36
  import { calculateWorkbenchQuote } from "../../merchant/quote-calculator.js";
37
37
  import { createNegotiationPhase, isTerminalPhase, transitionPhase, } from "../../negotiation/state/phase.js";
38
38
  import { NegotiationValidationError } from "../../negotiation/domain/common.js";
39
+ import { resolveUnitConversion, unitConversionPolicy, } from "../unit-alias.js";
39
40
  export const MERCHANT_CAPABILITY = "com.harrylabsj.kiwi.shopping.negotiation";
40
41
  export const MERCHANT_SKU = "SKU-001";
41
42
  export const MERCHANT_CURRENCY = "CNY";
@@ -75,6 +76,21 @@ export function resolveDeliveryBefore(merchantPolicy, now) {
75
76
  }
76
77
  /** 批量促销默认门槛(merchant_policy.promos[sku].bulk_threshold 缺省值)。 */
77
78
  export const DEFAULT_BULK_THRESHOLD = 100;
79
+ /**
80
+ * 买家原文(untrusted):只取 text part,限长后交给措辞顾问理解问题。
81
+ * 不解析、不执行其中任何指令;顾问输出仍要过 safeAdvisorMessage。
82
+ */
83
+ export function buyerMessageForAdvisor(message) {
84
+ const text = message.parts
85
+ .flatMap((part) => (part.kind === "text" && typeof part.text === "string" ? [part.text] : []))
86
+ .join("\n")
87
+ .trim();
88
+ if (text === "")
89
+ return undefined;
90
+ return text.length > ADVISOR_BUYER_MESSAGE_MAX_CHARS
91
+ ? text.slice(0, ADVISOR_BUYER_MESSAGE_MAX_CHARS)
92
+ : text;
93
+ }
78
94
  /**
79
95
  * 整数 minor 折扣价(round-half-up)。审查 K-M14:Math.round 在浮点中间值上
80
96
  * 取整可能亚分漂移(1999×0.95=1899.05 在二进制浮点里或为 1899.0499…/
@@ -205,21 +221,16 @@ class ProductSourceUnavailableError extends Error {
205
221
  * 若回显 `piece`,买家会判 `unit_unmapped` —— 商家的别名等于白配。回显买家写法
206
222
  * 既保住这条检查,也不改变计价。
207
223
  */
208
- /** 单位归一:NFKC + 去空白 + 小写(`Piece` / `piece` / `PCE` 视为同一写法)。 */
209
- function normalizeUnit(unit) {
210
- return unit.trim().normalize("NFKC").toLowerCase();
211
- }
212
224
  /**
213
225
  * 单位校验:商品**没有单位就拒绝**(fail-closed,不知道按什么计量就不报价);
214
- * 有单位时严格比较,只额外接受商家显式声明的别名,绝不猜同义词。
226
+ * 有单位时严格比较,只额外接受商家显式声明的别名,或内建的 box/盒 1:1 写法。
227
+ * 不做“个/件 = 盒”的自动换算,也不改变数量/单价/金额。
215
228
  */
216
- function unitMismatch(productUnit, requestedUnit, aliases) {
217
- const declared = (productUnit ?? "").trim();
218
- if (declared === "")
219
- return true;
220
- if (normalizeUnit(declared) === normalizeUnit(requestedUnit))
221
- return false;
222
- return aliases[normalizeUnit(requestedUnit)] !== normalizeUnit(declared);
229
+ function unitMismatch(productUnit, requestedUnit, policy) {
230
+ const resolution = resolveUnitConversion(policy, productUnit, requestedUnit);
231
+ // KNP 的 offer/counter/accept 不能安全改写数量;只有 identity/alias 或
232
+ // 1:1 包装倍率可以接受,>1 的换算必须拒绝,绝不退化为内建别名。
233
+ return resolution.kind === "mismatch" || (resolution.kind === "factor" && resolution.factor !== 1);
223
234
  }
224
235
  const declineReply = (reasonCode = "state_conflict", message) => ({
225
236
  kind: "declined",
@@ -227,6 +238,20 @@ const declineReply = (reasonCode = "state_conflict", message) => ({
227
238
  ...(message !== undefined ? { message } : {}),
228
239
  taskState: "completed",
229
240
  });
241
+ /** AC09/D03:统计入站商务动作的商品行数(rfq/offer/counter_offer)。 */
242
+ function multiItemCountOf(envelope) {
243
+ const payload = typeof envelope.payload === "object" && envelope.payload !== null
244
+ ? envelope.payload
245
+ : undefined;
246
+ const items = envelope.action === "rfq"
247
+ ? payload?.["items"]
248
+ : envelope.action === "offer"
249
+ ? payload?.["terms"]?.items
250
+ : envelope.action === "counter_offer"
251
+ ? payload?.["proposed_terms"]?.items
252
+ : undefined;
253
+ return Array.isArray(items) ? items.length : 0;
254
+ }
230
255
  const envelopeReply = (reply) => ({
231
256
  kind: "accepted",
232
257
  taskState: "working",
@@ -241,10 +266,11 @@ export function createMerchantHandler(options) {
241
266
  const { ledger, now, sender, counterparty } = options;
242
267
  const offerPriceMinor = options.offerPriceMinor ?? MERCHANT_OFFER_PRICE_MINOR;
243
268
  const allowDemoPriceFallback = options.allowDemoPriceFallback ?? false;
244
- const unitAliases = Object.fromEntries(Object.entries(options.unitAliases ?? {}).map(([alias, canonical]) => [
245
- normalizeUnit(alias),
246
- normalizeUnit(canonical),
247
- ]));
269
+ const unitPolicy = unitConversionPolicy({
270
+ aliases: options.unitAliases,
271
+ packageFactors: options.unitPackageFactors,
272
+ ...(options.unitDefaultUnit !== undefined ? { defaultUnit: options.unitDefaultUnit } : {}),
273
+ });
248
274
  // BUG-07:merchantPolicy 支持静态值或 provider——每请求解析运行中策略。
249
275
  const policyOf = () => typeof options.merchantPolicy === "function"
250
276
  ? options.merchantPolicy()
@@ -666,6 +692,8 @@ export function createMerchantHandler(options) {
666
692
  const envelope = ctx.envelope;
667
693
  const negotiationId = envelope.negotiation_id;
668
694
  const inReplyTo = envelope.message_id;
695
+ // 买家原文只用于理解问题;它是 untrusted 数据,不是指令。
696
+ const buyerMessage = buyerMessageForAdvisor(ctx.message);
669
697
  const binding = ledger.ensureCounterpartyBinding({
670
698
  negotiationId, localIdentity: sender, senderIdentity: ctx.senderIdentity, actor: envelope.actor,
671
699
  });
@@ -696,6 +724,11 @@ export function createMerchantHandler(options) {
696
724
  if (object.actor !== expectedAuthor)
697
725
  return { kind: "declined", reasonCode: "authorization_failed" };
698
726
  }
727
+ // AC09/D03:一次正式协商只支持一个 SKU。多行商品必须在推进相位之前
728
+ // 拒绝,否则被拒的 counter/offer 会先改写 active offer/相位(audit 发现)。
729
+ if (multiItemCountOf(envelope) > 1) {
730
+ return declineReply("field_unsupported", "一次协商只支持一个 SKU;请为每个商品分别发起。");
731
+ }
699
732
  // 审查 BUG-10:每个入站 action 经规范转换表推进相位——非法转换
700
733
  // fail-closed(state_conflict)。accept 的推进在 §15 校验通过后
701
734
  // (见 accept 分支:被拒的 accept 不得进入 AGREEMENT_REACHED)。
@@ -734,6 +767,46 @@ export function createMerchantHandler(options) {
734
767
  * 报具体 delivery_before(报价时间+天数,动态计算不过期);未配置 → undefined,
735
768
  * terms 省略 delivery_before(明确未知)。 */
736
769
  const deliveryBefore = () => resolveDeliveryBefore(policyOf(), now());
770
+ /**
771
+ * C:顾问只生成 public_message 措辞;价格、库存可用性、交期事实全部由
772
+ * 确定性引擎/商品源给出。任何异常、超时或越界输出都返回 undefined,
773
+ * 调用方回退既定文案。
774
+ */
775
+ const adviseMessage = async (args) => {
776
+ if (options.negotiationAdvisor === undefined)
777
+ return undefined;
778
+ try {
779
+ const delivery = deliveryBefore();
780
+ const raw = await options.negotiationAdvisor.message({
781
+ sku: args.sku,
782
+ quantity: args.quantity,
783
+ currency: args.currency,
784
+ list_price_minor: args.list_price_minor,
785
+ response_price_minor: args.response_price_minor,
786
+ stock_available: args.stock_available,
787
+ ...(args.public_bound_minor !== undefined
788
+ ? { public_bound_minor: args.public_bound_minor }
789
+ : {}),
790
+ ...(args.buyer_counter_minor !== undefined
791
+ ? { buyer_counter_minor: args.buyer_counter_minor }
792
+ : {}),
793
+ ...(delivery !== undefined ? { delivery_before: delivery } : {}),
794
+ ...(buyerMessage !== undefined ? { buyer_message: buyerMessage } : {}),
795
+ });
796
+ return safeAdvisorMessage(raw, {
797
+ priceMinorValues: [
798
+ args.list_price_minor,
799
+ args.public_bound_minor,
800
+ args.response_price_minor,
801
+ ].filter((value) => typeof value === "number"),
802
+ quantities: [args.quantity, ...(args.extraQuantities ?? [])],
803
+ ...(delivery !== undefined ? { deliveryDates: [delivery] } : {}),
804
+ });
805
+ }
806
+ catch {
807
+ return undefined;
808
+ }
809
+ };
737
810
  /** 买家还价(major→minor;KNP 里 buyer counter 的 unit_price)。 */
738
811
  const clampToBounds = (minor, floor, list) => Math.min(list, Math.max(minor, floor));
739
812
  /**
@@ -791,7 +864,119 @@ export function createMerchantHandler(options) {
791
864
  : product.note === undefined ? {} : { public_message: product.note };
792
865
  switch (envelope.action) {
793
866
  case "inquiry": {
794
- return textReply("Please provide a product SKU, quantity and declared unit for a source-backed quote.");
867
+ const inquiry = envelope.payload;
868
+ const structuredSku = typeof inquiry.subject?.sku === "string" && inquiry.subject.sku.trim() !== ""
869
+ ? inquiry.subject.sku.trim()
870
+ : undefined;
871
+ const questionCodes = (Array.isArray(inquiry.questions) ? inquiry.questions : [])
872
+ .flatMap((question) => (typeof question.code === "string" ? [question.code] : []));
873
+ // 结构化问题代码是协议数据:映射成接待主题,决定回答哪些事实。
874
+ const structuredTopics = new Set();
875
+ for (const code of questionCodes) {
876
+ const head = code.split(".")[0] ?? "";
877
+ if (head === "price")
878
+ structuredTopics.add("price");
879
+ else if (head === "stock" || head === "availability")
880
+ structuredTopics.add("stock");
881
+ else if (head === "delivery" || head === "fulfillment")
882
+ structuredTopics.add("delivery");
883
+ }
884
+ // P0a:inquiry 与普通 A2A 文本统一走接待引擎——结构化 SKU 是协议
885
+ // 数据(权威),自由文本只是补充;引擎故障回退既有确定性路径。
886
+ if (options.reception !== undefined) {
887
+ try {
888
+ const received = await options.reception.engine.respond({
889
+ merchantId: options.reception.merchantId,
890
+ identity: ctx.senderIdentity,
891
+ identityVerified: ctx.identityVerified === true,
892
+ contextId: negotiationId,
893
+ text: buyerMessage ?? "",
894
+ now: now(),
895
+ messageId: envelope.message_id,
896
+ ...(structuredSku !== undefined || structuredTopics.size > 0
897
+ ? {
898
+ structured: {
899
+ ...(structuredSku !== undefined ? { sku: structuredSku } : {}),
900
+ ...(structuredTopics.size > 0
901
+ ? { topics: [...structuredTopics] }
902
+ : {}),
903
+ },
904
+ }
905
+ : {}),
906
+ });
907
+ return textReply(received.text);
908
+ }
909
+ catch {
910
+ // 接待引擎不可用:回退确定性组装(下述既有路径)。
911
+ }
912
+ }
913
+ // P2:自由文本只用于理解问题;模型输出只是候选,事实仍由商品源决定。
914
+ let interpreted;
915
+ if (options.inquiryInterpreter !== undefined && buyerMessage !== undefined) {
916
+ try {
917
+ interpreted = await options.inquiryInterpreter.interpret({
918
+ buyer_message: buyerMessage,
919
+ });
920
+ }
921
+ catch {
922
+ interpreted = undefined;
923
+ }
924
+ }
925
+ const sku = structuredSku ?? interpreted?.sku;
926
+ if (sku === undefined) {
927
+ return textReply("Please provide a product SKU, quantity and declared unit for a source-backed quote.");
928
+ }
929
+ const topics = new Set(structuredTopics);
930
+ for (const topic of interpreted?.topics ?? [])
931
+ topics.add(topic);
932
+ const language = interpreted?.language ?? "en";
933
+ const resolved = await resolveProductOrDecline(sku);
934
+ if ("declined" in resolved) {
935
+ // 询价不是商业承诺:商品源确认不了就要求核对 SKU,不发 decline 信封。
936
+ return textReply(language === "zh"
937
+ ? `暂时无法从商品源确认 SKU ${sku};请核对 SKU 或稍后重试。`
938
+ : `I could not confirm SKU ${sku} from the product source; please check the SKU or retry later.`);
939
+ }
940
+ const product = resolved.product;
941
+ const floorMinor = floorMinorForSku(sku);
942
+ const quantity = interpreted?.quantity;
943
+ const stockAvailable = product.stock !== undefined &&
944
+ (quantity !== undefined ? product.stock >= quantity : product.stock > 0);
945
+ const delivery = deliveryBefore();
946
+ const askAll = topics.size === 0;
947
+ const lines = [];
948
+ // list 价低于私有底价是配置矛盾:此时不报价格(否则等于泄露底价)。
949
+ if ((askAll || topics.has("price")) && floorMinor !== null && product.priceMinor >= floorMinor) {
950
+ const priceText = `${(product.priceMinor / 100).toFixed(2)} ${product.currency}`;
951
+ lines.push(language === "zh"
952
+ ? `SKU ${sku} 的公开标价是 ${priceText}。`
953
+ : `SKU ${sku} list price is ${priceText}.`);
954
+ }
955
+ if ((askAll || topics.has("stock")) && product.stock !== undefined) {
956
+ const tail = quantity !== undefined ? (language === "zh" ? ` ${quantity} 件` : ` for ${quantity} units`) : "";
957
+ lines.push(stockAvailable
958
+ ? language === "zh"
959
+ ? `库存可以覆盖${tail}。`
960
+ : `Stock is available${tail}.`
961
+ : language === "zh"
962
+ ? `当前库存不足以覆盖${tail}。`
963
+ : `Stock does not cover${tail}.`);
964
+ }
965
+ else if (topics.has("stock")) {
966
+ lines.push(language === "zh" ? "库存状态待确认。" : "Stock status needs confirmation.");
967
+ }
968
+ if ((askAll || topics.has("delivery")) && delivery !== undefined) {
969
+ lines.push(language === "zh"
970
+ ? `预计交期不晚于 ${delivery.slice(0, 10)}。`
971
+ : `Estimated delivery is by ${delivery.slice(0, 10)}.`);
972
+ }
973
+ else if (topics.has("delivery")) {
974
+ lines.push(language === "zh" ? "交期待确认。" : "Delivery date needs confirmation.");
975
+ }
976
+ lines.push(language === "zh"
977
+ ? "以上为非约束性信息;请发送 RFQ(SKU、数量、单位)获取正式报价。"
978
+ : "This is non-binding; send an RFQ with SKU, quantity and unit for a binding quote.");
979
+ return textReply(lines.join(" "));
795
980
  }
796
981
  case "rfq": {
797
982
  const payload = envelope.payload;
@@ -809,7 +994,7 @@ export function createMerchantHandler(options) {
809
994
  return resolved.declined;
810
995
  const product = resolved.product;
811
996
  const { priceMinor, currency } = product;
812
- if (unitMismatch(product.unit, requestedUnit, unitAliases))
997
+ if (unitMismatch(product.unit, requestedUnit, unitPolicy))
813
998
  return declineReply("field_unsupported");
814
999
  const handoff_destination = product.stock === undefined || product.source_evidence === undefined ? undefined : product.handoff_destination;
815
1000
  if (factsUnusable(product, quantity))
@@ -824,6 +1009,21 @@ export function createMerchantHandler(options) {
824
1009
  const effectivePriceMinor = promotion.kind === "applied" ? promotion.priceMinor : priceMinor;
825
1010
  if (effectivePriceMinor < floorMinor)
826
1011
  return declineReply("approval_required");
1012
+ // 库存/来源证据未确认时必须保留 needs_confirmation 安全文案,
1013
+ // 不能让顾问的措辞把“待确认”美化掉。
1014
+ const sourceConfirmed = product.stock !== undefined && product.source_evidence !== undefined;
1015
+ const advisedMessage = sourceConfirmed
1016
+ ? await adviseMessage({
1017
+ sku,
1018
+ quantity,
1019
+ currency,
1020
+ list_price_minor: priceMinor,
1021
+ response_price_minor: effectivePriceMinor,
1022
+ stock_available: product.stock !== undefined && quantity <= product.stock,
1023
+ })
1024
+ : undefined;
1025
+ const quoteNote = quoteMessage(product);
1026
+ const publicMessage = advisedMessage ?? quoteNote.public_message;
827
1027
  const reply = seedEnvelope({
828
1028
  negotiation_id: negotiationId,
829
1029
  in_reply_to: inReplyTo,
@@ -844,7 +1044,7 @@ export function createMerchantHandler(options) {
844
1044
  ...quoteValidity(product, promotion.kind === "applied" ? promotion.endsAt : undefined),
845
1045
  }, now()),
846
1046
  },
847
- ...quoteMessage(product),
1047
+ ...(publicMessage !== undefined ? { public_message: publicMessage } : {}),
848
1048
  });
849
1049
  // 审查 BUG-10:merchant 侧相位由自己的出站动作推进——rfq 的 offer
850
1050
  // 回复是 OPEN→OFFER_OPEN 的边(入站侧 rfq 是起始动作无事件)。
@@ -883,7 +1083,7 @@ export function createMerchantHandler(options) {
883
1083
  return resolved.declined;
884
1084
  const product = resolved.product;
885
1085
  const { priceMinor, currency } = product;
886
- if (unitMismatch(product.unit, requestedUnit, unitAliases))
1086
+ if (unitMismatch(product.unit, requestedUnit, unitPolicy))
887
1087
  return declineReply("field_unsupported");
888
1088
  const handoff_destination = product.stock === undefined || product.source_evidence === undefined ? undefined : product.handoff_destination;
889
1089
  if (factsUnusable(product, quantity))
@@ -898,6 +1098,19 @@ export function createMerchantHandler(options) {
898
1098
  const effectivePriceMinor = promotion.kind === "applied" ? promotion.priceMinor : priceMinor;
899
1099
  if (effectivePriceMinor < floorMinor)
900
1100
  return declineReply("approval_required");
1101
+ const sourceConfirmed = product.stock !== undefined && product.source_evidence !== undefined;
1102
+ const advisedMessage = sourceConfirmed
1103
+ ? await adviseMessage({
1104
+ sku,
1105
+ quantity,
1106
+ currency,
1107
+ list_price_minor: priceMinor,
1108
+ response_price_minor: effectivePriceMinor,
1109
+ stock_available: product.stock !== undefined && quantity <= product.stock,
1110
+ })
1111
+ : undefined;
1112
+ const quoteNote = quoteMessage(product);
1113
+ const publicMessage = advisedMessage ?? quoteNote.public_message;
901
1114
  const reply = seedEnvelope({
902
1115
  negotiation_id: negotiationId,
903
1116
  in_reply_to: inReplyTo,
@@ -919,7 +1132,7 @@ export function createMerchantHandler(options) {
919
1132
  ...quoteValidity(product, promotion.kind === "applied" ? promotion.endsAt : undefined),
920
1133
  }, now()),
921
1134
  },
922
- ...quoteMessage(product),
1135
+ ...(publicMessage !== undefined ? { public_message: publicMessage } : {}),
923
1136
  });
924
1137
  // 审查 P2:推进被拒 → 不落账不发出(防 OFFER_OPEN 下重复还价分裂)。
925
1138
  const advanced = await advancePhase(negotiationId, {
@@ -950,7 +1163,7 @@ export function createMerchantHandler(options) {
950
1163
  return resolved.declined;
951
1164
  const product = resolved.product;
952
1165
  const { priceMinor, currency } = product;
953
- if (unitMismatch(product.unit, requestedUnit, unitAliases))
1166
+ if (unitMismatch(product.unit, requestedUnit, unitPolicy))
954
1167
  return declineReply("field_unsupported");
955
1168
  const handoff_destination = product.stock === undefined || product.source_evidence === undefined ? undefined : product.handoff_destination;
956
1169
  if (factsUnusable(product, quantity))
@@ -1031,28 +1244,19 @@ export function createMerchantHandler(options) {
1031
1244
  ? bulkMinor
1032
1245
  : undefined;
1033
1246
  // C:顾问只改措辞。任何异常/越界输出都回退到既有文案,价格不变。
1034
- let advisedMessage;
1035
- if (options.negotiationAdvisor !== undefined) {
1036
- try {
1037
- const raw = await options.negotiationAdvisor.message({
1038
- sku,
1039
- quantity,
1040
- currency,
1041
- list_price_minor: priceMinor,
1042
- ...(publicBoundMinor !== undefined ? { public_bound_minor: publicBoundMinor } : {}),
1043
- ...(typeof buyerCounterMinor === "number" ? { buyer_counter_minor: buyerCounterMinor } : {}),
1044
- response_price_minor: responsiveMinor,
1045
- ...(deliveryBefore() !== undefined ? { delivery_before: deliveryBefore() } : {}),
1046
- });
1047
- advisedMessage = safeAdvisorMessage(raw, {
1048
- priceMinorValues: [priceMinor, publicBoundMinor, responsiveMinor].filter((value) => typeof value === "number"),
1049
- quantities: [quantity, bulkThreshold],
1050
- });
1051
- }
1052
- catch {
1053
- advisedMessage = undefined;
1054
- }
1055
- }
1247
+ const advisedMessage = await adviseMessage({
1248
+ sku,
1249
+ quantity,
1250
+ currency,
1251
+ list_price_minor: priceMinor,
1252
+ ...(publicBoundMinor !== undefined ? { public_bound_minor: publicBoundMinor } : {}),
1253
+ ...(typeof buyerCounterMinor === "number"
1254
+ ? { buyer_counter_minor: buyerCounterMinor }
1255
+ : {}),
1256
+ response_price_minor: responsiveMinor,
1257
+ stock_available: product.stock !== undefined && quantity <= product.stock,
1258
+ extraQuantities: [bulkThreshold],
1259
+ });
1056
1260
  const reply = seedEnvelope({
1057
1261
  negotiation_id: negotiationId,
1058
1262
  in_reply_to: inReplyTo,
@@ -1236,7 +1440,14 @@ export function createMerchantHandler(options) {
1236
1440
  if (saved === undefined || saved.offer_id !== acceptedOfferId)
1237
1441
  return declineReply("offer_unknown");
1238
1442
  const agreedItem = agreedTerms.items?.[0];
1239
- if (agreedItem?.sku !== saved.snapshot.sku || agreedItem.quantity?.value !== saved.snapshot.quantity || agreedItem.quantity?.unit !== saved.snapshot.unit)
1443
+ const agreedUnit = agreedItem?.quantity?.unit;
1444
+ // 1:1 alias(box/盒)和商家显式别名可接受;显式包装倍率 >1 的
1445
+ // 单位在 KNP accept 阶段不能安全换算,unitMismatch 会拒绝。数量/
1446
+ // 单价/金额仍必须与保存的报价快照完全一致。
1447
+ if (agreedItem?.sku !== saved.snapshot.sku ||
1448
+ agreedItem.quantity?.value !== saved.snapshot.quantity ||
1449
+ typeof agreedUnit !== "string" ||
1450
+ unitMismatch(saved.snapshot.unit, agreedUnit, unitPolicy))
1240
1451
  return declineReply("approval_required");
1241
1452
  const refreshedFacts = await resolveProductOrDecline(saved.snapshot.sku, { force: true });
1242
1453
  if ("declined" in refreshedFacts)