@harrylabsj/kiwi-merchant-cloud 0.12.23 → 0.12.25

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 (86) hide show
  1. package/app/a2a/node.js +209 -7
  2. package/app/a2a/node.js.map +1 -1
  3. package/app/a2a/reception/agent-runtime.d.ts +91 -0
  4. package/app/a2a/reception/agent-runtime.js +840 -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 +722 -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 +20 -0
  39. package/app/a2a/server/inquiry-interpreter.js +47 -3
  40. package/app/a2a/server/inquiry-interpreter.js.map +1 -1
  41. package/app/a2a/server/merchant-handler.d.ts +21 -0
  42. package/app/a2a/server/merchant-handler.js +86 -30
  43. package/app/a2a/server/merchant-handler.js.map +1 -1
  44. package/app/a2a/server/negotiation-approvals.d.ts +10 -0
  45. package/app/a2a/server/negotiation-approvals.js +46 -0
  46. package/app/a2a/server/negotiation-approvals.js.map +1 -1
  47. package/app/a2a/server/pipeline.d.ts +1 -1
  48. package/app/a2a/server/pipeline.js +10 -2
  49. package/app/a2a/server/pipeline.js.map +1 -1
  50. package/app/a2a/server/server.js +1 -1
  51. package/app/a2a/server/server.js.map +1 -1
  52. package/app/a2a/server/types.d.ts +2 -0
  53. package/app/a2a/unit-alias.d.ts +79 -0
  54. package/app/a2a/unit-alias.js +163 -0
  55. package/app/a2a/unit-alias.js.map +1 -0
  56. package/app/buyer-core/a2a-quote-fetcher.js +20 -3
  57. package/app/buyer-core/a2a-quote-fetcher.js.map +1 -1
  58. package/app/buyer-core/build-service.d.ts +6 -0
  59. package/app/buyer-core/build-service.js +12 -1
  60. package/app/buyer-core/build-service.js.map +1 -1
  61. package/app/buyer-core/service.js +38 -1
  62. package/app/buyer-core/service.js.map +1 -1
  63. package/app/cloud-sample/products.json +3 -3
  64. package/app/config/profile.d.ts +5 -0
  65. package/app/config/profile.js +38 -2
  66. package/app/config/profile.js.map +1 -1
  67. package/app/mcp/merchant-ops-server.d.ts +29 -0
  68. package/app/mcp/merchant-ops-server.js +17 -0
  69. package/app/mcp/merchant-ops-server.js.map +1 -1
  70. package/app/mcp/merchant-runtime-assembly.js +71 -0
  71. package/app/mcp/merchant-runtime-assembly.js.map +1 -1
  72. package/app/mcp/merchant-server.d.ts +3 -0
  73. package/app/mcp/merchant-server.js +2 -1
  74. package/app/mcp/merchant-server.js.map +1 -1
  75. package/app/merchant/ai-runtime/sqlite-budget-store.d.ts +5 -0
  76. package/app/merchant/ai-runtime/sqlite-budget-store.js +20 -0
  77. package/app/merchant/ai-runtime/sqlite-budget-store.js.map +1 -1
  78. package/app/merchant/negotiation-ops.js +5 -0
  79. package/app/merchant/negotiation-ops.js.map +1 -1
  80. package/app/merchant/watch/detect.js +10 -7
  81. package/app/merchant/watch/detect.js.map +1 -1
  82. package/build-manifest.json +279 -99
  83. package/package.json +1 -1
  84. package/runtime-package.json +1 -1
  85. package/shipping-sbom.cdx.json +6 -6
  86. package/shipping-source.json +12 -12
