tenjin-cli 0.1.0-alpha.3 → 0.1.0-alpha.5

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 (157) hide show
  1. package/README.md +322 -197
  2. package/dist/{_esm-FEASBWRP.js → _esm-N4KAVXQR.js} +9 -9
  3. package/dist/buy-YMXXVNFH.js +42 -0
  4. package/dist/candidate-H7FR4AU5.js +22 -0
  5. package/dist/{ccip-XR5NE5QK.js → ccip-RPPPKTJR.js} +5 -5
  6. package/dist/{ccip-NQXCEK2U.js → ccip-ZGGWQN4X.js} +4 -4
  7. package/dist/{chunk-MUBUQVC3.js → chunk-2JQ5JSG6.js} +3 -2
  8. package/dist/{chunk-MUBUQVC3.js.map → chunk-2JQ5JSG6.js.map} +1 -1
  9. package/dist/{chunk-662MSGZB.js → chunk-3IRDP7TN.js} +100 -66
  10. package/dist/chunk-3IRDP7TN.js.map +1 -0
  11. package/dist/{chunk-YALGASEU.js → chunk-47PP7TAG.js} +1610 -1610
  12. package/dist/chunk-47PP7TAG.js.map +1 -0
  13. package/dist/{buy-EE6SEXP6.js → chunk-4WVKXKDK.js} +27 -59
  14. package/dist/chunk-4WVKXKDK.js.map +1 -0
  15. package/dist/chunk-5SCU253N.js +412 -0
  16. package/dist/chunk-5SCU253N.js.map +1 -0
  17. package/dist/{chunk-UGX7YPX2.js → chunk-7FK2UN2T.js} +65 -65
  18. package/dist/{chunk-UGX7YPX2.js.map → chunk-7FK2UN2T.js.map} +1 -1
  19. package/dist/chunk-ADJYSM45.js +135 -0
  20. package/dist/chunk-ADJYSM45.js.map +1 -0
  21. package/dist/{chunk-DXTQ3CSI.js → chunk-BIKAUVC2.js} +43 -11
  22. package/dist/chunk-BIKAUVC2.js.map +1 -0
  23. package/dist/{chunk-Z6MFJV5Z.js → chunk-C444K6MI.js} +266 -55
  24. package/dist/chunk-C444K6MI.js.map +1 -0
  25. package/dist/{chunk-JPHG2JW3.js → chunk-CVX6JNGD.js} +26 -26
  26. package/dist/chunk-CVX6JNGD.js.map +1 -0
  27. package/dist/{chunk-S3IGX57D.js → chunk-FU6MCSLG.js} +9 -9
  28. package/dist/{lookup-ZPN2Q67N.js → chunk-HTDALK7M.js} +46 -32
  29. package/dist/chunk-HTDALK7M.js.map +1 -0
  30. package/dist/chunk-IOPWPMT2.js +239 -0
  31. package/dist/chunk-IOPWPMT2.js.map +1 -0
  32. package/dist/{chunk-5CLSD5YN.js → chunk-KYQVEKP5.js} +7 -7
  33. package/dist/{chunk-RRN3YTK7.js → chunk-KZAAWQNP.js} +3 -3
  34. package/dist/{chunk-7KUW4MJD.js → chunk-L4IHCN6B.js} +11 -7
  35. package/dist/chunk-L4IHCN6B.js.map +1 -0
  36. package/dist/{chunk-XHC6FCGZ.js → chunk-LAM66WFJ.js} +25 -11
  37. package/dist/chunk-LAM66WFJ.js.map +1 -0
  38. package/dist/{chunk-NCE5NSN6.js → chunk-M2O56UK7.js} +158 -158
  39. package/dist/chunk-M2O56UK7.js.map +1 -0
  40. package/dist/{chunk-GO75V3NZ.js → chunk-MDDGEGSW.js} +8 -6
  41. package/dist/chunk-MDDGEGSW.js.map +1 -0
  42. package/dist/{chunk-XJIW7USF.js → chunk-MJZZTKCC.js} +112 -6
  43. package/dist/chunk-MJZZTKCC.js.map +1 -0
  44. package/dist/{chunk-Z52RA3NC.js → chunk-NFSOVL3C.js} +51 -21
  45. package/dist/chunk-NFSOVL3C.js.map +1 -0
  46. package/dist/{chunk-FJPLRISB.js → chunk-NJF2WENW.js} +5 -4
  47. package/dist/chunk-NJF2WENW.js.map +1 -0
  48. package/dist/{chunk-OYMYCW7J.js → chunk-PAUXMRSF.js} +45 -4
  49. package/dist/{chunk-OYMYCW7J.js.map → chunk-PAUXMRSF.js.map} +1 -1
  50. package/dist/{chunk-ZABPQJ3M.js → chunk-POJRB2AE.js} +2 -2
  51. package/dist/{publish-BKBQQAW4.js → chunk-PYNSGYBE.js} +254 -57
  52. package/dist/chunk-PYNSGYBE.js.map +1 -0
  53. package/dist/{chunk-YN5SHIXQ.js → chunk-QONTBYQW.js} +12 -9
  54. package/dist/chunk-QONTBYQW.js.map +1 -0
  55. package/dist/chunk-QW2Q2KAH.js +27 -0
  56. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  57. package/dist/chunk-RTJLLPFA.js +599 -0
  58. package/dist/chunk-RTJLLPFA.js.map +1 -0
  59. package/dist/{chunk-CYOF7ROH.js → chunk-S5RYMCV6.js} +3 -3
  60. package/dist/chunk-TXPPMK4L.js +59 -0
  61. package/dist/chunk-TXPPMK4L.js.map +1 -0
  62. package/dist/{chunk-ZMHYXMO6.js → chunk-U5S527PP.js} +3 -3
  63. package/dist/{chunk-RY4XKNV3.js → chunk-UHTVXQ2O.js} +3 -3
  64. package/dist/{chunk-QVX5MWJZ.js → chunk-W6R3HAAG.js} +2 -2
  65. package/dist/{chunk-3OV7E5G5.js → chunk-WWX32ML4.js} +1 -1
  66. package/dist/{chunk-3OV7E5G5.js.map → chunk-WWX32ML4.js.map} +1 -1
  67. package/dist/{chunk-HIVZG55D.js → chunk-XJN5WUKL.js} +2 -2
  68. package/dist/{chunk-HSDCI7OV.js → chunk-YLYINX2H.js} +3 -3
  69. package/dist/{chunk-4ONXEEQL.js → chunk-ZDY2KY5X.js} +2 -2
  70. package/dist/{chunk-4ONXEEQL.js.map → chunk-ZDY2KY5X.js.map} +1 -1
  71. package/dist/{chunk-TLCMMYLY.js → chunk-ZIYVN4CD.js} +6 -6
  72. package/dist/chunk-ZIYVN4CD.js.map +1 -0
  73. package/dist/{candidate-ERMSYYQZ.js → chunk-ZW3B5LWX.js} +15 -19
  74. package/dist/{candidate-ERMSYYQZ.js.map → chunk-ZW3B5LWX.js.map} +1 -1
  75. package/dist/{cli-SBXI5AMS.js → cli-IW76QTN3.js} +64 -40
  76. package/dist/{cli-SBXI5AMS.js.map → cli-IW76QTN3.js.map} +1 -1
  77. package/dist/{config-VELDKLHY.js → config-VCOS7P5K.js} +8 -6
  78. package/dist/{doctor-T3KWNNP2.js → doctor-WS65JG3V.js} +9 -8
  79. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-WHYKB6HA.js} +5 -5
  80. package/dist/index.js +1 -1
  81. package/dist/inspect-SFJWUQHO.js +33 -0
  82. package/dist/install-RVPQPCKH.js +589 -0
  83. package/dist/install-RVPQPCKH.js.map +1 -0
  84. package/dist/outcome-GNYCSZ7J.js +20 -0
  85. package/dist/publish-DSFWQRUN.js +36 -0
  86. package/dist/publish-DSFWQRUN.js.map +1 -0
  87. package/dist/run-OMPKA43G.js +16807 -0
  88. package/dist/run-OMPKA43G.js.map +1 -0
  89. package/dist/search-KOI6Y7P6.js +24 -0
  90. package/dist/search-KOI6Y7P6.js.map +1 -0
  91. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-XRPVBC6V.js} +3 -3
  92. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  93. package/dist/send-3G4C64HJ.js +222 -0
  94. package/dist/send-3G4C64HJ.js.map +1 -0
  95. package/dist/usdc-4VCDHFWX.js +38 -0
  96. package/dist/usdc-4VCDHFWX.js.map +1 -0
  97. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-TUQJBMHM.js} +5 -5
  98. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  99. package/dist/wallet-B7KJS2R5.js +40 -0
  100. package/dist/wallet-B7KJS2R5.js.map +1 -0
  101. package/dist/wallet-PP22LAX7.js +31 -0
  102. package/dist/wallet-PP22LAX7.js.map +1 -0
  103. package/package.json +4 -3
  104. package/skills/tenjin/SKILL.md +83 -15
  105. package/skills/tenjin-publish/SKILL.md +118 -18
  106. package/skills/tenjin-search/SKILL.md +149 -31
  107. package/dist/buy-EE6SEXP6.js.map +0 -1
  108. package/dist/chunk-662MSGZB.js.map +0 -1
  109. package/dist/chunk-7KUW4MJD.js.map +0 -1
  110. package/dist/chunk-AWPAWHNX.js +0 -333
  111. package/dist/chunk-AWPAWHNX.js.map +0 -1
  112. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  113. package/dist/chunk-ESPNTPQ2.js +0 -207
  114. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  115. package/dist/chunk-FJPLRISB.js.map +0 -1
  116. package/dist/chunk-GO75V3NZ.js.map +0 -1
  117. package/dist/chunk-JPHG2JW3.js.map +0 -1
  118. package/dist/chunk-NCE5NSN6.js.map +0 -1
  119. package/dist/chunk-TLCMMYLY.js.map +0 -1
  120. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  121. package/dist/chunk-XJIW7USF.js.map +0 -1
  122. package/dist/chunk-YALGASEU.js.map +0 -1
  123. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  124. package/dist/chunk-Z52RA3NC.js.map +0 -1
  125. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  126. package/dist/inspect-LMKOXE4Y.js +0 -96
  127. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  128. package/dist/install-LEX3ENQ6.js +0 -387
  129. package/dist/install-LEX3ENQ6.js.map +0 -1
  130. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  131. package/dist/outcome-N7TAK6WR.js +0 -66
  132. package/dist/outcome-N7TAK6WR.js.map +0 -1
  133. package/dist/publish-BKBQQAW4.js.map +0 -1
  134. package/dist/usdc-JIAJW4SV.js +0 -22
  135. package/dist/wallet-CWEMYVIH.js +0 -179
  136. package/dist/wallet-CWEMYVIH.js.map +0 -1
  137. package/dist/wallet-PA54CRBL.js +0 -30
  138. /package/dist/{_esm-FEASBWRP.js.map → _esm-N4KAVXQR.js.map} +0 -0
  139. /package/dist/{ccip-NQXCEK2U.js.map → buy-YMXXVNFH.js.map} +0 -0
  140. /package/dist/{ccip-XR5NE5QK.js.map → candidate-H7FR4AU5.js.map} +0 -0
  141. /package/dist/{config-VELDKLHY.js.map → ccip-RPPPKTJR.js.map} +0 -0
  142. /package/dist/{doctor-T3KWNNP2.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  143. /package/dist/{chunk-S3IGX57D.js.map → chunk-FU6MCSLG.js.map} +0 -0
  144. /package/dist/{chunk-5CLSD5YN.js.map → chunk-KYQVEKP5.js.map} +0 -0
  145. /package/dist/{chunk-RRN3YTK7.js.map → chunk-KZAAWQNP.js.map} +0 -0
  146. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POJRB2AE.js.map} +0 -0
  147. /package/dist/{chunk-CYOF7ROH.js.map → chunk-S5RYMCV6.js.map} +0 -0
  148. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-U5S527PP.js.map} +0 -0
  149. /package/dist/{chunk-RY4XKNV3.js.map → chunk-UHTVXQ2O.js.map} +0 -0
  150. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-W6R3HAAG.js.map} +0 -0
  151. /package/dist/{chunk-HIVZG55D.js.map → chunk-XJN5WUKL.js.map} +0 -0
  152. /package/dist/{chunk-HSDCI7OV.js.map → chunk-YLYINX2H.js.map} +0 -0
  153. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → config-VCOS7P5K.js.map} +0 -0
  154. /package/dist/{secp256k1-N3ZHU7LB.js.map → doctor-WS65JG3V.js.map} +0 -0
  155. /package/dist/{usdc-JIAJW4SV.js.map → ethersCompat-Df4a6QIZ-WHYKB6HA.js.map} +0 -0
  156. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → inspect-SFJWUQHO.js.map} +0 -0
  157. /package/dist/{wallet-PA54CRBL.js.map → outcome-GNYCSZ7J.js.map} +0 -0
