@harrylabsj/kiwi 0.12.25 → 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.
@@ -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";
@@ -150,6 +152,7 @@ export class KiwiBuyerService {
150
152
  principal;
151
153
  buyerAgentId;
152
154
  sessionId;
155
+ ownerHash;
153
156
  policySnapshot;
154
157
  policyDigest;
155
158
  /** 兼容既有内部读取点:一律指向已冻结快照,不再暴露可变原对象。 */
@@ -160,12 +163,19 @@ export class KiwiBuyerService {
160
163
  quoteFetcher;
161
164
  negotiator;
162
165
  followsClient;
166
+ staleWake;
167
+ staleWakeTimeoutMs;
168
+ wakeAttemptAt = new Map();
169
+ wakeInFlight = new Map();
163
170
  now;
164
171
  constructor(options) {
165
172
  this.store = options.store;
166
173
  this.principal = options.principal;
167
174
  this.buyerAgentId = options.buyerAgentId;
168
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")}`;
169
179
  const clock = options.now ?? utcNow;
170
180
  this.now = () => new Date(Date.parse(clock())).toISOString();
171
181
  // A 卡:授权与摘要必须使用同一份 deep-clone/deep-freeze 的 plain-JSON 快照,
@@ -176,6 +186,97 @@ export class KiwiBuyerService {
176
186
  this.quoteFetcher = options.quoteFetcher;
177
187
  this.negotiator = options.negotiator;
178
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;
179
280
  }
180
281
  // ---- Northbound:kiwi_search ----------------------------------------------
181
282
  async search(input) {
@@ -196,7 +297,7 @@ export class KiwiBuyerService {
196
297
  });
197
298
  // 单侧降级/离线说明如实标注;不静默、不补全。
198
299
  return {
199
- merchants,
300
+ merchants: await this.refreshStaleMerchants(merchants),
200
301
  ...(diagnostics.notes.length > 0 ? { note: diagnostics.notes.join(";") } : {}),
201
302
  network_search: diagnostics,
202
303
  };
@@ -213,7 +314,7 @@ export class KiwiBuyerService {
213
314
  notes,
214
315
  });
215
316
  return {
216
- merchants,
317
+ merchants: await this.refreshStaleMerchants(merchants),
217
318
  ...(notes.length > 0 ? { note: notes.join(";") } : {}),
218
319
  network_search: diagnostics,
219
320
  };
@@ -309,6 +410,7 @@ export class KiwiBuyerService {
309
410
  : [];
310
411
  const task = {
311
412
  task_id: taskId,
413
+ owner_hash: this.ownerHash,
312
414
  task_kind: "request_quotes",
313
415
  status: "in_progress",
314
416
  idempotency_key: idempotencyKey,
@@ -335,6 +437,11 @@ export class KiwiBuyerService {
335
437
  };
336
438
  const { task: persisted, created: isCreated } = this.store.createTask(task);
337
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
+ }
338
445
  if (this.quoteFetcher?.recoverQuotes !== undefined) {
339
446
  const original = this.decodeTask(persisted).intent;
340
447
  if (original !== undefined && contentDigest(original) !== contentDigest(input.intent))
@@ -497,7 +604,7 @@ export class KiwiBuyerService {
497
604
  }
498
605
  // ---- Northbound:kiwi_get_task --------------------------------------------
499
606
  getTask(taskId) {
500
- const task = this.store.getTask(taskId);
607
+ const task = this.taskFor(taskId);
501
608
  if (task === undefined)
502
609
  throw new McpError("task_not_found", `task ${taskId} not found`);
503
610
  if (task.expires_at !== undefined && Date.parse(task.expires_at) < Date.parse(this.now())) {
@@ -519,7 +626,7 @@ export class KiwiBuyerService {
519
626
  (!Number.isSafeInteger(explicitTarget.amount_minor) || explicitTarget.amount_minor <= 0)) {
520
627
  throw new McpError("invalid_params", "target_unit_price.amount_minor 必须是正整数(最小货币单位)");
521
628
  }
522
- const task = this.store.getTask(input.task_id);
629
+ const task = this.taskFor(input.task_id);
523
630
  if (task === undefined)
524
631
  throw new McpError("task_not_found", `task ${input.task_id} not found`);
525
632
  if (task.expires_at !== undefined && Date.parse(task.expires_at) < Date.parse(this.now())) {
@@ -623,7 +730,7 @@ export class KiwiBuyerService {
623
730
  }
624
731
  // ---- Northbound:kiwi_accept_agreement ------------------------------------
625
732
  async acceptAgreement(input) {
626
- const task = this.store.getTask(input.task_id);
733
+ const task = this.taskFor(input.task_id);
627
734
  if (task === undefined)
628
735
  throw new McpError("task_not_found", `task ${input.task_id} not found`);
629
736
  if (task.expires_at !== undefined && Date.parse(task.expires_at) < Date.parse(this.now())) {
@@ -679,18 +786,47 @@ export class KiwiBuyerService {
679
786
  }
680
787
  const existingAgreement = this.store.findAgreementByTerms(input.task_id, termsDigest);
681
788
  let merchantAgreement;
682
- if (existingAgreement === undefined && this.negotiator?.acceptNonbinding !== undefined) {
683
- // 只有 A2A 候选才向商家发 accept;本地/演示候选保持本地协议语义。
789
+ if (existingAgreement === undefined) {
684
790
  const provenance = preCandidate.provenance ?? {};
685
- if (typeof provenance.a2a_endpoint === "string" &&
686
- provenance.a2a_endpoint !== "" &&
687
- provenance.latest_offer_type === "conditional_offer") {
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
+ }
688
806
  const accepted = await this.negotiator.acceptNonbinding({
689
807
  taskId: input.task_id,
690
808
  candidate: preCandidate,
691
809
  context: this.protocolContext(task),
692
810
  });
693
- merchantAgreement = accepted.agreement;
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;
694
830
  }
695
831
  }
696
832
  // review P1-2(A316 校准):短事务原子消费——事务内重读授权、写
@@ -698,12 +834,12 @@ export class KiwiBuyerService {
698
834
  // 无事后补偿、不烧毁有效批准——同绑定重试重新进入本事务)。node:sqlite
699
835
  // 同步执行 + BEGIN IMMEDIATE 写锁,进程内/跨连接均互斥。
700
836
  return this.store.transaction(() => {
701
- const freshTask = this.store.getTask(input.task_id);
837
+ const freshTask = this.taskFor(input.task_id);
702
838
  if (freshTask === undefined) {
703
839
  throw new McpError("task_not_found", `task ${input.task_id} not found`);
704
840
  }
705
841
  if (input.approval_id !== undefined) {
706
- const fresh = this.store.getApproval(input.approval_id);
842
+ const fresh = this.approvalFor(input.approval_id);
707
843
  if (fresh === undefined) {
708
844
  throw new McpError("approval_required", `approval ${input.approval_id} 不存在`, {
709
845
  approval_id: input.approval_id,
@@ -751,13 +887,13 @@ export class KiwiBuyerService {
751
887
  consumed.binding === consumedBinding) {
752
888
  // 同逻辑重放:返回库里既有的同一 agreement(非虚构结果)。
753
889
  const existing = consumed.ref.startsWith("agreement-")
754
- ? this.store.getAgreement(consumed.ref)
890
+ ? this.agreementFor(consumed.ref)
755
891
  : undefined;
756
892
  if (existing === undefined) {
757
893
  throw new McpError("approval_denied", `approval ${input.approval_id} 已消费但绑定效果不可读;需要人工对账`);
758
894
  }
759
895
  return {
760
- task: this.decodeTask(this.store.getTask(input.task_id)),
896
+ task: this.decodeTask(this.taskFor(input.task_id)),
761
897
  agreement: JSON.parse(existing.payload),
762
898
  authorization,
763
899
  };
@@ -830,7 +966,7 @@ export class KiwiBuyerService {
830
966
  }),
831
967
  }, freshTask);
832
968
  if (input.approval_id !== undefined) {
833
- const approval = this.store.getApproval(input.approval_id);
969
+ const approval = this.approvalFor(input.approval_id);
834
970
  if (approval !== undefined) {
835
971
  this.store.setApproval(approval.task_id, {
836
972
  ...approval,
@@ -847,7 +983,7 @@ export class KiwiBuyerService {
847
983
  }
848
984
  // ---- Northbound:kiwi_get_agreement ---------------------------------------
849
985
  getAgreement(agreementId) {
850
- const stored = this.store.getAgreement(agreementId);
986
+ const stored = this.agreementFor(agreementId);
851
987
  if (stored === undefined) {
852
988
  throw new McpError("agreement_not_found", `agreement ${agreementId} not found`);
853
989
  }
@@ -855,7 +991,7 @@ export class KiwiBuyerService {
855
991
  }
856
992
  // ---- Northbound:kiwi_handoff ---------------------------------------------
857
993
  async handoff(input) {
858
- const stored = this.store.getAgreement(input.agreement_id);
994
+ const stored = this.agreementFor(input.agreement_id);
859
995
  if (stored === undefined) {
860
996
  throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
861
997
  }
@@ -907,17 +1043,17 @@ export class KiwiBuyerService {
907
1043
  // 消费;同绑定重放返回**库里记录的同一 ref**(非虚构);失败 ROLLBACK
908
1044
  // 不烧毁审批。
909
1045
  return this.store.transaction(() => {
910
- const approval = this.store.getApproval(input.approval_id);
1046
+ const approval = this.approvalFor(input.approval_id);
911
1047
  if (approval === undefined) {
912
1048
  throw new McpError("invalid_params", `approval ${input.approval_id} 不存在`);
913
1049
  }
914
1050
  // A 卡:同事务重读 task/agreement,核验意图(含 agreement 摘要、terms 现值、
915
1051
  // policy 摘要与全部有效期限);旧审批(无 intent)在此拒绝。
916
- const freshTask = this.store.getTask(approval.task_id);
1052
+ const freshTask = this.taskFor(approval.task_id);
917
1053
  if (freshTask === undefined) {
918
1054
  throw new McpError("task_not_found", `task ${approval.task_id} not found`);
919
1055
  }
920
- const freshAgreement = this.store.getAgreement(input.agreement_id);
1056
+ const freshAgreement = this.agreementFor(input.agreement_id);
921
1057
  if (freshAgreement === undefined) {
922
1058
  throw new McpError("agreement_not_found", `agreement ${input.agreement_id} not found`);
923
1059
  }
@@ -1018,7 +1154,7 @@ export class KiwiBuyerService {
1018
1154
  requestHandoffApproval(args) {
1019
1155
  const nowIso = this.now();
1020
1156
  const nowMs = Date.parse(nowIso);
1021
- const task = this.store.getTask(args.agreement.task_id);
1157
+ const task = this.taskFor(args.agreement.task_id);
1022
1158
  if (task === undefined)
1023
1159
  throw new McpError("task_not_found", `task ${args.agreement.task_id} not found`);
1024
1160
  // policy 自身期限在 ASK 侧同样独立校验(同一 now 样本)。
@@ -1089,7 +1225,7 @@ export class KiwiBuyerService {
1089
1225
  if (args.approval.intent_digest === undefined) {
1090
1226
  throw new McpError("approval_denied", `approval ${args.approval.approval_id} 缺少 handoff 意图(旧审批),请重新 ASK`);
1091
1227
  }
1092
- const intent = this.store.getHandoffIntent(args.approval.intent_digest);
1228
+ const intent = this.handoffFor(args.approval.intent_digest);
1093
1229
  if (intent === undefined) {
1094
1230
  throw new McpError("approval_denied", `approval ${args.approval.approval_id} 的意图不存在`);
1095
1231
  }
@@ -1139,7 +1275,7 @@ export class KiwiBuyerService {
1139
1275
  }
1140
1276
  /** 创建 pending 审批记录(ASK 动作触发)。返回持久 approval_id。 */
1141
1277
  requestApproval(input) {
1142
- const task = this.store.getTask(input.task_id);
1278
+ const task = this.taskFor(input.task_id);
1143
1279
  if (task === undefined)
1144
1280
  throw new McpError("task_not_found", `task ${input.task_id} not found`);
1145
1281
  const approvalId = `approval-${uuidv7()}`;
@@ -1156,7 +1292,7 @@ export class KiwiBuyerService {
1156
1292
  }
1157
1293
  /** 批准一个 pending 审批(绑定授权记录)。 */
1158
1294
  approveApproval(input) {
1159
- const stored = this.store.getApproval(input.approval_id);
1295
+ const stored = this.approvalFor(input.approval_id);
1160
1296
  if (stored === undefined)
1161
1297
  throw new McpError("invalid_params", `approval ${input.approval_id} not found`);
1162
1298
  if (stored.status !== "pending" || this.approvalConsumed(stored) !== undefined) {
@@ -1172,7 +1308,7 @@ export class KiwiBuyerService {
1172
1308
  }
1173
1309
  /** 拒绝一个 pending 审批(deny 路径;deny 优先,§5.5)。 */
1174
1310
  rejectApproval(input) {
1175
- const stored = this.store.getApproval(input.approval_id);
1311
+ const stored = this.approvalFor(input.approval_id);
1176
1312
  if (stored === undefined)
1177
1313
  throw new McpError("invalid_params", `approval ${input.approval_id} not found`);
1178
1314
  this.store.setApproval(stored.task_id, {
@@ -1192,7 +1328,7 @@ export class KiwiBuyerService {
1192
1328
  * kiwi_accept_agreement / kiwi_handoff。
1193
1329
  */
1194
1330
  approve(input) {
1195
- const stored = this.store.getApproval(input.approval_id);
1331
+ const stored = this.approvalFor(input.approval_id);
1196
1332
  if (stored === undefined)
1197
1333
  throw new McpError("invalid_params", `approval ${input.approval_id} not found`);
1198
1334
  if (stored.status !== "pending") {
@@ -1224,7 +1360,7 @@ export class KiwiBuyerService {
1224
1360
  }
1225
1361
  /** 宿主拒绝一个 pending 审批(deny 优先路径;拒绝后不可再批准)。 */
1226
1362
  reject(input) {
1227
- const stored = this.store.getApproval(input.approval_id);
1363
+ const stored = this.approvalFor(input.approval_id);
1228
1364
  if (stored === undefined)
1229
1365
  throw new McpError("invalid_params", `approval ${input.approval_id} not found`);
1230
1366
  if (stored.status !== "pending") {
@@ -1250,7 +1386,7 @@ export class KiwiBuyerService {
1250
1386
  else if (mode === "ask") {
1251
1387
  // ASK:必须有已批准的持久审批;approval 动作必须与请求动作一致。
1252
1388
  const expectedAction = action === "accept_nonbinding" ? "accept_nonbinding" : "handoff";
1253
- const approval = opts.approvalId !== undefined ? this.store.getApproval(opts.approvalId) : undefined;
1389
+ const approval = opts.approvalId !== undefined ? this.approvalFor(opts.approvalId) : undefined;
1254
1390
  if (opts.approvalId !== undefined && approval === undefined) {
1255
1391
  throw new McpError("approval_required", `approval ${opts.approvalId} 不存在`, {
1256
1392
  approval_id: opts.approvalId,
@@ -1650,7 +1786,7 @@ export class KiwiBuyerService {
1650
1786
  expires_at: task.expires_at,
1651
1787
  resumable: task.resumable,
1652
1788
  candidates: this.northboundCandidates(task.task_id),
1653
- approval: this.store.listApprovalsByTask(task.task_id)[0],
1789
+ approval: this.approvalsForTask(task.task_id)[0],
1654
1790
  };
1655
1791
  }
1656
1792
  /**
@@ -1685,6 +1821,14 @@ export class KiwiBuyerService {
1685
1821
  // 与上一门区分:这里商家**开通过**实时询价,只是当前不在线——错误码不同,
1686
1822
  // 处置也不同(稍后重试/联系商家,而不是"从未开通")。
1687
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
+ }
1688
1832
  throw new McpError("merchant_offline", `商家 ${merchantId}(${record.name})的服务当前不在线(未在有效期内上报心跳),` +
1689
1833
  "暂不可实时询价;其公开资料仍可查看,可稍后重试", { merchant_id: merchantId, freshness_state: record.freshness_state ?? "stale" });
1690
1834
  }