@@ -0,0 +1,722 @@
1
+ /**
2
+ * 商家 AI 接待引擎(P0a):
3
+ * 买家原文 → 意图候选(模型)→ 商品源事实 → 类型化 ResponsePlan → 发布校验 → zh-CN 文本。
4
+ *
5
+ * 红线:
6
+ * - 模型只负责理解(SKU/数量/单位/主题),不生成价格、库存或交期;
7
+ * - 所有商务数字来自商品源与商家策略;未知就明确说未知;
8
+ * - 普通 A2A 文本不创建 KNP Offer,只准备需求并提示发送 RFQ;
9
+ * - 非中文请求只返回中文范围提示,不用未验收的翻译生成正式需求。
10
+ */
11
+ import { uuidv7 } from "../../negotiation/domain/identifiers.js";
12
+ import { contentDigest } from "../../negotiation/jcs.js";
13
+ import { toMinorUnits as losslessToMinorUnits } from "../../protocol/legacy-shopping-negotiation/money.js";
14
+ import { applyDiscountPercentMinor } from "../server/merchant-handler.js";
15
+ import { multiplyQuantitySafe, resolveUnitConversion, unitConversionPolicy, } from "../unit-alias.js";
16
+ import { RECEPTION_CONFIG_DEFAULTS } from "./config.js";
17
+ import { factRevision, InMemoryFactRegistry, publishResponsePlan } from "./publish.js";
18
+ const BUYER_MESSAGE_MAX_CHARS = 1_000;
19
+ /** 简单 CJK 检测:没有任何汉字且含拉丁字母时按非中文处理(D05)。 */
20
+ function looksNonChinese(text) {
21
+ return !/[一-鿿]/.test(text) && /[A-Za-z]/.test(text);
22
+ }
23
+ export function resolveDeliveryBefore(policy, now) {
24
+ const days = policy?.delivery_lead_days;
25
+ if (days === undefined || !Number.isFinite(days) || days <= 0)
26
+ return undefined;
27
+ const base = Date.parse(now);
28
+ if (!Number.isFinite(base))
29
+ return undefined;
30
+ return new Date(base + days * 86_400_000).toISOString();
31
+ }
32
+ function privateFloorMajor(policy, sku) {
33
+ const floor = policy?.price_floors?.[sku] ?? policy?.min_unit_price_private;
34
+ return typeof floor === "number" && Number.isFinite(floor) ? floor : undefined;
35
+ }
36
+ const CN_QUANTITY_UNITS = [
37
+ "盒",
38
+ "件",
39
+ "个",
40
+ "只",
41
+ "箱",
42
+ "瓶",
43
+ "包",
44
+ "袋",
45
+ "台",
46
+ "套",
47
+ "双",
48
+ "张",
49
+ "份",
50
+ ];
51
+ const CN_DIGITS = {
52
+ 一: 1,
53
+ 二: 2,
54
+ 两: 2,
55
+ 三: 3,
56
+ 四: 4,
57
+ 五: 5,
58
+ 六: 6,
59
+ 七: 7,
60
+ 八: 8,
61
+ 九: 9,
62
+ };
63
+ function chineseNumeralToInt(raw) {
64
+ if (raw === "十")
65
+ return 10;
66
+ const tenIndex = raw.indexOf("十");
67
+ if (tenIndex === -1) {
68
+ return raw.length === 1 ? CN_DIGITS[raw] : undefined;
69
+ }
70
+ if (raw.indexOf("十", tenIndex + 1) !== -1)
71
+ return undefined;
72
+ const tens = tenIndex === 0 ? 1 : CN_DIGITS[raw.slice(0, tenIndex)];
73
+ const ones = tenIndex === raw.length - 1 ? 0 : CN_DIGITS[raw.slice(tenIndex + 1)];
74
+ if (tens === undefined || ones === undefined)
75
+ return undefined;
76
+ return tens * 10 + ones;
77
+ }
78
+ /**
79
+ * 中文数量兜底(如“十盒”“两件”)。模型偶发漏抽中文数字时,避免多轮
80
+ * 变更静默沿用旧数量;数字前 4 字符内出现阿拉伯数字/货币符号时视为价格
81
+ * 语境(“98 一件”),不当作数量。
82
+ */
83
+ export function parseChineseQuantity(text) {
84
+ const pattern = new RegExp(`([一二两三四五六七八九十]+)\\s*(${CN_QUANTITY_UNITS.join("|")})`, "u");
85
+ const match = pattern.exec(text);
86
+ if (match === null || match.index === undefined)
87
+ return undefined;
88
+ const prefix = text.slice(Math.max(0, match.index - 4), match.index);
89
+ if (/[\d¥¥元块]/.test(prefix))
90
+ return undefined;
91
+ const quantity = chineseNumeralToInt(match[1]);
92
+ if (quantity === undefined || quantity <= 0)
93
+ return undefined;
94
+ return { quantity, unit: match[2] };
95
+ }
96
+ const CN_ORDINALS = {
97
+ 一: 1,
98
+ 二: 2,
99
+ 三: 3,
100
+ 四: 4,
101
+ 五: 5,
102
+ 六: 6,
103
+ 七: 7,
104
+ 八: 8,
105
+ 九: 9,
106
+ 十: 10,
107
+ };
108
+ /**
109
+ * 多商品澄清后的序号指代(“第一个”“选2”“第二款”)。只在上轮持久化了
110
+ * 候选时生效;解析失败返回 undefined,让调用方继续追问。
111
+ */
112
+ export function ordinalSkuOf(text, candidates) {
113
+ if (candidates === undefined || candidates.length === 0)
114
+ return undefined;
115
+ const match = text.match(/(?:第|选)\s*(?:第)?\s*([1-9]\d?|[一二三四五六七八九十])\s*(?:个|款|项|号)?/);
116
+ if (match === null)
117
+ return undefined;
118
+ const raw = match[1];
119
+ const index = /^\d+$/.test(raw) ? Number(raw) : CN_ORDINALS[raw];
120
+ if (index === undefined || index < 1 || index > candidates.length)
121
+ return undefined;
122
+ return candidates[index - 1];
123
+ }
124
+ /** 发布结果为空(所有块被拒绝)时的固定兜底,不回显原文、不编造事实。 */
125
+ const EMPTY_PUBLISH_FALLBACK = "抱歉,当前无法处理这条消息,请稍后重试,或直接发送 RFQ(SKU、数量、单位)。";
126
+ export function createMerchantReceptionEngine(deps) {
127
+ const unitPolicy = unitConversionPolicy({
128
+ aliases: deps.unitAliases,
129
+ packageFactors: deps.unitPackageFactors,
130
+ ...(deps.unitDefaultUnit !== undefined ? { defaultUnit: deps.unitDefaultUnit } : {}),
131
+ });
132
+ return {
133
+ async respond(input) {
134
+ // §17.1:每次接待写入前先固化已到期的审批,避免新会话面对陈旧 pending。
135
+ try {
136
+ deps.approvals?.sweepExpired?.();
137
+ }
138
+ catch {
139
+ // 审批存储故障不阻断接待;ops/CLI 读取时还会再扫一次。
140
+ }
141
+ const text = input.text.trim().slice(0, BUYER_MESSAGE_MAX_CHARS);
142
+ const structuredSku = input.structured?.sku;
143
+ const structuredTopics = input.structured?.topics ?? [];
144
+ const previous = deps.store.get(input.merchantId, input.identity, input.contextId);
145
+ // 每回合事实注册表:快照只在发布当回合有效(不持久化、不跨回合复用)。
146
+ const registry = new InMemoryFactRegistry();
147
+ // D07/§18:从 admitted_at 起 30 秒硬截止;超时不再发起新工具调用,
148
+ // 降级确定性回复(不承诺跑满时限,也不把超时伪装成理解结果)。
149
+ const admittedAt = Date.parse(input.now);
150
+ const deadlineMs = deps.deadlineMs ?? RECEPTION_CONFIG_DEFAULTS.runDeadlineMs;
151
+ const deadlineExceeded = () => Number.isFinite(admittedAt) && Date.parse(deps.now()) - admittedAt > deadlineMs;
152
+ if (text === "" && structuredSku === undefined) {
153
+ return finish(input, previous, registry, [{ kind: "ask_clarification", missing: ["sku"], reason: "empty_message" }]);
154
+ }
155
+ if (text !== "" && looksNonChinese(text) && structuredSku === undefined) {
156
+ return finish(input, previous, registry, [
157
+ { kind: "ask_clarification", missing: ["sku"], reason: "non_chinese" },
158
+ ]);
159
+ }
160
+ // M2:Pi 工具循环(可选)。存在已批准候选时先走确定性消费路径,
161
+ // 避免模型绕过“批准价只生效一次”的回环。
162
+ const hasApprovedCandidate = deps.approvals
163
+ ?.list?.("approved")
164
+ ?.some((candidate) => candidate.negotiation_id === input.contextId) === true;
165
+ if (deps.agent !== undefined && !hasApprovedCandidate && text !== "" && !deadlineExceeded()) {
166
+ try {
167
+ const agentResult = await deps.agent.run({
168
+ merchantId: input.merchantId,
169
+ identity: input.identity,
170
+ contextId: input.contextId,
171
+ text,
172
+ ...(structuredSku !== undefined ? { structuredSku } : {}),
173
+ ...(previous !== undefined ? { previousNeed: previous.need } : {}),
174
+ registry,
175
+ now: input.now,
176
+ });
177
+ if (agentResult !== undefined &&
178
+ (structuredSku === undefined ||
179
+ agentResultMatchesStructuredSku(agentResult, structuredSku))) {
180
+ // 模型选择转人工时,仍由服务端登记审批候选(模型没有写能力)。
181
+ const humanBlocks = agentResult.plan.blocks.filter((block) => block.kind === "request_human_help");
182
+ // Exactly one submitted human block may become one server-verified
183
+ // block. Multiple model blocks are never all published on the
184
+ // strength of a single approval.
185
+ const human = humanBlocks.length === 1 ? humanBlocks[0] : undefined;
186
+ const needSku = agentResult.need?.sku ?? previous?.need.sku;
187
+ const needQuantity = agentResult.need?.quantity ?? previous?.need.quantity;
188
+ const needUnit = agentResult.need?.unit ?? previous?.need.unit;
189
+ let verifiedHuman;
190
+ if (human?.buyerTargetPrice !== undefined &&
191
+ human.currency !== undefined &&
192
+ needSku !== undefined &&
193
+ needQuantity !== undefined &&
194
+ deps.productSource !== undefined &&
195
+ deps.approvals !== undefined) {
196
+ try {
197
+ const product = await deps.productSource.getProduct(needSku);
198
+ if (human.currency !== product.currency) {
199
+ // Buyer-visible target currency and the authoritative product
200
+ // currency disagree; never persist one and display the other.
201
+ verifiedHuman = undefined;
202
+ }
203
+ else {
204
+ const policyNow = deps.policy?.();
205
+ const boundary = belowPublicBound(human.buyerTargetPrice, product, needSku, policyNow);
206
+ if (boundary !== undefined) {
207
+ const floorMinor = minorOf(privateFloorMajor(policyNow, needSku));
208
+ const created = deps.approvals.recordPending({
209
+ negotiation_id: input.contextId,
210
+ sku: needSku,
211
+ currency: product.currency,
212
+ quantity: needQuantity,
213
+ ...(needUnit !== undefined ? { unit: needUnit } : {}),
214
+ buyer_offer_minor: boundary.targetMinor,
215
+ public_bound_minor: boundary.publicBoundMinor,
216
+ ...(floorMinor !== undefined ? { floor_minor: floorMinor } : {}),
217
+ ttl_seconds: deps.approvalTtlSeconds ?? RECEPTION_CONFIG_DEFAULTS.approvalTtlSeconds,
218
+ });
219
+ if (pendingApprovalExists(deps.approvals, {
220
+ negotiationId: input.contextId,
221
+ sku: needSku,
222
+ currency: product.currency,
223
+ quantity: needQuantity,
224
+ ...(needUnit !== undefined ? { unit: needUnit } : {}),
225
+ buyerOfferMinor: boundary.targetMinor,
226
+ }, created)) {
227
+ verifiedHuman = {
228
+ kind: "request_human_help",
229
+ topic: "price_below_public_bound",
230
+ buyerTargetPrice: boundary.targetMajor,
231
+ currency: product.currency,
232
+ };
233
+ }
234
+ }
235
+ }
236
+ }
237
+ catch {
238
+ // 事实/审批存储不可用:不保留 request_human_help,走真实兜底。
239
+ verifiedHuman = undefined;
240
+ }
241
+ }
242
+ const blocks = humanBlocks.length === 0
243
+ ? agentResult.plan.blocks
244
+ : verifiedHuman !== undefined
245
+ ? [
246
+ ...agentResult.plan.blocks.filter((block) => block.kind !== "request_human_help"),
247
+ verifiedHuman,
248
+ ]
249
+ : truthfulHumanFallback(agentResult.plan.blocks, {
250
+ ...(needSku !== undefined ? { sku: needSku } : {}),
251
+ ...(needQuantity !== undefined ? { quantity: needQuantity } : {}),
252
+ });
253
+ const agentStated = {
254
+ ...(agentResult.need?.sku !== undefined ? { sku: "model" } : {}),
255
+ ...(agentResult.need?.quantity !== undefined ? { quantity: "model" } : {}),
256
+ ...(agentResult.need?.unit !== undefined ? { unit: "model" } : {}),
257
+ };
258
+ return finish(input, previous, registry, blocks, agentResult.need, agentStated);
259
+ }
260
+ }
261
+ catch {
262
+ // 回退确定性路径。
263
+ }
264
+ }
265
+ let interpreted;
266
+ if (deps.interpreter !== undefined && text !== "" && !deadlineExceeded()) {
267
+ try {
268
+ interpreted = await deps.interpreter.interpret({ buyer_message: text });
269
+ }
270
+ catch {
271
+ interpreted = undefined;
272
+ }
273
+ }
274
+ // 结构化字段是协议数据(权威),模型候选其次,最后沿用会话已确认值。
275
+ const candidateSkus = interpreted?.skus ?? (interpreted?.sku !== undefined ? [interpreted.sku] : []);
276
+ // AC09/D03:多商品澄清后,买家可以用“第一个/第二款”指代候选;候选来自
277
+ // 上一轮持久化的 pendingSkus,序号解析不依赖模型。
278
+ const ordinalSku = ordinalSkuOf(text, previous?.need.pendingSkus);
279
+ // 中文数量兜底(模型偶发漏抽中文数字)。
280
+ const chineseQuantity = parseChineseQuantity(text);
281
+ // 字段证据来源:协议字段 > 模型/搜索候选;只有本轮明确给出的字段才更新。
282
+ const stated = {
283
+ ...(structuredSku !== undefined ? { sku: "structured" } : {}),
284
+ ...(interpreted?.quantity !== undefined
285
+ ? { quantity: "model" }
286
+ : chineseQuantity !== undefined
287
+ ? { quantity: "model" }
288
+ : {}),
289
+ ...(interpreted?.unit !== undefined
290
+ ? { unit: "model" }
291
+ : chineseQuantity !== undefined
292
+ ? { unit: "model" }
293
+ : {}),
294
+ };
295
+ if (stated.sku === undefined && (ordinalSku !== undefined || candidateSkus.length === 1)) {
296
+ stated.sku = "model";
297
+ }
298
+ // 一条消息提到多个商品时明确提示并请买家选择,禁止静默只取第一项;
299
+ // 结构化 SKU 是协议数据(单值),不参与多候选判定。
300
+ if (structuredSku === undefined && ordinalSku === undefined && candidateSkus.length > 1) {
301
+ return finish(input, previous, registry, [
302
+ {
303
+ kind: "ask_clarification",
304
+ missing: ["sku"],
305
+ reason: "multiple_skus",
306
+ candidates: candidateSkus,
307
+ },
308
+ ], { quantity: interpreted?.quantity, unit: interpreted?.unit, pendingSkus: candidateSkus }, stated);
309
+ }
310
+ let sku = structuredSku ?? ordinalSku ?? candidateSkus[0] ?? previous?.need.sku;
311
+ let quantity = interpreted?.quantity ?? chineseQuantity?.quantity ?? previous?.need.quantity;
312
+ let unit = interpreted?.unit ?? chineseQuantity?.unit ?? previous?.need.unit;
313
+ let convertedFrom;
314
+ // M2:买家没说 SKU 时按本店公开商品搜索;唯一命中直接进入事实回答,
315
+ // 多命中列出候选请买家选择,零命中才回固定追问。搜索失败不阻断接待。
316
+ if (sku === undefined && text !== "" && deps.productSource?.searchProducts !== undefined && !deadlineExceeded()) {
317
+ let searchResults = [];
318
+ try {
319
+ searchResults = await deps.productSource.searchProducts(text);
320
+ }
321
+ catch {
322
+ searchResults = [];
323
+ }
324
+ if (searchResults.length === 1) {
325
+ sku = searchResults[0].sku;
326
+ if (stated.sku === undefined)
327
+ stated.sku = "model";
328
+ }
329
+ else if (searchResults.length > 1) {
330
+ const candidates = searchResults.map((result) => result.sku);
331
+ return finish(input, previous, registry, [
332
+ {
333
+ kind: "ask_clarification",
334
+ missing: ["sku"],
335
+ reason: "product_candidates",
336
+ candidates,
337
+ },
338
+ ], { quantity, unit, pendingSkus: candidates }, stated);
339
+ }
340
+ }
341
+ if (sku === undefined) {
342
+ return finish(input, previous, registry, [{ kind: "ask_clarification", missing: ["sku"], reason: "missing_sku" }], { quantity, unit }, stated);
343
+ }
344
+ if (deps.productSource === undefined) {
345
+ return finish(input, previous, registry, [{ kind: "ask_clarification", missing: ["sku"], reason: "unknown_sku" }]);
346
+ }
347
+ // 模型回合结束后复验时限:超时不再调用事实工具,降级确定性回复。
348
+ if (deadlineExceeded()) {
349
+ return finish(input, previous, registry, [{ kind: "ask_clarification", missing: ["sku"], reason: "service_busy" }], { sku, quantity, unit }, stated);
350
+ }
351
+ let product;
352
+ try {
353
+ product = await deps.productSource.getProduct(sku);
354
+ }
355
+ catch {
356
+ return finish(input, previous, registry, [{ kind: "ask_clarification", missing: ["sku"], reason: "unknown_sku" }]);
357
+ }
358
+ // AC13:过期事实不得报价/登记审批;先拒绝本轮,要求重新确认。
359
+ if (product.valid_until !== undefined) {
360
+ const until = Date.parse(product.valid_until);
361
+ if (!Number.isFinite(until) || until <= Date.parse(input.now)) {
362
+ return finish(input, previous, registry, [{ kind: "ask_clarification", missing: ["sku"], reason: "facts_stale" }], { sku, quantity, unit }, stated);
363
+ }
364
+ }
365
+ // AC06:商品源单位与请求同义时始终 1:1;包装倍率只对 default_unit
366
+ // 目标生效,其他情况或别名冲突一律安全拒绝,不猜倍率。
367
+ if (product.unit !== undefined && unit !== undefined) {
368
+ const resolution = resolveUnitConversion(unitPolicy, product.unit, unit);
369
+ if (resolution.kind === "factor") {
370
+ // AC06:使用商家声明的包装倍率;没有数量时先问数量,绝不猜 1 箱=1 件。
371
+ if (quantity === undefined) {
372
+ return finish(input, previous, registry, [{ kind: "ask_clarification", missing: ["quantity"], reason: "missing_quantity" }], { sku }, stated);
373
+ }
374
+ const convertedQuantity = multiplyQuantitySafe(quantity, resolution.factor);
375
+ if (convertedQuantity === undefined) {
376
+ return finish(input, previous, registry, [{ kind: "ask_clarification", missing: ["quantity"], reason: "quantity_overflow" }], { sku, quantity }, stated);
377
+ }
378
+ convertedFrom = { quantity, unit, factor: resolution.factor };
379
+ quantity = convertedQuantity;
380
+ unit = product.unit;
381
+ }
382
+ else if (resolution.kind === "identity" || resolution.kind === "alias") {
383
+ unit = product.unit;
384
+ }
385
+ else {
386
+ return finish(input, previous, registry, [
387
+ {
388
+ kind: "ask_clarification",
389
+ missing: ["sku"],
390
+ reason: "unit_mismatch",
391
+ supportedUnit: product.unit,
392
+ },
393
+ ], { sku, quantity }, stated);
394
+ }
395
+ }
396
+ const policy = deps.policy?.();
397
+ const floor = privateFloorMajor(policy, sku);
398
+ // D15 审批回环:商家在 /ops 批准的候选,买家下一轮命中即一次性消费,
399
+ // 用批准价渲染(不再重复登记 pending)。数量/单位变化时不消费。
400
+ const targetMinor = minorOf(interpreted?.target_price);
401
+ const currentFloorMinor = minorOf(floor);
402
+ const approvalTopicsOk = structuredTopics.length === 0 || structuredTopics.includes("price");
403
+ const approved = approvalTopicsOk
404
+ ? deps.approvals?.list?.("approved")?.find((candidate) => candidate.negotiation_id === input.contextId &&
405
+ candidate.sku === sku &&
406
+ candidate.currency === product.currency &&
407
+ (quantity === undefined || candidate.quantity === quantity) &&
408
+ (unit === undefined || candidate.unit === undefined || candidate.unit === unit) &&
409
+ candidate.approved_minor !== undefined &&
410
+ // 批准后策略/底价可能已变化:当前底价高于批准价时不再消费(AC27)。
411
+ (currentFloorMinor === undefined || candidate.approved_minor >= currentFloorMinor) &&
412
+ (targetMinor === undefined || candidate.approved_minor >= targetMinor))
413
+ : undefined;
414
+ if (approved !== undefined && approved.approved_minor !== undefined) {
415
+ const consumed = deps.approvals?.consume?.({
416
+ negotiation_id: input.contextId,
417
+ sku,
418
+ currency: product.currency,
419
+ quantity: approved.quantity,
420
+ ...(approved.unit !== undefined ? { unit: approved.unit } : {}),
421
+ });
422
+ if (consumed !== undefined) {
423
+ const approvedFacts = {
424
+ ...factsForWithSku(product, quantity ?? approved.quantity, policy, floor, input.now),
425
+ approvedPrice: approved.approved_minor / 100,
426
+ };
427
+ const approvedSnapshot = {
428
+ merchantId: input.merchantId,
429
+ sku,
430
+ visibility: "public",
431
+ issuedAt: input.now,
432
+ ...(product.valid_until !== undefined ? { expiresAt: product.valid_until } : {}),
433
+ facts: approvedFacts,
434
+ };
435
+ const approvedRef = registry.register({
436
+ ...approvedSnapshot,
437
+ revision: factRevision(approvedSnapshot),
438
+ });
439
+ return finish(input, previous, registry, [
440
+ {
441
+ kind: "acknowledge_need",
442
+ sku,
443
+ ...(quantity !== undefined ? { quantity } : {}),
444
+ ...(unit !== undefined ? { unit } : {}),
445
+ },
446
+ {
447
+ kind: "show_commercial_terms",
448
+ ref: approvedRef,
449
+ ...(structuredTopics.length > 0 ? { topics: structuredTopics } : {}),
450
+ },
451
+ { kind: "next_step", action: "send_rfq" },
452
+ ], {
453
+ sku,
454
+ quantity,
455
+ unit,
456
+ ...(convertedFrom !== undefined
457
+ ? { inputQuantity: convertedFrom.quantity, inputUnit: convertedFrom.unit }
458
+ : {}),
459
+ }, stated);
460
+ }
461
+ }
462
+ const facts = factsForWithSku(product, quantity, policy, floor, input.now);
463
+ // 事实快照注册后只以引用进入计划;发布器从同一快照渲染(§11)。
464
+ const snapshotBase = {
465
+ merchantId: input.merchantId,
466
+ sku,
467
+ visibility: "public",
468
+ issuedAt: input.now,
469
+ ...(product.valid_until !== undefined ? { expiresAt: product.valid_until } : {}),
470
+ facts,
471
+ };
472
+ const ref = registry.register({ ...snapshotBase, revision: factRevision(snapshotBase) });
473
+ const acknowledge = {
474
+ kind: "acknowledge_need",
475
+ sku,
476
+ ...(quantity !== undefined ? { quantity } : {}),
477
+ ...(unit !== undefined ? { unit } : {}),
478
+ ...(convertedFrom !== undefined ? { convertedFrom } : {}),
479
+ };
480
+ // D15 自动发布边界:买家明确目标价低于公开折扣边界(list×(1-max(自动
481
+ // 折扣%,促销%)),与确定性报价同口径)→ 登记审批候选并如实告知"需要
482
+ // 商家确认";不泄露公开边界数值与私有底价。边界内或无法精确换算时按
483
+ // 普通事实回答(接待本身不发布 Offer,正式报价仍走 KNP fast path)。
484
+ const boundary = belowPublicBound(interpreted?.target_price, product, sku, policy);
485
+ if (boundary !== undefined &&
486
+ quantity !== undefined &&
487
+ deps.approvals !== undefined) {
488
+ try {
489
+ const floorMinor = minorOf(floor);
490
+ const created = deps.approvals.recordPending({
491
+ negotiation_id: input.contextId,
492
+ sku,
493
+ currency: product.currency,
494
+ quantity,
495
+ ...(unit !== undefined ? { unit } : {}),
496
+ buyer_offer_minor: boundary.targetMinor,
497
+ public_bound_minor: boundary.publicBoundMinor,
498
+ ...(floorMinor !== undefined ? { floor_minor: floorMinor } : {}),
499
+ ttl_seconds: deps.approvalTtlSeconds ?? RECEPTION_CONFIG_DEFAULTS.approvalTtlSeconds,
500
+ });
501
+ if (pendingApprovalExists(deps.approvals, {
502
+ negotiationId: input.contextId,
503
+ sku,
504
+ currency: product.currency,
505
+ quantity,
506
+ ...(unit !== undefined ? { unit } : {}),
507
+ buyerOfferMinor: boundary.targetMinor,
508
+ }, created)) {
509
+ return finish(input, previous, registry, [
510
+ acknowledge,
511
+ {
512
+ kind: "show_commercial_terms",
513
+ ref,
514
+ ...(structuredTopics.length > 0 ? { topics: structuredTopics } : {}),
515
+ },
516
+ {
517
+ kind: "request_human_help",
518
+ topic: "price_below_public_bound",
519
+ buyerTargetPrice: boundary.targetMajor,
520
+ currency: product.currency,
521
+ },
522
+ ], {
523
+ sku,
524
+ quantity,
525
+ unit,
526
+ ...(convertedFrom !== undefined
527
+ ? { inputQuantity: convertedFrom.quantity, inputUnit: convertedFrom.unit }
528
+ : {}),
529
+ }, stated);
530
+ }
531
+ }
532
+ catch {
533
+ // 审批存储失败:不声称待商家确认,继续普通事实回答。
534
+ }
535
+ }
536
+ const blocks = [
537
+ acknowledge,
538
+ {
539
+ kind: "show_commercial_terms",
540
+ ref,
541
+ ...(structuredTopics.length > 0 ? { topics: structuredTopics } : {}),
542
+ },
543
+ { kind: "next_step", action: "send_rfq" },
544
+ ];
545
+ return finish(input, previous, registry, blocks, {
546
+ sku,
547
+ quantity,
548
+ unit,
549
+ ...(convertedFrom !== undefined
550
+ ? { inputQuantity: convertedFrom.quantity, inputUnit: convertedFrom.unit }
551
+ : {}),
552
+ }, stated);
553
+ },
554
+ };
555
+ function finish(input, previous, registry, blocks, need, stated) {
556
+ const merged = {
557
+ sku: need?.sku ?? previous?.need.sku,
558
+ quantity: need?.quantity ?? previous?.need.quantity,
559
+ unit: need?.unit ?? previous?.need.unit,
560
+ };
561
+ // 字段证据:只有本轮明确给出的字段才签发新的 source_message_id;
562
+ // 其余字段沿用上一轮证据。模型输出不能设置 confirmed。
563
+ const evidence = {
564
+ ...previous?.need.evidence,
565
+ ...(need?.evidence ?? {}),
566
+ };
567
+ if (input.messageId !== undefined && stated !== undefined) {
568
+ for (const field of ["sku", "quantity", "unit"]) {
569
+ const source = stated[field];
570
+ if (source !== undefined) {
571
+ evidence[field] = {
572
+ source_message_id: input.messageId,
573
+ observed_at: input.now,
574
+ source,
575
+ };
576
+ }
577
+ }
578
+ }
579
+ // 买家选定 SKU 后清空候选;仍在多商品澄清中则继续保留,供“第一个”指代。
580
+ const pendingSkus = need?.sku !== undefined
581
+ ? undefined
582
+ : (need?.pendingSkus ?? previous?.need.pendingSkus);
583
+ const conversation = deps.store.put(input.merchantId, input.identity, input.contextId, {
584
+ ...(merged.sku !== undefined ? { sku: merged.sku } : {}),
585
+ ...(merged.quantity !== undefined ? { quantity: merged.quantity } : {}),
586
+ ...(merged.unit !== undefined ? { unit: merged.unit } : {}),
587
+ ...(pendingSkus !== undefined && pendingSkus.length > 0 ? { pendingSkus } : {}),
588
+ ...(need?.inputQuantity !== undefined ? { inputQuantity: need.inputQuantity } : {}),
589
+ ...(need?.inputUnit !== undefined ? { inputUnit: need.inputUnit } : {}),
590
+ ...(Object.keys(evidence).length > 0 ? { evidence } : {}),
591
+ });
592
+ const plan = { locale: "zh-CN", blocks };
593
+ // 发布前校验(引用存在性/版本/租户/可见性/有效期)后才渲染公开文本。
594
+ const published = publishResponsePlan({
595
+ plan,
596
+ registry,
597
+ merchantId: input.merchantId,
598
+ now: input.now,
599
+ });
600
+ const text = published.text === "" ? EMPTY_PUBLISH_FALLBACK : published.text;
601
+ // §16.1:合法回复发布事务内按会话分配严格递增序号;登记出站记录
602
+ // (P0a 同步投递即 dispatched,重试复用同一 response_id 由 outbox 幂等)。
603
+ const responseId = `resp_${uuidv7()}`;
604
+ const replySeq = deps.store.allocateReplySeq(input.merchantId, input.identity, input.contextId);
605
+ deps.outbox.record({
606
+ response_id: responseId,
607
+ merchantId: input.merchantId,
608
+ identity: input.identity,
609
+ contextId: input.contextId,
610
+ reply_seq: replySeq,
611
+ text_digest: contentDigest(text),
612
+ dispatch_class: "automatic",
613
+ status: "dispatched",
614
+ });
615
+ return { plan, text, conversation, reply: { response_id: responseId, reply_seq: replySeq } };
616
+ }
617
+ }
618
+ /** major(元)→ minor(分)的无损换算;无法精确表达返回 undefined。 */
619
+ function minorOf(major) {
620
+ if (major === undefined)
621
+ return undefined;
622
+ const converted = losslessToMinorUnits(major, 2);
623
+ return converted.lossless ? converted.amount_minor : undefined;
624
+ }
625
+ /** 公开折扣边界(与 merchant-handler publicDiscountBoundMinor 同口径):
626
+ * 公开边界 = list×(1-max(max_auto_discount_percent, promos[sku].bulk_discount_percent))。 */
627
+ function publicBoundMinorOf(listMinor, sku, policy) {
628
+ const autoRaw = policy?.max_auto_discount_percent;
629
+ const auto = typeof autoRaw === "number" && Number.isFinite(autoRaw) && autoRaw > 0 ? autoRaw : 0;
630
+ const promoPct = policy?.promos?.[sku]?.bulk_discount_percent ?? 0;
631
+ const pct = Math.max(auto, Number.isFinite(promoPct) && promoPct > 0 ? promoPct : 0);
632
+ return applyDiscountPercentMinor(listMinor, pct);
633
+ }
634
+ /** 买家目标价是否低于公开折扣边界;无法精确换算(lossy)时按未越界处理。 */
635
+ /**
636
+ * Verify that a pending approval really exists server-side and matches the
637
+ * exact buyer request. A successful-looking return value alone is not enough:
638
+ * storage may have failed after the caller saw an object. Only list("pending")
639
+ * is treated as authoritative.
640
+ */
641
+ function pendingApprovalExists(approvals, expected, created) {
642
+ if (approvals.list === undefined)
643
+ return false;
644
+ const approvalId = created?.approval_id;
645
+ if (typeof approvalId !== "string" || approvalId === "")
646
+ return false;
647
+ try {
648
+ const pending = approvals.list("pending");
649
+ return pending.some((candidate) => candidate.approval_id === approvalId &&
650
+ candidate.negotiation_id === expected.negotiationId &&
651
+ candidate.sku === expected.sku &&
652
+ candidate.currency === expected.currency &&
653
+ candidate.quantity === expected.quantity &&
654
+ (expected.unit === undefined || candidate.unit === expected.unit) &&
655
+ (candidate.buyer_offer_minor === undefined ||
656
+ candidate.buyer_offer_minor === expected.buyerOfferMinor));
657
+ }
658
+ catch {
659
+ return false;
660
+ }
661
+ }
662
+ /** Server-side structured SKU is immutable; a model plan for another SKU is ignored. */
663
+ function agentResultMatchesStructuredSku(result, structuredSku) {
664
+ if (result.need?.sku !== undefined && result.need.sku !== structuredSku)
665
+ return false;
666
+ return result.plan.blocks.every((block) => {
667
+ if (block.kind === "acknowledge_need") {
668
+ return block.sku === undefined || block.sku === structuredSku;
669
+ }
670
+ if (block.kind === "show_commercial_terms")
671
+ return block.ref.sku === structuredSku;
672
+ if (block.kind === "recommend_option") {
673
+ return (block.ref.sku === structuredSku &&
674
+ (block.comparedRefs ?? []).every((ref) => ref.sku === structuredSku));
675
+ }
676
+ return true;
677
+ });
678
+ }
679
+ function truthfulHumanFallback(blocks, need) {
680
+ if (need.sku === undefined) {
681
+ return [{ kind: "ask_clarification", missing: ["sku"], reason: "missing_sku" }];
682
+ }
683
+ if (need.quantity === undefined) {
684
+ return [{ kind: "ask_clarification", missing: ["quantity"], reason: "missing_quantity" }];
685
+ }
686
+ const filtered = blocks.filter((block) => block.kind !== "request_human_help");
687
+ if (filtered.some((block) => block.kind === "ask_clarification" || block.kind === "next_step")) {
688
+ return filtered;
689
+ }
690
+ return [...filtered, { kind: "next_step", action: "send_rfq" }];
691
+ }
692
+ function belowPublicBound(targetPrice, product, sku, policy) {
693
+ if (targetPrice === undefined)
694
+ return undefined;
695
+ const target = losslessToMinorUnits(targetPrice, 2);
696
+ const list = losslessToMinorUnits(product.price, 2);
697
+ if (!target.lossless || !list.lossless)
698
+ return undefined;
699
+ const bound = publicBoundMinorOf(list.amount_minor, sku, policy);
700
+ if (target.amount_minor >= bound)
701
+ return undefined;
702
+ return { targetMinor: target.amount_minor, targetMajor: targetPrice, publicBoundMinor: bound };
703
+ }
704
+ function factsForWithSku(product, quantity, policy, floor, now) {
705
+ const listPrice = floor !== undefined && product.price < floor ? undefined : product.price;
706
+ const stockAvailable = product.stock === undefined
707
+ ? undefined
708
+ : quantity !== undefined
709
+ ? product.stock >= quantity
710
+ : product.stock > 0;
711
+ const delivery = resolveDeliveryBefore(policy, now);
712
+ return {
713
+ ...(listPrice !== undefined ? { listPrice, currency: product.currency } : {}),
714
+ ...(stockAvailable !== undefined ? { stockAvailable } : {}),
715
+ ...(delivery !== undefined ? { deliveryBefore: delivery } : {}),
716
+ ...(product.tax_included !== undefined ? { taxIncluded: product.tax_included } : {}),
717
+ ...(product.shipping_included !== undefined
718
+ ? { shippingIncluded: product.shipping_included }
719
+ : {}),
720
+ };
721
+ }
722
+ //# sourceMappingURL=engine.js.map