@@ -0,0 +1,135 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ fetchRead
4
+ } from "./chunk-BIKAUVC2.js";
5
+ import {
6
+ headingOutline
7
+ } from "./chunk-FU6MCSLG.js";
8
+ import {
9
+ resolveResourceRef
10
+ } from "./chunk-L4IHCN6B.js";
11
+ import {
12
+ sanitizeForTerminal
13
+ } from "./chunk-NFSOVL3C.js";
14
+ import {
15
+ resolveContextSettings
16
+ } from "./chunk-MDDGEGSW.js";
17
+ import {
18
+ toMoney
19
+ } from "./chunk-5SCU253N.js";
20
+
21
+ // src/commands/inspect.ts
22
+ async function runInspect(args, ctx, deps = {}) {
23
+ const settings = await resolveContextSettings(ctx);
24
+ const ref = await resolveResourceRef(args.ref, ctx.dataDir, settings.baseUrl);
25
+ const result = await fetchRead(ref.url, {
26
+ timeoutMs: ctx.flags.timeout,
27
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
28
+ });
29
+ if (result.kind === "entitled") {
30
+ const body = result.body;
31
+ return {
32
+ data: {
33
+ url: ref.url,
34
+ resourceId: body.id,
35
+ access: "free",
36
+ title: body.title,
37
+ price: toMoney(body.price),
38
+ headings: headingOutline(body.bodyMd)
39
+ },
40
+ humanLines: [
41
+ `${sanitizeForTerminal(body.title)}, free (${body.price} atomic). Read it with \`tenjin buy\`.`
42
+ ]
43
+ };
44
+ }
45
+ if (result.kind === "payment_required") {
46
+ const requirement = result.paymentRequired.accepts[0];
47
+ const price = requirement !== void 0 ? toMoney(requirement.amount) : void 0;
48
+ const card = result.preview.card;
49
+ return {
50
+ data: {
51
+ url: ref.url,
52
+ ...ref.resourceId !== void 0 ? { resourceId: ref.resourceId } : {},
53
+ access: "paid",
54
+ ...price !== void 0 ? { price } : {},
55
+ payment: requirement !== void 0 ? {
56
+ scheme: requirement.scheme,
57
+ network: requirement.network,
58
+ asset: requirement.asset,
59
+ payTo: requirement.payTo,
60
+ amount: requirement.amount
61
+ } : void 0,
62
+ // The card stays where the wire puts it, inside `preview`, and is emitted
63
+ // exactly once: it is the largest object in this envelope, and a second
64
+ // hoisted copy would double every inspect payload to save one key of
65
+ // depth.
66
+ preview: result.preview,
67
+ ...result.cardError === true ? { cardError: true } : {}
68
+ },
69
+ humanLines: [
70
+ `Paid resource${price !== void 0 ? `, ${price.usd} USD (${price.atomic} atomic)` : ""}.`,
71
+ ...cardLines(card),
72
+ // Three distinct states behind an absent card, and they call for three
73
+ // different actions: the piece attests nothing (a signal, judge on that),
74
+ // the server could not load a card it has (transient, retry), or this CLI
75
+ // could not parse what arrived (a client-side bug or server drift). Only
76
+ // the last is ours. `cardUnavailable` is server-sent and never rides
77
+ // alongside a card, so it is only worth saying when there is no card.
78
+ ...card === void 0 && result.preview.cardUnavailable === true ? ["The piece has a card the server could not load; retry later."] : [],
79
+ ...result.cardError === true ? [
80
+ "The server sent an answer card this CLI could not parse; judging on price and preview only."
81
+ ] : [],
82
+ "This is the pre-purchase card; run `tenjin buy` to pay and read."
83
+ ]
84
+ };
85
+ }
86
+ return {
87
+ data: { url: ref.url, access: "entitled", message: result.message },
88
+ humanLines: [sanitizeForTerminal(result.message)]
89
+ };
90
+ }
91
+ var CARD_BOUNDS = {
92
+ list: 10 * 200 + 9 * 2,
93
+ appliesTo: 8 * (32 + 1 + 20 * 120 + 19 * 2) + 7 * 2,
94
+ prose: 500,
95
+ cadence: 120,
96
+ // artifactType and temporalMode are open strings on the wire, so the composed
97
+ // freshness line gets a bound of its own rather than trusting them.
98
+ freshness: 200
99
+ };
100
+ var CLIP_MARKER = "...";
101
+ function cardLine(label, value, max) {
102
+ if (value === null) return [];
103
+ const text = sanitizeForTerminal(value).trim();
104
+ if (text.length === 0) return [];
105
+ return [`${label}: ${text.length > max ? `${text.slice(0, max)}${CLIP_MARKER}` : text}`];
106
+ }
107
+ function cardLines(card) {
108
+ if (card === void 0) return [];
109
+ const list = (items) => items.length > 0 ? items.join("; ") : null;
110
+ const appliesTo = Object.entries(card.appliesTo).map(
111
+ ([key, values]) => `${key}=${values.join(", ")}`
112
+ );
113
+ return [
114
+ ...cardLine("Answers", list(card.questionsAnswered), CARD_BOUNDS.list),
115
+ ...cardLine("Tasks", list(card.tasksSupported), CARD_BOUNDS.list),
116
+ ...cardLine("Applies to", list(appliesTo), CARD_BOUNDS.appliesTo),
117
+ ...cardLine("Scope", card.scope, CARD_BOUNDS.prose),
118
+ ...cardLine("Excludes", card.exclusions, CARD_BOUNDS.prose),
119
+ ...cardLine("Freshness", freshness(card), CARD_BOUNDS.freshness),
120
+ ...cardLine("Provenance", card.provenanceSummary, CARD_BOUNDS.prose),
121
+ ...cardLine("Method", card.methodologySummary, CARD_BOUNDS.prose),
122
+ ...cardLine("Maintenance", card.maintenanceCadence, CARD_BOUNDS.cadence)
123
+ ];
124
+ }
125
+ function freshness(card) {
126
+ const parts = [card.artifactType, card.temporalMode].filter((s) => s.trim().length > 0);
127
+ if (card.asOf !== null) parts.push(`as of ${card.asOf}`);
128
+ if (card.validUntil !== null) parts.push(`valid until ${card.validUntil}`);
129
+ return parts.join(", ");
130
+ }
131
+
132
+ export {
133
+ runInspect
134
+ };
135
+ //# sourceMappingURL=chunk-ADJYSM45.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/inspect.ts"],"sourcesContent":["import { resolveResourceRef } from '../lib/resource-ref';\nimport { resolveContextSettings } from '../lib/settings';\nimport { fetchRead, type PreviewCard } from '../lib/read-client';\nimport { toMoney } from '../lib/money';\nimport { headingOutline } from '../lib/markdown';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin inspect <resource-url-or-id>`, fetch the pre-purchase answer card /\n * preview from the read route's 402 body WITHOUT paying (spec 10). A free\n * resource returns 200 with the whole body; a paid one returns the leak-safe\n * preview plus the advertised price/network, and the answer card when the piece\n * carries one. Never signs, never pays, never saves.\n *\n * The card is the depth half of the search/inspect split: search v2 candidates are\n * lean, so this free call is where an agent gets what it answers, what it applies\n * to, what it excludes, and how it is dated, before spending anything.\n */\n\nexport interface InspectArgs {\n ref: string;\n}\n\nexport interface InspectDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runInspect(\n args: InspectArgs,\n ctx: CommandContext,\n deps: InspectDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const ref = await resolveResourceRef(args.ref, ctx.dataDir, settings.baseUrl);\n\n const result = await fetchRead(ref.url, {\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n if (result.kind === 'entitled') {\n // Free (or already-entitled) resource: the body is readable now, no payment.\n const body = result.body;\n return {\n data: {\n url: ref.url,\n resourceId: body.id,\n access: 'free',\n title: body.title,\n price: toMoney(body.price),\n headings: headingOutline(body.bodyMd),\n },\n humanLines: [\n `${sanitizeForTerminal(body.title)}, free (${body.price} atomic). Read it with \\`tenjin buy\\`.`,\n ],\n };\n }\n\n if (result.kind === 'payment_required') {\n const requirement = result.paymentRequired.accepts[0];\n const price = requirement !== undefined ? toMoney(requirement.amount) : undefined;\n const card = result.preview.card;\n return {\n data: {\n url: ref.url,\n ...(ref.resourceId !== undefined ? { resourceId: ref.resourceId } : {}),\n access: 'paid',\n ...(price !== undefined ? { price } : {}),\n payment:\n requirement !== undefined\n ? {\n scheme: requirement.scheme,\n network: requirement.network,\n asset: requirement.asset,\n payTo: requirement.payTo,\n amount: requirement.amount,\n }\n : undefined,\n // The card stays where the wire puts it, inside `preview`, and is emitted\n // exactly once: it is the largest object in this envelope, and a second\n // hoisted copy would double every inspect payload to save one key of\n // depth.\n preview: result.preview,\n ...(result.cardError === true ? { cardError: true } : {}),\n },\n humanLines: [\n `Paid resource${price !== undefined ? `, ${price.usd} USD (${price.atomic} atomic)` : ''}.`,\n ...cardLines(card),\n // Three distinct states behind an absent card, and they call for three\n // different actions: the piece attests nothing (a signal, judge on that),\n // the server could not load a card it has (transient, retry), or this CLI\n // could not parse what arrived (a client-side bug or server drift). Only\n // the last is ours. `cardUnavailable` is server-sent and never rides\n // alongside a card, so it is only worth saying when there is no card.\n ...(card === undefined && result.preview.cardUnavailable === true\n ? ['The piece has a card the server could not load; retry later.']\n : []),\n ...(result.cardError === true\n ? [\n 'The server sent an answer card this CLI could not parse; judging on price and preview only.',\n ]\n : []),\n 'This is the pre-purchase card; run `tenjin buy` to pay and read.',\n ],\n };\n }\n\n // already_purchased without a payment header is unexpected; report it plainly.\n return {\n data: { url: ref.url, access: 'entitled', message: result.message },\n humanLines: [sanitizeForTerminal(result.message)],\n };\n}\n\n/**\n * Per-line caps for the rendered card, each derived from the server's write-time\n * bound for that field, so a VALID card is never clipped: the two lists are 10\n * items x 200 chars joined with '; '; appliesTo is 8 keys (<=32 chars) x 20\n * values x 120 chars; the prose fields have a 500-char column bound and cadence\n * 120. Exceeding one means a server that broke its own bounds.\n *\n * When that happens the clip is MARKED. A silently shortened claim reads as a\n * whole one, and \"applies to Postgres 14, 15\" is a different promise from\n * \"applies to Postgres 14, 15, 16\". The `--json` payload stays verbatim either\n * way, because that copy is what an agent decides a non-refundable purchase on.\n */\nconst CARD_BOUNDS = {\n list: 10 * 200 + 9 * 2,\n appliesTo: 8 * (32 + 1 + 20 * 120 + 19 * 2) + 7 * 2,\n prose: 500,\n cadence: 120,\n // artifactType and temporalMode are open strings on the wire, so the composed\n // freshness line gets a bound of its own rather than trusting them.\n freshness: 200,\n} as const;\n\nconst CLIP_MARKER = '...';\n\nfunction cardLine(label: string, value: string | null, max: number): string[] {\n if (value === null) return [];\n const text = sanitizeForTerminal(value).trim();\n if (text.length === 0) return [];\n return [`${label}: ${text.length > max ? `${text.slice(0, max)}${CLIP_MARKER}` : text}`];\n}\n\n/**\n * The answer card off the 402 body, as human lines. This is the depth half of the\n * search/inspect split: search v2 returns lean hits, and the card an agent judges\n * fit on arrives here, for free. Empty when the piece carries no card, so an\n * uncarded inspect renders exactly as it did before.\n */\nfunction cardLines(card: PreviewCard | undefined): string[] {\n if (card === undefined) return [];\n const list = (items: string[]): string | null => (items.length > 0 ? items.join('; ') : null);\n const appliesTo = Object.entries(card.appliesTo).map(\n ([key, values]) => `${key}=${values.join(', ')}`,\n );\n return [\n ...cardLine('Answers', list(card.questionsAnswered), CARD_BOUNDS.list),\n ...cardLine('Tasks', list(card.tasksSupported), CARD_BOUNDS.list),\n ...cardLine('Applies to', list(appliesTo), CARD_BOUNDS.appliesTo),\n ...cardLine('Scope', card.scope, CARD_BOUNDS.prose),\n ...cardLine('Excludes', card.exclusions, CARD_BOUNDS.prose),\n ...cardLine('Freshness', freshness(card), CARD_BOUNDS.freshness),\n ...cardLine('Provenance', card.provenanceSummary, CARD_BOUNDS.prose),\n ...cardLine('Method', card.methodologySummary, CARD_BOUNDS.prose),\n ...cardLine('Maintenance', card.maintenanceCadence, CARD_BOUNDS.cadence),\n ];\n}\n\n/** Type, temporal mode and the two dates on one line: they answer the single\n * question a buyer asks of freshness, which is whether this is still true here.\n *\n * Both labels are open strings on the wire, so an empty one is dropped rather\n * than joined: otherwise the line leads with a comma and reads as a rendering\n * bug. All four empty yields '', and cardLine then omits the line entirely. */\nfunction freshness(card: PreviewCard): string {\n const parts = [card.artifactType, card.temporalMode].filter((s) => s.trim().length > 0);\n if (card.asOf !== null) parts.push(`as of ${card.asOf}`);\n if (card.validUntil !== null) parts.push(`valid until ${card.validUntil}`);\n return parts.join(', ');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,MAAM,MAAM,mBAAmB,KAAK,KAAK,IAAI,SAAS,SAAS,OAAO;AAE5E,QAAM,SAAS,MAAM,UAAU,IAAI,KAAK;AAAA,IACtC,WAAW,IAAI,MAAM;AAAA,IACrB,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,EACtE,CAAC;AAED,MAAI,OAAO,SAAS,YAAY;AAE9B,UAAM,OAAO,OAAO;AACpB,WAAO;AAAA,MACL,MAAM;AAAA,QACJ,KAAK,IAAI;AAAA,QACT,YAAY,KAAK;AAAA,QACjB,QAAQ;AAAA,QACR,OAAO,KAAK;AAAA,QACZ,OAAO,QAAQ,KAAK,KAAK;AAAA,QACzB,UAAU,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AAY,SAAS;AAAA,IAC/D,GAAG,SAAS,cAAc,KAAK,mBAAmB,YAAY,KAAK;AAAA,IACnE,GAAG,SAAS,UAAU,KAAK,oBAAoB,YAAY,KAAK;AAAA,IAChE,GAAG,SAAS,eAAe,KAAK,oBAAoB,YAAY,OAAO;AAAA,EACzE;AACF;AAQA,SAAS,UAAU,MAA2B;AAC5C,QAAM,QAAQ,CAAC,KAAK,cAAc,KAAK,YAAY,EAAE,OAAO,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC;AACtF,MAAI,KAAK,SAAS,KAAM,OAAM,KAAK,SAAS,KAAK,IAAI,EAAE;AACvD,MAAI,KAAK,eAAe,KAAM,OAAM,KAAK,eAAe,KAAK,UAAU,EAAE;AACzE,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
@@ -3,22 +3,22 @@ import {
3
3
  SIWX_HEADER,
4
4
  decodePaymentRequiredHeader,
5
5
  decodePaymentResponseHeader
6
- } from "./chunk-S3IGX57D.js";
6
+ } from "./chunk-FU6MCSLG.js";
7
7
  import {
8
8
  rateLimitError
9
- } from "./chunk-662MSGZB.js";
9
+ } from "./chunk-3IRDP7TN.js";
10
10
  import {
11
11
  SLUG_RE,
12
12
  UUID_RE
13
- } from "./chunk-3OV7E5G5.js";
13
+ } from "./chunk-WWX32ML4.js";
14
14
  import {
15
15
  CLIENT_HEADER,
16
16
  httpRequest
17
- } from "./chunk-4ONXEEQL.js";
17
+ } from "./chunk-ZDY2KY5X.js";
18
18
  import {
19
19
  CliError,
20
20
  external_exports
21
- } from "./chunk-OYMYCW7J.js";
21
+ } from "./chunk-PAUXMRSF.js";
22
22
 
