tenjin-cli 0.1.0-alpha.17 → 0.1.0-alpha.19

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.
Files changed (112) hide show
  1. package/README.md +152 -38
  2. package/dist/{_esm-CE7KNONL.js → _esm-OVVGTKHH.js} +4 -4
  3. package/dist/{chunk-5QHHRMRA.js → chunk-2SQEFBAM.js} +4 -3
  4. package/dist/chunk-3KKKB2AQ.js +40 -0
  5. package/dist/chunk-3KKKB2AQ.js.map +1 -0
  6. package/dist/{chunk-LJ4DMVFI.js → chunk-3VYGDRRL.js} +5 -5
  7. package/dist/{chunk-PDA2BVFY.js → chunk-5DOHKQ24.js} +4 -15
  8. package/dist/chunk-5DOHKQ24.js.map +1 -0
  9. package/dist/{chunk-N35E6CM2.js → chunk-6DCELMQA.js} +6 -6
  10. package/dist/{chunk-WXC57XGG.js → chunk-A36LQPHV.js} +1 -1
  11. package/dist/chunk-A36LQPHV.js.map +1 -0
  12. package/dist/{chunk-56MOAIP5.js → chunk-A6CY6BUW.js} +11 -8
  13. package/dist/chunk-A6CY6BUW.js.map +1 -0
  14. package/dist/{chunk-TP4D47BY.js → chunk-AISBL7EY.js} +3 -3
  15. package/dist/{chunk-KK4YGYTV.js → chunk-AMG4SONW.js} +138 -58
  16. package/dist/chunk-AMG4SONW.js.map +1 -0
  17. package/dist/{chunk-AUKDYPPX.js → chunk-BG2EXNAA.js} +7 -6
  18. package/dist/chunk-BG2EXNAA.js.map +1 -0
  19. package/dist/{chunk-O4ZNKFRU.js → chunk-FHBGTOFA.js} +121 -40
  20. package/dist/chunk-FHBGTOFA.js.map +1 -0
  21. package/dist/{chunk-HPWO4O6S.js → chunk-FPUPBQHX.js} +2 -2
  22. package/dist/{chunk-3AUDA53C.js → chunk-KTAW4KGH.js} +6 -5
  23. package/dist/{chunk-J5INH7WB.js → chunk-LSWVVSFX.js} +106 -5
  24. package/dist/chunk-LSWVVSFX.js.map +1 -0
  25. package/dist/chunk-O2JYBOUO.js +47 -0
  26. package/dist/chunk-O2JYBOUO.js.map +1 -0
  27. package/dist/{chunk-5UDD5VSY.js → chunk-PZQRSZJV.js} +2 -2
  28. package/dist/{chunk-5UDD5VSY.js.map → chunk-PZQRSZJV.js.map} +1 -1
  29. package/dist/{chunk-QDD2RN7G.js → chunk-SCAOYGKX.js} +356 -90
  30. package/dist/chunk-SCAOYGKX.js.map +1 -0
  31. package/dist/{chunk-35M3VITA.js → chunk-TDGN476R.js} +60 -7
  32. package/dist/chunk-TDGN476R.js.map +1 -0
  33. package/dist/{chunk-AR7U7BRG.js → chunk-UNV4K45L.js} +12 -18
  34. package/dist/{chunk-AR7U7BRG.js.map → chunk-UNV4K45L.js.map} +1 -1
  35. package/dist/{chunk-MRGADYDD.js → chunk-VFVFVQM6.js} +4 -4
  36. package/dist/{chunk-2JGT3KDW.js → chunk-WUU3BH6G.js} +2 -2
  37. package/dist/{chunk-KUBEYXSO.js → chunk-XDADPAWW.js} +22 -22
  38. package/dist/{chunk-WGQVJM56.js → chunk-XNP6VUAJ.js} +3 -3
  39. package/dist/{chunk-AWQPGIR6.js → chunk-Y66XUXVI.js} +5 -5
  40. package/dist/{chunk-XZOEUYMX.js → chunk-ZDKEU2GF.js} +2 -2
  41. package/dist/{chunk-WLMJE3GJ.js → chunk-ZTFIQC4C.js} +2 -2
  42. package/dist/{cli-VHYYYYXM.js → cli-456F77ZY.js} +33 -28
  43. package/dist/{cli-VHYYYYXM.js.map → cli-456F77ZY.js.map} +1 -1
  44. package/dist/{config-5ADBAAXU.js → config-BLUWOH6S.js} +9 -12
  45. package/dist/{doctor-Q35VQW3S.js → doctor-PS45CR3T.js} +37 -29
  46. package/dist/{doctor-Q35VQW3S.js.map → doctor-PS45CR3T.js.map} +1 -1
  47. package/dist/{fund-GDDPL2BB.js → fund-4SW2ZBWC.js} +18 -17
  48. package/dist/{fund-GDDPL2BB.js.map → fund-4SW2ZBWC.js.map} +1 -1
  49. package/dist/{hook-command-PBERPRE3.js → hook-command-YTV7X333.js} +318 -37
  50. package/dist/hook-command-YTV7X333.js.map +1 -0
  51. package/dist/index.js +2 -2
  52. package/dist/{install-OKDKGUXM.js → install-U4BIDCHH.js} +14 -13
  53. package/dist/{install-wallet-SI4LZ73K.js → install-wallet-EYHELQMG.js} +15 -14
  54. package/dist/{install-wallet-SI4LZ73K.js.map → install-wallet-EYHELQMG.js.map} +1 -1
  55. package/dist/{mcp-XX3WRQEZ.js → mcp-AC4PIXH5.js} +43 -28
  56. package/dist/{mcp-XX3WRQEZ.js.map → mcp-AC4PIXH5.js.map} +1 -1
  57. package/dist/{pay-3SYKHKWJ.js → pay-VJOP6TFT.js} +24 -19
  58. package/dist/{send-LQRKTEJT.js → send-YH75Z6LB.js} +15 -14
  59. package/dist/{send-LQRKTEJT.js.map → send-YH75Z6LB.js.map} +1 -1
  60. package/dist/{status-FFC6FO72.js → status-5CHCDLUE.js} +24 -17
  61. package/dist/status-5CHCDLUE.js.map +1 -0
  62. package/dist/{status-line-SAXSU6CR.js → status-line-CZAZUOAY.js} +6 -6
  63. package/dist/{status-line-wiring-L2WYIYBM.js → status-line-wiring-2ABDVXSJ.js} +4 -4
  64. package/dist/tenjin-daemon.mjs +3 -14
  65. package/dist/{uninstall-OACH27UV.js → uninstall-BYVGAQMO.js} +36 -18
  66. package/dist/uninstall-BYVGAQMO.js.map +1 -0
  67. package/dist/{update-4W6EKLGZ.js → update-7QJDSHST.js} +5 -5
  68. package/dist/{viemAdapter-By13KInL-X2VY6CY3.js → viemAdapter-By13KInL-N2GIVMZ7.js} +2 -2
  69. package/dist/{wallet-BMEXRR3P.js → wallet-YZOXIXBC.js} +15 -14
  70. package/docs/agent-permissions.md +30 -14
  71. package/docs/safety-model.md +7 -1
  72. package/package.json +1 -1
  73. package/dist/chunk-35M3VITA.js.map +0 -1
  74. package/dist/chunk-56MOAIP5.js.map +0 -1
  75. package/dist/chunk-AUKDYPPX.js.map +0 -1
  76. package/dist/chunk-J5INH7WB.js.map +0 -1
  77. package/dist/chunk-KK4YGYTV.js.map +0 -1
  78. package/dist/chunk-O4ZNKFRU.js.map +0 -1
  79. package/dist/chunk-PDA2BVFY.js.map +0 -1
  80. package/dist/chunk-QDD2RN7G.js.map +0 -1
  81. package/dist/chunk-U2DZISAH.js +0 -111
  82. package/dist/chunk-U2DZISAH.js.map +0 -1
  83. package/dist/chunk-WS4JA6TC.js +0 -137
  84. package/dist/chunk-WS4JA6TC.js.map +0 -1
  85. package/dist/chunk-WXC57XGG.js.map +0 -1
  86. package/dist/hook-command-PBERPRE3.js.map +0 -1
  87. package/dist/skill-placement-JMDPSKE6.js +0 -299
  88. package/dist/skill-placement-JMDPSKE6.js.map +0 -1
  89. package/dist/status-FFC6FO72.js.map +0 -1
  90. package/dist/uninstall-OACH27UV.js.map +0 -1
  91. /package/dist/{_esm-CE7KNONL.js.map → _esm-OVVGTKHH.js.map} +0 -0
  92. /package/dist/{chunk-5QHHRMRA.js.map → chunk-2SQEFBAM.js.map} +0 -0
  93. /package/dist/{chunk-LJ4DMVFI.js.map → chunk-3VYGDRRL.js.map} +0 -0
  94. /package/dist/{chunk-N35E6CM2.js.map → chunk-6DCELMQA.js.map} +0 -0
  95. /package/dist/{chunk-TP4D47BY.js.map → chunk-AISBL7EY.js.map} +0 -0
  96. /package/dist/{chunk-HPWO4O6S.js.map → chunk-FPUPBQHX.js.map} +0 -0
  97. /package/dist/{chunk-3AUDA53C.js.map → chunk-KTAW4KGH.js.map} +0 -0
  98. /package/dist/{chunk-MRGADYDD.js.map → chunk-VFVFVQM6.js.map} +0 -0
  99. /package/dist/{chunk-2JGT3KDW.js.map → chunk-WUU3BH6G.js.map} +0 -0
  100. /package/dist/{chunk-KUBEYXSO.js.map → chunk-XDADPAWW.js.map} +0 -0
  101. /package/dist/{chunk-WGQVJM56.js.map → chunk-XNP6VUAJ.js.map} +0 -0
  102. /package/dist/{chunk-AWQPGIR6.js.map → chunk-Y66XUXVI.js.map} +0 -0
  103. /package/dist/{chunk-XZOEUYMX.js.map → chunk-ZDKEU2GF.js.map} +0 -0
  104. /package/dist/{chunk-WLMJE3GJ.js.map → chunk-ZTFIQC4C.js.map} +0 -0
  105. /package/dist/{config-5ADBAAXU.js.map → config-BLUWOH6S.js.map} +0 -0
  106. /package/dist/{install-OKDKGUXM.js.map → install-U4BIDCHH.js.map} +0 -0
  107. /package/dist/{pay-3SYKHKWJ.js.map → pay-VJOP6TFT.js.map} +0 -0
  108. /package/dist/{status-line-SAXSU6CR.js.map → status-line-CZAZUOAY.js.map} +0 -0
  109. /package/dist/{status-line-wiring-L2WYIYBM.js.map → status-line-wiring-2ABDVXSJ.js.map} +0 -0
  110. /package/dist/{update-4W6EKLGZ.js.map → update-7QJDSHST.js.map} +0 -0
  111. /package/dist/{viemAdapter-By13KInL-X2VY6CY3.js.map → viemAdapter-By13KInL-N2GIVMZ7.js.map} +0 -0
  112. /package/dist/{wallet-BMEXRR3P.js.map → wallet-YZOXIXBC.js.map} +0 -0
