@mysten-incubation/suipay-mcp 0.3.0-dev.2 → 0.3.0-dev.21

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.
@@ -448,6 +448,14 @@ var SERVICE_STATE_TRANSITIONS = Object.freeze([
448
448
  to: "payout_change",
449
449
  actors: ["system"],
450
450
  requires: ["reason_code"]
451
+ },
452
+ {
453
+ id: "T25",
454
+ dimension: "suspension",
455
+ from: ["binding_changed"],
456
+ to: "none",
457
+ actors: ["system"],
458
+ requires: ["reason_code"]
451
459
  }
452
460
  ]);
453
461
 
@@ -949,6 +957,70 @@ function createSpendAccountChain(options) {
949
957
  });
950
958
  return kindBytes(tx);
951
959
  },
960
+ async buildCreatePolicyAndGrantKind(input) {
961
+ if (!input.policy.targets?.length) {
962
+ throw new Error("create_spend_policy requires at least one target");
963
+ }
964
+ if (!input.policy.totalCap || BigInt(input.policy.totalCap) <= 0n) {
965
+ throw new Error("create_spend_policy requires a non-zero total_cap");
966
+ }
967
+ if (!input.policy.maxPerPayment || BigInt(input.policy.maxPerPayment) <= 0n) {
968
+ throw new Error("create_spend_policy requires a non-zero max_per_payment");
969
+ }
970
+ if (!input.grant.sessionCap || BigInt(input.grant.sessionCap) <= 0n) {
971
+ throw new Error("create_grant requires a non-zero session_cap");
972
+ }
973
+ if (!input.grant.maxPerPayment || BigInt(input.grant.maxPerPayment) <= 0n) {
974
+ throw new Error("create_grant requires a non-zero max_per_payment");
975
+ }
976
+ const tx = new Transaction2();
977
+ tx.setSender(input.owner);
978
+ const targetResults = input.policy.targets.map((t) => {
979
+ const hash = targetHashBytes(t.targetHash);
980
+ return tx.moveCall({
981
+ target: target("new_policy_target"),
982
+ arguments: [
983
+ tx.pure.vector("u8", Array.from(hash)),
984
+ tx.pure.address(t.recipient),
985
+ tx.pure.u64(BigInt(t.maxPerPayment))
986
+ ]
987
+ });
988
+ });
989
+ const targetsVec = tx.makeMoveVec({
990
+ type: `${packageId}::${MODULE}::PolicyTarget`,
991
+ elements: targetResults
992
+ });
993
+ const policyExpires = input.policy.expiresAtMs === void 0 || input.policy.expiresAtMs === null ? 0n : BigInt(input.policy.expiresAtMs);
994
+ const policyIdResult = tx.moveCall({
995
+ target: target("create_spend_policy"),
996
+ typeArguments: [input.coinType],
997
+ arguments: [
998
+ tx.object(input.poolObjectId),
999
+ targetsVec,
1000
+ tx.pure.u64(BigInt(input.policy.totalCap)),
1001
+ tx.pure.u64(BigInt(input.policy.maxPerPayment)),
1002
+ tx.pure.u64(policyExpires)
1003
+ ]
1004
+ });
1005
+ const policyIdsVec = tx.makeMoveVec({
1006
+ type: "u64",
1007
+ elements: [policyIdResult]
1008
+ });
1009
+ const grantExpires = input.grant.expiresAtMs === void 0 || input.grant.expiresAtMs === null ? 0n : BigInt(input.grant.expiresAtMs);
1010
+ tx.moveCall({
1011
+ target: target("create_policy_grant"),
1012
+ typeArguments: [input.coinType],
1013
+ arguments: [
1014
+ tx.object(input.poolObjectId),
1015
+ tx.pure.address(input.delegate),
1016
+ tx.pure.option("u64", BigInt(input.grant.sessionCap)),
1017
+ tx.pure.option("u64", BigInt(input.grant.maxPerPayment)),
1018
+ tx.pure.u64(grantExpires),
1019
+ policyIdsVec
1020
+ ]
1021
+ });
1022
+ return kindBytes(tx);
1023
+ },
952
1024
  async buildPausePolicyKind(input) {
953
1025
  const tx = new Transaction2();
954
1026
  tx.setSender(input.owner);
@@ -1687,12 +1759,6 @@ import { fromBase64 as fromBase644, toBase64 as toBase643 } from "@mysten/sui/ut
1687
1759
 
1688
1760
  // ../sdk/dist/protocol/auth-params.js
1689
1761
  var TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
1690
- function formatAuthParams(params) {
1691
- return Object.entries(params).map(([k, v]) => `${k}=${TOKEN.test(v) ? v : quote(v)}`).join(", ");
1692
- }
1693
- function quote(value) {
1694
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
1695
- }
1696
1762
  function parseAuthHeader(header) {
1697
1763
  const trimmed = header.trim();
1698
1764
  const firstSpace = trimmed.indexOf(" ");
@@ -1771,6 +1837,19 @@ function bytesToBase64Url(bytes) {
1771
1837
  const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
1772
1838
  return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
1773
1839
  }
1840
+ function bytesFromBase64Url(s) {
1841
+ const normalized = s.replace(/-/g, "+").replace(/_/g, "/");
1842
+ const pad = (4 - normalized.length % 4) % 4;
1843
+ const base64 = normalized + "=".repeat(pad);
1844
+ if (typeof globalThis.atob === "function") {
1845
+ const binary = globalThis.atob(base64);
1846
+ const out = new Uint8Array(binary.length);
1847
+ for (let i = 0; i < binary.length; i++)
1848
+ out[i] = binary.charCodeAt(i);
1849
+ return out;
1850
+ }
1851
+ return Uint8Array.from(Buffer.from(base64, "base64"));
1852
+ }
1774
1853
 
1775
1854
  // ../sdk/dist/protocol/challenge.js
1776
1855
  import { Ed25519PublicKey } from "@mysten/sui/keypairs/ed25519";
@@ -2115,9 +2194,220 @@ function offerToBase64Url(offer) {
2115
2194
  }
2116
2195
  var MPP_SCHEME = "Payment";
2117
2196
  var MPP_METHOD = "sui.charge";
2197
+ var MPP_SUI_METHOD = "sui";
2198
+ var MPP_CHARGE_INTENT = "charge";
2199
+ var MPP_RECEIPT_STATUS = "success";
2200
+ var LEGACY_RECEIPT_STATUS = "settled";
2118
2201
  var MPP_CHALLENGE_HEADER = "WWW-Authenticate";
2119
2202
  var MPP_CREDENTIAL_HEADER = "Authorization";
2120
2203
  var MPP_RECEIPT_HEADER = "Payment-Receipt";
2204
+ var HEADER_TEXT_REPLACEMENTS = {
2205
+ "\u2264": "<=",
2206
+ // ≤ less-than-or-equal
2207
+ "\u2265": ">=",
2208
+ // ≥ greater-than-or-equal
2209
+ "\u2014": "-",
2210
+ // — em dash
2211
+ "\u2013": "-",
2212
+ // – en dash
2213
+ "\u2018": "'",
2214
+ // ' left single quote
2215
+ "\u2019": "'",
2216
+ // ' right single quote
2217
+ "\u201C": '"',
2218
+ // " left double quote
2219
+ "\u201D": '"'
2220
+ // " right double quote
2221
+ };
2222
+ function latin1HeaderText(value) {
2223
+ let out = "";
2224
+ for (const ch of value) {
2225
+ const mapped = HEADER_TEXT_REPLACEMENTS[ch];
2226
+ if (mapped !== void 0)
2227
+ out += mapped;
2228
+ else if (ch.codePointAt(0) > 255)
2229
+ out += "?";
2230
+ else
2231
+ out += ch;
2232
+ }
2233
+ return out;
2234
+ }
2235
+ var DAY_MS = 864e5;
2236
+ function billingPeriod(periodMs) {
2237
+ if (!Number.isInteger(periodMs) || periodMs < DAY_MS || periodMs % DAY_MS !== 0)
2238
+ return null;
2239
+ const days = periodMs / DAY_MS;
2240
+ if (days % 7 === 0)
2241
+ return { periodCount: String(days / 7), periodUnit: "week" };
2242
+ return { periodCount: String(days), periodUnit: "day" };
2243
+ }
2244
+ function billingPeriodMs(unit, count) {
2245
+ if (!Number.isInteger(count) || count <= 0)
2246
+ return null;
2247
+ if (unit === "day")
2248
+ return count * DAY_MS;
2249
+ if (unit === "week")
2250
+ return count * 7 * DAY_MS;
2251
+ return null;
2252
+ }
2253
+ function expiresWire(offer) {
2254
+ if (typeof offer.expiresAt !== "number" || !Number.isFinite(offer.expiresAt))
2255
+ return void 0;
2256
+ return new Date(offer.expiresAt).toISOString();
2257
+ }
2258
+ function flatParams(offer) {
2259
+ const params = {
2260
+ amount: offer.amount,
2261
+ asset: offer.asset,
2262
+ network: offer.network,
2263
+ recipient: offer.payTo,
2264
+ package: offer.packageId,
2265
+ resource: offer.resource,
2266
+ digest: offer.digest
2267
+ };
2268
+ if (typeof offer.decimals === "number")
2269
+ params.decimals = String(offer.decimals);
2270
+ if (typeof offer.description === "string") {
2271
+ params.description = latin1HeaderText(offer.description);
2272
+ }
2273
+ if (typeof offer.issuedAt === "number" && Number.isFinite(offer.issuedAt)) {
2274
+ params.issued = new Date(offer.issuedAt).toISOString();
2275
+ }
2276
+ if (typeof offer.expiresAt === "number" && Number.isFinite(offer.expiresAt)) {
2277
+ params.expires = new Date(offer.expiresAt).toISOString();
2278
+ }
2279
+ if (offer.netAmount !== void 0)
2280
+ params.net_amount = offer.netAmount;
2281
+ if (offer.platformFee !== void 0)
2282
+ params.platform_fee = offer.platformFee;
2283
+ if (offer.digestVersion !== void 0)
2284
+ params.digest_version = String(offer.digestVersion);
2285
+ if (offer.settlementRail !== void 0)
2286
+ params.settlement_rail = offer.settlementRail;
2287
+ if (offer.serviceId !== void 0)
2288
+ params.service_id = offer.serviceId;
2289
+ if (offer.serviceRevision !== void 0) {
2290
+ params.service_revision = String(offer.serviceRevision);
2291
+ }
2292
+ if (offer.targetHash !== void 0)
2293
+ params.target_hash = offer.targetHash;
2294
+ if (offer.authorizationEpoch !== void 0) {
2295
+ params.authorization_epoch = String(offer.authorizationEpoch);
2296
+ }
2297
+ if (offer.method !== void 0)
2298
+ params.http_method = offer.method;
2299
+ if (offer.path !== void 0)
2300
+ params.http_path = offer.path;
2301
+ if (offer.bodyHash !== void 0)
2302
+ params.body_hash = offer.bodyHash;
2303
+ if (offer.contentType !== void 0)
2304
+ params.content_type = offer.contentType;
2305
+ if (offer.intent !== void 0)
2306
+ params.intent = offer.intent;
2307
+ if (offer.periodMs !== void 0)
2308
+ params.period_ms = String(offer.periodMs);
2309
+ if (offer.periodCount !== void 0)
2310
+ params.period_count = String(offer.periodCount);
2311
+ if (offer.refundable !== void 0)
2312
+ params.refundable = offer.refundable ? "true" : "false";
2313
+ if (offer.refundWindowMs !== void 0) {
2314
+ params.refund_window_ms = String(offer.refundWindowMs);
2315
+ }
2316
+ if (offer.decideWindowMs !== void 0) {
2317
+ params.decide_window_ms = String(offer.decideWindowMs);
2318
+ }
2319
+ if (offer.chainId !== void 0)
2320
+ params.chain_id = String(offer.chainId);
2321
+ if (offer.paymentSalt !== void 0)
2322
+ params.payment_salt = offer.paymentSalt;
2323
+ if (offer.refundConfigId !== void 0)
2324
+ params.refund_config_id = offer.refundConfigId;
2325
+ if (offer.refundTo !== void 0)
2326
+ params.refund_to = offer.refundTo;
2327
+ if (offer.sponsorGasOwner !== void 0) {
2328
+ params.sponsor_gas_owner = offer.sponsorGasOwner;
2329
+ }
2330
+ if (offer.sponsorGasBudget !== void 0) {
2331
+ params.sponsor_gas_budget = offer.sponsorGasBudget;
2332
+ }
2333
+ if (offer.sponsorGasPrice !== void 0) {
2334
+ params.sponsor_gas_price = offer.sponsorGasPrice;
2335
+ }
2336
+ if (offer.sponsorGasPayment !== void 0) {
2337
+ params.sponsor_gas_payment = offer.sponsorGasPayment;
2338
+ }
2339
+ if (offer.acceptedRails !== void 0) {
2340
+ params.accepted_rails = offer.acceptedRails.join(",");
2341
+ }
2342
+ if (offer.exclusionProtocolVersion !== void 0) {
2343
+ params.exclusion_protocol_version = String(offer.exclusionProtocolVersion);
2344
+ }
2345
+ if (offer.registryIdentity !== void 0) {
2346
+ params.registry_identity = offer.registryIdentity;
2347
+ }
2348
+ if (offer.sig !== void 0)
2349
+ params.sig = offer.sig;
2350
+ if (offer.sigKid !== void 0)
2351
+ params.sig_kid = offer.sigKid;
2352
+ return params;
2353
+ }
2354
+ function legacyRequestBlob(offer, copies = false) {
2355
+ const params = flatParams(offer);
2356
+ if (copies) {
2357
+ params.method = MPP_SUI_METHOD;
2358
+ params.realm = "suipay";
2359
+ params.challenge = offer.challengeId;
2360
+ if (typeof offer.mimeType === "string")
2361
+ params.type = offer.mimeType;
2362
+ }
2363
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJson(params)));
2364
+ }
2365
+ function requestBlob(offer) {
2366
+ const flat = flatParams(offer);
2367
+ const details = { ...flat };
2368
+ delete details.amount;
2369
+ delete details.asset;
2370
+ delete details.recipient;
2371
+ delete details.description;
2372
+ delete details.expires;
2373
+ const body = {
2374
+ amount: flat.amount,
2375
+ currency: flat.asset,
2376
+ methodDetails: details
2377
+ };
2378
+ if (flat.recipient !== void 0)
2379
+ body.recipient = flat.recipient;
2380
+ if (flat.description !== void 0)
2381
+ body.description = flat.description;
2382
+ if (wireIntent(offer) === "subscription") {
2383
+ delete details.period_ms;
2384
+ const periodMs = offer.periodMs;
2385
+ const billing = typeof periodMs === "number" ? billingPeriod(periodMs) : null;
2386
+ if (!billing) {
2387
+ throw new Error("subscription periodMs is not an exact number of days");
2388
+ }
2389
+ body.periodCount = billing.periodCount;
2390
+ body.periodUnit = billing.periodUnit;
2391
+ const periodCount = offer.periodCount;
2392
+ const issuedAt = offer.issuedAt;
2393
+ if (typeof periodMs === "number" && typeof periodCount === "number" && typeof issuedAt === "number" && Number.isSafeInteger(periodMs) && Number.isSafeInteger(periodCount) && Number.isSafeInteger(issuedAt) && Number.isSafeInteger(periodMs * periodCount)) {
2394
+ const end = issuedAt + periodMs * periodCount;
2395
+ if (Number.isSafeInteger(end))
2396
+ body.subscriptionExpires = new Date(end).toISOString();
2397
+ }
2398
+ }
2399
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)));
2400
+ }
2401
+ function issuedRequestBlob(offer) {
2402
+ return requestBlob(offer);
2403
+ }
2404
+ function echoedRequestBlob(offer) {
2405
+ try {
2406
+ return issuedRequestBlob(offer);
2407
+ } catch {
2408
+ return legacyRequestBlob(offer);
2409
+ }
2410
+ }
2121
2411
  function splitChallenges(header) {
2122
2412
  const scheme = `${MPP_SCHEME} `;
2123
2413
  const value = header.trim();
@@ -2177,11 +2467,120 @@ function decodeChallenge(header, opts) {
2177
2467
  }
2178
2468
  return null;
2179
2469
  }
