@harrylabsj/kiwi 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.
- package/dist/a2a/node.js +225 -7
- package/dist/a2a/node.js.map +1 -1
- package/dist/a2a/reception/agent-runtime.d.ts +89 -0
- package/dist/a2a/reception/agent-runtime.js +809 -0
- package/dist/a2a/reception/agent-runtime.js.map +1 -0
- package/dist/a2a/reception/budget.d.ts +51 -0
- package/dist/a2a/reception/budget.js +101 -0
- package/dist/a2a/reception/budget.js.map +1 -0
- package/dist/a2a/reception/config.d.ts +37 -0
- package/dist/a2a/reception/config.js +50 -0
- package/dist/a2a/reception/config.js.map +1 -0
- package/dist/a2a/reception/conversation-store.d.ts +36 -0
- package/dist/a2a/reception/conversation-store.js +110 -0
- package/dist/a2a/reception/conversation-store.js.map +1 -0
- package/dist/a2a/reception/engine.d.ts +148 -0
- package/dist/a2a/reception/engine.js +702 -0
- package/dist/a2a/reception/engine.js.map +1 -0
- package/dist/a2a/reception/probe.d.ts +44 -0
- package/dist/a2a/reception/probe.js +110 -0
- package/dist/a2a/reception/probe.js.map +1 -0
- package/dist/a2a/reception/publish.d.ts +42 -0
- package/dist/a2a/reception/publish.js +254 -0
- package/dist/a2a/reception/publish.js.map +1 -0
- package/dist/a2a/reception/reply-outbox.d.ts +53 -0
- package/dist/a2a/reception/reply-outbox.js +73 -0
- package/dist/a2a/reception/reply-outbox.js.map +1 -0
- package/dist/a2a/reception/responder.d.ts +12 -0
- package/dist/a2a/reception/responder.js +56 -0
- package/dist/a2a/reception/responder.js.map +1 -0
- package/dist/a2a/reception/retention.d.ts +22 -0
- package/dist/a2a/reception/retention.js +40 -0
- package/dist/a2a/reception/retention.js.map +1 -0
- package/dist/a2a/reception/types.d.ts +130 -0
- package/dist/a2a/reception/types.js +10 -0
- package/dist/a2a/reception/types.js.map +1 -0
- package/dist/a2a/server/generic-responder.d.ts +5 -1
- package/dist/a2a/server/generic-responder.js.map +1 -1
- package/dist/a2a/server/inquiry-interpreter.d.ts +69 -0
- package/dist/a2a/server/inquiry-interpreter.js +171 -0
- package/dist/a2a/server/inquiry-interpreter.js.map +1 -0
- package/dist/a2a/server/merchant-handler.d.ts +31 -0
- package/dist/a2a/server/merchant-handler.js +257 -46
- package/dist/a2a/server/merchant-handler.js.map +1 -1
- package/dist/a2a/server/negotiation-advisor.d.ts +17 -0
- package/dist/a2a/server/negotiation-advisor.js +38 -5
- package/dist/a2a/server/negotiation-advisor.js.map +1 -1
- package/dist/a2a/server/negotiation-approvals.d.ts +10 -0
- package/dist/a2a/server/negotiation-approvals.js +46 -0
- package/dist/a2a/server/negotiation-approvals.js.map +1 -1
- package/dist/a2a/server/pipeline.d.ts +1 -1
- package/dist/a2a/server/pipeline.js +10 -2
- package/dist/a2a/server/pipeline.js.map +1 -1
- package/dist/a2a/server/server.js +1 -1
- package/dist/a2a/server/server.js.map +1 -1
- package/dist/a2a/server/types.d.ts +2 -0
- package/dist/a2a/unit-alias.d.ts +79 -0
- package/dist/a2a/unit-alias.js +163 -0
- package/dist/a2a/unit-alias.js.map +1 -0
- package/dist/buyer-core/a2a-quote-fetcher.d.ts +6 -0
- package/dist/buyer-core/a2a-quote-fetcher.js +100 -8
- package/dist/buyer-core/a2a-quote-fetcher.js.map +1 -1
- package/dist/buyer-core/build-service.d.ts +6 -0
- package/dist/buyer-core/build-service.js +12 -1
- package/dist/buyer-core/build-service.js.map +1 -1
- package/dist/buyer-core/merchant-index.js +176 -23
- package/dist/buyer-core/merchant-index.js.map +1 -1
- package/dist/buyer-core/protocol-recovery.d.ts +7 -0
- package/dist/buyer-core/protocol-recovery.js +17 -0
- package/dist/buyer-core/protocol-recovery.js.map +1 -1
- package/dist/cloud/bootstrap.js +4 -0
- package/dist/cloud/bootstrap.js.map +1 -1
- package/dist/cloud/http-router.d.ts +3 -0
- package/dist/cloud/http-router.js +55 -0
- package/dist/cloud/http-router.js.map +1 -1
- package/dist/config/profile.d.ts +5 -0
- package/dist/config/profile.js +38 -2
- package/dist/config/profile.js.map +1 -1
- package/dist/http/merchant-management/page.js +226 -52
- package/dist/http/merchant-management/page.js.map +1 -1
- package/dist/mcp/merchant-ops-server.d.ts +29 -0
- package/dist/mcp/merchant-ops-server.js +17 -0
- package/dist/mcp/merchant-ops-server.js.map +1 -1
- package/dist/mcp/merchant-runtime-assembly.d.ts +7 -0
- package/dist/mcp/merchant-runtime-assembly.js +77 -0
- package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
- package/dist/mcp/merchant-server.d.ts +10 -0
- package/dist/mcp/merchant-server.js +24 -9
- package/dist/mcp/merchant-server.js.map +1 -1
- package/dist/merchant/ai-runtime/sqlite-budget-store.d.ts +5 -0
- package/dist/merchant/ai-runtime/sqlite-budget-store.js +20 -0
- package/dist/merchant/ai-runtime/sqlite-budget-store.js.map +1 -1
- package/dist/merchant/negotiation-ops.js +5 -0
- package/dist/merchant/negotiation-ops.js.map +1 -1
- package/dist/merchant/watch/detect.js +10 -7
- package/dist/merchant/watch/detect.js.map +1 -1
- package/dist/merchant-admin/pending-page.d.ts +4 -1
- package/dist/merchant-admin/pending-page.js +2 -1
- package/dist/merchant-admin/pending-page.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,809 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 接待 Pi 运行时(M2):受控工具循环。
|
|
3
|
+
*
|
|
4
|
+
* 模型只通过四个工具工作:
|
|
5
|
+
* search_products → 本店公开候选
|
|
6
|
+
* get_commercial_facts → 服务端事实快照引用(价格/库存/交期)
|
|
7
|
+
* propose_need_patch → 本轮需求增量(待服务端合并)
|
|
8
|
+
* propose_reply → 类型化回复计划(终态)
|
|
9
|
+
*
|
|
10
|
+
* 红线:
|
|
11
|
+
* - 模型拿不到价格/交期字面值以外的写能力;所有金额经 fact ref 由发布器渲染;
|
|
12
|
+
* - 工具参数与模型输出都按不可信处理;schema 之外直接拒绝;
|
|
13
|
+
* - propose_reply 之后不再接受工具调用;超时/异常返回 undefined,调用方回退
|
|
14
|
+
* 确定性接待路径。
|
|
15
|
+
*/
|
|
16
|
+
import { Agent, } from "@earendil-works/pi-agent-core";
|
|
17
|
+
import { canonicalUnitToken, multiplyQuantitySafe, resolveUnitConversion, unitConversionPolicy, } from "../unit-alias.js";
|
|
18
|
+
import { factRevision } from "./publish.js";
|
|
19
|
+
export const TOOL_SEARCH_PRODUCTS = "search_products";
|
|
20
|
+
export const TOOL_COMPARE_PRODUCTS = "compare_products";
|
|
21
|
+
export const TOOL_GET_COMMERCIAL_FACTS = "get_commercial_facts";
|
|
22
|
+
export const TOOL_PROPOSE_NEED_PATCH = "propose_need_patch";
|
|
23
|
+
export const TOOL_PROPOSE_REPLY = "propose_reply";
|
|
24
|
+
const RECEPTION_TOOL_ALLOWLIST = [
|
|
25
|
+
TOOL_SEARCH_PRODUCTS,
|
|
26
|
+
TOOL_COMPARE_PRODUCTS,
|
|
27
|
+
TOOL_GET_COMMERCIAL_FACTS,
|
|
28
|
+
TOOL_PROPOSE_NEED_PATCH,
|
|
29
|
+
TOOL_PROPOSE_REPLY,
|
|
30
|
+
];
|
|
31
|
+
const BLOCK_KINDS = new Set([
|
|
32
|
+
"acknowledge_need",
|
|
33
|
+
"ask_clarification",
|
|
34
|
+
"show_commercial_terms",
|
|
35
|
+
"recommend_option",
|
|
36
|
+
"request_human_help",
|
|
37
|
+
"next_step",
|
|
38
|
+
]);
|
|
39
|
+
const DEFAULT_SYSTEM_PROMPT = [
|
|
40
|
+
"You are a Kiwi merchant reception agent serving one buyer at a time.",
|
|
41
|
+
"Reply in Simplified Chinese (zh-CN) only. One product per conversation.",
|
|
42
|
+
"Use search_products when the buyer has not named a SKU.",
|
|
43
|
+
"Call get_commercial_facts for the chosen SKU and quantity. Never invent a price,",
|
|
44
|
+
"stock count, delivery date or any commercial fact; only the facts tool is authoritative.",
|
|
45
|
+
"When the request is ambiguous or a required field is missing, ask one short",
|
|
46
|
+
"clarification question. When ready, call propose_reply with typed blocks:",
|
|
47
|
+
"acknowledge_need, ask_clarification, show_commercial_terms (using the fact ref),",
|
|
48
|
+
"request_human_help or next_step. You may use recommend_option with a fact ref and",
|
|
49
|
+
"compared refs from compare_products; reasonCode must be lowest_public_price or in_stock.",
|
|
50
|
+
"Never write free-form commercial text.",
|
|
51
|
+
].join(" ");
|
|
52
|
+
function toolResult(text, details = {}) {
|
|
53
|
+
return { content: [{ type: "text", text }], details };
|
|
54
|
+
}
|
|
55
|
+
const BUYER_QUANTITY_UNIT = "盒|件|个|只|箱|瓶|包|袋|台|套|双|张|份|piece(?:s)?|box(?:es)?|pcs?|units?";
|
|
56
|
+
const BUYER_CN_DIGITS = {
|
|
57
|
+
一: 1,
|
|
58
|
+
二: 2,
|
|
59
|
+
两: 2,
|
|
60
|
+
三: 3,
|
|
61
|
+
四: 4,
|
|
62
|
+
五: 5,
|
|
63
|
+
六: 6,
|
|
64
|
+
七: 7,
|
|
65
|
+
八: 8,
|
|
66
|
+
九: 9,
|
|
67
|
+
};
|
|
68
|
+
function buyerChineseNumber(raw) {
|
|
69
|
+
if (raw === "十")
|
|
70
|
+
return 10;
|
|
71
|
+
if (raw.includes("十")) {
|
|
72
|
+
const [tensRaw, onesRaw] = raw.split("十");
|
|
73
|
+
const tens = tensRaw === "" ? 1 : BUYER_CN_DIGITS[tensRaw ?? ""];
|
|
74
|
+
const ones = onesRaw === "" ? 0 : BUYER_CN_DIGITS[onesRaw ?? ""];
|
|
75
|
+
if (tens === undefined || ones === undefined)
|
|
76
|
+
return undefined;
|
|
77
|
+
return tens * 10 + ones;
|
|
78
|
+
}
|
|
79
|
+
return BUYER_CN_DIGITS[raw];
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Server-side buyer quantity/unit extraction. The model may not shrink a
|
|
83
|
+
* requested quantity for a stock claim; compare_products/get_commercial_facts
|
|
84
|
+
* only bind stock to this independently parsed value.
|
|
85
|
+
*/
|
|
86
|
+
export function parseBuyerQuantity(text) {
|
|
87
|
+
const candidates = [];
|
|
88
|
+
const chinesePattern = new RegExp(`([一二两三四五六七八九十]+)\\s*(${BUYER_QUANTITY_UNIT})`, "gu");
|
|
89
|
+
for (const match of text.matchAll(chinesePattern)) {
|
|
90
|
+
const prefix = text.slice(Math.max(0, (match.index ?? 0) - 4), match.index ?? 0);
|
|
91
|
+
const quantity = buyerChineseNumber(match[1] ?? "");
|
|
92
|
+
if (quantity !== undefined && quantity > 0) {
|
|
93
|
+
// Keep price-context candidates for the ambiguity check below, but do
|
|
94
|
+
// not let them become the sole quantity when no other candidate exists.
|
|
95
|
+
candidates.push({
|
|
96
|
+
quantity,
|
|
97
|
+
unit: match[2] ?? "",
|
|
98
|
+
priceContext: /[\d¥¥元块]/.test(prefix),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const arabicPattern = new RegExp(`(?:^|[^\\d])(\\d+)\\s*(${BUYER_QUANTITY_UNIT})`, "giu");
|
|
103
|
+
for (const match of text.matchAll(arabicPattern)) {
|
|
104
|
+
const quantity = Number(match[1]);
|
|
105
|
+
if (Number.isSafeInteger(quantity) && quantity > 0) {
|
|
106
|
+
candidates.push({ quantity, unit: match[2] ?? "", priceContext: false });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const distinct = new Map();
|
|
110
|
+
for (const item of candidates) {
|
|
111
|
+
const key = `${item.quantity}:${canonicalUnitToken(item.unit)}`;
|
|
112
|
+
const existing = distinct.get(key);
|
|
113
|
+
distinct.set(key, {
|
|
114
|
+
quantity: item.quantity,
|
|
115
|
+
unit: item.unit,
|
|
116
|
+
priceContext: existing === undefined ? item.priceContext : existing.priceContext && item.priceContext,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
// Ambiguity is checked over ALL candidate expressions, including ones that
|
|
120
|
+
// looked like price context. "原先1件要十件" must not silently bind to 1.
|
|
121
|
+
if (distinct.size !== 1)
|
|
122
|
+
return undefined;
|
|
123
|
+
const only = [...distinct.values()][0];
|
|
124
|
+
return only.priceContext ? undefined : { quantity: only.quantity, unit: only.unit };
|
|
125
|
+
}
|
|
126
|
+
function buyerUnitMatchesPolicy(policy, buyerUnit, requestedUnit) {
|
|
127
|
+
const buyer = canonicalUnitToken(buyerUnit);
|
|
128
|
+
const requested = canonicalUnitToken(requestedUnit);
|
|
129
|
+
return (buyer === requested ||
|
|
130
|
+
policy.aliases[buyer] === requested ||
|
|
131
|
+
policy.aliases[requested] === buyer);
|
|
132
|
+
}
|
|
133
|
+
function isObject(value) {
|
|
134
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
135
|
+
}
|
|
136
|
+
/** 把模型提交的 blocks 限缩到白名单结构;引用仍由发布器校验。 */
|
|
137
|
+
export function sanitizeReceptionBlocks(value) {
|
|
138
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > 6)
|
|
139
|
+
return undefined;
|
|
140
|
+
const blocks = [];
|
|
141
|
+
for (const item of value) {
|
|
142
|
+
if (!isObject(item) || typeof item.kind !== "string" || !BLOCK_KINDS.has(item.kind)) {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
switch (item.kind) {
|
|
146
|
+
case "acknowledge_need": {
|
|
147
|
+
const sku = typeof item.sku === "string" && item.sku.trim() !== "" ? item.sku.trim() : undefined;
|
|
148
|
+
const quantity = typeof item.quantity === "number" && Number.isSafeInteger(item.quantity) && item.quantity > 0
|
|
149
|
+
? item.quantity
|
|
150
|
+
: undefined;
|
|
151
|
+
const unit = typeof item.unit === "string" && item.unit.trim() !== "" ? item.unit.trim() : undefined;
|
|
152
|
+
blocks.push({
|
|
153
|
+
kind: "acknowledge_need",
|
|
154
|
+
...(sku !== undefined ? { sku } : {}),
|
|
155
|
+
...(quantity !== undefined ? { quantity } : {}),
|
|
156
|
+
...(unit !== undefined ? { unit } : {}),
|
|
157
|
+
});
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
case "ask_clarification": {
|
|
161
|
+
const reason = item.reason;
|
|
162
|
+
if (reason !== "missing_sku" &&
|
|
163
|
+
reason !== "unknown_sku" &&
|
|
164
|
+
reason !== "non_chinese" &&
|
|
165
|
+
reason !== "empty_message" &&
|
|
166
|
+
reason !== "service_busy" &&
|
|
167
|
+
reason !== "multiple_skus" &&
|
|
168
|
+
reason !== "product_candidates") {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
const candidates = Array.isArray(item.candidates)
|
|
172
|
+
? item.candidates.filter((candidate) => typeof candidate === "string").slice(0, 8)
|
|
173
|
+
: undefined;
|
|
174
|
+
blocks.push({
|
|
175
|
+
kind: "ask_clarification",
|
|
176
|
+
missing: ["sku"],
|
|
177
|
+
reason,
|
|
178
|
+
...(candidates !== undefined ? { candidates } : {}),
|
|
179
|
+
});
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
case "show_commercial_terms": {
|
|
183
|
+
const ref = item.ref;
|
|
184
|
+
if (!isObject(ref) ||
|
|
185
|
+
typeof ref.sku !== "string" ||
|
|
186
|
+
typeof ref.revision !== "string") {
|
|
187
|
+
return undefined;
|
|
188
|
+
}
|
|
189
|
+
const topics = Array.isArray(item.topics)
|
|
190
|
+
? item.topics.filter((topic) => topic === "price" || topic === "stock" || topic === "delivery")
|
|
191
|
+
: undefined;
|
|
192
|
+
blocks.push({
|
|
193
|
+
kind: "show_commercial_terms",
|
|
194
|
+
ref: { sku: ref.sku, revision: ref.revision },
|
|
195
|
+
...(topics !== undefined && topics.length > 0 ? { topics } : {}),
|
|
196
|
+
});
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
case "recommend_option": {
|
|
200
|
+
const ref = item.ref;
|
|
201
|
+
if (!isObject(ref) || typeof ref.sku !== "string" || typeof ref.revision !== "string") {
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
const comparedRefs = Array.isArray(item.comparedRefs)
|
|
205
|
+
? item.comparedRefs
|
|
206
|
+
.filter((candidate) => isObject(candidate) &&
|
|
207
|
+
typeof candidate.sku === "string" &&
|
|
208
|
+
typeof candidate.revision === "string")
|
|
209
|
+
.slice(0, 3)
|
|
210
|
+
: undefined;
|
|
211
|
+
const reasonCode = item.reasonCode;
|
|
212
|
+
if (reasonCode !== "lowest_public_price" && reasonCode !== "in_stock") {
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
blocks.push({
|
|
216
|
+
kind: "recommend_option",
|
|
217
|
+
ref: { sku: ref.sku, revision: ref.revision },
|
|
218
|
+
...(comparedRefs !== undefined && comparedRefs.length > 0 ? { comparedRefs } : {}),
|
|
219
|
+
reasonCode,
|
|
220
|
+
});
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
case "request_human_help": {
|
|
224
|
+
if (item.topic !== "price_below_public_bound")
|
|
225
|
+
return undefined;
|
|
226
|
+
const buyerTargetPrice = typeof item.buyerTargetPrice === "number" && Number.isFinite(item.buyerTargetPrice)
|
|
227
|
+
? item.buyerTargetPrice
|
|
228
|
+
: undefined;
|
|
229
|
+
const currency = typeof item.currency === "string" ? item.currency : undefined;
|
|
230
|
+
blocks.push({
|
|
231
|
+
kind: "request_human_help",
|
|
232
|
+
topic: "price_below_public_bound",
|
|
233
|
+
...(buyerTargetPrice !== undefined ? { buyerTargetPrice } : {}),
|
|
234
|
+
...(currency !== undefined ? { currency } : {}),
|
|
235
|
+
});
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
case "next_step": {
|
|
239
|
+
if (item.action !== "send_rfq")
|
|
240
|
+
return undefined;
|
|
241
|
+
blocks.push({ kind: "next_step", action: "send_rfq" });
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return blocks;
|
|
247
|
+
}
|
|
248
|
+
function policyFloorMinor(policy, sku) {
|
|
249
|
+
const floor = policy?.price_floors?.[sku] ?? policy?.min_unit_price_private;
|
|
250
|
+
if (typeof floor !== "number" || !Number.isFinite(floor))
|
|
251
|
+
return undefined;
|
|
252
|
+
return Math.round(floor * 100);
|
|
253
|
+
}
|
|
254
|
+
function deliveryBefore(policy, now) {
|
|
255
|
+
const days = policy?.delivery_lead_days;
|
|
256
|
+
if (days === undefined || !Number.isFinite(days) || days <= 0)
|
|
257
|
+
return undefined;
|
|
258
|
+
const base = Date.parse(now);
|
|
259
|
+
if (!Number.isFinite(base))
|
|
260
|
+
return undefined;
|
|
261
|
+
return new Date(base + days * 86_400_000).toISOString();
|
|
262
|
+
}
|
|
263
|
+
export function createPiReceptionRuntime(options) {
|
|
264
|
+
const unitPolicy = unitConversionPolicy({
|
|
265
|
+
aliases: options.unitAliases,
|
|
266
|
+
packageFactors: options.unitPackageFactors,
|
|
267
|
+
...(options.unitDefaultUnit !== undefined ? { defaultUnit: options.unitDefaultUnit } : {}),
|
|
268
|
+
});
|
|
269
|
+
return {
|
|
270
|
+
async run(input) {
|
|
271
|
+
const policy = options.policy?.();
|
|
272
|
+
let plan;
|
|
273
|
+
let needPatch = {};
|
|
274
|
+
const factUnits = new Map();
|
|
275
|
+
const rejectedFactUnits = new Map();
|
|
276
|
+
const buyerQuantity = parseBuyerQuantity(input.text);
|
|
277
|
+
let steps = 0;
|
|
278
|
+
let toolAttempts = 0;
|
|
279
|
+
let timedOut = false;
|
|
280
|
+
const guard = async (context) => {
|
|
281
|
+
if (!RECEPTION_TOOL_ALLOWLIST.includes(context.toolCall.name)) {
|
|
282
|
+
return { block: true, reason: "tool_not_allowed" };
|
|
283
|
+
}
|
|
284
|
+
if (plan !== undefined) {
|
|
285
|
+
return { block: true, reason: "reply_already_proposed" };
|
|
286
|
+
}
|
|
287
|
+
toolAttempts += 1;
|
|
288
|
+
if (toolAttempts > (options.maxToolAttempts ?? 12)) {
|
|
289
|
+
return { block: true, reason: "tool_budget_exhausted" };
|
|
290
|
+
}
|
|
291
|
+
const serialized = JSON.stringify(context.toolCall.arguments ?? {});
|
|
292
|
+
if (serialized.length > 8_000) {
|
|
293
|
+
return { block: true, reason: "arguments_too_large" };
|
|
294
|
+
}
|
|
295
|
+
return undefined;
|
|
296
|
+
};
|
|
297
|
+
const tools = [
|
|
298
|
+
{
|
|
299
|
+
name: TOOL_SEARCH_PRODUCTS,
|
|
300
|
+
label: "Search products",
|
|
301
|
+
description: "Search this merchant's public products by the buyer's words.",
|
|
302
|
+
parameters: {
|
|
303
|
+
type: "object",
|
|
304
|
+
additionalProperties: false,
|
|
305
|
+
properties: { query: { type: "string" } },
|
|
306
|
+
required: ["query"],
|
|
307
|
+
},
|
|
308
|
+
execute: async (_id, params) => {
|
|
309
|
+
const args = params;
|
|
310
|
+
const query = isObject(args) && typeof args.query === "string" ? args.query : "";
|
|
311
|
+
if (options.productSource?.searchProducts === undefined) {
|
|
312
|
+
return toolResult(JSON.stringify({ candidates: [], note: "search_not_configured" }));
|
|
313
|
+
}
|
|
314
|
+
const candidates = await options.productSource.searchProducts(query).catch(() => []);
|
|
315
|
+
return toolResult(JSON.stringify({
|
|
316
|
+
candidates: candidates.slice(0, 5).map((candidate) => ({
|
|
317
|
+
sku: candidate.sku,
|
|
318
|
+
...(candidate.title !== undefined ? { title: candidate.title } : {}),
|
|
319
|
+
price: candidate.price,
|
|
320
|
+
currency: candidate.currency,
|
|
321
|
+
...(candidate.stock !== undefined ? { stock: candidate.stock } : {}),
|
|
322
|
+
})),
|
|
323
|
+
}));
|
|
324
|
+
},
|
|
325
|
+
},
|
|
326
|
+
{
|
|
327
|
+
name: TOOL_COMPARE_PRODUCTS,
|
|
328
|
+
label: "Compare products",
|
|
329
|
+
description: "Read public price, stock and delivery facts for up to three SKUs so you can compare them.",
|
|
330
|
+
parameters: {
|
|
331
|
+
type: "object",
|
|
332
|
+
additionalProperties: false,
|
|
333
|
+
properties: {
|
|
334
|
+
skus: { type: "array" },
|
|
335
|
+
quantity: { type: "integer", minimum: 1 },
|
|
336
|
+
unit: { type: "string" },
|
|
337
|
+
},
|
|
338
|
+
required: ["skus"],
|
|
339
|
+
},
|
|
340
|
+
execute: async (_id, params) => {
|
|
341
|
+
const args = params;
|
|
342
|
+
const rawSkus = isObject(args) && Array.isArray(args.skus) ? args.skus : [];
|
|
343
|
+
const skus = rawSkus
|
|
344
|
+
.filter((sku) => typeof sku === "string")
|
|
345
|
+
.map((sku) => sku.trim())
|
|
346
|
+
.filter((sku) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(sku))
|
|
347
|
+
.slice(0, 3);
|
|
348
|
+
if (skus.length === 0 || options.productSource === undefined) {
|
|
349
|
+
return toolResult(JSON.stringify({ products: [] }));
|
|
350
|
+
}
|
|
351
|
+
const requestedQuantity = isObject(args) &&
|
|
352
|
+
typeof args.quantity === "number" &&
|
|
353
|
+
Number.isSafeInteger(args.quantity) &&
|
|
354
|
+
args.quantity > 0
|
|
355
|
+
? args.quantity
|
|
356
|
+
: undefined;
|
|
357
|
+
const requestedUnit = isObject(args) && typeof args.unit === "string" && args.unit.trim() !== ""
|
|
358
|
+
? args.unit.trim()
|
|
359
|
+
: undefined;
|
|
360
|
+
const products = [];
|
|
361
|
+
for (const sku of skus) {
|
|
362
|
+
try {
|
|
363
|
+
const product = await options.productSource.getProduct(sku);
|
|
364
|
+
if (product.valid_until !== undefined) {
|
|
365
|
+
const until = Date.parse(product.valid_until);
|
|
366
|
+
if (!Number.isFinite(until) || until <= Date.parse(input.now)) {
|
|
367
|
+
products.push({ sku, error: "facts_stale" });
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
const floorMinor = policyFloorMinor(policy, sku);
|
|
372
|
+
const listPrice = floorMinor !== undefined && Math.round(product.price * 100) < floorMinor
|
|
373
|
+
? undefined
|
|
374
|
+
: product.price;
|
|
375
|
+
let unit = product.unit;
|
|
376
|
+
let stockQuantity = requestedQuantity;
|
|
377
|
+
if (product.unit !== undefined && requestedUnit !== undefined) {
|
|
378
|
+
const resolution = resolveUnitConversion(unitPolicy, product.unit, requestedUnit);
|
|
379
|
+
if (resolution.kind === "factor") {
|
|
380
|
+
stockQuantity =
|
|
381
|
+
requestedQuantity === undefined
|
|
382
|
+
? undefined
|
|
383
|
+
: multiplyQuantitySafe(requestedQuantity, resolution.factor);
|
|
384
|
+
unit = product.unit;
|
|
385
|
+
}
|
|
386
|
+
else if (resolution.kind === "identity" || resolution.kind === "alias") {
|
|
387
|
+
unit = product.unit;
|
|
388
|
+
}
|
|
389
|
+
else {
|
|
390
|
+
products.push({ sku, error: "unit_mismatch", supported_unit: product.unit });
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
const buyerBound = requestedQuantity !== undefined &&
|
|
395
|
+
requestedUnit !== undefined &&
|
|
396
|
+
buyerQuantity !== undefined &&
|
|
397
|
+
buyerQuantity.quantity === requestedQuantity &&
|
|
398
|
+
buyerUnitMatchesPolicy(unitPolicy, buyerQuantity.unit, requestedUnit);
|
|
399
|
+
const stockAvailable = buyerBound &&
|
|
400
|
+
product.stock !== undefined &&
|
|
401
|
+
product.unit !== undefined &&
|
|
402
|
+
stockQuantity !== undefined
|
|
403
|
+
? product.stock >= stockQuantity
|
|
404
|
+
: undefined;
|
|
405
|
+
const delivery = deliveryBefore(policy, input.now);
|
|
406
|
+
const facts = {
|
|
407
|
+
...(listPrice !== undefined
|
|
408
|
+
? { listPrice, currency: product.currency }
|
|
409
|
+
: {}),
|
|
410
|
+
...(unit !== undefined ? { unit } : {}),
|
|
411
|
+
...(stockAvailable !== undefined ? { stockAvailable } : {}),
|
|
412
|
+
...(delivery !== undefined ? { deliveryBefore: delivery } : {}),
|
|
413
|
+
...(product.tax_included !== undefined
|
|
414
|
+
? { taxIncluded: product.tax_included }
|
|
415
|
+
: {}),
|
|
416
|
+
...(product.shipping_included !== undefined
|
|
417
|
+
? { shippingIncluded: product.shipping_included }
|
|
418
|
+
: {}),
|
|
419
|
+
};
|
|
420
|
+
const base = {
|
|
421
|
+
merchantId: input.merchantId,
|
|
422
|
+
sku,
|
|
423
|
+
visibility: "public",
|
|
424
|
+
issuedAt: input.now,
|
|
425
|
+
...(product.valid_until !== undefined ? { expiresAt: product.valid_until } : {}),
|
|
426
|
+
facts,
|
|
427
|
+
};
|
|
428
|
+
const ref = input.registry.register({
|
|
429
|
+
...base,
|
|
430
|
+
revision: factRevision(base),
|
|
431
|
+
});
|
|
432
|
+
products.push({
|
|
433
|
+
sku,
|
|
434
|
+
ref,
|
|
435
|
+
...(listPrice !== undefined
|
|
436
|
+
? { listPrice, currency: product.currency }
|
|
437
|
+
: {}),
|
|
438
|
+
...(product.stock !== undefined ? { stock: product.stock } : {}),
|
|
439
|
+
...(product.unit !== undefined ? { unit: product.unit } : {}),
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
products.push({ sku, error: "unknown_sku" });
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return toolResult(JSON.stringify({ products }));
|
|
447
|
+
},
|
|
448
|
+
},
|
|
449
|
+
{
|
|
450
|
+
name: TOOL_GET_COMMERCIAL_FACTS,
|
|
451
|
+
label: "Get commercial facts",
|
|
452
|
+
description: "Read the authoritative price, stock and delivery facts for one SKU and quantity.",
|
|
453
|
+
parameters: {
|
|
454
|
+
type: "object",
|
|
455
|
+
additionalProperties: false,
|
|
456
|
+
properties: {
|
|
457
|
+
sku: { type: "string" },
|
|
458
|
+
quantity: { type: "integer", minimum: 1 },
|
|
459
|
+
unit: { type: "string" },
|
|
460
|
+
},
|
|
461
|
+
required: ["sku"],
|
|
462
|
+
},
|
|
463
|
+
execute: async (_id, params) => {
|
|
464
|
+
const args = params;
|
|
465
|
+
const sku = isObject(args) && typeof args.sku === "string" ? args.sku.trim() : "";
|
|
466
|
+
const quantity = isObject(args) &&
|
|
467
|
+
typeof args.quantity === "number" &&
|
|
468
|
+
Number.isSafeInteger(args.quantity) &&
|
|
469
|
+
args.quantity > 0
|
|
470
|
+
? args.quantity
|
|
471
|
+
: undefined;
|
|
472
|
+
const requestedUnit = isObject(args) && typeof args.unit === "string" && args.unit.trim() !== ""
|
|
473
|
+
? args.unit.trim()
|
|
474
|
+
: undefined;
|
|
475
|
+
if (sku === "" || options.productSource === undefined) {
|
|
476
|
+
return toolResult(JSON.stringify({ error: "unknown_sku" }));
|
|
477
|
+
}
|
|
478
|
+
let product;
|
|
479
|
+
try {
|
|
480
|
+
product = await options.productSource.getProduct(sku);
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
return toolResult(JSON.stringify({ error: "unknown_sku" }));
|
|
484
|
+
}
|
|
485
|
+
// AC13:过期事实不得进入回复或审批。
|
|
486
|
+
if (product.valid_until !== undefined) {
|
|
487
|
+
const until = Date.parse(product.valid_until);
|
|
488
|
+
if (!Number.isFinite(until) || until <= Date.parse(input.now)) {
|
|
489
|
+
return toolResult(JSON.stringify({ error: "facts_stale" }));
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
// AC06:商品源单位与请求同义时始终 1:1;包装倍率只对 default_unit
|
|
493
|
+
// 目标生效,其他情况或别名冲突一律安全拒绝,不猜倍率。
|
|
494
|
+
// Unit facts are source-unit provenance: a model-supplied spelling
|
|
495
|
+
// is not merchant/source evidence when the product has no unit.
|
|
496
|
+
let unit = product.unit;
|
|
497
|
+
let effectiveQuantity = quantity;
|
|
498
|
+
let factFactor;
|
|
499
|
+
if (product.unit !== undefined && requestedUnit !== undefined) {
|
|
500
|
+
const resolution = resolveUnitConversion(unitPolicy, product.unit, requestedUnit);
|
|
501
|
+
if (resolution.kind === "factor") {
|
|
502
|
+
if (quantity === undefined) {
|
|
503
|
+
rejectedFactUnits.set(sku, { inputUnit: requestedUnit });
|
|
504
|
+
return toolResult(JSON.stringify({ error: "missing_quantity" }));
|
|
505
|
+
}
|
|
506
|
+
const convertedQuantity = multiplyQuantitySafe(quantity, resolution.factor);
|
|
507
|
+
if (convertedQuantity === undefined) {
|
|
508
|
+
rejectedFactUnits.set(sku, { inputQuantity: quantity, inputUnit: requestedUnit });
|
|
509
|
+
return toolResult(JSON.stringify({ error: "quantity_overflow" }));
|
|
510
|
+
}
|
|
511
|
+
effectiveQuantity = convertedQuantity;
|
|
512
|
+
unit = product.unit;
|
|
513
|
+
factFactor = resolution.factor;
|
|
514
|
+
}
|
|
515
|
+
else if (resolution.kind === "identity" || resolution.kind === "alias") {
|
|
516
|
+
unit = product.unit;
|
|
517
|
+
}
|
|
518
|
+
else {
|
|
519
|
+
rejectedFactUnits.set(sku, { inputQuantity: quantity, inputUnit: requestedUnit });
|
|
520
|
+
return toolResult(JSON.stringify({
|
|
521
|
+
error: "unit_mismatch",
|
|
522
|
+
supported_unit: product.unit,
|
|
523
|
+
}));
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
if (factFactor !== undefined && effectiveQuantity !== undefined && unit !== undefined &&
|
|
527
|
+
quantity !== undefined && requestedUnit !== undefined) {
|
|
528
|
+
factUnits.set(sku, {
|
|
529
|
+
inputQuantity: quantity,
|
|
530
|
+
inputUnit: requestedUnit,
|
|
531
|
+
quantity: effectiveQuantity,
|
|
532
|
+
unit,
|
|
533
|
+
factor: factFactor,
|
|
534
|
+
});
|
|
535
|
+
rejectedFactUnits.delete(sku);
|
|
536
|
+
}
|
|
537
|
+
else if (effectiveQuantity !== undefined || unit !== undefined) {
|
|
538
|
+
factUnits.set(sku, {
|
|
539
|
+
...(effectiveQuantity !== undefined ? { quantity: effectiveQuantity } : {}),
|
|
540
|
+
...(unit !== undefined ? { unit } : {}),
|
|
541
|
+
});
|
|
542
|
+
rejectedFactUnits.delete(sku);
|
|
543
|
+
}
|
|
544
|
+
const floorMinor = policyFloorMinor(policy, sku);
|
|
545
|
+
const listPrice = floorMinor !== undefined && Math.round(product.price * 100) < floorMinor
|
|
546
|
+
? undefined
|
|
547
|
+
: product.price;
|
|
548
|
+
const stockBound = quantity !== undefined &&
|
|
549
|
+
requestedUnit !== undefined &&
|
|
550
|
+
buyerQuantity !== undefined &&
|
|
551
|
+
buyerQuantity.quantity === quantity &&
|
|
552
|
+
buyerUnitMatchesPolicy(unitPolicy, buyerQuantity.unit, requestedUnit);
|
|
553
|
+
const stockAvailable = stockBound &&
|
|
554
|
+
product.stock !== undefined &&
|
|
555
|
+
product.unit !== undefined &&
|
|
556
|
+
effectiveQuantity !== undefined
|
|
557
|
+
? product.stock >= effectiveQuantity
|
|
558
|
+
: undefined;
|
|
559
|
+
const delivery = deliveryBefore(policy, input.now);
|
|
560
|
+
const facts = {
|
|
561
|
+
...(listPrice !== undefined
|
|
562
|
+
? { listPrice, currency: product.currency }
|
|
563
|
+
: {}),
|
|
564
|
+
...(unit !== undefined ? { unit } : {}),
|
|
565
|
+
...(stockAvailable !== undefined ? { stockAvailable } : {}),
|
|
566
|
+
...(delivery !== undefined ? { deliveryBefore: delivery } : {}),
|
|
567
|
+
...(product.tax_included !== undefined
|
|
568
|
+
? { taxIncluded: product.tax_included }
|
|
569
|
+
: {}),
|
|
570
|
+
...(product.shipping_included !== undefined
|
|
571
|
+
? { shippingIncluded: product.shipping_included }
|
|
572
|
+
: {}),
|
|
573
|
+
};
|
|
574
|
+
const base = {
|
|
575
|
+
merchantId: input.merchantId,
|
|
576
|
+
sku,
|
|
577
|
+
visibility: "public",
|
|
578
|
+
issuedAt: input.now,
|
|
579
|
+
facts,
|
|
580
|
+
};
|
|
581
|
+
const ref = input.registry.register({
|
|
582
|
+
...base,
|
|
583
|
+
revision: factRevision(base),
|
|
584
|
+
});
|
|
585
|
+
return toolResult(JSON.stringify({
|
|
586
|
+
ref,
|
|
587
|
+
facts,
|
|
588
|
+
...(unit !== undefined ? { unit } : product.unit !== undefined ? { unit: product.unit } : {}),
|
|
589
|
+
...(effectiveQuantity !== undefined ? { quantity: effectiveQuantity } : {}),
|
|
590
|
+
note: "Only these facts may appear in show_commercial_terms.",
|
|
591
|
+
}));
|
|
592
|
+
},
|
|
593
|
+
},
|
|
594
|
+
{
|
|
595
|
+
name: TOOL_PROPOSE_NEED_PATCH,
|
|
596
|
+
label: "Propose need patch",
|
|
597
|
+
description: "Record the product, quantity and unit the buyer has confirmed so far.",
|
|
598
|
+
parameters: {
|
|
599
|
+
type: "object",
|
|
600
|
+
additionalProperties: false,
|
|
601
|
+
properties: {
|
|
602
|
+
sku: { type: "string" },
|
|
603
|
+
quantity: { type: "integer", minimum: 1 },
|
|
604
|
+
unit: { type: "string" },
|
|
605
|
+
},
|
|
606
|
+
},
|
|
607
|
+
execute: async (_id, params) => {
|
|
608
|
+
const args = params;
|
|
609
|
+
if (!isObject(args))
|
|
610
|
+
return toolResult(JSON.stringify({ error: "invalid_patch" }));
|
|
611
|
+
const sku = typeof args.sku === "string" && args.sku.trim() !== "" ? args.sku.trim() : undefined;
|
|
612
|
+
const quantity = typeof args.quantity === "number" &&
|
|
613
|
+
Number.isSafeInteger(args.quantity) &&
|
|
614
|
+
args.quantity > 0
|
|
615
|
+
? args.quantity
|
|
616
|
+
: undefined;
|
|
617
|
+
const unit = typeof args.unit === "string" && args.unit.trim() !== "" ? args.unit.trim() : undefined;
|
|
618
|
+
const effectiveSku = sku ?? needPatch.sku;
|
|
619
|
+
const rejected = effectiveSku !== undefined ? rejectedFactUnits.get(effectiveSku) : undefined;
|
|
620
|
+
if (rejected !== undefined) {
|
|
621
|
+
return toolResult(JSON.stringify({ error: "need_patch_conflict" }));
|
|
622
|
+
}
|
|
623
|
+
const conversion = effectiveSku !== undefined ? factUnits.get(effectiveSku) : undefined;
|
|
624
|
+
if (conversion?.factor !== undefined) {
|
|
625
|
+
const inputMatches = quantity === conversion.inputQuantity &&
|
|
626
|
+
unit !== undefined &&
|
|
627
|
+
conversion.inputUnit !== undefined &&
|
|
628
|
+
canonicalUnitToken(unit) === canonicalUnitToken(conversion.inputUnit);
|
|
629
|
+
const effectiveMatches = quantity === conversion.quantity &&
|
|
630
|
+
unit !== undefined &&
|
|
631
|
+
conversion.unit !== undefined &&
|
|
632
|
+
canonicalUnitToken(unit) === canonicalUnitToken(conversion.unit);
|
|
633
|
+
const omitted = quantity === undefined && unit === undefined;
|
|
634
|
+
if (!omitted && !inputMatches && !effectiveMatches) {
|
|
635
|
+
return toolResult(JSON.stringify({ error: "need_patch_conflict" }));
|
|
636
|
+
}
|
|
637
|
+
if (conversion.quantity === undefined ||
|
|
638
|
+
conversion.unit === undefined ||
|
|
639
|
+
conversion.inputQuantity === undefined ||
|
|
640
|
+
conversion.inputUnit === undefined) {
|
|
641
|
+
return toolResult(JSON.stringify({ error: "need_patch_conflict" }));
|
|
642
|
+
}
|
|
643
|
+
needPatch = {
|
|
644
|
+
...needPatch,
|
|
645
|
+
sku: effectiveSku,
|
|
646
|
+
quantity: conversion.quantity,
|
|
647
|
+
unit: conversion.unit,
|
|
648
|
+
inputQuantity: conversion.inputQuantity,
|
|
649
|
+
inputUnit: conversion.inputUnit,
|
|
650
|
+
};
|
|
651
|
+
return toolResult(JSON.stringify({ accepted: true }));
|
|
652
|
+
}
|
|
653
|
+
needPatch = {
|
|
654
|
+
...needPatch,
|
|
655
|
+
...(effectiveSku !== undefined ? { sku: effectiveSku } : {}),
|
|
656
|
+
...(quantity !== undefined ? { quantity } : {}),
|
|
657
|
+
...(unit !== undefined ? { unit } : {}),
|
|
658
|
+
};
|
|
659
|
+
return toolResult(JSON.stringify({ accepted: true }));
|
|
660
|
+
},
|
|
661
|
+
},
|
|
662
|
+
{
|
|
663
|
+
name: TOOL_PROPOSE_REPLY,
|
|
664
|
+
label: "Propose reply",
|
|
665
|
+
description: "Submit the final typed response plan. Ends the turn.",
|
|
666
|
+
parameters: {
|
|
667
|
+
type: "object",
|
|
668
|
+
additionalProperties: false,
|
|
669
|
+
properties: {
|
|
670
|
+
blocks: { type: "array" },
|
|
671
|
+
},
|
|
672
|
+
required: ["blocks"],
|
|
673
|
+
},
|
|
674
|
+
execute: async (_id, params) => {
|
|
675
|
+
const args = params;
|
|
676
|
+
if (!isObject(args))
|
|
677
|
+
return toolResult(JSON.stringify({ accepted: false, error: "invalid_plan" }));
|
|
678
|
+
const blocks = sanitizeReceptionBlocks(args.blocks);
|
|
679
|
+
if (blocks === undefined) {
|
|
680
|
+
return toolResult(JSON.stringify({ accepted: false, error: "invalid_blocks" }));
|
|
681
|
+
}
|
|
682
|
+
const normalizedBlocks = blocks.map((block) => {
|
|
683
|
+
if (block.kind !== "acknowledge_need" ||
|
|
684
|
+
needPatch.sku === undefined ||
|
|
685
|
+
(block.sku !== undefined && block.sku !== needPatch.sku)) {
|
|
686
|
+
return block;
|
|
687
|
+
}
|
|
688
|
+
const conversion = factUnits.get(needPatch.sku);
|
|
689
|
+
return {
|
|
690
|
+
...block,
|
|
691
|
+
sku: needPatch.sku,
|
|
692
|
+
...(needPatch.quantity !== undefined ? { quantity: needPatch.quantity } : {}),
|
|
693
|
+
...(needPatch.unit !== undefined ? { unit: needPatch.unit } : {}),
|
|
694
|
+
...(conversion?.factor !== undefined &&
|
|
695
|
+
needPatch.inputQuantity !== undefined &&
|
|
696
|
+
needPatch.inputUnit !== undefined
|
|
697
|
+
? {
|
|
698
|
+
convertedFrom: {
|
|
699
|
+
quantity: needPatch.inputQuantity,
|
|
700
|
+
unit: needPatch.inputUnit,
|
|
701
|
+
factor: conversion.factor,
|
|
702
|
+
},
|
|
703
|
+
}
|
|
704
|
+
: {}),
|
|
705
|
+
};
|
|
706
|
+
});
|
|
707
|
+
plan = { locale: "zh-CN", blocks: normalizedBlocks };
|
|
708
|
+
return toolResult(JSON.stringify({ accepted: true }));
|
|
709
|
+
},
|
|
710
|
+
},
|
|
711
|
+
];
|
|
712
|
+
const agent = new Agent({
|
|
713
|
+
streamFn: options.streamFn,
|
|
714
|
+
initialState: {
|
|
715
|
+
systemPrompt: options.systemPrompt ?? DEFAULT_SYSTEM_PROMPT,
|
|
716
|
+
model: options.model,
|
|
717
|
+
tools,
|
|
718
|
+
},
|
|
719
|
+
convertToLlm: (messages) => messages,
|
|
720
|
+
toolExecution: "sequential",
|
|
721
|
+
beforeToolCall: guard,
|
|
722
|
+
...(options.getApiKey !== undefined ? { getApiKey: options.getApiKey } : {}),
|
|
723
|
+
});
|
|
724
|
+
const maxSteps = options.maxSteps ?? 6;
|
|
725
|
+
const metrics = {
|
|
726
|
+
steps: 0,
|
|
727
|
+
toolCalls: {},
|
|
728
|
+
usage: { input: 0, output: 0, total: 0 },
|
|
729
|
+
};
|
|
730
|
+
let activeLease;
|
|
731
|
+
let lastSettledOutput = 0;
|
|
732
|
+
let quotaRejected = false;
|
|
733
|
+
agent.subscribe((event) => {
|
|
734
|
+
if (event.type === "turn_start") {
|
|
735
|
+
if (options.budget !== undefined) {
|
|
736
|
+
const begin = options.budget.begin();
|
|
737
|
+
if ("rejected" in begin) {
|
|
738
|
+
quotaRejected = true;
|
|
739
|
+
options.budget.onRejected(begin.rejected);
|
|
740
|
+
agent.abort();
|
|
741
|
+
return undefined;
|
|
742
|
+
}
|
|
743
|
+
activeLease = begin.leaseId;
|
|
744
|
+
}
|
|
745
|
+
return undefined;
|
|
746
|
+
}
|
|
747
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
748
|
+
const usage = event.message.usage;
|
|
749
|
+
metrics.usage.input += usage.input;
|
|
750
|
+
metrics.usage.output += usage.output;
|
|
751
|
+
metrics.usage.total += usage.totalTokens;
|
|
752
|
+
return undefined;
|
|
753
|
+
}
|
|
754
|
+
if (event.type === "tool_execution_start") {
|
|
755
|
+
metrics.toolCalls[event.toolName] = (metrics.toolCalls[event.toolName] ?? 0) + 1;
|
|
756
|
+
return undefined;
|
|
757
|
+
}
|
|
758
|
+
if (event.type === "turn_end") {
|
|
759
|
+
steps += 1;
|
|
760
|
+
metrics.steps = steps;
|
|
761
|
+
if (activeLease !== undefined && options.budget !== undefined) {
|
|
762
|
+
const delta = Math.max(0, metrics.usage.output - lastSettledOutput);
|
|
763
|
+
options.budget.settle(activeLease, delta);
|
|
764
|
+
lastSettledOutput = metrics.usage.output;
|
|
765
|
+
activeLease = undefined;
|
|
766
|
+
}
|
|
767
|
+
if (steps >= maxSteps) {
|
|
768
|
+
timedOut = true;
|
|
769
|
+
agent.abort();
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
return undefined;
|
|
773
|
+
});
|
|
774
|
+
const timer = setTimeout(() => {
|
|
775
|
+
timedOut = true;
|
|
776
|
+
agent.abort();
|
|
777
|
+
}, options.timeoutMs ?? 30_000);
|
|
778
|
+
try {
|
|
779
|
+
await agent.prompt(JSON.stringify({
|
|
780
|
+
buyer_message: input.text,
|
|
781
|
+
previous_need: input.previousNeed ?? {},
|
|
782
|
+
locale: "zh-CN",
|
|
783
|
+
}));
|
|
784
|
+
await agent.waitForIdle();
|
|
785
|
+
}
|
|
786
|
+
catch {
|
|
787
|
+
// 回退确定性路径;未结算的预算 lease 在 finally 按未知用量保留。
|
|
788
|
+
}
|
|
789
|
+
finally {
|
|
790
|
+
clearTimeout(timer);
|
|
791
|
+
if (activeLease !== undefined && options.budget !== undefined) {
|
|
792
|
+
options.budget.settle(activeLease, undefined);
|
|
793
|
+
activeLease = undefined;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
if (quotaRejected)
|
|
797
|
+
metrics.quotaRejected = true;
|
|
798
|
+
options.onMetrics?.(metrics);
|
|
799
|
+
if (plan === undefined || timedOut || quotaRejected)
|
|
800
|
+
return undefined;
|
|
801
|
+
return {
|
|
802
|
+
plan,
|
|
803
|
+
...(Object.keys(needPatch).length > 0 ? { need: needPatch } : {}),
|
|
804
|
+
metrics,
|
|
805
|
+
};
|
|
806
|
+
},
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
//# sourceMappingURL=agent-runtime.js.map
|