@@ -4,6 +4,7 @@ import {
4
4
  } from "./chunk-2G2WLVHB.js";
5
5
  import {
6
6
  HTTPFacilitatorClient,
7
+ PaymentRequirementsV2Schema,
7
8
  SIGN_IN_WITH_X,
8
9
  SIWX_HEADER,
9
10
  buildSiwxHeader,
@@ -15,11 +16,11 @@ import {
15
16
  http,
16
17
  x402HTTPClient,
17
18
  x402Version
18
- } from "./chunk-3AUDA53C.js";
19
+ } from "./chunk-KTAW4KGH.js";
19
20
  import {
20
21
  fetchFailureToCliError,
21
22
  httpRequest
22
- } from "./chunk-5QHHRMRA.js";
23
+ } from "./chunk-2SQEFBAM.js";
23
24
  import {
24
25
  encodeFunctionData,
25
26
  getAddress as getAddress2,
@@ -33,31 +34,35 @@ import {
33
34
  } from "./chunk-LHHMV4GU.js";
34
35
  import {
35
36
  USDC_ADDRESS
36
- } from "./chunk-56MOAIP5.js";
37
+ } from "./chunk-A6CY6BUW.js";
38
+ import {
39
+ readUsdcBalance
40
+ } from "./chunk-3KKKB2AQ.js";
37
41
  import {
38
42
  describeWallet,
39
43
  resolveSpendAuthorizer,
40
44
  resolveWalletProvider
41
- } from "./chunk-KUBEYXSO.js";
45
+ } from "./chunk-XDADPAWW.js";
42
46
  import {
43
47
  getAddress
44
48
  } from "./chunk-EGELTSPU.js";