2470
+ function canonicalJson(fields) {
2471
+ const keys = Object.keys(fields).sort();
2472
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${JSON.stringify(fields[key])}`).join(",")}}`;
2473
+ }
2474
+ function canonicalJsonValue(value) {
2475
+ if (value === null || typeof value !== "object")
2476
+ return JSON.stringify(value);
2477
+ if (Array.isArray(value))
2478
+ return `[${value.map(canonicalJsonValue).join(",")}]`;
2479
+ const fields = value;
2480
+ const keys = Object.keys(fields).sort();
2481
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJsonValue(fields[key])}`).join(",")}}`;
2482
+ }
2483
+ function wireIntent(offer) {
2484
+ return offer.intent === "subscription" ? "subscription" : MPP_CHARGE_INTENT;
2485
+ }
2486
+ var REQUEST_TOP_LEVEL = /* @__PURE__ */ new Set([
2487
+ "amount",
2488
+ "asset",
2489
+ "currency",
2490
+ "description",
2491
+ "externalId",
2492
+ "recipient",
2493
+ "subscriptionExpires"
2494
+ ]);
2495
+ function takeStrings(source, into) {
2496
+ for (const [key, value] of Object.entries(source)) {
2497
+ if (typeof value !== "string")
2498
+ return false;
2499
+ into[key] = value;
2500
+ }
2501
+ return true;
2502
+ }
2503
+ function officialParams(params) {
2504
+ if (params.method !== MPP_SUI_METHOD || !params.request)
2505
+ return null;
2506
+ if (params.intent !== MPP_CHARGE_INTENT && params.intent !== "subscription")
2507
+ return null;
2508
+ let body;
2509
+ try {
2510
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(params.request)));
2511
+ } catch {
2512
+ return null;
2513
+ }
2514
+ if (!body || typeof body !== "object" || Array.isArray(body))
2515
+ return null;
2516
+ const record = body;
2517
+ const fields = {};
2518
+ const details = record.methodDetails;
2519
+ if (details !== void 0) {
2520
+ if (!details || typeof details !== "object" || Array.isArray(details))
2521
+ return null;
2522
+ if (!takeStrings(details, fields))
2523
+ return null;
2524
+ for (const [key, value] of Object.entries(record)) {
2525
+ if (key === "methodDetails" || key === "periodCount" || key === "periodUnit")
2526
+ continue;
2527
+ if (typeof value !== "string" || !REQUEST_TOP_LEVEL.has(key))
2528
+ return null;
2529
+ if (fields[key] !== void 0 && fields[key] !== value)
2530
+ return null;
2531
+ fields[key] = value;
2532
+ }
2533
+ const periodCount = record.periodCount;
2534
+ const periodUnit = record.periodUnit;
2535
+ if (periodCount !== void 0 || periodUnit !== void 0) {
2536
+ if (typeof periodCount !== "string" || typeof periodUnit !== "string")
2537
+ return null;
2538
+ if (!/^[1-9]\d*$/.test(periodCount))
2539
+ return null;
2540
+ const ms = billingPeriodMs(periodUnit, Number(periodCount));
2541
+ if (ms === null)
2542
+ return null;
2543
+ if (fields.period_ms !== void 0 && fields.period_ms !== String(ms))
2544
+ return null;
2545
+ fields.period_ms = String(ms);
2546
+ }
2547
+ if (params.intent === "subscription" && fields.period_ms === void 0)
2548
+ return null;
2549
+ } else if (!takeStrings(record, fields)) {
2550
+ return null;
2551
+ }
2552
+ if (fields.currency !== void 0) {
2553
+ if (fields.asset !== void 0 && fields.asset !== fields.currency)
2554
+ return null;
2555
+ fields.asset = fields.currency;
2556
+ }
2557
+ if (params.expires !== void 0) {
2558
+ if (fields.expires !== void 0 && fields.expires !== params.expires)
2559
+ return null;
2560
+ if (fields.expires === void 0)
2561
+ fields.expires = params.expires;
2562
+ }
2563
+ if (!fields.challenge && params.id)
2564
+ fields.challenge = params.id;
2565
+ if (fields.method === void 0)
2566
+ fields.method = MPP_SUI_METHOD;
2567
+ if (fields.method !== MPP_METHOD && fields.method !== MPP_SUI_METHOD)
2568
+ return null;
2569
+ if (fields.intent !== void 0 && fields.intent !== params.intent)
2570
+ return null;
2571
+ if (fields.intent === void 0 && params.intent === "subscription")
2572
+ return null;
2573
+ fields.method = MPP_METHOD;
2574
+ return fields;
2575
+ }
2180
2576
  function decodeSingleChallenge(header) {
2181
2577
  const parsed = parseAuthHeader(header);
2182
2578
  if (!parsed || parsed.scheme !== MPP_SCHEME)
2183
2579
  return null;
2184
- const p = parsed.params;
2580
+ const pinned = officialParams(parsed.params);
2581
+ const p = { ...pinned ?? parsed.params };
2582
+ if (p.method === MPP_SUI_METHOD)
2583
+ p.method = MPP_METHOD;
2185
2584
  if (p.method !== MPP_METHOD)
2186
2585
  return null;
2187
2586
  const required = [
@@ -2266,13 +2665,15 @@ function decodeSingleChallenge(header) {
2266
2665
  offer.intent = p.intent;
2267
2666
  if (p.period_ms !== void 0) {
2268
2667
  const ms = Number(p.period_ms);
2269
- if (Number.isFinite(ms))
2270
- offer.periodMs = ms;
2668
+ if (!Number.isSafeInteger(ms) || ms <= 0)
2669
+ return null;
2670
+ offer.periodMs = ms;
2271
2671
  }
2272
2672
  if (p.period_count !== void 0) {
2273
2673
  const count = Number(p.period_count);
2274
- if (Number.isFinite(count))
2275
- offer.periodCount = count;
2674
+ if (!Number.isSafeInteger(count) || count <= 0)
2675
+ return null;
2676
+ offer.periodCount = count;
2276
2677
  }
2277
2678
  if (p.refundable === "true")
2278
2679
  offer.refundable = true;
@@ -2332,25 +2733,46 @@ function decodeSingleChallenge(header) {
2332
2733
  offer.sigKid = p.sig_kid;
2333
2734
  return offer;
2334
2735
  }
2736
+ function echoedChallenge(offer, challengeId) {
2737
+ const challenge = {
2738
+ id: challengeId,
2739
+ realm: "suipay",
2740
+ method: MPP_SUI_METHOD,
2741
+ intent: wireIntent(offer),
2742
+ // Section 5.2 echoes the original challenge, including its request.
2743
+ request: echoedRequestBlob(offer)
2744
+ };
2745
+ const expires = expiresWire(offer);
2746
+ if (expires !== void 0)
2747
+ challenge.expires = expires;
2748
+ return challenge;
2749
+ }
2750
+ function encodeOfficialMessage(body) {
2751
+ return `${MPP_SCHEME} ${bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)))}`;
2752
+ }
2335
2753
  function encodeProof(proof) {
2336
- return `${MPP_SCHEME} ${formatAuthParams({
2337
- method: MPP_METHOD,
2338
- challenge: proof.challengeId,
2339
- payer: proof.payer,
2340
- offer: offerToBase64Url(proof.offer),
2341
- digest: proof.txDigest
2342
- })}`;
2754
+ return encodeOfficialMessage({
2755
+ challenge: echoedChallenge(proof.offer, proof.challengeId),
2756
+ payload: {
2757
+ payer: proof.payer,
2758
+ offer: offerToBase64Url(proof.offer),
2759
+ digest: proof.txDigest
2760
+ }
2761
+ });
2343
2762
  }
2344
- function decodeReceipt(header) {
2345
- const parsed = parseAuthHeader(`X ${header}`);
2346
- if (!parsed)
2763
+ function receiptFromParams(p) {
2764
+ if (p.method !== MPP_METHOD && p.method !== MPP_SUI_METHOD)
2765
+ return null;
2766
+ if (p.status !== MPP_RECEIPT_STATUS && p.status !== LEGACY_RECEIPT_STATUS)
2347
2767
  return null;
2348
- const p = parsed.params;
2349
- if (!p.challenge || !p.tx_digest || !p.payer || !p.amount || !p.asset || !p.network)
2768
+ if (p.tx_digest && p.reference && p.tx_digest !== p.reference)
2769
+ return null;
2770
+ const txDigest = p.tx_digest || p.reference;
2771
+ if (!p.challenge || !txDigest || !p.payer || !p.amount || !p.asset || !p.network)
2350
2772
  return null;
2351
2773
  const receipt = {
2352
2774
  challengeId: p.challenge,
2353
- txDigest: p.tx_digest,
2775
+ txDigest,
2354
2776
  network: p.network,
2355
2777
  payer: p.payer,
2356
2778
  amount: p.amount,
@@ -2371,6 +2793,34 @@ function decodeReceipt(header) {
2371
2793
  receipt.periodIndex = p.period_index;
2372
2794
  return receipt;
2373
2795
  }
2796
+ function decodeOfficialReceipt(header) {
2797
+ const token = header.trim();
2798
+ if (!/^[A-Za-z0-9_-]+$/.test(token))
2799
+ return null;
2800
+ let body;
2801
+ try {
2802
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(token)));
2803
+ } catch {
2804
+ return null;
2805
+ }
2806
+ if (!body || typeof body !== "object" || Array.isArray(body))
2807
+ return null;
2808
+ const fields = {};
2809
+ for (const [key, value] of Object.entries(body)) {
2810
+ if (typeof value !== "string")
2811
+ return null;
2812
+ fields[key] = value;
2813
+ }
2814
+ return receiptFromParams(fields);
2815
+ }
2816
+ function decodeReceipt(header) {
2817
+ if (/^[A-Za-z0-9_-]+$/.test(header.trim()))
2818
+ return decodeOfficialReceipt(header);
2819
+ const parsed = parseAuthHeader(`X ${header}`);
2820
+ if (!parsed)
2821
+ return null;
2822
+ return receiptFromParams(parsed.params);
2823
+ }
2374
2824
 
2375
2825
  // ../sdk/dist/protocol/x402.js
2376
2826
  import { fromBase64 as fromBase643, toBase64 as toBase642 } from "@mysten/sui/utils";
@@ -3846,6 +4296,17 @@ var INDEXER_CODES = {
3846
4296
  user: null,
3847
4297
  logOnly: true
3848
4298
  },
4299
+ "indexer.native_settlement_deferred": {
4300
+ surfaces: ["indexer"],
4301
+ status: null,
4302
+ title: "Native settlement is deferred; holding the checkpoint",
4303
+ paymentState: "not_charged",
4304
+ retry: "after_delay",
4305
+ retryAfterSeconds: 5,
4306
+ nextAction: "retry_later",
4307
+ user: null,
4308
+ logOnly: true
4309
+ },
3849
4310
  "indexer.config_invalid": {
3850
4311
  surfaces: ["indexer"],
3851
4312
  status: null,
@@ -3976,7 +4437,7 @@ var LIMIT_CODES = {
3976
4437
  }
3977
4438
  },
3978
4439
  "limit.rate_limited": {
3979
- surfaces: ["gateway", "console_server"],
4440
+ surfaces: ["gateway", "console_server", "sdk"],
3980
4441
  status: 429,
3981
4442
  title: "Rate limit exceeded",
3982
4443
  paymentState: "not_charged",
@@ -4460,6 +4921,55 @@ var REQUEST_CODES = {
4460
4921
  nextAction: "fix_request",
4461
4922
  user: { title: "Address not found", message: "That web address doesn't exist. Check the spelling and try again." }
4462
4923
  },
4924
+ "request.recipient_changed": {
4925
+ surfaces: ["gateway"],
4926
+ status: 409,
4927
+ title: "Pay-to address changed while its registry was being checked",
4928
+ paymentState: "not_charged",
4929
+ retry: "never",
4930
+ nextAction: "fix_request",
4931
+ user: {
4932
+ title: "Retry this publish",
4933
+ message: "The payout address changed while its payment registry was being checked. Retry so the current address is checked."
4934
+ }
4935
+ },
4936
+ "request.recipient_registry_invalid": {
4937
+ surfaces: ["gateway"],
4938
+ status: 409,
4939
+ title: "Payment registry does not verify for this deployment",
4940
+ paymentState: "not_charged",
4941
+ retry: "never",
4942
+ nextAction: "fix_request",
4943
+ user: {
4944
+ title: "Registry does not match",
4945
+ message: "The payout address's payment registry does not match this deployment. Fix it, then publish again."
4946
+ }
4947
+ },
4948
+ "request.recipient_registry_missing": {
4949
+ surfaces: ["gateway"],
4950
+ status: 409,
4951
+ title: "Pay-to address has no payment registry",
4952
+ paymentState: "not_charged",
4953
+ retry: "never",
4954
+ nextAction: "fix_request",
4955
+ user: {
4956
+ title: "Create a payment registry",
4957
+ message: "This payout address has no payment registry on this network yet. Create it in the seller console, then publish again."
4958
+ }
4959
+ },
4960
+ "request.recipient_registry_unreadable": {
4961
+ surfaces: ["gateway"],
4962
+ status: 503,
4963
+ title: "Payment registry could not be read",
4964
+ paymentState: "not_charged",
4965
+ retry: "after_delay",
4966
+ retryAfterSeconds: 5,
4967
+ nextAction: "retry_later",
4968
+ user: {
4969
+ title: "Registry unread",
4970
+ message: "The payment registry could not be read just now. Wait a moment and try again."
4971
+ }
4972
+ },
4463
4973
  "request.redirect_refused": {
4464
4974
  surfaces: ["console_server", "sdk"],
4465
4975
  status: 422,
@@ -5232,8 +5742,8 @@ function redactSecrets(text2) {
5232
5742
  out = out.replace(KEY_VALUE_PATTERN, (match, prefix, value) => {
5233
5743
  if (COUNTER_KEY_PATTERN.test(prefix.replace(/\s*[:=]\s*$/, "")))
5234
5744
  return match;
5235
- const quote3 = value[0] === '"' || value[0] === "'" ? value[0] : "";
5236
- return `${prefix}${quote3}${REDACTED}${quote3}`;
5745
+ const quote2 = value[0] === '"' || value[0] === "'" ? value[0] : "";
5746
+ return `${prefix}${quote2}${REDACTED}${quote2}`;
5237
5747
  });
5238
5748
  return out;
5239
5749
  }
@@ -5298,7 +5808,7 @@ function redactOAuthAuthorizationCodes(text2) {
5298
5808
  if (!OAUTH_HINT.test(text2))
5299
5809
  return text2;
5300
5810
  let out = text2.replace(OAUTH_FORM_CODE, `$1code=${REDACTED}`);
5301
- out = out.replace(OAUTH_INSPECT_CODE, (match2, prefix, quote3, value) => isSystemErrorCode(value) ? match2 : `${prefix}code: ${quote3}${REDACTED}${quote3}`);
5811
+ out = out.replace(OAUTH_INSPECT_CODE, (match2, prefix, quote2, value) => isSystemErrorCode(value) ? match2 : `${prefix}code: ${quote2}${REDACTED}${quote2}`);
5302
5812
  OAUTH_JSON_CODE_KEY.lastIndex = 0;
5303
5813
  let last = 0;
5304
5814
  let rebuilt = "";
@@ -5322,8 +5832,8 @@ function redactOAuthAuthorizationCodes(text2) {
5322
5832
  }
5323
5833
  function scanQuotedString(text2, i) {
5324
5834
  const escapedOpen = text2[i] === "\\" && (text2[i + 1] === '"' || text2[i + 1] === "'") ? 1 : 0;
5325
- const quote3 = text2[i + escapedOpen];
5326
- if (quote3 !== '"' && quote3 !== "'")
5835
+ const quote2 = text2[i + escapedOpen];
5836
+ if (quote2 !== '"' && quote2 !== "'")
5327
5837
  return { end: i, open: "", close: "" };
5328
5838
  const open2 = text2.slice(i, i + escapedOpen + 1);
5329
5839
  if (escapedOpen === 1) {
@@ -5346,7 +5856,7 @@ function scanQuotedString(text2, i) {
5346
5856
  innerEscaped = true;
5347
5857
  continue;
5348
5858
  }
5349
- if (decoded === quote3)
5859
+ if (decoded === quote2)
5350
5860
  return { end: k2, open: open2, close: open2 };
5351
5861
  }
5352
5862
  return { end: text2.length, open: open2, close: "" };
@@ -5357,8 +5867,8 @@ function scanQuotedString(text2, i) {
5357
5867
  k += 2;
5358
5868
  continue;
5359
5869
  }
5360
- if (text2[k] === quote3)
5361
- return { end: k + 1, open: open2, close: quote3 };
5870
+ if (text2[k] === quote2)
5871
+ return { end: k + 1, open: open2, close: quote2 };
5362
5872
  k += 1;
5363
5873
  }
5364
5874
  return { end: text2.length, open: open2, close: "" };
@@ -5699,6 +6209,8 @@ var CONTEXT_ALLOWLIST = /* @__PURE__ */ new Set([
5699
6209
  "seedId",
5700
6210
  "grantId",
5701
6211
  "grantObjectId",
6212
+ "policyId",
6213
+ "onChainPolicyId",
5702
6214
  "sameGrantObjectId",
5703
6215
  "verifiedGrant",
5704
6216
  "poolObjectId",
@@ -5764,6 +6276,11 @@ var CONTEXT_ALLOWLIST = /* @__PURE__ */ new Set([
5764
6276
  "rails",
5765
6277
  "shard",
5766
6278
  "metric",
6279
+ // Gateway readiness gauge. Fixed marks only: 0 or 1, and up, down, skipped, unknown.
6280
+ "ready",
6281
+ "grpc",
6282
+ "enoki",
6283
+ "postgres",
5767
6284
  "alarm",
5768
6285
  "alert",
5769
6286
  "from",
@@ -6192,7 +6709,7 @@ function normalizePaidHttpRequest(input) {
6192
6709
  bodyHash: hashRequestBody(body)
6193
6710
  });
6194
6711
  }
6195
- function canonicalJson(value, seen = /* @__PURE__ */ new Set()) {
6712
+ function canonicalJson2(value, seen = /* @__PURE__ */ new Set()) {
6196
6713
  if (value === null)
6197
6714
  return "null";
6198
6715
  const type = typeof value;
@@ -6219,10 +6736,10 @@ function canonicalJson(value, seen = /* @__PURE__ */ new Set()) {
6219
6736
  seen.add(object);
6220
6737
  try {
6221
6738
  if (Array.isArray(object)) {
6222
- return `[${object.map((item) => canonicalJson(item, seen)).join(",")}]`;
6739
+ return `[${object.map((item) => canonicalJson2(item, seen)).join(",")}]`;
6223
6740
  }
6224
6741
  const entries = Object.entries(object).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
6225
- return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item, seen)}`).join(",")}}`;
6742
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson2(item, seen)}`).join(",")}}`;
6226
6743
  } finally {
6227
6744
  seen.delete(object);
6228
6745
  }
@@ -6244,7 +6761,7 @@ function normalizeMcpPaidHttpRequest(input) {
6244
6761
  return normalizePaidHttpRequest({
6245
6762
  url: input.url,
6246
6763
  method,
6247
- body: canonicalJson(input.json),
6764
+ body: canonicalJson2(input.json),
6248
6765
  contentType: MCP_JSON_CONTENT_TYPE
6249
6766
  });
6250
6767
  }
@@ -9862,6 +10379,7 @@ import { bytesToHex as bytesToHex4 } from "@noble/hashes/utils.js";
9862
10379
 
9863
10380
  // src/config.ts
9864
10381
  import { homedir } from "os";
10382
+ import { createHash as createHash4 } from "crypto";
9865
10383
  import { join as join2 } from "path";
9866
10384
  import { SuiGrpcClient as SuiGrpcClient2 } from "@mysten/sui/grpc";
9867
10385
  import { normalizeSuiAddress as normalizeSuiAddress7 } from "@mysten/sui/utils";
@@ -9928,6 +10446,11 @@ function configError(detail) {
9928
10446
  }
9929
10447
  function mcpCredentialsPath() {
9930
10448
  const home = process.env.HOME ?? process.env.USERPROFILE ?? homedir();
10449
+ const profile2 = process.env.SUIPAY_MCP_PROFILE?.trim();
10450
+ if (profile2) {
10451
+ const id = createHash4("sha256").update(profile2).digest("hex");
10452
+ return join2(home, ".suipay", "profiles", id, "credentials.json");
10453
+ }
9931
10454
  return join2(home, ".suipay", "credentials.json");
9932
10455
  }
9933
10456
  var MCP_TARGET_PRESETS = {
@@ -10753,6 +11276,22 @@ async function settlePreparedMcpPayment(args) {
10753
11276
  });
10754
11277
  }
10755
11278
 
11279
+ // src/mcp-client-header.ts
11280
+ var MCP_CLIENT_HEADER = "x-suipay-client";
11281
+ var MCP_CLIENT_HEADER_VALUE = "mcp";
11282
+ function withMcpClientFetch(base = fetch) {
11283
+ return (input, init) => {
11284
+ const headers = new Headers(input instanceof Request ? input.headers : void 0);
11285
+ if (init?.headers) {
11286
+ new Headers(init.headers).forEach((value, key) => headers.set(key, value));
11287
+ }
11288
+ if (!headers.has(MCP_CLIENT_HEADER)) {
11289
+ headers.set(MCP_CLIENT_HEADER, MCP_CLIENT_HEADER_VALUE);
11290
+ }
11291
+ return base(input, { ...init, headers });
11292
+ };
11293
+ }
11294
+
10756
11295
  // ../sdk/dist/agent-sdk/delegate-agent.js
10757
11296
  import { normalizeSuiAddress as normalizeSuiAddress12 } from "@mysten/sui/utils";
10758
11297
 
@@ -11673,7 +12212,9 @@ async function resolvePayerSession(options) {
11673
12212
  ok: false,
11674
12213
  // The gateway's stable code, never a raw body — the read client already
11675
12214
  // sanitized it, and an operator needs to tell 429 from 401.
11676
- error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, `bootstrap was refused (${bootstrap.error}${bootstrap.code ? `: ${bootstrap.code}` : ""})`)
12215
+ // A 429 is the gateway's rate limit, not a manifest the agent can fix, so
12216
+ // it keeps the retryable code instead of the manifest default.
12217
+ error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, `bootstrap was refused (${bootstrap.error}${bootstrap.code ? `: ${bootstrap.code}` : ""})`, bootstrap.status === 429 ? "limit.rate_limited" : void 0)
11677
12218
  };
11678
12219
  }
11679
12220
  const whole = manifestToSession({
@@ -12556,7 +13097,7 @@ async function prepareSpendAccountPayment(args) {
12556
13097
  ...refundConfigInitialSharedVersion ? { refundConfigInitialSharedVersion } : {}
12557
13098
  });
12558
13099
  };
12559
- const rawFetch = deps.fetchImpl ?? fetch;
13100
+ const rawFetch = withMcpClientFetch(deps.fetchImpl ?? fetch);
12560
13101
  const wrappedFetch = (input, init) => {
12561
13102
  const probeUrl = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
12562
13103
  if (probeUrl === request.url || probeUrl === args.url) {
@@ -13056,6 +13597,13 @@ function receiptChallengeId(receipt) {
13056
13597
  return typeof id === "string" && id.length > 0 ? id : void 0;
13057
13598
  }
13058
13599
  var MCP_SAVE_ERROR = "delivery file was not written; do not call pay again";
13600
+ var MCP_EMPTY_DELIVERY = "the seller returned an empty delivery body; no file was written; do not call pay again";
13601
+ function deliverySaveError(cause, result) {
13602
+ const code = cause?.code;
13603
+ const reason = typeof code === "string" && /^E[A-Z0-9_]+$/.test(code) ? code : "file-system operation failed";
13604
+ const recovery = result.paid === true && result.txDigest ? `the body was not saved locally and cannot be re-fetched here; transaction digest ${result.txDigest} identifies the settlement for support` : "no confirmed transaction digest is available";
13605
+ return `${MCP_SAVE_ERROR}; cause: ${reason}; ${recovery}`;
13606
+ }
13059
13607
  function paidResult(result) {
13060
13608
  if (!isBinaryBody(result.body)) return text(result);
13061
13609
  const body = result.body;
@@ -13065,6 +13613,7 @@ function paidResult(result) {
13065
13613
  byteLength: body.byteLength
13066
13614
  };
13067
13615
  let savedTo;
13616
+ let saveError = MCP_EMPTY_DELIVERY;
13068
13617
  try {
13069
13618
  savedTo = saveDeliveredBody({
13070
13619
  bytes: body.bytes,
@@ -13072,8 +13621,8 @@ function paidResult(result) {
13072
13621
  digest: result.txDigest,
13073
13622
  challengeId: receiptChallengeId(result.receipt)
13074
13623
  });
13075
- } catch {
13076
- savedTo = void 0;
13624
+ } catch (cause) {
13625
+ saveError = deliverySaveError(cause, result);
13077
13626
  }
13078
13627
  const payload = savedTo ? {
13079
13628
  savedTo,
@@ -13082,7 +13631,7 @@ function paidResult(result) {
13082
13631
  body: shape
13083
13632
  } : {
13084
13633
  savedTo: null,
13085
- saveError: MCP_SAVE_ERROR,
13634
+ saveError,
13086
13635
  saveErrorCode: "client.delivery_file_not_saved",
13087
13636
  ...result,
13088
13637
  body: shape
@@ -13474,7 +14023,7 @@ async function delegateProofHeaders(resourceUrl, method, key, fetchImpl) {
13474
14023
  [DELEGATE_PROOF_HEADER]: signature
13475
14024
  };
13476
14025
  }
13477
- async function quote2(resourceUrl, probeBody, options = {}) {
14026
+ async function quote(resourceUrl, probeBody, options = {}) {
13478
14027
  const doFetch = options.fetchImpl ?? fetch;
13479
14028
  const remedy = options.remedy ?? "Supply them and quote again.";
13480
14029
  const method = liveHttpMethod(options.method);
@@ -13637,6 +14186,12 @@ function normalizePayIntent(args) {
13637
14186
  }
13638
14187
  intent.maxAmount = BigInt(raw);
13639
14188
  }
14189
+ if (args.dialect !== void 0 && args.dialect !== null) {
14190
+ if (args.dialect !== "mpp" && args.dialect !== "x402") {
14191
+ throw invalidArgument("dialect must be mpp or x402");
14192
+ }
14193
+ intent.dialect = args.dialect;
14194
+ }
13640
14195
  return intent;
13641
14196
  }
13642
14197
  function intentViolation(intent, prepared) {
@@ -13662,6 +14217,9 @@ function intentViolation(intent, prepared) {
13662
14217
  return `prepared payment costs ${amount} which exceeds the requested maxAmount ${intent.maxAmount}`;
13663
14218
  }
13664
14219
  }
14220
+ if (intent.dialect && prepared.dialect !== intent.dialect) {
14221
+ return `prepared payment uses ${prepared.dialect}, not the requested dialect ${intent.dialect}`;
14222
+ }
13665
14223
  return null;
13666
14224
  }
13667
14225
  async function pay(args, cfg, deps = {}) {
@@ -13708,6 +14266,12 @@ async function pay(args, cfg, deps = {}) {
13708
14266
  return mcpFailure(kind === "too_large" ? "request.body_too_large" : "request.invalid", detail);
13709
14267
  }
13710
14268
  if (deps.auth?.spendAccountPay) {
14269
+ if (deps.agentHeld && intent.dialect === "x402") {
14270
+ return mcpFailure(
14271
+ "account.policy_rejected",
14272
+ "dialect x402 is not supported when settling a prepared payment here; use stdio pay"
14273
+ );
14274
+ }
13711
14275
  const sp = deps.auth.spendAccountPay;
13712
14276
  const trace = payerTrace(deps);
13713
14277
  const liveKindBuilder = !deps.buildPayKind && !deps.agentHeld ? createSpendAccountChain({
@@ -13726,8 +14290,9 @@ async function pay(args, cfg, deps = {}) {
13726
14290
  ...sp.assertLive ? { assertLive: sp.assertLive } : {}
13727
14291
  },
13728
14292
  cfg,
14293
+ ...intent.dialect ? { preferredDialect: intent.dialect } : {},
13729
14294
  deps: {
13730
- ...deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {},
14295
+ fetchImpl: withMcpClientFetch(deps.fetchImpl ?? fetch),
13731
14296
  ...trace ? { trace } : {},
13732
14297
  ...deps.resolveExclusionRegistry ? { resolveExclusionRegistry: deps.resolveExclusionRegistry } : {},
13733
14298
  ...deps.buildPayKind ? { buildPayKind: deps.buildPayKind } : liveKindBuilder ? {
@@ -13779,7 +14344,9 @@ async function pay(args, cfg, deps = {}) {
13779
14344
  cfg: { gatewayUrl: cfg.gatewayUrl },
13780
14345
  deps: {
13781
14346
  ...deps.agentHeld.payerDeps,
13782
- ...deps.fetchImpl && !deps.agentHeld.payerDeps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}
14347
+ fetchImpl: withMcpClientFetch(
14348
+ deps.agentHeld.payerDeps.fetchImpl ?? deps.fetchImpl ?? fetch
14349
+ )
13783
14350
  }
13784
14351
  });
13785
14352
  return renderSettled(settled);
@@ -13832,7 +14399,7 @@ function grantObjectIdFromBootstrap(grants, nowMs) {
13832
14399
  }
13833
14400
  if (live.length === 1) return { kind: "live", grantObjectId: live[0] };
13834
14401
  if (live.length > 1) return { kind: "ambiguous" };
13835
- if (named > 0) return { kind: "absent" };
14402
+ if (named > 0) return { kind: "expired" };
13836
14403
  if (grants.length > 0) return { kind: "unknown", detail: "delegate grants list was not usable" };
13837
14404
  return { kind: "absent" };
13838
14405
  }
@@ -13889,6 +14456,7 @@ async function payStdioWithLocalKey(args) {
13889
14456
  method: request.method,
13890
14457
  ...request.method === "POST" ? { body: request.body } : {},
13891
14458
  ...request.contentType ? { contentType: request.contentType } : {},
14459
+ ...intent.dialect ? { dialect: intent.dialect } : {},
13892
14460
  intent: {
13893
14461
  maxAmount,
13894
14462
  asset: payer.grant.coinType,
@@ -13903,7 +14471,7 @@ async function payStdioWithLocalKey(args) {
13903
14471
  async function openGrantQuote(request, maxAmount, coinType, deps) {
13904
14472
  let quoted;
13905
14473
  try {
13906
- quoted = await quote2(new URL(request.url), new TextDecoder().decode(request.body), {
14474
+ quoted = await quote(new URL(request.url), new TextDecoder().decode(request.body), {
13907
14475
  ...deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {},
13908
14476
  method: request.method,
13909
14477
  rail: "delegate"
@@ -14005,7 +14573,7 @@ async function stdioPayerAndReader(cfg, deps) {
14005
14573
  gatewayUrl,
14006
14574
  keypair,
14007
14575
  ...select ? { select } : {},
14008
- ...deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {},
14576
+ fetchImpl: withMcpClientFetch(deps.fetchImpl ?? fetch),
14009
14577
  ...cfg.rpcUrl ? { fullnodeUrl: cfg.rpcUrl } : {}
14010
14578
  });
14011
14579
  if (!built.ok) {
@@ -14279,7 +14847,8 @@ async function suipayLogin(args, cfg, deps = {}) {
14279
14847
  target: target ?? cfg.target,
14280
14848
  delegateAddress: identity.delegateAddress,
14281
14849
  gatewayUrl: endpoints.gatewayUrl,
14282
- message: "Credentials are already saved for this agent. The existing grant could not be checked just now, so no new sign-in was started and the key file was left unchanged. Retry suipay_login in a moment."
14850
+ nextAction: "poll suipay_login_status to verify authorization before retrying payment",
14851
+ message: "Credentials are already saved for this agent. The existing grant could not be checked just now, so no new sign-in was started and the key file was left unchanged. Poll suipay_login_status in a moment."
14283
14852
  });
14284
14853
  }
14285
14854
  }
@@ -14314,7 +14883,7 @@ async function suipayLogin(args, cfg, deps = {}) {
14314
14883
  ``,
14315
14884
  `1. Use the browser window that just opened, or open the URL above`,
14316
14885
  `2. Connect the owner wallet, create a key, then Authorize on the review step`,
14317
- `3. Once Connected appears, retry the original request \u2014 credentials at \`~/.suipay/credentials.json\` are picked up on the next tool call`,
14886
+ `3. Poll \`suipay_login_status\` to confirm authorization \u2014 credentials at \`~/.suipay/credentials.json\` are active once approved`,
14318
14887
  ``,
14319
14888
  `_The login link stays valid for 5 minutes. If it expires, call \`suipay_login\` again._`,
14320
14889
  ``,
@@ -14324,11 +14893,113 @@ async function suipayLogin(args, cfg, deps = {}) {
14324
14893
  delegateAddress: identity.delegateAddress,
14325
14894
  connectUrl: url,
14326
14895
  consoleUrl: endpoints.consoleUrl,
14327
- gatewayUrl: endpoints.gatewayUrl
14896
+ gatewayUrl: endpoints.gatewayUrl,
14897
+ nextAction: "poll suipay_login_status to verify authorization before retrying payment"
14328
14898
  })
14329
14899
  ].join("\n")
14330
14900
  );
14331
14901
  }
14902
+ function defaultKeyName(delegateAddress) {
14903
+ const clean = delegateAddress.trim().toLowerCase();
14904
+ const hex = clean.startsWith("0x") ? clean.slice(2) : clean;
14905
+ const prefix = hex.slice(0, 8).padEnd(8, "0");
14906
+ return `agent-${prefix}`;
14907
+ }
14908
+ function safeRetryDetail(rawDetail) {
14909
+ if (!rawDetail) {
14910
+ return "Grant status could not be verified on chain. Retry shortly.";
14911
+ }
14912
+ let stripped = rawDetail.replace(/https?:\/\/[^\s"'<>]+/gi, "[redacted]");
14913
+ if (stripped.includes("ECONNREFUSED") || stripped.includes("ETIMEDOUT") || stripped.includes("fetch failed")) {
14914
+ return "Network connection to gateway or chain node failed. Retry shortly.";
14915
+ }
14916
+ return stripped;
14917
+ }
14918
+ var loginStatusCache = /* @__PURE__ */ new Map();
14919
+ var DEFAULT_LOGIN_STATUS_RETRY_AFTER_MS = 2e3;
14920
+ var DEFAULT_LOGIN_STATUS_CACHE_TTL_MS = 1500;
14921
+ async function suipayLoginStatus(_args = {}, cfg, deps = {}) {
14922
+ if (deps.auth) {
14923
+ return mcpFailure(
14924
+ "request.local_only",
14925
+ "suipay_login_status is for local stdio only; hosted /mcp never holds a spendable key"
14926
+ );
14927
+ }
14928
+ const loadKeypair = deps.loadLocalKeypair ?? loadLocalKeypair;
14929
+ const keypair = loadKeypair();
14930
+ if (!keypair) {
14931
+ return text({
14932
+ status: "not_started",
14933
+ nextAction: "run suipay_login"
14934
+ });
14935
+ }
14936
+ const delegateAddress = keypair.toSuiAddress();
14937
+ const stored = loadLocalSigningKeyRecord();
14938
+ const gatewayUrl = stored?.gatewayUrl ?? cfg.gatewayUrl;
14939
+ const cacheKey = `${gatewayUrl}:${delegateAddress}`;
14940
+ const now = Date.now();
14941
+ const cacheTtlMs = deps.cacheTtlMs ?? DEFAULT_LOGIN_STATUS_CACHE_TTL_MS;
14942
+ if (!deps.bypassCache) {
14943
+ const cached = loginStatusCache.get(cacheKey);
14944
+ if (cached && now - cached.timestamp < cacheTtlMs) {
14945
+ return cached.result;
14946
+ }
14947
+ }
14948
+ const checkFn = deps.checkLiveDelegateGrant ?? checkLiveDelegateGrant;
14949
+ let live;
14950
+ try {
14951
+ live = await checkFn({
14952
+ gatewayUrl,
14953
+ delegateAddress,
14954
+ signPersonalMessage: async (bytes) => {
14955
+ const { signature } = await keypair.signPersonalMessage(bytes);
14956
+ return signature;
14957
+ },
14958
+ ...deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}
14959
+ });
14960
+ } catch (err) {
14961
+ const rawMessage = err instanceof Error ? err.message : String(err);
14962
+ live = {
14963
+ kind: "unknown",
14964
+ detail: rawMessage
14965
+ };
14966
+ }
14967
+ let result;
14968
+ if (live.kind === "live") {
14969
+ result = text({
14970
+ status: "connected",
14971
+ grantObjectId: live.grantObjectId,
14972
+ delegateAddress
14973
+ });
14974
+ } else if (live.kind === "expired") {
14975
+ result = text({
14976
+ status: "expired",
14977
+ delegateAddress,
14978
+ detail: "Grant has expired. Run suipay_login to reconnect.",
14979
+ nextAction: "run suipay_login"
14980
+ });
14981
+ } else if (live.kind === "absent") {
14982
+ result = text({
14983
+ status: "pending",
14984
+ delegateAddress,
14985
+ defaultKeyName: defaultKeyName(delegateAddress)
14986
+ });
14987
+ } else if (live.kind === "ambiguous") {
14988
+ result = text({
14989
+ status: "ambiguous",
14990
+ delegateAddress,
14991
+ detail: "Multiple live grants found for this delegate key. Revoke the duplicate grants and reconnect."
14992
+ });
14993
+ } else {
14994
+ result = text({
14995
+ status: "retry",
14996
+ retryAfterMs: DEFAULT_LOGIN_STATUS_RETRY_AFTER_MS,
14997
+ detail: safeRetryDetail(live.detail)
14998
+ });
14999
+ }
15000
+ loginStatusCache.set(cacheKey, { timestamp: Date.now(), result });
15001
+ return result;
15002
+ }
14332
15003
  async function logout(args, _cfg, deps = {}) {
14333
15004
  if (args.force) {
14334
15005
  clearCreds();
@@ -14382,6 +15053,11 @@ var TOOLS = [
14382
15053
  maxAmount: {
14383
15054
  type: "string",
14384
15055
  description: "Atomic ceiling you will spend on this call. The payment is refused, unsigned, if the offer costs more."
15056
+ },
15057
+ dialect: {
15058
+ type: "string",
15059
+ enum: ["mpp", "x402"],
15060
+ description: "Payment dialect to settle in when the 402 offers both. Defaults to mpp. A declared dialect the payment cannot use is refused, unsigned."
14385
15061
  }
14386
15062
  },
14387
15063
  required: ["url"]
@@ -14432,6 +15108,14 @@ var TOOLS = [
14432
15108
  }
14433
15109
  }
14434
15110
  },
15111
+ {
15112
+ name: "suipay_login_status",
15113
+ description: `Check whether the local delegate key has an approved, active spend-account grant, read from the gateway's delegate-grant state. Read-only and pollable (does not mint keys, write credentials, or sign transactions). Returns one of five states: (1) "not_started" if no local key exists yet (call suipay_login first); (2) "connected" if a live grant exists for this local delegate key (note: "connected" means a live grant exists for this delegate key, which may be pre-existing from a prior session); (3) "pending" if the key exists but no grant has been approved yet (includes delegateAddress and a defaultKeyName of format "agent-<first-8-hex-chars-of-address-without-0x>"; note that if the owner already has a live key with this normalized name, creating it may yield 409 CONFLICT); (4) "ambiguous" (terminal) if several live grants exist for this delegate key \u2014 stop polling and revoke the duplicates; (5) "retry" if the status could not be verified (includes retryAfterMs floor and safe detail). Stdio only; hosted /mcp never holds a spendable key.`,
15114
+ inputSchema: {
15115
+ type: "object",
15116
+ properties: {}
15117
+ }
15118
+ },
14435
15119
  {
14436
15120
  name: "suipay_logout",
14437
15121
  description: "Remove the local delegate-key credentials file. Missing file is success. Force clears a corrupt file without printing the seed.",
@@ -14522,7 +15206,8 @@ function createServer2(cfg, auth, trace, options = {}) {
14522
15206
  ...args.json !== void 0 ? { json: args.json } : {},
14523
15207
  ...transport === "stdio" ? fileArgs : {},
14524
15208
  ...args.recipient !== void 0 ? { recipient: args.recipient } : {},
14525
- ...args.maxAmount !== void 0 ? { maxAmount: args.maxAmount } : {}
15209
+ ...args.maxAmount !== void 0 ? { maxAmount: args.maxAmount } : {},
15210
+ ...args.dialect !== void 0 ? { dialect: args.dialect } : {}
14526
15211
  },
14527
15212
  cfg,
14528
15213
  {
@@ -14579,6 +15264,14 @@ function createServer2(cfg, auth, trace, options = {}) {
14579
15264
  }
14580
15265
  );
14581
15266
  }
15267
+ case "suipay_login_status":
15268
+ if (auth) {
15269
+ return mcpFailure(
15270
+ "request.local_only",
15271
+ "suipay_login_status is for local stdio only; hosted /mcp never holds a spendable key"
15272
+ );
15273
+ }
15274
+ return await suipayLoginStatus(args, cfg, { auth });
14582
15275
  case "suipay_logout":
14583
15276
  if (auth) {
14584
15277
  return mcpFailure(