23
23
  // src/lib/read-client.ts
24
24
  var PAYMENT_REQUIRED_HEADER = "PAYMENT-REQUIRED";
@@ -34,11 +34,37 @@ var readBodySchema = external_exports.object({
34
34
  walletAddress: external_exports.string().nullish()
35
35
  }).passthrough()
36
36
  }).passthrough();
37
+ var previewCardSchema = external_exports.object({
38
+ artifactType: external_exports.string(),
39
+ temporalMode: external_exports.string(),
40
+ asOf: external_exports.string().nullable(),
41
+ validUntil: external_exports.string().nullable(),
42
+ questionsAnswered: external_exports.array(external_exports.string()),
43
+ tasksSupported: external_exports.array(external_exports.string()),
44
+ appliesTo: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
45
+ scope: external_exports.string().nullable(),
46
+ exclusions: external_exports.string().nullable(),
47
+ provenanceSummary: external_exports.string().nullable(),
48
+ methodologySummary: external_exports.string().nullable(),
49
+ maintenanceCadence: external_exports.string().nullable()
50
+ }).passthrough();
37
51
  var previewSchema = external_exports.object({
38
52
  id: external_exports.string().optional(),
39
53
  title: external_exports.string().optional(),
40
54
  price: external_exports.string().optional(),
41
- creator: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
55
+ creator: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
56
+ // `.catch` keeps a botched card from taking the rest of the preview with it:
57
+ // every other preview field is optional, so before the card existed a parse
58
+ // failure here was near-impossible, and a server that half-fills the card
59
+ // should still not cost the caller the title and the price it came for.
60
+ // The drop is NOT silent: see `cardError` on the result below.
61
+ card: previewCardSchema.optional().catch(void 0),
62
+ // Set by the SERVER when the piece has a card it could not load, so an absent
63
+ // card is never ambiguous: no flag means uncarded, this flag means temporarily
64
+ // unreadable. Never false and never sent beside `card` (tenjin#500), and the
65
+ // same fail-soft as above so a bogus `false` drops the flag rather than the
66
+ // whole preview.
67
+ cardUnavailable: external_exports.literal(true).optional().catch(void 0)
42
68
  }).passthrough();
