@harrylabsj/kiwi 0.12.5 → 0.12.6
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/buyer-core/service.d.ts +22 -1
- package/dist/buyer-core/service.js +325 -33
- package/dist/buyer-core/service.js.map +1 -1
- package/dist/buyer-core/store.d.ts +23 -0
- package/dist/buyer-core/store.js +71 -8
- package/dist/buyer-core/store.js.map +1 -1
- package/dist/cloud/bootstrap.d.ts +13 -0
- package/dist/cloud/bootstrap.js +27 -4
- package/dist/cloud/bootstrap.js.map +1 -1
- package/dist/cloud/config.d.ts +26 -0
- package/dist/cloud/config.js +75 -3
- package/dist/cloud/config.js.map +1 -1
- package/dist/cloud/main.d.ts +69 -0
- package/dist/cloud/main.js +285 -0
- package/dist/cloud/main.js.map +1 -1
- package/dist/cloud/owned-clock.d.ts +27 -0
- package/dist/cloud/owned-clock.js +98 -0
- package/dist/cloud/owned-clock.js.map +1 -0
- package/dist/cloud/owned-runtime.d.ts +188 -0
- package/dist/cloud/owned-runtime.js +1041 -0
- package/dist/cloud/owned-runtime.js.map +1 -0
- package/dist/demo/demo-runner.js +6 -0
- package/dist/demo/demo-runner.js.map +1 -1
- package/dist/handoff/destination.d.ts +2 -0
- package/dist/handoff/destination.js +4 -0
- package/dist/handoff/destination.js.map +1 -1
- package/package.json +1 -1
|
@@ -220,7 +220,10 @@ export declare class KiwiBuyerService {
|
|
|
220
220
|
private readonly principal;
|
|
221
221
|
private readonly buyerAgentId;
|
|
222
222
|
private readonly sessionId;
|
|
223
|
-
private readonly
|
|
223
|
+
private readonly policySnapshot;
|
|
224
|
+
private readonly policyDigest;
|
|
225
|
+
/** 兼容既有内部读取点:一律指向已冻结快照,不再暴露可变原对象。 */
|
|
226
|
+
private get policy();
|
|
224
227
|
private readonly merchantIndex?;
|
|
225
228
|
private readonly quoteFetcher?;
|
|
226
229
|
private readonly negotiator?;
|
|
@@ -316,6 +319,24 @@ export declare class KiwiBuyerService {
|
|
|
316
319
|
};
|
|
317
320
|
authorization: AuthorizationRecord;
|
|
318
321
|
}>;
|
|
322
|
+
/** 目的地归一:类型词表校验 + URL 归一(http/https、无凭据、无 fragment)。 */
|
|
323
|
+
private normalizeHandoffDestination;
|
|
324
|
+
/** 意图对象(不含 intent_digest);字段集固定,缺失一律 null。 */
|
|
325
|
+
private buildHandoffIntent;
|
|
326
|
+
/**
|
|
327
|
+
* 意图感知的 ASK:在泛型 evaluateAuthorization 之前由 handoff 调用,
|
|
328
|
+
* 同事务写 intent 与 approval,杜绝"先产生无目的地审批再补绑定"。
|
|
329
|
+
*/
|
|
330
|
+
private requestHandoffApproval;
|
|
331
|
+
/**
|
|
332
|
+
* 由存储的 intent 重建 canonical body(字段集与 `buildHandoffIntent` 完全一致,
|
|
333
|
+
* 排除 `intent_digest` 自身)。任何字段被改都会改变重算摘要。
|
|
334
|
+
*/
|
|
335
|
+
private handoffIntentBody;
|
|
336
|
+
/** policy 自身期限必须独立有效(不能只靠 DB 其它期限间接代表)。 */
|
|
337
|
+
private assertPolicyActive;
|
|
338
|
+
/** 消费前的意图核验:重算摘要 + 逐字段 + 重算 agreement 摘要 + 现值 terms + policy 期限/摘要 + 全部期限。 */
|
|
339
|
+
private assertHandoffIntentMatches;
|
|
319
340
|
/** 创建 pending 审批记录(ASK 动作触发)。返回持久 approval_id。 */
|
|
320
341
|
requestApproval(input: {
|
|
321
342
|
task_id: string;
|
|
@@ -28,7 +28,8 @@
|
|
|
28
28
|
* 执行 seam(Phase 2 接线真实 merchant 网络):MerchantIndex / QuoteFetcher /
|
|
29
29
|
* Negotiator 为可注入接口。v0.1 默认使用 Static 实现或由宿主注入。
|
|
30
30
|
*/
|
|
31
|
-
import { contentDigest } from "../negotiation/jcs.js";
|
|
31
|
+
import { contentDigest, sha256Hex } from "../negotiation/jcs.js";
|
|
32
|
+
import { isDestinationType, isSessionDestinationType, isUrlDestinationType } from "../handoff/destination.js";
|
|
32
33
|
import { uuidv7 } from "@earendil-works/pi-ai";
|
|
33
34
|
import { assertNorthboundContractValid, validateCommerceIntent, validateEffectiveAuthorization, } from "../contracts/northbound-schema.js";
|
|
34
35
|
import { CatalogSourceError } from "../discovery/catalog-source/errors.js";
|
|
@@ -40,6 +41,17 @@ function agentIsFresh(record) {
|
|
|
40
41
|
const state = record.freshness_state;
|
|
41
42
|
return state === undefined || (state !== "stale" && state !== "unreachable");
|
|
42
43
|
}
|
|
44
|
+
const HANDOFF_INTENT_VERSION = "1";
|
|
45
|
+
/** 深冻结(plain JSON):保证授权与摘要使用同一不可变快照。 */
|
|
46
|
+
function deepFreezePlain(value) {
|
|
47
|
+
if (value !== null && typeof value === "object") {
|
|
48
|
+
for (const key of Object.keys(value)) {
|
|
49
|
+
deepFreezePlain(value[key]);
|
|
50
|
+
}
|
|
51
|
+
Object.freeze(value);
|
|
52
|
+
}
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
43
55
|
function utcNow() {
|
|
44
56
|
return new Date().toISOString();
|
|
45
57
|
}
|
|
@@ -63,7 +75,12 @@ export class KiwiBuyerService {
|
|
|
63
75
|
principal;
|
|
64
76
|
buyerAgentId;
|
|
65
77
|
sessionId;
|
|
66
|
-
|
|
78
|
+
policySnapshot;
|
|
79
|
+
policyDigest;
|
|
80
|
+
/** 兼容既有内部读取点:一律指向已冻结快照,不再暴露可变原对象。 */
|
|
81
|
+
get policy() {
|
|
82
|
+
return this.policySnapshot;
|
|
83
|
+
}
|
|
67
84
|
merchantIndex;
|
|
68
85
|
quoteFetcher;
|
|
69
86
|
negotiator;
|
|
@@ -76,7 +93,10 @@ export class KiwiBuyerService {
|
|
|
76
93
|
this.sessionId = options.sessionId;
|
|
77
94
|
const clock = options.now ?? utcNow;
|
|
78
95
|
this.now = () => new Date(Date.parse(clock())).toISOString();
|
|
79
|
-
|
|
96
|
+
// A 卡:授权与摘要必须使用同一份 deep-clone/deep-freeze 的 plain-JSON 快照,
|
|
97
|
+
// 避免"原对象被就地改写、摘要仍是旧值"的漂移。
|
|
98
|
+
this.policySnapshot = deepFreezePlain(JSON.parse(JSON.stringify((options.delegationPolicy ?? {}))));
|
|
99
|
+
this.policyDigest = contentDigest(this.policySnapshot);
|
|
80
100
|
this.merchantIndex = options.merchantIndex;
|
|
81
101
|
this.quoteFetcher = options.quoteFetcher;
|
|
82
102
|
this.negotiator = options.negotiator;
|
|
@@ -281,27 +301,93 @@ export class KiwiBuyerService {
|
|
|
281
301
|
if (this.quoteFetcher !== undefined) {
|
|
282
302
|
const merchants = input.merchant_ids ?? [];
|
|
283
303
|
const index = this.merchantIndex;
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
304
|
+
let dispatchStarted = false;
|
|
305
|
+
let dispatchOutcomeUnknown = false;
|
|
306
|
+
let catalogLookupCompleted = false;
|
|
307
|
+
try {
|
|
308
|
+
// 用意图的商品查询解析商家(拿到各自 matching_skus,供 RFQ 用商家自有 SKU)。
|
|
309
|
+
const resolved = index !== undefined ? await index.search(this.firstQuery(input.intent)) : [];
|
|
310
|
+
const merchantRecords = await Promise.all(merchants.map(async (m) => {
|
|
311
|
+
const found = resolved.find((r) => r.merchant_id === m);
|
|
312
|
+
if (found !== undefined)
|
|
313
|
+
return found;
|
|
314
|
+
// intent query 文本未命中 catalog LIKE 时按 merchant_id 直接解析
|
|
315
|
+
// (保 agent_card_url,A2A 才能磋商;host 的 merchant_ids 来自一次
|
|
316
|
+
// 成功的 kiwi_search,不该因意图措辞丢失完整记录)。
|
|
317
|
+
if (index !== undefined) {
|
|
318
|
+
const byId = await index.resolveById(m);
|
|
319
|
+
if (byId !== undefined)
|
|
320
|
+
return byId;
|
|
321
|
+
}
|
|
322
|
+
return { merchant_id: m, name: m, verified: false, capabilities: [] };
|
|
323
|
+
}));
|
|
324
|
+
catalogLookupCompleted = true;
|
|
325
|
+
const protocolContext = this.protocolContext(persisted, merchants);
|
|
326
|
+
// 一旦调用 quoteFetcher,就不能把抛错解释成“没发送”:adapter 可能已
|
|
327
|
+
// 写入/发送部分 RFQ。没有 receipt 时保守落为 non-retryable unknown。
|
|
328
|
+
dispatchStarted = true;
|
|
329
|
+
quotedResults = await this.quoteFetcher.requestQuotes(input.intent, merchantRecords, protocolContext);
|
|
330
|
+
dispatchOutcomeUnknown = quotedResults.some((result) => result.status === "failed" &&
|
|
331
|
+
result.failure?.classification === "protocol_error" &&
|
|
332
|
+
result.failure.retryable === false);
|
|
333
|
+
const returnedMerchants = new Set(quotedResults.map((result) => result.merchant_id));
|
|
334
|
+
const missingResults = merchants.filter((merchantId) => !returnedMerchants.has(merchantId));
|
|
335
|
+
if (missingResults.length > 0)
|
|
336
|
+
dispatchOutcomeUnknown = true;
|
|
337
|
+
quotedResults = [
|
|
338
|
+
...quotedResults,
|
|
339
|
+
...missingResults.map((merchantId) => ({
|
|
340
|
+
merchant_id: merchantId,
|
|
341
|
+
status: "failed",
|
|
342
|
+
failure: {
|
|
343
|
+
classification: "protocol_error",
|
|
344
|
+
retryable: false,
|
|
345
|
+
detail: "RFQ dispatch returned no per-merchant result; remote outcome is unknown",
|
|
346
|
+
},
|
|
347
|
+
})),
|
|
348
|
+
];
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
// Catalog lookup resolves before quoteFetcher: this branch is known not sent.
|
|
352
|
+
// Once quoteFetcher was entered, an exception can follow a remote side effect,
|
|
353
|
+
// so record UNKNOWN and block automatic resend by the same task key.
|
|
354
|
+
const failure = dispatchStarted
|
|
355
|
+
? {
|
|
356
|
+
classification: "protocol_error",
|
|
357
|
+
retryable: false,
|
|
358
|
+
detail: "RFQ dispatch outcome is unknown; a remote side effect may have occurred. Reconcile before retrying",
|
|
359
|
+
}
|
|
360
|
+
: catalogLookupCompleted
|
|
361
|
+
? {
|
|
362
|
+
classification: "other",
|
|
363
|
+
retryable: true,
|
|
364
|
+
detail: "Local RFQ preparation failed before dispatch; no RFQ was sent",
|
|
365
|
+
}
|
|
366
|
+
: {
|
|
367
|
+
classification: "unreachable",
|
|
368
|
+
retryable: true,
|
|
369
|
+
detail: "Catalog lookup failed before RFQ dispatch; no RFQ was sent",
|
|
370
|
+
};
|
|
371
|
+
dispatchOutcomeUnknown = dispatchStarted;
|
|
372
|
+
quotedResults = merchants.map((merchantId) => ({
|
|
373
|
+
merchant_id: merchantId,
|
|
374
|
+
status: "failed",
|
|
375
|
+
failure,
|
|
376
|
+
}));
|
|
377
|
+
}
|
|
378
|
+
if (merchants.length === 0) {
|
|
379
|
+
status = "failed";
|
|
380
|
+
}
|
|
381
|
+
else if (quotedResults.length > 0) {
|
|
382
|
+
const successes = quotedResults.filter((r) => r.status === "succeeded").length;
|
|
383
|
+
status =
|
|
384
|
+
successes === quotedResults.length
|
|
385
|
+
? "succeeded"
|
|
386
|
+
: successes === 0
|
|
387
|
+
? dispatchOutcomeUnknown
|
|
388
|
+
? "in_progress"
|
|
389
|
+
: "failed"
|
|
390
|
+
: "partial_success";
|
|
305
391
|
}
|
|
306
392
|
}
|
|
307
393
|
return this.store.transaction(() => {
|
|
@@ -309,7 +395,10 @@ export class KiwiBuyerService {
|
|
|
309
395
|
this.store.addCandidate(taskId, { candidate_id: `cand-${uuidv7()}`, merchant_id: r.merchant_id, status: r.status, provenance: r.provenance, terms: r.terms, failure: r.failure, retryable: r.status === "failed" ? (r.failure?.retryable ?? false) : false });
|
|
310
396
|
const updated = this.store.updateTask(taskId, {
|
|
311
397
|
status,
|
|
312
|
-
|
|
398
|
+
// A terminal failure is not silently resumed under this idempotency key.
|
|
399
|
+
// A known pre-send failure may be submitted as a new task; an unknown A2A
|
|
400
|
+
// outcome remains non-retryable on its candidate and needs reconciliation.
|
|
401
|
+
resumable: status !== "failed",
|
|
313
402
|
payload: JSON.stringify({
|
|
314
403
|
...this.decodeTask(task),
|
|
315
404
|
status,
|
|
@@ -596,12 +685,20 @@ export class KiwiBuyerService {
|
|
|
596
685
|
if (stored === undefined) {
|
|
597
686
|
throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
|
|
598
687
|
}
|
|
688
|
+
// A 卡:目的地先归一;非法即拒绝,且不落任何意图/审批行。
|
|
689
|
+
const destination = this.normalizeHandoffDestination(input);
|
|
690
|
+
// A 卡:ask 且无 approval_id 时,必须在泛型 evaluateAuthorization 之前
|
|
691
|
+
// 走意图感知的 ASK——否则 evaluateAuthorization 会先写一条无目的地审批。
|
|
692
|
+
if (input.approval_id === undefined && policyActionMode(this.policySnapshot, "handoff") === "ask") {
|
|
693
|
+
const approval_id = this.requestHandoffApproval({ agreement: stored, destination });
|
|
694
|
+
throw new McpError("approval_required", "action=handoff 需要持久审批", { approval_id });
|
|
695
|
+
}
|
|
599
696
|
// review P1-2(A316 校准):handoff 消费绑定 = 结构化 canonical digest
|
|
600
697
|
//(agreement/destination/url),无分隔符歧义。
|
|
601
698
|
const consumedBinding = this.consumeBinding({
|
|
602
699
|
agreement_id: input.agreement_id,
|
|
603
|
-
destination_type:
|
|
604
|
-
url:
|
|
700
|
+
destination_type: destination.destination_type,
|
|
701
|
+
url: destination.url,
|
|
605
702
|
});
|
|
606
703
|
const authorization = await this.evaluateAuthorization("handoff", {
|
|
607
704
|
taskId: stored.task_id,
|
|
@@ -614,8 +711,8 @@ export class KiwiBuyerService {
|
|
|
614
711
|
if (input.approval_id === undefined) {
|
|
615
712
|
const handoffRef = {
|
|
616
713
|
handoff_id: `handoff-${uuidv7()}`,
|
|
617
|
-
destination_type:
|
|
618
|
-
...(
|
|
714
|
+
destination_type: destination.destination_type,
|
|
715
|
+
...(destination.url !== null ? { url: destination.url } : {}),
|
|
619
716
|
};
|
|
620
717
|
return { handoff_ref: handoffRef, authorization };
|
|
621
718
|
}
|
|
@@ -627,14 +724,30 @@ export class KiwiBuyerService {
|
|
|
627
724
|
if (approval === undefined) {
|
|
628
725
|
throw new McpError("invalid_params", `approval ${input.approval_id} 不存在`);
|
|
629
726
|
}
|
|
727
|
+
// A 卡:同事务重读 task/agreement,核验意图(含 agreement 摘要、terms 现值、
|
|
728
|
+
// policy 摘要与全部有效期限);旧审批(无 intent)在此拒绝。
|
|
729
|
+
const freshTask = this.store.getTask(approval.task_id);
|
|
730
|
+
if (freshTask === undefined) {
|
|
731
|
+
throw new McpError("task_not_found", `task ${approval.task_id} not found`);
|
|
732
|
+
}
|
|
733
|
+
const freshAgreement = this.store.getAgreement(input.agreement_id);
|
|
734
|
+
if (freshAgreement === undefined) {
|
|
735
|
+
throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
|
|
736
|
+
}
|
|
737
|
+
this.assertHandoffIntentMatches({
|
|
738
|
+
approval,
|
|
739
|
+
task: freshTask,
|
|
740
|
+
agreement: freshAgreement,
|
|
741
|
+
destination,
|
|
742
|
+
});
|
|
630
743
|
if (approval.status === "used") {
|
|
631
744
|
const consumed = this.approvalConsumed(approval);
|
|
632
745
|
if (consumed !== undefined && consumed.binding === consumedBinding) {
|
|
633
746
|
return {
|
|
634
747
|
handoff_ref: {
|
|
635
748
|
handoff_id: consumed.ref,
|
|
636
|
-
destination_type:
|
|
637
|
-
...(
|
|
749
|
+
destination_type: destination.destination_type,
|
|
750
|
+
...(destination.url !== null ? { url: destination.url } : {}),
|
|
638
751
|
},
|
|
639
752
|
authorization,
|
|
640
753
|
};
|
|
@@ -643,8 +756,8 @@ export class KiwiBuyerService {
|
|
|
643
756
|
}
|
|
644
757
|
const handoffRef = {
|
|
645
758
|
handoff_id: `handoff-${uuidv7()}`,
|
|
646
|
-
destination_type:
|
|
647
|
-
...(
|
|
759
|
+
destination_type: destination.destination_type,
|
|
760
|
+
...(destination.url !== null ? { url: destination.url } : {}),
|
|
648
761
|
};
|
|
649
762
|
this.store.setApproval(approval.task_id, {
|
|
650
763
|
...approval,
|
|
@@ -658,6 +771,185 @@ export class KiwiBuyerService {
|
|
|
658
771
|
});
|
|
659
772
|
}
|
|
660
773
|
// ---- 持久审批(宿主适配面;kiwi_approve / kiwi_reject 为 MCP 工具)----------
|
|
774
|
+
// ---- A 卡:handoff 意图(版本化、摘要不含自身、与 approval 同事务)----------
|
|
775
|
+
/** 目的地归一:类型词表校验 + URL 归一(http/https、无凭据、无 fragment)。 */
|
|
776
|
+
normalizeHandoffDestination(input) {
|
|
777
|
+
if (!isDestinationType(input.destination_type)) {
|
|
778
|
+
throw new McpError("invalid_params", `未知 destination_type:${String(input.destination_type)}`);
|
|
779
|
+
}
|
|
780
|
+
const type = input.destination_type;
|
|
781
|
+
let url = null;
|
|
782
|
+
if (input.url !== undefined) {
|
|
783
|
+
let parsed;
|
|
784
|
+
try {
|
|
785
|
+
parsed = new URL(input.url);
|
|
786
|
+
}
|
|
787
|
+
catch {
|
|
788
|
+
throw new McpError("invalid_params", `destination url 不是合法绝对 URL:${input.url}`);
|
|
789
|
+
}
|
|
790
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
791
|
+
throw new McpError("invalid_params", `destination url 必须是 http(s):${input.url}`);
|
|
792
|
+
}
|
|
793
|
+
if (parsed.username !== "" || parsed.password !== "") {
|
|
794
|
+
throw new McpError("invalid_params", "destination url 不得内嵌凭据");
|
|
795
|
+
}
|
|
796
|
+
if (parsed.hash !== "") {
|
|
797
|
+
throw new McpError("invalid_params", "destination url 不得携带 fragment");
|
|
798
|
+
}
|
|
799
|
+
url = parsed.href;
|
|
800
|
+
}
|
|
801
|
+
if (isUrlDestinationType(type) && url === null) {
|
|
802
|
+
throw new McpError("invalid_params", `destination_type=${type} 必须提供 url`);
|
|
803
|
+
}
|
|
804
|
+
if (isSessionDestinationType(type) && url !== null) {
|
|
805
|
+
throw new McpError("invalid_params", `destination_type=${type} 不得携带 url(会话类为 opaque ref)`);
|
|
806
|
+
}
|
|
807
|
+
return { destination_type: type, url };
|
|
808
|
+
}
|
|
809
|
+
/** 意图对象(不含 intent_digest);字段集固定,缺失一律 null。 */
|
|
810
|
+
buildHandoffIntent(args) {
|
|
811
|
+
const body = {
|
|
812
|
+
intent_version: HANDOFF_INTENT_VERSION,
|
|
813
|
+
action: "handoff",
|
|
814
|
+
task_id: args.task.task_id,
|
|
815
|
+
agreement_id: args.agreement.agreement_id,
|
|
816
|
+
destination_type: args.destination.destination_type,
|
|
817
|
+
url: args.destination.url,
|
|
818
|
+
agreement_sha256: `sha256:${sha256Hex(args.agreement.payload)}`,
|
|
819
|
+
terms_digest: args.agreement.terms_digest ?? null,
|
|
820
|
+
policy_id: this.policySnapshot.policy_id,
|
|
821
|
+
policy_digest: this.policyDigest,
|
|
822
|
+
issued_at: args.issuedAt,
|
|
823
|
+
expires_at: args.expiresAt,
|
|
824
|
+
};
|
|
825
|
+
return { intent_id: `intent-${uuidv7()}`, intent_digest: contentDigest(body), ...body };
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* 意图感知的 ASK:在泛型 evaluateAuthorization 之前由 handoff 调用,
|
|
829
|
+
* 同事务写 intent 与 approval,杜绝"先产生无目的地审批再补绑定"。
|
|
830
|
+
*/
|
|
831
|
+
requestHandoffApproval(args) {
|
|
832
|
+
const nowIso = this.now();
|
|
833
|
+
const nowMs = Date.parse(nowIso);
|
|
834
|
+
const task = this.store.getTask(args.agreement.task_id);
|
|
835
|
+
if (task === undefined)
|
|
836
|
+
throw new McpError("task_not_found", `task ${args.agreement.task_id} not found`);
|
|
837
|
+
// policy 自身期限在 ASK 侧同样独立校验(同一 now 样本)。
|
|
838
|
+
this.assertPolicyActive(nowMs);
|
|
839
|
+
const taskExpiry = task.expires_at === undefined ? Number.NaN : Date.parse(task.expires_at);
|
|
840
|
+
if (!Number.isFinite(taskExpiry) || taskExpiry <= nowMs) {
|
|
841
|
+
throw new McpError("invalid_params", `task ${task.task_id} 已过期或缺少有效期限`);
|
|
842
|
+
}
|
|
843
|
+
if (args.agreement.expires_at != null) {
|
|
844
|
+
const agreementExpiry = Date.parse(args.agreement.expires_at);
|
|
845
|
+
if (!Number.isFinite(agreementExpiry) || agreementExpiry <= nowMs) {
|
|
846
|
+
throw new McpError("invalid_params", `agreement ${args.agreement.agreement_id} 已过期或期限非法`);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
const intent = this.buildHandoffIntent({
|
|
850
|
+
task,
|
|
851
|
+
agreement: args.agreement,
|
|
852
|
+
destination: args.destination,
|
|
853
|
+
issuedAt: nowIso,
|
|
854
|
+
expiresAt: task.expires_at,
|
|
855
|
+
});
|
|
856
|
+
return this.store.transaction(() => {
|
|
857
|
+
this.store.setHandoffIntent(intent);
|
|
858
|
+
const created = this.requestApproval({
|
|
859
|
+
task_id: task.task_id,
|
|
860
|
+
action: "handoff",
|
|
861
|
+
candidate_digest: undefined,
|
|
862
|
+
});
|
|
863
|
+
if (!this.store.bindApprovalIntent(created.approval_id, intent.intent_digest)) {
|
|
864
|
+
throw new McpError("approval_denied", `approval ${created.approval_id} 无法绑定意图`);
|
|
865
|
+
}
|
|
866
|
+
return created.approval_id;
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* 由存储的 intent 重建 canonical body(字段集与 `buildHandoffIntent` 完全一致,
|
|
871
|
+
* 排除 `intent_digest` 自身)。任何字段被改都会改变重算摘要。
|
|
872
|
+
*/
|
|
873
|
+
handoffIntentBody(intent) {
|
|
874
|
+
return {
|
|
875
|
+
intent_version: intent.intent_version,
|
|
876
|
+
action: "handoff",
|
|
877
|
+
task_id: intent.task_id,
|
|
878
|
+
agreement_id: intent.agreement_id,
|
|
879
|
+
destination_type: intent.destination_type,
|
|
880
|
+
url: intent.url ?? null,
|
|
881
|
+
agreement_sha256: intent.agreement_sha256,
|
|
882
|
+
terms_digest: intent.terms_digest ?? null,
|
|
883
|
+
policy_id: intent.policy_id,
|
|
884
|
+
policy_digest: intent.policy_digest,
|
|
885
|
+
issued_at: intent.issued_at,
|
|
886
|
+
expires_at: intent.expires_at,
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
/** policy 自身期限必须独立有效(不能只靠 DB 其它期限间接代表)。 */
|
|
890
|
+
assertPolicyActive(nowMs) {
|
|
891
|
+
const raw = this.policySnapshot.expires_at;
|
|
892
|
+
const ms = typeof raw === "string" ? Date.parse(raw) : Number.NaN;
|
|
893
|
+
if (!Number.isFinite(ms) || ms <= nowMs) {
|
|
894
|
+
throw new McpError("approval_denied", "委托策略已过期或缺少有效期限");
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
/** 消费前的意图核验:重算摘要 + 逐字段 + 重算 agreement 摘要 + 现值 terms + policy 期限/摘要 + 全部期限。 */
|
|
898
|
+
assertHandoffIntentMatches(args) {
|
|
899
|
+
if (args.approval.action !== "handoff") {
|
|
900
|
+
throw new McpError("approval_denied", `approval ${args.approval.approval_id} 动作不是 handoff`);
|
|
901
|
+
}
|
|
902
|
+
if (args.approval.intent_digest === undefined) {
|
|
903
|
+
throw new McpError("approval_denied", `approval ${args.approval.approval_id} 缺少 handoff 意图(旧审批),请重新 ASK`);
|
|
904
|
+
}
|
|
905
|
+
const intent = this.store.getHandoffIntent(args.approval.intent_digest);
|
|
906
|
+
if (intent === undefined) {
|
|
907
|
+
throw new McpError("approval_denied", `approval ${args.approval.approval_id} 的意图不存在`);
|
|
908
|
+
}
|
|
909
|
+
const nowMs = Date.parse(this.now());
|
|
910
|
+
// (1) policy 自身期限独立校验(同一 now 样本)。
|
|
911
|
+
this.assertPolicyActive(nowMs);
|
|
912
|
+
// (2) 重建 canonical body 并重算摘要:必须同时等于存储摘要与 approval 绑定,
|
|
913
|
+
// 防止"只改持久字段、摘要与绑定不动"的漂移。
|
|
914
|
+
const rebuiltDigest = contentDigest(this.handoffIntentBody(intent));
|
|
915
|
+
if (rebuiltDigest !== intent.intent_digest || rebuiltDigest !== args.approval.intent_digest) {
|
|
916
|
+
throw new McpError("approval_denied", "handoff 意图摘要与存储不一致(内容被改动)");
|
|
917
|
+
}
|
|
918
|
+
const expiries = [intent.expires_at, args.approval.expires_at, args.task.expires_at];
|
|
919
|
+
if (args.agreement.expires_at != null)
|
|
920
|
+
expiries.push(args.agreement.expires_at);
|
|
921
|
+
for (const value of expiries) {
|
|
922
|
+
if (value === undefined)
|
|
923
|
+
continue;
|
|
924
|
+
const ms = Date.parse(value);
|
|
925
|
+
if (!Number.isFinite(ms) || ms <= nowMs) {
|
|
926
|
+
throw new McpError("approval_denied", `handoff 期限已过或非法:${String(value)}`);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
const mismatch = [];
|
|
930
|
+
if (intent.intent_version !== HANDOFF_INTENT_VERSION)
|
|
931
|
+
mismatch.push("intent_version");
|
|
932
|
+
if (intent.task_id !== args.task.task_id)
|
|
933
|
+
mismatch.push("task_id");
|
|
934
|
+
if (intent.agreement_id !== args.agreement.agreement_id)
|
|
935
|
+
mismatch.push("agreement_id");
|
|
936
|
+
if (intent.destination_type !== args.destination.destination_type)
|
|
937
|
+
mismatch.push("destination_type");
|
|
938
|
+
if (intent.url !== args.destination.url)
|
|
939
|
+
mismatch.push("url");
|
|
940
|
+
if (intent.agreement_sha256 !== `sha256:${sha256Hex(args.agreement.payload)}`)
|
|
941
|
+
mismatch.push("agreement_sha256");
|
|
942
|
+
if (intent.terms_digest !== (args.agreement.terms_digest ?? null))
|
|
943
|
+
mismatch.push("terms_digest");
|
|
944
|
+
if (intent.policy_digest !== this.policyDigest)
|
|
945
|
+
mismatch.push("policy_digest");
|
|
946
|
+
if (intent.policy_id !== this.policySnapshot.policy_id)
|
|
947
|
+
mismatch.push("policy_id");
|
|
948
|
+
if (mismatch.length > 0) {
|
|
949
|
+
throw new McpError("approval_denied", `handoff 意图与当前请求不一致:${mismatch.join(",")}`);
|
|
950
|
+
}
|
|
951
|
+
return intent;
|
|
952
|
+
}
|
|
661
953
|
/** 创建 pending 审批记录(ASK 动作触发)。返回持久 approval_id。 */
|
|
662
954
|
requestApproval(input) {
|
|
663
955
|
const task = this.store.getTask(input.task_id);
|