49
+ import {
50
+ sanitizeForTerminal
51
+ } from "./chunk-ZTFIQC4C.js";
45
52
  import {
46
53
  mask
47
54
  } from "./chunk-7QKHZQKW.js";
48
- import {
49
- sanitizeForTerminal
50
- } from "./chunk-WLMJE3GJ.js";
51
55
  import {
52
56
  resolveContextSettings
53
- } from "./chunk-PDA2BVFY.js";
57
+ } from "./chunk-5DOHKQ24.js";
54
58
  import {
55
59
  parseUsdToAtomic,
56
60
  toMoney
57
- } from "./chunk-U2DZISAH.js";
61
+ } from "./chunk-O2JYBOUO.js";
58
62
  import {
63
+ external_exports,
59
64
  isSameDeployment
60
- } from "./chunk-AR7U7BRG.js";
65
+ } from "./chunk-UNV4K45L.js";
61
66
  import {
62
67
  CliError
63
68
  } from "./chunk-JLEF5WHM.js";
@@ -8044,6 +8049,9 @@ var require_dist = __commonJS({
8044
8049
  }
8045
8050
  });
8046
8051
 
8052
+ // src/commands/pay.ts
8053
+ import { setTimeout as delay } from "node:timers/promises";
8054
+
8047
8055
  // src/lib/bazaar.ts
8048
8056
  import { readFile } from "node:fs/promises";
8049
8057
  import { join } from "node:path";
@@ -8278,6 +8286,94 @@ function withBazaar(client2) {
8278
8286
 
8279
8287
  // src/lib/bazaar.ts
8280
8288
  var PAGE_LIMIT = 100;
8289
+ var SEARCH_LIMIT = 20;
8290
+ var MAX_PAGES = 5;
8291
+ var MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
8292
+ var ULTRAVIOLETA_ORIGIN = "https://facilitator.ultravioletadao.xyz";
8293
+ function isUltravioleta(registry) {
8294
+ return new URL(registry).origin === ULTRAVIOLETA_ORIGIN;
8295
+ }
8296
+ var paymentTerms = external_exports.custom((value) => {
8297
+ const parsed = PaymentRequirementsV2Schema.safeParse(value);
8298
+ return parsed.success && /^\d+$/.test(parsed.data.amount);
8299
+ });
8300
+ var ultravioletResource = external_exports.object({
8301
+ url: external_exports.string().url(),
8302
+ type: external_exports.string(),
8303
+ x402Version: external_exports.number().int(),
8304
+ description: external_exports.string().optional(),
8305
+ accepts: external_exports.array(paymentTerms).max(100),
8306
+ lastUpdated: external_exports.number().int().nonnegative().max(864e10)
8307
+ });
8308
+ var paginationSchema = external_exports.object({
8309
+ limit: external_exports.number().int().positive().max(PAGE_LIMIT),
8310
+ offset: external_exports.number().int().nonnegative(),
8311
+ total: external_exports.number().int().nonnegative()
8312
+ });
8313
+ async function boundedJson(res) {
8314
+ const reader = res.body?.getReader();
8315
+ if (!reader) throw new Error("Registry response has no body");
8316
+ const chunks = [];
8317
+ let bytes = 0;
8318
+ try {
8319
+ for (; ; ) {
8320
+ const next = await reader.read();
8321
+ if (next.done) break;
8322
+ bytes += next.value.byteLength;
8323
+ if (bytes > MAX_RESPONSE_BYTES) throw new Error("Registry response exceeds size limit");
8324
+ chunks.push(next.value);
8325
+ }
8326
+ } finally {
8327
+ await reader.cancel();
8328
+ }
8329
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
8330
+ }
8331
+ async function ultravioletListings(registry, timeoutMs, query) {
8332
+ const deadline = Date.now() + timeoutMs;
8333
+ const items = [];
8334
+ let offset = 0;
8335
+ let incomplete;
8336
+ for (let page = 0; page < MAX_PAGES; page++) {
8337
+ const remaining = deadline - Date.now();
8338
+ if (remaining <= 0) throw new Error("Registry lookup deadline exceeded");
8339
+ const params = new URLSearchParams({
8340
+ limit: String(PAGE_LIMIT),
8341
+ offset: String(offset),
8342
+ ...query !== void 0 ? { q: query } : {}
8343
+ });
8344
+ const res = await fetch(`${new URL(registry).origin}/discovery/resources?${params}`, {
8345
+ headers: { accept: "application/json" },
8346
+ signal: AbortSignal.timeout(remaining),
8347
+ redirect: "error"
8348
+ });
8349
+ if (!res.ok) throw new Error(`listing ${registry} answered ${res.status}`);
8350
+ const response = external_exports.object({ items: external_exports.array(external_exports.unknown()).max(PAGE_LIMIT), pagination: paginationSchema }).parse(await boundedJson(res));
8351
+ const pagination = response.pagination;
8352
+ if (pagination.offset !== offset || response.items.length > pagination.limit)
8353
+ throw new Error("Invalid registry pagination");
8354
+ for (const record of response.items) {
8355
+ const parsed = ultravioletResource.safeParse(record);
8356
+ if (!parsed.success) {
8357
+ incomplete = "Registry search skipped malformed records";
8358
+ continue;
8359
+ }
8360
+ const item = parsed.data;
8361
+ items.push({
8362
+ resource: item.url,
8363
+ type: item.type,
8364
+ x402Version: item.x402Version,
8365
+ accepts: item.accepts,
8366
+ lastUpdated: new Date(item.lastUpdated * 1e3).toISOString(),
8367
+ ...item.description !== void 0 ? { description: item.description } : {}
8368
+ });
8369
+ }
8370
+ const next = pagination.offset + response.items.length;
8371
+ if (next >= pagination.total) return { items, ...incomplete ? { incomplete } : {} };
8372
+ if (response.items.length === 0) break;
8373
+ offset = next;
8374
+ }
8375
+ return { items, incomplete: "Registry search truncated at the pagination limit" };
8376
+ }
8281
8377
  function client(registry) {
8282
8378
  return withBazaar(new HTTPFacilitatorClient({ url: registry }));
8283
8379
  }
@@ -8325,17 +8421,62 @@ async function storedListingsFor(dataDir, url, now) {
8325
8421
  });