43
69
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
44
70
  var paymentRequiredSchema = external_exports.object({
@@ -58,7 +84,7 @@ async function fetchRead(url, opts) {
58
84
  accept: "application/json",
59
85
  "x-tenjin-client": CLIENT_HEADER
60
86
  };
61
- if (opts.lookupId !== void 0) headers["x-tenjin-lookup-id"] = opts.lookupId;
87
+ if (opts.searchId !== void 0) headers["x-tenjin-search-id"] = opts.searchId;
62
88
  if (opts.siwxHeader !== void 0) headers[SIWX_HEADER] = opts.siwxHeader;
63
89
  if (opts.paymentHeaders !== void 0) Object.assign(headers, opts.paymentHeaders);
64
90
  const res = await httpRequest(url, {
@@ -114,17 +140,19 @@ async function fetchRead(url, opts) {
114
140
  "CONTRACT_MISMATCH",
115
141
  "The 402 challenge is not a valid x402 v2 payment declaration.",
116
142
  {
117
- fix: "Update tenjin-cli, or check --base-url points at a Tenjin deployment.",
143
+ fix: "Update tenjin-cli, or check the configured base URL (`tenjin config get baseUrl`) points at a Tenjin deployment.",
118
144
  details: validated.error.issues
119
145
  }
120
146
  );
121
147
  }
122
148
  const paymentRequired = decoded;
123
- const preview = previewSchema.safeParse(res.json);
149
+ const parsed = previewSchema.safeParse(res.json);
150
+ const preview = parsed.success ? parsed.data : {};
124
151
  return {
125
152
  kind: "payment_required",
126
153
  paymentRequired,
127
- preview: preview.success ? preview.data : {}
154
+ preview,
155
+ ...sentUnparsableCard(res.json, preview) ? { cardError: true } : {}
128
156
  };
129
157
  }
130
158
  if (res.status === 409) {
@@ -145,6 +173,10 @@ async function fetchRead(url, opts) {
145
173
  }
146
174
  );
147
175
  }
176
+ function sentUnparsableCard(json, preview) {
177
+ if (typeof json !== "object" || json === null) return false;
178
+ return "card" in json && preview.card === void 0;
179
+ }
148
180
  function decodeSettlement(header) {
149
181
  if (header === void 0) return void 0;
150
182
  try {
@@ -168,4 +200,4 @@ function readMessage(json) {
168
200
  export {
169
201
  fetchRead
170
202
  };
171
- //# sourceMappingURL=chunk-DXTQ3CSI.js.map
203
+ //# sourceMappingURL=chunk-BIKAUVC2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/read-client.ts"],"sourcesContent":["import { z } from 'zod';\nimport { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';\nimport type { PaymentRequired } from '@x402/core/types';\nimport { CliError } from './errors';\nimport { rateLimitError } from './agent-api';\nimport { httpRequest } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { SIWX_HEADER } from './siwx';\n\n/**\n * The read-route (`GET /api/read/<handle>/<slug>`) client, always JSON/x402, so\n * it is the robust agent target (llms-full). It surfaces the three outcomes the\n * buy flow branches on: `entitled` (200 with the full body, free post, SIWX\n * re-read, or freshly paid), `payment_required` (402 with the decoded\n * PAYMENT-REQUIRED header + the leak-safe preview body), and `already_purchased`\n * (409 owned-re-pay gate, nothing charged). Purchase attribution rides\n * `X-Tenjin-Client` always and `X-Tenjin-Search-Id` when a search preceded the buy.\n */\n\nconst PAYMENT_REQUIRED_HEADER = 'PAYMENT-REQUIRED';\nconst PAYMENT_RESPONSE_HEADER = 'PAYMENT-RESPONSE';\n\n// id/slug become filesystem path segments (the local library), so they are\n// validated as a uuid + the server's slug charset HERE, at the trust boundary, so\n// a hostile id='../../evil' or slug fails as CONTRACT_MISMATCH before delivery.\nimport { SLUG_RE, UUID_RE as RESOURCE_ID_RE } from './ids';\n\n/** The full essay body a 200 returns (loose: require what the CLI reads, keep the rest). */\nconst readBodySchema = z\n .object({\n id: z.string().regex(RESOURCE_ID_RE, 'resource id must be a uuid'),\n slug: z.string().regex(SLUG_RE, 'unsafe slug').max(80),\n title: z.string(),\n bodyMd: z.string(),\n price: z.string(),\n creator: z\n .object({\n handle: z.string().nullish(),\n walletAddress: z.string().nullish(),\n })\n .passthrough(),\n })\n .passthrough();\n\nexport type ReadBody = z.infer<typeof readBodySchema>;\n\n/**\n * The public half of the piece's answer card, carried on the 402 body when the\n * piece has one. The key is ABSENT (never null) on an uncarded piece, so callers\n * branch on presence; the projection emits every field whenever it emits the card\n * at all, so a present card is never partial. Nullable fields carry null.\n *\n * This is the depth half of the search/inspect split: the card left the search\n * candidate in search v2 and lives here, one free unpaid GET away.\n */\nexport const previewCardSchema = z\n .object({\n artifactType: z.string(),\n temporalMode: z.string(),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n questionsAnswered: z.array(z.string()),\n tasksSupported: z.array(z.string()),\n appliesTo: z.record(z.string(), z.array(z.string())),\n scope: z.string().nullable(),\n exclusions: z.string().nullable(),\n provenanceSummary: z.string().nullable(),\n methodologySummary: z.string().nullable(),\n maintenanceCadence: z.string().nullable(),\n })\n .passthrough();\n\nexport type PreviewCard = z.infer<typeof previewCardSchema>;\n\n/** The leak-safe 402 preview body, never the paid content. */\nconst previewSchema = z\n .object({\n id: z.string().optional(),\n title: z.string().optional(),\n price: z.string().optional(),\n creator: z.record(z.string(), z.unknown()).optional(),\n // `.catch` keeps a botched card from taking the rest of the preview with it:\n // every other preview field is optional, so before the card existed a parse\n // failure here was near-impossible, and a server that half-fills the card\n // should still not cost the caller the title and the price it came for.\n // The drop is NOT silent: see `cardError` on the result below.\n card: previewCardSchema.optional().catch(undefined),\n // Set by the SERVER when the piece has a card it could not load, so an absent\n // card is never ambiguous: no flag means uncarded, this flag means temporarily\n // unreadable. Never false and never sent beside `card` (tenjin#500), and the\n // same fail-soft as above so a bogus `false` drops the flag rather than the\n // whole preview.\n cardUnavailable: z.literal(true).optional().catch(undefined),\n })\n .passthrough();\n\nexport type Preview = z.infer<typeof previewSchema>;\n\n// The decoded PAYMENT-REQUIRED is money-path input: validate the fields the pay\n// path consumes (amount as an atomic integer, CAIP-2 network, 0x asset/payTo)\n// at THIS boundary instead of trusting raw base64 JSON. Loose otherwise so new\n// server fields never break an older CLI.\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\nconst paymentRequiredSchema = z\n .object({\n x402Version: z.literal(2),\n accepts: z.array(\n z\n .object({\n scheme: z.string(),\n network: z.string().regex(/^eip155:\\d+$/, 'network must be CAIP-2 eip155'),\n asset: z.string().regex(ADDRESS_RE, 'asset must be a 0x address'),\n amount: z.string().regex(/^\\d{1,39}$/, 'amount must be an atomic integer string'),\n payTo: z.string().regex(ADDRESS_RE, 'payTo must be a 0x address'),\n })\n .passthrough(),\n ),\n })\n .passthrough();\n\nexport type ReadResult =\n | { kind: 'entitled'; body: ReadBody; settlementTxHash?: string }\n | {\n kind: 'payment_required';\n paymentRequired: PaymentRequired;\n preview: Preview;\n /** The 402 carried a `card` this CLI could not parse, so `preview.card` is\n * absent for a reason that is NOT \"the piece is uncarded\". The two must\n * stay distinguishable: an uncarded piece is a real signal a buyer acts\n * on, and this 402 is the only pre-purchase depth there is. */\n cardError?: true;\n }\n | { kind: 'already_purchased'; message: string };\n\nexport interface ReadRequestOptions {\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** A `SIGN-IN-WITH-X` header for the entitled free re-read. */\n siwxHeader?: string;\n /** The `PAYMENT-SIGNATURE` header(s) for a paid request. */\n paymentHeaders?: Record<string, string>;\n /** Attribute a following purchase to the search that surfaced it. */\n searchId?: string;\n}\n\nexport async function fetchRead(url: string, opts: ReadRequestOptions): Promise<ReadResult> {\n const headers: Record<string, string> = {\n accept: 'application/json',\n 'x-tenjin-client': CLIENT_HEADER,\n };\n if (opts.searchId !== undefined) headers['x-tenjin-search-id'] = opts.searchId;\n if (opts.siwxHeader !== undefined) headers[SIWX_HEADER] = opts.siwxHeader;\n if (opts.paymentHeaders !== undefined) Object.assign(headers, opts.paymentHeaders);\n\n const res = await httpRequest(url, {\n method: 'GET',\n timeoutMs: opts.timeoutMs,\n headers,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) {\n const code =\n res.kind === 'network' || res.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n throw new CliError(code, `${url}: ${res.message}`, {\n fix: 'Check the resource URL and your network, then retry.',\n });\n }\n\n if (res.status === 200) {\n const parsed = readBodySchema.safeParse(res.json);\n if (!parsed.success) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n 'The read response did not match the expected contract',\n {\n fix: 'Update tenjin-cli; the read contract may have changed.',\n details: parsed.error.issues,\n },\n );\n }\n const settlement = decodeSettlement(res.header(PAYMENT_RESPONSE_HEADER));\n return {\n kind: 'entitled',\n body: parsed.data,\n ...(settlement !== undefined ? { settlementTxHash: settlement } : {}),\n };\n }\n\n if (res.status === 402) {\n const encoded = res.header(PAYMENT_REQUIRED_HEADER);\n if (encoded === undefined) {\n throw new CliError('CONTRACT_MISMATCH', 'The 402 carried no PAYMENT-REQUIRED header', {\n fix: 'The server may be misconfigured; try another resource or update tenjin-cli.',\n });\n }\n let decoded: PaymentRequired;\n try {\n decoded = decodePaymentRequiredHeader(encoded);\n } catch (err) {\n throw new CliError('CONTRACT_MISMATCH', 'Could not decode the PAYMENT-REQUIRED header', {\n fix: 'Update tenjin-cli; the x402 header format may have changed.',\n cause: err,\n });\n }\n const validated = paymentRequiredSchema.safeParse(decoded);\n if (!validated.success) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n 'The 402 challenge is not a valid x402 v2 payment declaration.',\n {\n fix: 'Update tenjin-cli, or check the configured base URL (`tenjin config get baseUrl`) points at a Tenjin deployment.',\n details: validated.error.issues,\n },\n );\n }\n const paymentRequired = decoded;\n const parsed = previewSchema.safeParse(res.json);\n const preview = parsed.success ? parsed.data : {};\n return {\n kind: 'payment_required',\n paymentRequired,\n preview,\n ...(sentUnparsableCard(res.json, preview) ? { cardError: true as const } : {}),\n };\n }\n\n if (res.status === 409) {\n // The owned-re-pay gate: a payment for a post this wallet already bought is\n // refused, nothing charged. The caller falls back to a SIWX free re-read.\n return { kind: 'already_purchased', message: readMessage(res.json) ?? 'Already purchased.' };\n }\n\n if (res.status === 404) {\n throw new CliError('RESOURCE_NOT_FOUND', `No resource at ${url}`, {\n fix: 'Check the handle/slug or resource id.',\n });\n }\n\n // 429 on the paid-read path is a recoverable pause, not an outage: surface\n // RATE_LIMITED + retryAfterSeconds like postSearch/postOutcomes do, so a looping\n // agent (the caller most likely to hit this) can back off instead of treating it\n // as API_UNREACHABLE.\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n\n throw new CliError(\n 'API_UNREACHABLE',\n readMessage(res.json) ?? `Unexpected status ${res.status} from ${url}`,\n {\n fix: 'Retry; if it persists the resource may be unavailable.',\n details: res.json,\n },\n );\n}\n\n/** The server sent a `card` key but nothing survived the parse. Distinguishes a\n * DROPPED card from an absent one, which the `.catch` above otherwise makes\n * look identical. */\nfunction sentUnparsableCard(json: unknown, preview: Preview): boolean {\n if (typeof json !== 'object' || json === null) return false;\n return 'card' in json && preview.card === undefined;\n}\n\nfunction decodeSettlement(header: string | undefined): string | undefined {\n if (header === undefined) return undefined;\n try {\n const settle = decodePaymentResponseHeader(header);\n const tx = (settle as { transaction?: unknown }).transaction;\n return typeof tx === 'string' ? tx : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction readMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n if (typeof rec.message === 'string') return rec.message;\n if (typeof rec.error === 'string') return rec.error;\n if (typeof rec.code === 'string') return rec.code;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,0BAA0B;AAChC,IAAM,0BAA0B;AAQhC,IAAM,iBAAiB,iBACpB,OAAO;AAAA,EACN,IAAI,iBAAE,OAAO,EAAE,MAAM,SAAgB,4BAA4B;AAAA,EACjE,MAAM,iBAAE,OAAO,EAAE,MAAM,SAAS,aAAa,EAAE,IAAI,EAAE;AAAA,EACrD,OAAO,iBAAE,OAAO;AAAA,EAChB,QAAQ,iBAAE,OAAO;AAAA,EACjB,OAAO,iBAAE,OAAO;AAAA,EAChB,SAAS,iBACN,OAAO;AAAA,IACN,QAAQ,iBAAE,OAAO,EAAE,QAAQ;AAAA,IAC3B,eAAe,iBAAE,OAAO,EAAE,QAAQ;AAAA,EACpC,CAAC,EACA,YAAY;AACjB,CAAC,EACA,YAAY;AAaR,IAAM,oBAAoB,iBAC9B,OAAO;AAAA,EACN,cAAc,iBAAE,OAAO;AAAA,EACvB,cAAc,iBAAE,OAAO;AAAA,EACvB,MAAM,iBAAE,OAAO,EAAE,SAAS;AAAA,EAC1B,YAAY,iBAAE,OAAO,EAAE,SAAS;AAAA,EAChC,mBAAmB,iBAAE,MAAM,iBAAE,OAAO,CAAC;AAAA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