@harrylabsj/kiwi 0.12.24 → 0.12.26
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/reception/agent-runtime.d.ts +2 -0
- package/dist/a2a/reception/agent-runtime.js +34 -3
- package/dist/a2a/reception/agent-runtime.js.map +1 -1
- package/dist/a2a/reception/engine.js +21 -1
- package/dist/a2a/reception/engine.js.map +1 -1
- package/dist/buyer-core/a2a-knp.d.ts +2 -0
- package/dist/buyer-core/a2a-knp.js +3 -0
- package/dist/buyer-core/a2a-knp.js.map +1 -1
- package/dist/buyer-core/a2a-negotiator.js +18 -14
- package/dist/buyer-core/a2a-negotiator.js.map +1 -1
- package/dist/buyer-core/a2a-quote-fetcher.d.ts +3 -0
- package/dist/buyer-core/a2a-quote-fetcher.js +42 -5
- package/dist/buyer-core/a2a-quote-fetcher.js.map +1 -1
- package/dist/buyer-core/build-service.d.ts +7 -1
- package/dist/buyer-core/build-service.js +7 -0
- package/dist/buyer-core/build-service.js.map +1 -1
- package/dist/buyer-core/errors.d.ts +1 -1
- package/dist/buyer-core/errors.js +1 -0
- package/dist/buyer-core/errors.js.map +1 -1
- package/dist/buyer-core/service.d.ts +35 -0
- package/dist/buyer-core/service.js +212 -31
- package/dist/buyer-core/service.js.map +1 -1
- package/dist/buyer-core/store.d.ts +10 -6
- package/dist/buyer-core/store.js +138 -33
- package/dist/buyer-core/store.js.map +1 -1
- package/dist/http/cli.js +40 -2
- package/dist/http/cli.js.map +1 -1
- package/dist/http/server.js +12 -0
- package/dist/http/server.js.map +1 -1
- package/dist/mcp/cli.d.ts +5 -0
- package/dist/mcp/cli.js +42 -2
- package/dist/mcp/cli.js.map +1 -1
- package/dist/mcp/session-owner.d.ts +12 -0
- package/dist/mcp/session-owner.js +129 -0
- package/dist/mcp/session-owner.js.map +1 -0
- package/package.json +1 -1
|
@@ -29,6 +29,8 @@
|
|
|
29
29
|
* Negotiator 为可注入接口。v0.1 默认使用 Static 实现或由宿主注入。
|
|
30
30
|
*/
|
|
31
31
|
import { contentDigest, sha256Hex } from "../negotiation/jcs.js";
|
|
32
|
+
import { validateAcceptedNonbindingAgreement } from "../negotiation/domain/objects.js";
|
|
33
|
+
import { randomBytes as cryptoRandomBytes } from "node:crypto";
|
|
32
34
|
import { isDestinationType, isSessionDestinationType, isUrlDestinationType } from "../handoff/destination.js";
|
|
33
35
|
import { uuidv7 } from "@earendil-works/pi-ai";
|
|
34
36
|
import { assertNorthboundContractValid, validateCommerceIntent, validateEffectiveAuthorization, } from "../contracts/northbound-schema.js";
|
|
@@ -93,6 +95,39 @@ function normalizeClarificationQuestions(input, summary) {
|
|
|
93
95
|
return reason === "" ? { field } : { field, reason };
|
|
94
96
|
});
|
|
95
97
|
}
|
|
98
|
+
/** 明确指定的单品 SKU;缺失/空白时返回 undefined(模糊需求允许商家选品)。 */
|
|
99
|
+
function explicitIntentItemSku(intent) {
|
|
100
|
+
const items = intent.items;
|
|
101
|
+
if (!Array.isArray(items) || items.length === 0)
|
|
102
|
+
return undefined;
|
|
103
|
+
const first = items[0];
|
|
104
|
+
if (typeof first !== "object" || first === null)
|
|
105
|
+
return undefined;
|
|
106
|
+
const sku = first.sku;
|
|
107
|
+
return typeof sku === "string" && sku.trim() !== "" ? sku : undefined;
|
|
108
|
+
}
|
|
109
|
+
/** 明确 SKU 的报价必须只包含该 SKU;商家换品/混入其他商品时拒绝接纳。 */
|
|
110
|
+
function rejectQuoteForOtherSku(result, explicitSku) {
|
|
111
|
+
if (explicitSku === undefined || result.status !== "succeeded")
|
|
112
|
+
return result;
|
|
113
|
+
const rawItems = result.terms?.items;
|
|
114
|
+
const items = Array.isArray(rawItems) ? rawItems : [];
|
|
115
|
+
const skus = items
|
|
116
|
+
.map((item) => item.sku)
|
|
117
|
+
.filter((sku) => typeof sku === "string" && sku !== "");
|
|
118
|
+
if (items.length > 0 && skus.length === items.length && skus.every((sku) => sku === explicitSku)) {
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
merchant_id: result.merchant_id,
|
|
123
|
+
status: "failed",
|
|
124
|
+
failure: {
|
|
125
|
+
classification: "protocol_error",
|
|
126
|
+
retryable: false,
|
|
127
|
+
detail: "merchant quote SKU does not match explicit intent SKU",
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
96
131
|
/** 候选当前可接受的条款摘要:优先商家最新 agreed terms,其次旧候选快照。 */
|
|
97
132
|
function acceptedTermsDigest(candidate) {
|
|
98
133
|
const provenance = candidate.provenance ?? {};
|
|
@@ -117,6 +152,7 @@ export class KiwiBuyerService {
|
|
|
117
152
|
principal;
|
|
118
153
|
buyerAgentId;
|
|
119
154
|
sessionId;
|
|
155
|
+
ownerHash;
|
|
120
156
|
policySnapshot;
|
|
121
157
|
policyDigest;
|
|
122
158
|
/** 兼容既有内部读取点:一律指向已冻结快照,不再暴露可变原对象。 */
|
|
@@ -127,12 +163,19 @@ export class KiwiBuyerService {
|
|
|
127
163
|
quoteFetcher;
|
|
128
164
|
negotiator;
|
|
129
165
|
followsClient;
|
|
166
|
+
staleWake;
|
|
167
|
+
staleWakeTimeoutMs;
|
|
168
|
+
wakeAttemptAt = new Map();
|
|
169
|
+
wakeInFlight = new Map();
|
|
130
170
|
now;
|
|
131
171
|
constructor(options) {
|
|
132
172
|
this.store = options.store;
|
|
133
173
|
this.principal = options.principal;
|
|
134
174
|
this.buyerAgentId = options.buyerAgentId;
|
|
135
175
|
this.sessionId = options.sessionId;
|
|
176
|
+
// No token/subscription means a fresh, random, non-recoverable owner.
|
|
177
|
+
// Never derive this from the caller-controlled session label.
|
|
178
|
+
this.ownerHash = options.sessionOwner ?? `ephemeral:${cryptoRandomBytes(32).toString("hex")}`;
|
|
136
179
|
const clock = options.now ?? utcNow;
|
|
137
180
|
this.now = () => new Date(Date.parse(clock())).toISOString();
|
|
138
181
|
// A 卡:授权与摘要必须使用同一份 deep-clone/deep-freeze 的 plain-JSON 快照,
|
|
@@ -143,6 +186,97 @@ export class KiwiBuyerService {
|
|
|
143
186
|
this.quoteFetcher = options.quoteFetcher;
|
|
144
187
|
this.negotiator = options.negotiator;
|
|
145
188
|
this.followsClient = options.followsClient;
|
|
189
|
+
this.staleWake = options.staleWake;
|
|
190
|
+
this.staleWakeTimeoutMs = options.staleWakeTimeoutMs ?? 5000;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Per-merchant singleflight + 60s cooldown. The probe never updates catalog
|
|
194
|
+
* state; only a subsequent catalog read showing a merchant heartbeat may
|
|
195
|
+
* allow the quote.
|
|
196
|
+
*/
|
|
197
|
+
taskFor(taskId) {
|
|
198
|
+
return this.store.getTask(taskId, this.ownerHash);
|
|
199
|
+
}
|
|
200
|
+
approvalFor(approvalId) {
|
|
201
|
+
return this.store.getApproval(approvalId, this.ownerHash);
|
|
202
|
+
}
|
|
203
|
+
agreementFor(agreementId) {
|
|
204
|
+
return this.store.getAgreement(agreementId, this.ownerHash);
|
|
205
|
+
}
|
|
206
|
+
handoffFor(intentDigest) {
|
|
207
|
+
return this.store.getHandoffIntent(intentDigest, this.ownerHash);
|
|
208
|
+
}
|
|
209
|
+
approvalsForTask(taskId) {
|
|
210
|
+
return this.store.listApprovalsByTask(taskId, this.ownerHash);
|
|
211
|
+
}
|
|
212
|
+
async tryStaleWake(record) {
|
|
213
|
+
if (this.staleWake === undefined || record.agent_card_url === undefined)
|
|
214
|
+
return false;
|
|
215
|
+
const id = record.merchant_id;
|
|
216
|
+
const existing = this.wakeInFlight.get(id);
|
|
217
|
+
if (existing !== undefined)
|
|
218
|
+
return existing;
|
|
219
|
+
const nowMs = Date.parse(this.now());
|
|
220
|
+
const last = this.wakeAttemptAt.get(id);
|
|
221
|
+
if (last !== undefined && Number.isFinite(nowMs) && nowMs - last < 60_000)
|
|
222
|
+
return false;
|
|
223
|
+
this.wakeAttemptAt.set(id, nowMs);
|
|
224
|
+
let timer;
|
|
225
|
+
const work = (async () => {
|
|
226
|
+
try {
|
|
227
|
+
const timeout = new Promise((resolve) => {
|
|
228
|
+
timer = setTimeout(() => resolve(false), this.staleWakeTimeoutMs);
|
|
229
|
+
});
|
|
230
|
+
const result = await Promise.race([
|
|
231
|
+
this.staleWake(record).then((value) => value === true).catch(() => false),
|
|
232
|
+
timeout,
|
|
233
|
+
]);
|
|
234
|
+
return result;
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
if (timer !== undefined)
|
|
238
|
+
clearTimeout(timer);
|
|
239
|
+
}
|
|
240
|
+
})();
|
|
241
|
+
this.wakeInFlight.set(id, work);
|
|
242
|
+
try {
|
|
243
|
+
return await work;
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
this.wakeInFlight.delete(id);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Wake at most three stale WorkBuddy merchants per search, concurrently.
|
|
251
|
+
* The catalog is re-read per merchant so only a real heartbeat can make the
|
|
252
|
+
* returned projection fresh; the probe itself never mutates status.
|
|
253
|
+
*/
|
|
254
|
+
async refreshStaleMerchants(merchants) {
|
|
255
|
+
const index = this.merchantIndex;
|
|
256
|
+
if (index === undefined || this.staleWake === undefined)
|
|
257
|
+
return merchants;
|
|
258
|
+
const stale = merchants
|
|
259
|
+
.map((merchant, indexInList) => ({ merchant, indexInList }))
|
|
260
|
+
.filter(({ merchant }) => !agentIsFresh(merchant) && merchant.agent_card_url !== undefined)
|
|
261
|
+
.slice(0, 3);
|
|
262
|
+
if (stale.length === 0)
|
|
263
|
+
return merchants;
|
|
264
|
+
const refreshed = await Promise.all(stale.map(async ({ merchant, indexInList }) => {
|
|
265
|
+
const sent = await this.tryStaleWake(merchant);
|
|
266
|
+
if (!sent)
|
|
267
|
+
return undefined;
|
|
268
|
+
const fresh = await index.resolveById(merchant.merchant_id).catch(() => undefined);
|
|
269
|
+
return fresh !== undefined && agentIsFresh(fresh)
|
|
270
|
+
? { indexInList, merchant: fresh }
|
|
271
|
+
: undefined;
|
|
272
|
+
}));
|
|
273
|
+
if (refreshed.every((entry) => entry === undefined))
|
|
274
|
+
return merchants;
|
|
275
|
+
const next = [...merchants];
|
|
276
|
+
for (const entry of refreshed)
|
|
277
|
+
if (entry !== undefined)
|
|
278
|
+
next[entry.indexInList] = entry.merchant;
|
|
279
|
+
return next;
|
|
146
280
|
}
|
|
147
281
|
// ---- Northbound:kiwi_search ----------------------------------------------
|
|
148
282
|
async search(input) {
|
|
@@ -163,7 +297,7 @@ export class KiwiBuyerService {
|
|
|
163
297
|
});
|
|
164
298
|
// 单侧降级/离线说明如实标注;不静默、不补全。
|
|
165
299
|
return {
|
|
166
|
-
merchants,
|
|
300
|
+
merchants: await this.refreshStaleMerchants(merchants),
|
|
167
301
|
...(diagnostics.notes.length > 0 ? { note: diagnostics.notes.join(";") } : {}),
|
|
168
302
|
network_search: diagnostics,
|
|
169
303
|
};
|
|
@@ -180,7 +314,7 @@ export class KiwiBuyerService {
|
|
|
180
314
|
notes,
|
|
181
315
|
});
|
|
182
316
|
return {
|
|
183
|
-
merchants,
|
|
317
|
+
merchants: await this.refreshStaleMerchants(merchants),
|
|
184
318
|
...(notes.length > 0 ? { note: notes.join(";") } : {}),
|
|
185
319
|
network_search: diagnostics,
|
|
186
320
|
};
|
|
@@ -276,6 +410,7 @@ export class KiwiBuyerService {
|
|
|
276
410
|
: [];
|
|
277
411
|
const task = {
|
|
278
412
|
task_id: taskId,
|
|
413
|
+
owner_hash: this.ownerHash,
|
|
279
414
|
task_kind: "request_quotes",
|
|
280
415
|
status: "in_progress",
|
|
281
416
|
idempotency_key: idempotencyKey,
|
|
@@ -302,6 +437,11 @@ export class KiwiBuyerService {
|
|
|
302
437
|
};
|
|
303
438
|
const { task: persisted, created: isCreated } = this.store.createTask(task);
|
|
304
439
|
if (!isCreated) {
|
|
440
|
+
// idempotency_key is globally unique in the local store. It must never
|
|
441
|
+
// become a side-channel that lets another session read/revive a task.
|
|
442
|
+
if (persisted.owner_hash !== this.ownerHash) {
|
|
443
|
+
throw new McpError("task_not_found", "idempotency key belongs to another session");
|
|
444
|
+
}
|
|
305
445
|
if (this.quoteFetcher?.recoverQuotes !== undefined) {
|
|
306
446
|
const original = this.decodeTask(persisted).intent;
|
|
307
447
|
if (original !== undefined && contentDigest(original) !== contentDigest(input.intent))
|
|
@@ -316,7 +456,9 @@ export class KiwiBuyerService {
|
|
|
316
456
|
// Recovery can only read previously persisted protocol receipts/results, never send.
|
|
317
457
|
if (this.quoteFetcher?.recoverQuotes !== undefined && ["in_progress", "partial_success"].includes(persisted.status) && !this.store.hasAgreementForTask(persisted.task_id)) {
|
|
318
458
|
const originalCandidates = this.store.listCandidates(persisted.task_id);
|
|
319
|
-
const
|
|
459
|
+
const recovered = await this.quoteFetcher.recoverQuotes(this.protocolContext(persisted, input.merchant_ids ?? []));
|
|
460
|
+
const explicitSku = explicitIntentItemSku(input.intent);
|
|
461
|
+
const results = recovered.map((result) => rejectQuoteForOtherSku(result, explicitSku));
|
|
320
462
|
if (results.length > 0)
|
|
321
463
|
return this.store.transaction(() => {
|
|
322
464
|
if (this.store.hasAgreementForTask(persisted.task_id) || contentDigest(this.store.listCandidates(persisted.task_id)) !== contentDigest(originalCandidates))
|
|
@@ -369,6 +511,8 @@ export class KiwiBuyerService {
|
|
|
369
511
|
// 写入/发送部分 RFQ。没有 receipt 时保守落为 non-retryable unknown。
|
|
370
512
|
dispatchStarted = true;
|
|
371
513
|
quotedResults = await this.quoteFetcher.requestQuotes(input.intent, merchantRecords, protocolContext);
|
|
514
|
+
const explicitSku = explicitIntentItemSku(input.intent);
|
|
515
|
+
quotedResults = quotedResults.map((result) => rejectQuoteForOtherSku(result, explicitSku));
|
|
372
516
|
dispatchOutcomeUnknown = quotedResults.some((result) => result.status === "failed" &&
|
|
373
517
|
result.failure?.classification === "protocol_error" &&
|
|
374
518
|
result.failure.retryable === false);
|
|
@@ -460,7 +604,7 @@ export class KiwiBuyerService {
|
|
|
460
604
|
}
|
|
461
605
|
// ---- Northbound:kiwi_get_task --------------------------------------------
|
|
462
606
|
getTask(taskId) {
|
|
463
|
-
const task = this.
|
|
607
|
+
const task = this.taskFor(taskId);
|
|
464
608
|
if (task === undefined)
|
|
465
609
|
throw new McpError("task_not_found", `task ${taskId} not found`);
|
|
466
610
|
if (task.expires_at !== undefined && Date.parse(task.expires_at) < Date.parse(this.now())) {
|
|
@@ -482,7 +626,7 @@ export class KiwiBuyerService {
|
|
|
482
626
|
(!Number.isSafeInteger(explicitTarget.amount_minor) || explicitTarget.amount_minor <= 0)) {
|
|
483
627
|
throw new McpError("invalid_params", "target_unit_price.amount_minor 必须是正整数(最小货币单位)");
|
|
484
628
|
}
|
|
485
|
-
const task = this.
|
|
629
|
+
const task = this.taskFor(input.task_id);
|
|
486
630
|
if (task === undefined)
|
|
487
631
|
throw new McpError("task_not_found", `task ${input.task_id} not found`);
|
|
488
632
|
if (task.expires_at !== undefined && Date.parse(task.expires_at) < Date.parse(this.now())) {
|
|
@@ -586,7 +730,7 @@ export class KiwiBuyerService {
|
|
|
586
730
|
}
|
|
587
731
|
// ---- Northbound:kiwi_accept_agreement ------------------------------------
|
|
588
732
|
async acceptAgreement(input) {
|
|
589
|
-
const task = this.
|
|
733
|
+
const task = this.taskFor(input.task_id);
|
|
590
734
|
if (task === undefined)
|
|
591
735
|
throw new McpError("task_not_found", `task ${input.task_id} not found`);
|
|
592
736
|
if (task.expires_at !== undefined && Date.parse(task.expires_at) < Date.parse(this.now())) {
|
|
@@ -642,18 +786,47 @@ export class KiwiBuyerService {
|
|
|
642
786
|
}
|
|
643
787
|
const existingAgreement = this.store.findAgreementByTerms(input.task_id, termsDigest);
|
|
644
788
|
let merchantAgreement;
|
|
645
|
-
if (existingAgreement === undefined
|
|
646
|
-
// 只有 A2A 候选才向商家发 accept;本地/演示候选保持本地协议语义。
|
|
789
|
+
if (existingAgreement === undefined) {
|
|
647
790
|
const provenance = preCandidate.provenance ?? {};
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
791
|
+
const isA2A = typeof provenance.a2a_endpoint === "string" && provenance.a2a_endpoint !== "";
|
|
792
|
+
if (isA2A) {
|
|
793
|
+
// A2A must receive the merchant's agreement artifact. An offer-like
|
|
794
|
+
// reply that is not a conditional_offer cannot be remotely accepted by
|
|
795
|
+
// the current KNP handler; never create a local agreement for it.
|
|
796
|
+
if (this.negotiator?.acceptNonbinding === undefined) {
|
|
797
|
+
throw new McpError("invalid_params", "A2A candidate cannot be accepted without a negotiator");
|
|
798
|
+
}
|
|
799
|
+
// Merchant handler normalizes a direct `offer` into the same
|
|
800
|
+
// accept_nonbinding object as a conditional_offer (conditions: []).
|
|
801
|
+
// Both are remote-acceptable; do not require a synthetic conditional
|
|
802
|
+
// round or a price change just to obtain the merchant agreement.
|
|
803
|
+
if (provenance.latest_offer_type !== "conditional_offer" && provenance.latest_offer_type !== "offer" && provenance.latest_offer_type !== "counter_offer" && provenance.latest_offer_type !== "counter_offer") {
|
|
804
|
+
throw new McpError("invalid_params", "A2A candidate latest reply is not an acceptable offer/conditional_offer; refusing to create a local agreement");
|
|
805
|
+
}
|
|
651
806
|
const accepted = await this.negotiator.acceptNonbinding({
|
|
652
807
|
taskId: input.task_id,
|
|
653
808
|
candidate: preCandidate,
|
|
654
809
|
context: this.protocolContext(task),
|
|
655
810
|
});
|
|
656
|
-
|
|
811
|
+
if (accepted?.agreement === undefined || accepted.agreement === null) {
|
|
812
|
+
throw new McpError("internal_error", "A2A accept returned no merchant agreement");
|
|
813
|
+
}
|
|
814
|
+
let checkedAgreement;
|
|
815
|
+
try {
|
|
816
|
+
checkedAgreement = validateAcceptedNonbindingAgreement(accepted.agreement);
|
|
817
|
+
}
|
|
818
|
+
catch {
|
|
819
|
+
throw new McpError("internal_error", "A2A merchant agreement is not a valid nonbinding agreement; reconciliation required", { reconciliation_required: true, merchant_agreement: accepted.agreement });
|
|
820
|
+
}
|
|
821
|
+
if (checkedAgreement.negotiation_id !== String(provenance.negotiation_id ?? "")
|
|
822
|
+
|| checkedAgreement.accepted_offer_id !== String(provenance.offer_id ?? "")
|
|
823
|
+
|| checkedAgreement.terms_digest !== termsDigest
|
|
824
|
+
|| contentDigest(checkedAgreement.agreed_terms) !== checkedAgreement.terms_digest
|
|
825
|
+
|| !checkedAgreement.accepted_by.includes("buyer")
|
|
826
|
+
|| !checkedAgreement.accepted_by.includes("merchant")) {
|
|
827
|
+
throw new McpError("internal_error", "A2A merchant agreement is not bound to the accepted terms; reconciliation required", { reconciliation_required: true, merchant_agreement: accepted.agreement });
|
|
828
|
+
}
|
|
829
|
+
merchantAgreement = checkedAgreement;
|
|
657
830
|
}
|
|
658
831
|
}
|
|
659
832
|
// review P1-2(A316 校准):短事务原子消费——事务内重读授权、写
|
|
@@ -661,12 +834,12 @@ export class KiwiBuyerService {
|
|
|
661
834
|
// 无事后补偿、不烧毁有效批准——同绑定重试重新进入本事务)。node:sqlite
|
|
662
835
|
// 同步执行 + BEGIN IMMEDIATE 写锁,进程内/跨连接均互斥。
|
|
663
836
|
return this.store.transaction(() => {
|
|
664
|
-
const freshTask = this.
|
|
837
|
+
const freshTask = this.taskFor(input.task_id);
|
|
665
838
|
if (freshTask === undefined) {
|
|
666
839
|
throw new McpError("task_not_found", `task ${input.task_id} not found`);
|
|
667
840
|
}
|
|
668
841
|
if (input.approval_id !== undefined) {
|
|
669
|
-
const fresh = this.
|
|
842
|
+
const fresh = this.approvalFor(input.approval_id);
|
|
670
843
|
if (fresh === undefined) {
|
|
671
844
|
throw new McpError("approval_required", `approval ${input.approval_id} 不存在`, {
|
|
672
845
|
approval_id: input.approval_id,
|
|
@@ -714,13 +887,13 @@ export class KiwiBuyerService {
|
|
|
714
887
|
consumed.binding === consumedBinding) {
|
|
715
888
|
// 同逻辑重放:返回库里既有的同一 agreement(非虚构结果)。
|
|
716
889
|
const existing = consumed.ref.startsWith("agreement-")
|
|
717
|
-
? this.
|
|
890
|
+
? this.agreementFor(consumed.ref)
|
|
718
891
|
: undefined;
|
|
719
892
|
if (existing === undefined) {
|
|
720
893
|
throw new McpError("approval_denied", `approval ${input.approval_id} 已消费但绑定效果不可读;需要人工对账`);
|
|
721
894
|
}
|
|
722
895
|
return {
|
|
723
|
-
task: this.decodeTask(this.
|
|
896
|
+
task: this.decodeTask(this.taskFor(input.task_id)),
|
|
724
897
|
agreement: JSON.parse(existing.payload),
|
|
725
898
|
authorization,
|
|
726
899
|
};
|
|
@@ -793,7 +966,7 @@ export class KiwiBuyerService {
|
|
|
793
966
|
}),
|
|
794
967
|
}, freshTask);
|
|
795
968
|
if (input.approval_id !== undefined) {
|
|
796
|
-
const approval = this.
|
|
969
|
+
const approval = this.approvalFor(input.approval_id);
|
|
797
970
|
if (approval !== undefined) {
|
|
798
971
|
this.store.setApproval(approval.task_id, {
|
|
799
972
|
...approval,
|
|
@@ -810,7 +983,7 @@ export class KiwiBuyerService {
|
|
|
810
983
|
}
|
|
811
984
|
// ---- Northbound:kiwi_get_agreement ---------------------------------------
|
|
812
985
|
getAgreement(agreementId) {
|
|
813
|
-
const stored = this.
|
|
986
|
+
const stored = this.agreementFor(agreementId);
|
|
814
987
|
if (stored === undefined) {
|
|
815
988
|
throw new McpError("agreement_not_found", `agreement ${agreementId} not found`);
|
|
816
989
|
}
|
|
@@ -818,7 +991,7 @@ export class KiwiBuyerService {
|
|
|
818
991
|
}
|
|
819
992
|
// ---- Northbound:kiwi_handoff ---------------------------------------------
|
|
820
993
|
async handoff(input) {
|
|
821
|
-
const stored = this.
|
|
994
|
+
const stored = this.agreementFor(input.agreement_id);
|
|
822
995
|
if (stored === undefined) {
|
|
823
996
|
throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
|
|
824
997
|
}
|
|
@@ -870,17 +1043,17 @@ export class KiwiBuyerService {
|
|
|
870
1043
|
// 消费;同绑定重放返回**库里记录的同一 ref**(非虚构);失败 ROLLBACK
|
|
871
1044
|
// 不烧毁审批。
|
|
872
1045
|
return this.store.transaction(() => {
|
|
873
|
-
const approval = this.
|
|
1046
|
+
const approval = this.approvalFor(input.approval_id);
|
|
874
1047
|
if (approval === undefined) {
|
|
875
1048
|
throw new McpError("invalid_params", `approval ${input.approval_id} 不存在`);
|
|
876
1049
|
}
|
|
877
1050
|
// A 卡:同事务重读 task/agreement,核验意图(含 agreement 摘要、terms 现值、
|
|
878
1051
|
// policy 摘要与全部有效期限);旧审批(无 intent)在此拒绝。
|
|
879
|
-
const freshTask = this.
|
|
1052
|
+
const freshTask = this.taskFor(approval.task_id);
|
|
880
1053
|
if (freshTask === undefined) {
|
|
881
1054
|
throw new McpError("task_not_found", `task ${approval.task_id} not found`);
|
|
882
1055
|
}
|
|
883
|
-
const freshAgreement = this.
|
|
1056
|
+
const freshAgreement = this.agreementFor(input.agreement_id);
|
|
884
1057
|
if (freshAgreement === undefined) {
|
|
885
1058
|
throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
|
|
886
1059
|
}
|
|
@@ -981,7 +1154,7 @@ export class KiwiBuyerService {
|
|
|
981
1154
|
requestHandoffApproval(args) {
|
|
982
1155
|
const nowIso = this.now();
|
|
983
1156
|
const nowMs = Date.parse(nowIso);
|
|
984
|
-
const task = this.
|
|
1157
|
+
const task = this.taskFor(args.agreement.task_id);
|
|
985
1158
|
if (task === undefined)
|
|
986
1159
|
throw new McpError("task_not_found", `task ${args.agreement.task_id} not found`);
|
|
987
1160
|
// policy 自身期限在 ASK 侧同样独立校验(同一 now 样本)。
|
|
@@ -1052,7 +1225,7 @@ export class KiwiBuyerService {
|
|
|
1052
1225
|
if (args.approval.intent_digest === undefined) {
|
|
1053
1226
|
throw new McpError("approval_denied", `approval ${args.approval.approval_id} 缺少 handoff 意图(旧审批),请重新 ASK`);
|
|
1054
1227
|
}
|
|
1055
|
-
const intent = this.
|
|
1228
|
+
const intent = this.handoffFor(args.approval.intent_digest);
|
|
1056
1229
|
if (intent === undefined) {
|
|
1057
1230
|
throw new McpError("approval_denied", `approval ${args.approval.approval_id} 的意图不存在`);
|
|
1058
1231
|
}
|
|
@@ -1102,7 +1275,7 @@ export class KiwiBuyerService {
|
|
|
1102
1275
|
}
|
|
1103
1276
|
/** 创建 pending 审批记录(ASK 动作触发)。返回持久 approval_id。 */
|
|
1104
1277
|
requestApproval(input) {
|
|
1105
|
-
const task = this.
|
|
1278
|
+
const task = this.taskFor(input.task_id);
|
|
1106
1279
|
if (task === undefined)
|
|
1107
1280
|
throw new McpError("task_not_found", `task ${input.task_id} not found`);
|
|
1108
1281
|
const approvalId = `approval-${uuidv7()}`;
|
|
@@ -1119,7 +1292,7 @@ export class KiwiBuyerService {
|
|
|
1119
1292
|
}
|
|
1120
1293
|
/** 批准一个 pending 审批(绑定授权记录)。 */
|
|
1121
1294
|
approveApproval(input) {
|
|
1122
|
-
const stored = this.
|
|
1295
|
+
const stored = this.approvalFor(input.approval_id);
|
|
1123
1296
|
if (stored === undefined)
|
|
1124
1297
|
throw new McpError("invalid_params", `approval ${input.approval_id} not found`);
|
|
1125
1298
|
if (stored.status !== "pending" || this.approvalConsumed(stored) !== undefined) {
|
|
@@ -1135,7 +1308,7 @@ export class KiwiBuyerService {
|
|
|
1135
1308
|
}
|
|
1136
1309
|
/** 拒绝一个 pending 审批(deny 路径;deny 优先,§5.5)。 */
|
|
1137
1310
|
rejectApproval(input) {
|
|
1138
|
-
const stored = this.
|
|
1311
|
+
const stored = this.approvalFor(input.approval_id);
|
|
1139
1312
|
if (stored === undefined)
|
|
1140
1313
|
throw new McpError("invalid_params", `approval ${input.approval_id} not found`);
|
|
1141
1314
|
this.store.setApproval(stored.task_id, {
|
|
@@ -1155,7 +1328,7 @@ export class KiwiBuyerService {
|
|
|
1155
1328
|
* kiwi_accept_agreement / kiwi_handoff。
|
|
1156
1329
|
*/
|
|
1157
1330
|
approve(input) {
|
|
1158
|
-
const stored = this.
|
|
1331
|
+
const stored = this.approvalFor(input.approval_id);
|
|
1159
1332
|
if (stored === undefined)
|
|
1160
1333
|
throw new McpError("invalid_params", `approval ${input.approval_id} not found`);
|
|
1161
1334
|
if (stored.status !== "pending") {
|
|
@@ -1187,7 +1360,7 @@ export class KiwiBuyerService {
|
|
|
1187
1360
|
}
|
|
1188
1361
|
/** 宿主拒绝一个 pending 审批(deny 优先路径;拒绝后不可再批准)。 */
|
|
1189
1362
|
reject(input) {
|
|
1190
|
-
const stored = this.
|
|
1363
|
+
const stored = this.approvalFor(input.approval_id);
|
|
1191
1364
|
if (stored === undefined)
|
|
1192
1365
|
throw new McpError("invalid_params", `approval ${input.approval_id} not found`);
|
|
1193
1366
|
if (stored.status !== "pending") {
|
|
@@ -1213,7 +1386,7 @@ export class KiwiBuyerService {
|
|
|
1213
1386
|
else if (mode === "ask") {
|
|
1214
1387
|
// ASK:必须有已批准的持久审批;approval 动作必须与请求动作一致。
|
|
1215
1388
|
const expectedAction = action === "accept_nonbinding" ? "accept_nonbinding" : "handoff";
|
|
1216
|
-
const approval = opts.approvalId !== undefined ? this.
|
|
1389
|
+
const approval = opts.approvalId !== undefined ? this.approvalFor(opts.approvalId) : undefined;
|
|
1217
1390
|
if (opts.approvalId !== undefined && approval === undefined) {
|
|
1218
1391
|
throw new McpError("approval_required", `approval ${opts.approvalId} 不存在`, {
|
|
1219
1392
|
approval_id: opts.approvalId,
|
|
@@ -1613,7 +1786,7 @@ export class KiwiBuyerService {
|
|
|
1613
1786
|
expires_at: task.expires_at,
|
|
1614
1787
|
resumable: task.resumable,
|
|
1615
1788
|
candidates: this.northboundCandidates(task.task_id),
|
|
1616
|
-
approval: this.
|
|
1789
|
+
approval: this.approvalsForTask(task.task_id)[0],
|
|
1617
1790
|
};
|
|
1618
1791
|
}
|
|
1619
1792
|
/**
|
|
@@ -1648,6 +1821,14 @@ export class KiwiBuyerService {
|
|
|
1648
1821
|
// 与上一门区分:这里商家**开通过**实时询价,只是当前不在线——错误码不同,
|
|
1649
1822
|
// 处置也不同(稍后重试/联系商家,而不是"从未开通")。
|
|
1650
1823
|
if (record !== undefined && !agentIsFresh(record)) {
|
|
1824
|
+
// On-demand cold-start probe for WorkBuddy-hosted merchants. It can
|
|
1825
|
+
// wake the app, but the merchant must send its own signed heartbeat
|
|
1826
|
+
// before this buyer allows a quote: no local flag is trusted.
|
|
1827
|
+
if (await this.tryStaleWake(record)) {
|
|
1828
|
+
const refreshed = await index.resolveById(merchantId).catch(() => undefined);
|
|
1829
|
+
if (refreshed !== undefined && agentIsFresh(refreshed))
|
|
1830
|
+
continue;
|
|
1831
|
+
}
|
|
1651
1832
|
throw new McpError("merchant_offline", `商家 ${merchantId}(${record.name})的服务当前不在线(未在有效期内上报心跳),` +
|
|
1652
1833
|
"暂不可实时询价;其公开资料仍可查看,可稍后重试", { merchant_id: merchantId, freshness_state: record.freshness_state ?? "stale" });
|
|
1653
1834
|
}
|