8326
8422
  }
8327
8423
  function sameResourceUrl(listed, requested) {
8328
- const identity = (u) => {
8329
- try {
8330
- const parsed = new URL(u);
8331
- const path = parsed.pathname.endsWith("/") ? parsed.pathname.slice(0, -1) : parsed.pathname;
8332
- return `${parsed.origin}${path}`;
8333
- } catch {
8334
- return null;
8424
+ const a = resourceIdentity(listed);
8425
+ return a !== null && a === resourceIdentity(requested);
8426
+ }
8427
+ function resourceIdentity(u) {
8428
+ try {
8429
+ const parsed = new URL(u);
8430
+ const path = parsed.pathname.endsWith("/") ? parsed.pathname.slice(0, -1) : parsed.pathname;
8431
+ return `${parsed.origin}${path}`;
8432
+ } catch {
8433
+ return null;
8434
+ }
8435
+ }
8436
+ async function listingsFor(registry, url, payTo, timeoutMs) {
8437
+ if (isUltravioleta(registry))
8438
+ return ultravioletListings(registry, timeoutMs, resourceIdentity(url) ?? url);
8439
+ const deadline = Date.now() + timeoutMs;
8440
+ const params = new URLSearchParams({
8441
+ urlSubstring: resourceIdentity(url) ?? url,
8442
+ limit: String(SEARCH_LIMIT)
8443
+ });
8444
+ const res = await fetch(`${registry.replace(/\/+$/, "")}/discovery/search?${params.toString()}`, {
8445
+ headers: { accept: "application/json" },
8446
+ signal: AbortSignal.timeout(timeoutMs),
8447
+ redirect: "error"
8448
+ });
8449
+ if (res.ok) {
8450
+ const answer = await boundedJson(res);
8451
+ if (Array.isArray(answer?.resources)) {
8452
+ return {
8453
+ items: answer.resources.slice(0, PAGE_LIMIT),
8454
+ ...answer.resources.length > PAGE_LIMIT || answer.partialResults === true || answer.pagination?.cursor != null ? { incomplete: "Registry search results are truncated" } : {}
8455
+ };
8335
8456
  }
8336
- };
8337
- const a = identity(listed);
8338
- return a !== null && a === identity(requested);
8457
+ } else if (res.status !== 400 && res.status !== 404) {
8458
+ throw new Error(`search on ${registry} answered ${res.status}`);
8459
+ }
8460
+ const bazaar = client(registry).extensions.bazaar;
8461
+ const items = [];
8462
+ let offset = 0;
8463
+ for (let page = 0; page < MAX_PAGES; page++) {
8464
+ const remaining = deadline - Date.now();
8465
+ if (remaining <= 0) throw new Error("Registry lookup deadline exceeded");
8466
+ const response = await withTimeout(
8467
+ bazaar.listResources({ type: "http", payTo, limit: PAGE_LIMIT, offset }),
8468
+ remaining,
8469
+ registry
8470
+ );
8471
+ const pagination = paginationSchema.parse(response.pagination);
8472
+ if (!Array.isArray(response.items) || response.items.length > PAGE_LIMIT || pagination.offset !== offset)
8473
+ throw new Error("Invalid registry page");
8474
+ items.push(...response.items);
8475
+ offset = pagination.offset + response.items.length;
8476
+ if (offset >= pagination.total) return { items };
8477
+ if (response.items.length === 0) break;
8478
+ }
8479
+ return { items, incomplete: "Registry listing truncated at the pagination limit" };
8339
8480
  }
8340
8481
  async function verifyAgainstRegistries(registries, url, live, timeoutMs, opts = {}) {
8341
8482
  const errors = [];
@@ -8348,16 +8489,19 @@ async function verifyAgainstRegistries(registries, url, live, timeoutMs, opts =
8348
8489
  mismatch ??= { registry: listing.registry, detail };
8349
8490
  }
8350
8491
  }
8492
+ const deadline = Date.now() + timeoutMs;
8351
8493
  for (const registry of registries) {
8352
8494
  try {
8353
- const bazaar = client(registry).extensions.bazaar;
8495
+ const remaining = deadline - Date.now();
8496
+ if (remaining <= 0) throw new Error("Registry lookup deadline exceeded");
8354
8497
  const listed = await withTimeout(
8355
- bazaar.listResources({ type: "http", payTo: live.payTo, limit: PAGE_LIMIT }),
8356
- timeoutMs,
8357
- `listing ${registry}`
8498
+ listingsFor(registry, url, live.payTo, remaining),
8499
+ remaining,
8500
+ `looking up this resource on ${registry}`
8358
8501
  );
8502
+ if (listed.incomplete) errors.push({ registry, message: listed.incomplete });
8359
8503
  const matches = listed.items.filter(
8360
- (item) => item.type === "http" && sameResourceUrl(item.resource, url)
8504
+ (item) => item != null && item.type === "http" && typeof item.resource === "string" && Array.isArray(item.accepts) && sameResourceUrl(item.resource, url)
8361
8505
  );
8362
8506
  if (matches.length === 0) continue;
8363
8507
  for (const item of matches) {
@@ -8370,14 +8514,20 @@ async function verifyAgainstRegistries(registries, url, live, timeoutMs, opts =
8370
8514
  }
8371
8515
  }
8372
8516
  if (mismatch !== void 0) return { outcome: "mismatch", ...mismatch };
8373
- if (errors.length === registries.length && registries.length > 0) {
8517
+ if (errors.length > 0) {
8374
8518
  return { outcome: "unavailable", errors };
8375
8519
  }
8376
8520
  return { outcome: "unlisted" };
8377
8521
  }
8378
8522
  function acceptsMismatch(advertised, live) {
8379
8523
  let closest = "the listing advertises no payment terms";
8380
- for (const adv of advertised) {
8524
+ for (const raw of advertised) {
8525
+ const parsed = paymentTerms.safeParse(raw);
8526
+ if (!parsed.success) {
8527
+ closest = "malformed advertised payment terms";
8528
+ continue;
8529
+ }
8530
+ const adv = parsed.data;
8381
8531
  if (adv.scheme !== live.scheme) {
8382
8532
  closest = `advertised scheme ${adv.scheme}, live ${live.scheme}`;
8383
8533
  continue;
@@ -8560,6 +8710,7 @@ function validateResultBody(schema, body) {
8560
8710
  async function gateSpend(input) {
8561
8711
  const { authorizer, amountAtomic } = input;
8562
8712
  const authorization = await authorizer.authorize({
8713
+ mode: input.mode,
8563
8714
  amountAtomic,
8564
8715
  creator: input.creator,
8565
8716
  ...input.maxPriceAtomic !== void 0 ? { maxPriceAtomic: input.maxPriceAtomic } : {},
@@ -8573,11 +8724,17 @@ async function gateSpend(input) {
8573
8724
  }
8574
8725
  const reservationId = authorization.reservationId;
8575
8726
  if (authorization.decision === "confirm") {
8576
- const approved = await confirmSpend(input);
8727
+ let approved;
8728
+ try {
8729
+ approved = await confirmSpend(input);
8730
+ } catch (err) {
8731
+ await authorizer.release(reservationId);
8732
+ throw err;
8733
+ }
8577
8734
  if (!approved) {
8578
8735
  await authorizer.release(reservationId);
8579
8736
  throw new CliError("POLICY_REFUSED", input.notConfirmedMessage, {
8580
- fix: "Re-run with --yes, or set a policy that auto-approves this spend.",
8737
+ fix: "Obtain explicit user consent for this quoted payment, then re-run with --yes or confirm interactively. Manual pay is never an autonomous workaround for a router refusal.",
8581
8738
  details: { reason: authorization.reason, amountAtomic: amountAtomic.toString() }
8582
8739
  });
8583
8740
  }
@@ -9789,6 +9946,38 @@ var PAYMENT_REQUIRED_HEADER = "PAYMENT-REQUIRED";
9789
9946
  var PAYMENT_RESPONSE_HEADER = "PAYMENT-RESPONSE";
9790
9947
  var BODY_PREVIEW_CHARS = 1200;
9791
9948
  async function runPay(args, ctx, deps = {}) {
9949
+ const warnings = [];
9950
+ try {
9951
+ return await executePay(args, ctx, deps, warnings);
9952
+ } catch (err) {
9953
+ if (err instanceof CliError && warnings.length > 0) {
9954
+ throw new CliError(err.code, err.message, {
9955
+ exitCode: err.exitCode,
9956
+ ...err.fix !== void 0 ? { fix: err.fix } : {},
9957
+ details: {
9958
+ ...typeof err.details === "object" && err.details !== null ? err.details : {},
9959
+ warnings
9960
+ },
9961
+ cause: err
9962
+ });
9963
+ }
9964
+ throw err;
9965
+ }
9966
+ }
9967
+ async function executePay(args, ctx, deps, warnings) {
9968
+ const router = args.execution === "router" || args.terms !== void 0;
9969
+ if (router) {
9970
+ const terms = args.terms;
9971
+ if (args.ignoreWarnings === true || !terms || typeof terms.maxAmountAtomic !== "string" || !/^\d+$/.test(terms.maxAmountAtomic) || [terms.network, terms.asset, terms.payTo, terms.source].some(
9972
+ (v) => v !== void 0 && (typeof v !== "string" || v.trim().length === 0)
9973
+ )) {
9974
+ throw new CliError(
9975
+ "REFUSED",
9976
+ "Router payments require valid advertised terms and cannot acknowledge registry warnings.",
9977
+ { details: { reason: "invalid_router_terms" } }
9978
+ );
9979
+ }
9980
+ }
9792
9981
  const settings = await resolveContextSettings(ctx);
9793
9982
  const maxPriceAtomic = args.maxPrice !== void 0 ? BigInt(parseUsdToAtomic(args.maxPrice)) : void 0;
9794
9983
  const openedSigner = {};
@@ -9825,10 +10014,15 @@ async function runPay(args, ctx, deps = {}) {
9825
10014
  });
9826
10015
  }
9827
10016
  if (probe.status !== 402) {
9828
- throw new CliError("API_UNREACHABLE", `${url} answered ${probe.status}.`, {
9829
- fix: "Check the URL and the endpoint status, then retry.",
9830
- details: { status: probe.status, body: probe.json }
9831
- });
10017
+ const said = providerMessage(probe.json);
10018
+ throw new CliError(
10019
+ "API_UNREACHABLE",
10020
+ `${url} answered ${probe.status}${said === null ? "." : `: ${said}`}`,
10021
+ {
10022
+ fix: probe.status === 404 ? "Nothing was paid. The same request will answer 404 again." : "Check the URL and the endpoint status, then retry.",
10023
+ details: { status: probe.status, body: probe.json }
10024
+ }
10025
+ );
9832
10026
  }
9833
10027
  const paymentRequired = decodeChallenge(probe, url);
9834
10028
  const payer = createPayerClient(() => signerOrThrow(openedSigner));
@@ -9841,8 +10035,15 @@ async function runPay(args, ctx, deps = {}) {
9841
10035
  let registry;
9842
10036
  let termsLabel;
9843
10037
  if (args.terms !== void 0) termsLabel = assertWithinTerms(args.terms, requirement);
9844
- else if (lane === "bazaar") {
9845
- registry = await assertRegistryVerified(settings, url, requirement, ctx.flags.timeout, ctx);
10038
+ else if (lane === "bazaar" && paymentRequired.extensions?.[SIGN_IN_WITH_X] === void 0) {
10039
+ registry = await checkRegistry(
10040
+ settings,
10041
+ url,
10042
+ requirement,
10043
+ ctx,
10044
+ args.ignoreWarnings === true,
10045
+ warnings
10046
+ );
9846
10047
  }
9847
10048
  const provider = resolveWalletProvider(
9848
10049
  ctx,
@@ -9901,10 +10102,24 @@ async function runPay(args, ctx, deps = {}) {
9901
10102
  }
9902
10103
  });
9903
10104
  }
10105
+ if (fresh.scheme !== requirement.scheme || fresh.network !== requirement.network || fresh.asset.toLowerCase() !== requirement.asset.toLowerCase() || fresh.payTo.toLowerCase() !== requirement.payTo.toLowerCase() || JSON.stringify(fresh.extra) !== JSON.stringify(requirement.extra)) {
10106
+ throw new CliError(
10107
+ "PAYMENT_FAILED",
10108
+ "The payment terms changed before signing; refusing to pay.",
10109
+ { fix: "Review a fresh challenge before paying again." }
10110
+ );
10111
+ }
9904
10112
  effectiveRequirement = fresh;
9905
10113
  if (args.terms !== void 0) termsLabel = assertWithinTerms(args.terms, fresh);
9906
10114
  else if (lane === "bazaar") {
9907
- registry = await assertRegistryVerified(settings, url, fresh, ctx.flags.timeout, ctx);
10115
+ registry = await checkRegistry(
10116
+ settings,
10117
+ url,
10118
+ fresh,
10119
+ ctx,
10120
+ args.ignoreWarnings === true,
10121
+ warnings
10122
+ );
9908
10123
  }
9909
10124
  }
9910
10125
  const amountAtomic = BigInt(effectiveRequirement.amount);
@@ -9915,7 +10130,9 @@ async function runPay(args, ctx, deps = {}) {
9915
10130
  );
9916
10131
  const verifiedVia = registry ?? termsLabel;
9917
10132
  const via = verifiedVia !== void 0 ? ` (${sanitizeForTerminal(verifiedVia)})` : "";
10133
+ const mode = router ? "automatic" : "manual";
9918
10134
  const reservationId = await gateSpend({
10135
+ mode,
9919
10136
  ctx,
9920
10137
  authorizer,
9921
10138
  amountAtomic,
@@ -9924,12 +10141,46 @@ async function runPay(args, ctx, deps = {}) {
9924
10141
  ...args.requestKey !== void 0 ? { requestKey: args.requestKey } : {},
9925
10142
  yes: args.yes === true,
9926
10143
  ...deps.confirm !== void 0 ? { confirm: deps.confirm } : {},
9927
- payeeLabel: `${sanitizeForTerminal(host)}${via}`,
10144
+ payeeLabel: `${sanitizeForTerminal(url)}${via}; recipient ${sanitizeForTerminal(effectiveRequirement.payTo)}, ${sanitizeForTerminal(effectiveRequirement.network)} / ${sanitizeForTerminal(effectiveRequirement.asset)}`,
9928
10145
  allowlistSubject: "this host",
9929
10146
  notConfirmedMessage: "Payment not confirmed."
9930
10147
  });
9931
10148
  let payment;
9932
10149
  try {
10150
+ if (amountAtomic > 0n) {
10151
+ const deadline = Date.now() + ctx.flags.timeout;
10152
+ const readBalance = deps.readBalance ?? readUsdcBalance;
10153
+ let balance = await readBalance(signer.address, settings.rpcUrl, {
10154
+ timeoutMs: Math.max(1, Math.floor(ctx.flags.timeout / 2))
10155
+ });
10156
+ if (balance === null && Date.now() < deadline) {
10157
+ await delay(Math.min(1100, Math.floor((deadline - Date.now()) / 2)));
10158
+ const remaining = deadline - Date.now();
10159
+ if (remaining > 0)
10160
+ balance = await readBalance(signer.address, settings.rpcUrl, { timeoutMs: remaining });
10161
+ }
10162
+ if (balance === null) {
10163
+ throw new CliError(
10164
+ "REFUSED",
10165
+ "The wallet balance could not be read; no payment was signed.",
10166
+ {
10167
+ fix: "Check the configured Base rpcUrl and retry when it is available.",
10168
+ details: { reason: "balance_unavailable", address: signer.address }
10169
+ }
10170
+ );
10171
+ }
10172
+ if (balance < amountAtomic) {
10173
+ throw new CliError("REFUSED", "The wallet has insufficient USDC; no payment was signed.", {
10174
+ fix: "Fund this wallet on Base with `tenjin wallet fund` before paying.",
10175
+ details: {
10176
+ reason: "insufficient_funds",
10177
+ address: signer.address,
10178
+ balanceAtomic: balance.toString(),
10179
+ requiredAtomic: amountAtomic.toString()
10180
+ }
10181
+ });
10182
+ }
10183
+ }
9933
10184
  payment = await buildExactPayment(effectiveChallenge, signer, effectiveRequirement);
9934
10185
  } catch (err) {
9935
10186
  await authorizer.release(reservationId);
@@ -9937,12 +10188,13 @@ async function runPay(args, ctx, deps = {}) {
9937
10188
  }
9938
10189
  const paid = await httpRequest(url, {
9939
10190
  ...fetchOpts,
10191
+ timeoutMs: paidLegTimeoutMs(effectiveRequirement, ctx.flags.timeout),
9940
10192
  headers: { ...headers, ...payment.headers }
9941
10193
  });
9942
- await authorizer.commit(reservationId, payment.amountAtomic);
10194
+ await authorizer.commit(reservationId, payment.amountAtomic, { mode });
9943
10195
  if (!paid.ok) {
9944
10196
  throw fetchFailureToCliError(paid, {
9945
- fix: `The authorization was transmitted and settlement is unknown; it is counted against the session budget. Do not simply retry: each attempt signs a fresh authorization. ${legFix(paid)}`,
10197
+ fix: `The authorization was transmitted and settlement is unknown; it is recorded as transmitted exposure. Do not simply retry: each attempt signs a fresh authorization. ${legFix(paid)}`,
9946
10198
  details: { amountAtomic: payment.amountAtomic.toString(), settlement: "unknown" }
9947
10199
  });
9948
10200
  }
@@ -9951,21 +10203,11 @@ async function runPay(args, ctx, deps = {}) {
9951
10203
  if (args.resultSchema !== void 0) {
9952
10204
  const check = validateResultBody(args.resultSchema, paid.text);
9953
10205
  if (check.unvalidated === true) caveat = unvalidatedCaveat(check);
9954
- else if (!check.valid) {
9955
- throw new CliError("CONTRACT_MISMATCH", `The paid response is not a usable result.`, {
9956
- fix: "The payment has already settled and is counted against the session budget. Do not retry blind: the endpoint answered 2xx with a body that fails the success rule it was paid under.",
9957
- details: {
9958
- status: paid.status,
9959
- reason: check.reason,
9960
- ...check.diagnosis !== void 0 ? { diagnosis: check.diagnosis } : {},
9961
- amountAtomic: payment.amountAtomic.toString(),
9962
- settlement: "reported"
9963
- }
9964
- });
9965
- }
10206
+ else if (!check.valid) caveat = failedRuleCaveat(check);
9966
10207
  }
9967
10208
  return deliver(url, lane, paid, {
9968
10209
  paid: true,
10210
+ warnings,
9969
10211
  amountAtomic: payment.amountAtomic,
9970
10212
  requirement: effectiveRequirement,
9971
10213
  ...registry !== void 0 ? { registry } : {},
@@ -9977,7 +10219,7 @@ async function runPay(args, ctx, deps = {}) {
9977
10219
  "PAYMENT_FAILED",
9978
10220
  paid.status === 402 ? "Payment was not accepted by the endpoint." : `The endpoint answered ${paid.status} on the paid request; whether it settled is unknown.`,
9979
10221
  {
9980
- fix: "The signed payment already left and is counted against the session budget; the endpoint may still settle it. Do not simply retry: each attempt signs a fresh authorization. Verify the endpoint (and this listing, if Bazaar) before paying again.",
10222
+ fix: "The signed payment already left and is recorded as transmitted exposure; the endpoint may still settle it. Do not simply retry: each attempt signs a fresh authorization. Verify the endpoint (and this listing, if Bazaar) before paying again.",
9981
10223
  // The amount rides on the failure so a caller can report what is at risk
9982
10224
  // rather than a zero. Settlement is unknown by construction here.
9983
10225
  details: {
@@ -9989,6 +10231,14 @@ async function runPay(args, ctx, deps = {}) {
9989
10231
  }
9990
10232
  );
9991
10233
  }
10234
+ var MAX_PAID_LEG_TIMEOUT_MS = 12e4;
10235
+ function paidLegTimeoutMs(requirement, cliTimeoutMs) {
10236
+ const advertised = requirement.maxTimeoutSeconds;
10237
+ if (typeof advertised !== "number" || !Number.isFinite(advertised) || advertised <= 0) {
10238
+ return cliTimeoutMs;
10239
+ }
10240
+ return Math.max(cliTimeoutMs, Math.min(advertised * 1e3, MAX_PAID_LEG_TIMEOUT_MS));
10241
+ }
9992
10242
  function resolveLane(url, settings) {
9993
10243
  let target;
9994
10244
  try {
@@ -10004,18 +10254,9 @@ function resolveLane(url, settings) {
10004
10254
  });
10005
10255
  }
10006
10256
  if (isSameDeployment(target.origin, new URL(settings.baseUrl).origin)) return "tenjin";
10007
- if (settings.bazaarPay !== true) {
10008
- throw new CliError(
10009
- "USAGE",
10010
- `${target.origin} is not the configured base URL, and the Bazaar pay lane is off.`,
10011
- {
10012
- fix: "An operator enables paying registry-listed non-Tenjin endpoints with `tenjin config set bazaarPay on`."
10013
- }
10014
- );
10015
- }
10016
10257
  if (target.protocol !== "https:") {
10017
10258
  throw new CliError("USAGE", "The Bazaar lane pays https endpoints only.", {
10018
- fix: "Use the https URL the registry lists."
10259
+ fix: "Use a public HTTPS endpoint."
10019
10260
  });
10020
10261
  }
10021
10262
  return "bazaar";
@@ -10100,9 +10341,19 @@ function assertUsableResult(schema, body, status, how) {
10100
10341
  function unvalidatedCaveat(check) {
10101
10342
  return `${check.reason ?? "The result could not be validated."} The body is delivered unverified: its shape was never checked against the success rule.`;
10102
10343
  }
10344
+ function failedRuleCaveat(check) {
10345
+ return `${check.reason ?? "The result does not satisfy its success schema."} The payment settled, so the body is delivered as received, unverified: treat it as possibly not the answer that was paid for.`;
10346
+ }
10103
10347
  function legFix(failure) {
10104
10348
  return failure.kind === "oversized-header" ? "Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes." : "";
10105
10349
  }
10350
+ function providerMessage(body) {
10351
+ const error = body?.error;
10352
+ const message = error?.message;
10353
+ if (typeof message !== "string") return null;
10354
+ const line = message.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim().slice(0, 300);
10355
+ return line.length > 0 ? line : null;
10356
+ }
10106
10357
  function noMatchingEntry(challenge, terms) {
10107
10358
  if (terms === void 0 || terms.network === void 0 && terms.asset === void 0) {
10108
10359
  return noPayableRequirement(challenge.accepts);
@@ -10139,39 +10390,47 @@ function assertWithinTerms(terms, requirement) {
10139
10390
  }
10140
10391
  return terms.source ?? "the advertised terms";
10141
10392
  }
10142
- async function assertRegistryVerified(settings, url, requirement, timeoutMs, ctx) {
10393
+ async function checkRegistry(settings, url, requirement, ctx, acknowledged, warnings) {
10143
10394
  const verification = await verifyAgainstRegistries(
10144
10395
  settings.bazaarRegistries,
10145
10396
  url,
10146
10397
  requirement,
10147
- timeoutMs,
10398
+ ctx.flags.timeout,
10148
10399
  { dataDir: ctx.dataDir }
10149
10400
  );
10150
- switch (verification.outcome) {
10151
- case "verified":
10152
- return verification.registry;
10153
- case "mismatch":
10154
- throw new CliError(
10155
- "REGISTRY_MISMATCH",
10156
- `The live 402 does not match what ${verification.registry} advertises for this resource (${verification.detail}).`,
10157
- {
10158
- fix: "Nothing was signed. Re-run `tenjin discover` to see the advertised terms; if the seller changed them, the registry will catch up.",
10159
- details: { registry: verification.registry, detail: verification.detail }
10160
- }
10161
- );
10162
- case "unlisted":
10163
- throw new CliError("USAGE", "No configured registry is known to list this resource.", {
10164
- fix: "The Bazaar lane pays publicly listed deals only, and pay-time lookup leans on the local `discover` cache: run `tenjin discover [query]` so a sweep can surface this endpoint, then re-run pay."
10165
- });
10401
+ if (verification.outcome === "verified") return verification.registry;
10402
+ if (verification.outcome === "unlisted") return void 0;
10403
+ const warning = {
10404
+ ...verification,
10405
+ acknowledged,
10406
+ quote: { url, ...requirement }
10407
+ };
10408
+ warnings.push(warning);
10409
+ const message = warningMessage(warning);
10410
+ if (!ctx.flags.json) {
10411
+ ctx.io.stderr.write(
10412
+ `Live quote: ${sanitizeForTerminal(url)}; recipient ${sanitizeForTerminal(requirement.payTo)}; ${sanitizeForTerminal(requirement.network)} / ${sanitizeForTerminal(requirement.asset)}; ${toMoney(requirement.amount).usd} USD
10413
+ `
10414
+ );
10415
+ ctx.io.stderr.write(
10416
+ `${sanitizeForTerminal(message)}${acknowledged ? " (acknowledged for this invocation)" : ""}
10417
+ `
10418
+ );
10419
+ }
10420
+ if (!acknowledged) {
10421
+ throw new CliError("REFUSED", message, {
10422
+ fix: "Review the live quote and use --ignore-warnings to acknowledge this registry warning for this invocation. --yes only confirms payment; normal payment checks still apply.",
10423
+ details: { reason: "registry_acknowledgement_required", quote: { url, ...requirement } }
10424
+ });
10425
+ }
10426
+ return void 0;
10427
+ }
10428
+ function warningMessage(warning) {
10429
+ switch (warning.outcome) {
10166
10430
  case "unavailable":
10167
- throw new CliError(
10168
- "NETWORK_ERROR",
10169
- "No configured registry answered; the Bazaar lane fails closed.",
10170
- {
10171
- fix: "Retry when the registries are reachable.",
10172
- details: { errors: verification.errors }
10173
- }
10174
- );
10431
+ return "Registry warning: verification is unavailable or incomplete.";
10432
+ case "mismatch":
10433
+ return `Registry warning: the live terms differ from ${warning.registry} (${warning.detail}).`;
10175
10434
  }
10176
10435
  }
10177
10436
  function deliver(url, lane, res, opts) {
@@ -10181,10 +10440,12 @@ function deliver(url, lane, res, opts) {
10181
10440
  lane,
10182
10441
  status: res.status,
10183
10442
  paid: opts.paid,
10443
+ ...opts.warnings !== void 0 ? { warnings: opts.warnings } : {},
10184
10444
  ...opts.paid ? {
10185
10445
  amountPaid: toMoney(opts.amountAtomic.toString()),
10186
10446
  payTo: opts.requirement.payTo,
10187
10447
  network: opts.requirement.network,
10448
+ asset: opts.requirement.asset,
10188
10449
  ...opts.registry !== void 0 ? { registry: opts.registry } : {}
10189
10450
  } : opts.entitled === true ? { entitled: true } : {},
10190
10451
  ...settlementTxHash !== void 0 ? { settlementTxHash } : {},
@@ -10205,6 +10466,9 @@ function deliver(url, lane, res, opts) {
10205
10466
  data,
10206
10467
  humanLines: [
10207
10468
  headline,
10469
+ ...(opts.warnings ?? []).map(
10470
+ (w) => `${sanitizeForTerminal(warningMessage(w))} (acknowledged)`
10471
+ ),
10208
10472
  ...opts.caveat !== void 0 ? [sanitizeForTerminal(opts.caveat)] : [],
10209
10473
  ...preview2.length > 0 ? [preview2] : []
10210
10474
  ]
@@ -10233,6 +10497,8 @@ export {
10233
10497
  require_dist,
10234
10498
  canonicalHash,
10235
10499
  assertResultSchema,
10236
- runPay
10500
+ runPay,
10501
+ MAX_PAID_LEG_TIMEOUT_MS,
10502
+ paidLegTimeoutMs
10237
10503
  };
10238
- //# sourceMappingURL=chunk-QDD2RN7G.js.map
10504
+ //# sourceMappingURL=chunk-SCAOYGKX.js.map