tenjin-cli 0.1.0-alpha.20 → 0.1.0-alpha.22

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 (107) hide show
  1. package/README.md +18 -3
  2. package/dist/{chunk-LI44XLMB.js → chunk-2RMXTNLT.js} +5 -5
  3. package/dist/{chunk-5FYKPQNX.js → chunk-3Q3UBMVB.js} +3 -3
  4. package/dist/{chunk-3BS55ANY.js → chunk-AG4DWNHO.js} +50 -4
  5. package/dist/{chunk-3BS55ANY.js.map → chunk-AG4DWNHO.js.map} +1 -1
  6. package/dist/{chunk-P42QX3QF.js → chunk-B4GA3HAK.js} +2 -2
  7. package/dist/{chunk-P42QX3QF.js.map → chunk-B4GA3HAK.js.map} +1 -1
  8. package/dist/{chunk-NSG5TVZQ.js → chunk-CYEUVU3F.js} +14 -10
  9. package/dist/chunk-CYEUVU3F.js.map +1 -0
  10. package/dist/{chunk-RPR2C2JO.js → chunk-DA53QKTD.js} +5 -5
  11. package/dist/{chunk-YEBNE5NW.js → chunk-DHCOGDJB.js} +5 -5
  12. package/dist/{chunk-BTX2QE2Y.js → chunk-F4IJQBGP.js} +4 -4
  13. package/dist/chunk-GONDQ27X.js +337 -0
  14. package/dist/chunk-GONDQ27X.js.map +1 -0
  15. package/dist/{chunk-TU7XH3JJ.js → chunk-K6AXXYCG.js} +14 -2
  16. package/dist/chunk-K6AXXYCG.js.map +1 -0
  17. package/dist/{chunk-2G2WLVHB.js → chunk-LAIZ2AQA.js} +9 -4
  18. package/dist/chunk-LAIZ2AQA.js.map +1 -0
  19. package/dist/{chunk-YREKMJPP.js → chunk-NYJCBQL5.js} +65 -6
  20. package/dist/chunk-NYJCBQL5.js.map +1 -0
  21. package/dist/{chunk-HH3PDYIG.js → chunk-NZYVSZNF.js} +5 -5
  22. package/dist/{chunk-4M5FBWT5.js → chunk-QF4SSCQV.js} +10 -1
  23. package/dist/chunk-QF4SSCQV.js.map +1 -0
  24. package/dist/{chunk-CCDOV45D.js → chunk-SAN5PFTL.js} +126 -12
  25. package/dist/chunk-SAN5PFTL.js.map +1 -0
  26. package/dist/{chunk-LN2HISWU.js → chunk-TU3IK7KK.js} +2 -2
  27. package/dist/{chunk-4AS52HUG.js → chunk-U5FFVIIF.js} +138 -28
  28. package/dist/chunk-U5FFVIIF.js.map +1 -0
  29. package/dist/{chunk-PO4HAXAW.js → chunk-UAT3Q7VF.js} +112 -26
  30. package/dist/chunk-UAT3Q7VF.js.map +1 -0
  31. package/dist/chunk-UFCN7NCE.js +130 -0
  32. package/dist/chunk-UFCN7NCE.js.map +1 -0
  33. package/dist/{chunk-72UHZRG6.js → chunk-UGLTSPXQ.js} +2 -2
  34. package/dist/{chunk-5KD5HRAJ.js → chunk-UHEMZEGW.js} +3 -2
  35. package/dist/chunk-UHEMZEGW.js.map +1 -0
  36. package/dist/{chunk-2E6GVIRP.js → chunk-UIOZRILX.js} +47 -9
  37. package/dist/chunk-UIOZRILX.js.map +1 -0
  38. package/dist/{chunk-7ACHDNJA.js → chunk-WXFVJPZD.js} +13 -4
  39. package/dist/chunk-WXFVJPZD.js.map +1 -0
  40. package/dist/{chunk-CXUYCDPX.js → chunk-XBYTP4SP.js} +4 -4
  41. package/dist/{cli-XJQYUOHI.js → cli-5WM56Y7K.js} +43 -30
  42. package/dist/{cli-XJQYUOHI.js.map → cli-5WM56Y7K.js.map} +1 -1
  43. package/dist/{config-KMJLFPSI.js → config-JBF5BZNO.js} +10 -8
  44. package/dist/{doctor-KMN55D7U.js → doctor-6KHBE77P.js} +25 -16
  45. package/dist/{doctor-KMN55D7U.js.map → doctor-6KHBE77P.js.map} +1 -1
  46. package/dist/{fund-LT6ZPGEQ.js → fund-GSFCXEF7.js} +10 -11
  47. package/dist/{fund-LT6ZPGEQ.js.map → fund-GSFCXEF7.js.map} +1 -1
  48. package/dist/{hook-command-U5XPEHAJ.js → hook-command-UQZ4DVDL.js} +373 -82
  49. package/dist/hook-command-UQZ4DVDL.js.map +1 -0
  50. package/dist/index.js +4 -4
  51. package/dist/{install-MMNXJ5LM.js → install-TDYC22KI.js} +13 -11
  52. package/dist/{install-identity-B7FVIWML.js → install-identity-QS4UFF27.js} +7 -7
  53. package/dist/{install-wallet-XMVUBCHS.js → install-wallet-T737X74E.js} +9 -10
  54. package/dist/{install-wallet-XMVUBCHS.js.map → install-wallet-T737X74E.js.map} +1 -1
  55. package/dist/{mcp-TUPRIPSI.js → mcp-JWOOSKLX.js} +624 -69
  56. package/dist/mcp-JWOOSKLX.js.map +1 -0
  57. package/dist/{paths-LRMWNTJP.js → paths-MUXHUOCM.js} +8 -2
  58. package/dist/{pay-XAWW3NV3.js → pay-TDYQFSKY.js} +17 -16
  59. package/dist/payments-26NVMFR2.js +47 -0
  60. package/dist/payments-26NVMFR2.js.map +1 -0
  61. package/dist/{send-HESQYRKM.js → send-4RUBQQKP.js} +9 -10
  62. package/dist/{send-HESQYRKM.js.map → send-4RUBQQKP.js.map} +1 -1
  63. package/dist/{status-ANZPRZJJ.js → status-CEHZKHBU.js} +6 -6
  64. package/dist/{status-line-J3TUWVRQ.js → status-line-QRAO3Y2E.js} +7 -7
  65. package/dist/{status-line-wiring-HSV7DXO5.js → status-line-wiring-XKUVI5UW.js} +5 -5
  66. package/dist/tenjin-daemon.mjs +61 -7
  67. package/dist/{uninstall-GUU34YKP.js → uninstall-SJ6R2W2M.js} +11 -11
  68. package/dist/{update-KO2NZRJ5.js → update-N2NZS3AA.js} +6 -6
  69. package/dist/{wallet-3URC5QPK.js → wallet-IB2EFAUP.js} +9 -10
  70. package/docs/agent-permissions.md +11 -9
  71. package/docs/safety-model.md +3 -3
  72. package/package.json +1 -1
  73. package/dist/chunk-2E6GVIRP.js.map +0 -1
  74. package/dist/chunk-2G2WLVHB.js.map +0 -1
  75. package/dist/chunk-3KKKB2AQ.js +0 -40
  76. package/dist/chunk-3KKKB2AQ.js.map +0 -1
  77. package/dist/chunk-4AS52HUG.js.map +0 -1
  78. package/dist/chunk-4M5FBWT5.js.map +0 -1
  79. package/dist/chunk-5KD5HRAJ.js.map +0 -1
  80. package/dist/chunk-7ACHDNJA.js.map +0 -1
  81. package/dist/chunk-CCDOV45D.js.map +0 -1
  82. package/dist/chunk-NSG5TVZQ.js.map +0 -1
  83. package/dist/chunk-PO4HAXAW.js.map +0 -1
  84. package/dist/chunk-TU7XH3JJ.js.map +0 -1
  85. package/dist/chunk-YREKMJPP.js.map +0 -1
  86. package/dist/hook-command-U5XPEHAJ.js.map +0 -1
  87. package/dist/mcp-TUPRIPSI.js.map +0 -1
  88. /package/dist/{chunk-LI44XLMB.js.map → chunk-2RMXTNLT.js.map} +0 -0
  89. /package/dist/{chunk-5FYKPQNX.js.map → chunk-3Q3UBMVB.js.map} +0 -0
  90. /package/dist/{chunk-RPR2C2JO.js.map → chunk-DA53QKTD.js.map} +0 -0
  91. /package/dist/{chunk-YEBNE5NW.js.map → chunk-DHCOGDJB.js.map} +0 -0
  92. /package/dist/{chunk-BTX2QE2Y.js.map → chunk-F4IJQBGP.js.map} +0 -0
  93. /package/dist/{chunk-HH3PDYIG.js.map → chunk-NZYVSZNF.js.map} +0 -0
  94. /package/dist/{chunk-LN2HISWU.js.map → chunk-TU3IK7KK.js.map} +0 -0
  95. /package/dist/{chunk-72UHZRG6.js.map → chunk-UGLTSPXQ.js.map} +0 -0
  96. /package/dist/{chunk-CXUYCDPX.js.map → chunk-XBYTP4SP.js.map} +0 -0
  97. /package/dist/{config-KMJLFPSI.js.map → config-JBF5BZNO.js.map} +0 -0
  98. /package/dist/{install-MMNXJ5LM.js.map → install-TDYC22KI.js.map} +0 -0
  99. /package/dist/{install-identity-B7FVIWML.js.map → install-identity-QS4UFF27.js.map} +0 -0
  100. /package/dist/{paths-LRMWNTJP.js.map → paths-MUXHUOCM.js.map} +0 -0
  101. /package/dist/{pay-XAWW3NV3.js.map → pay-TDYQFSKY.js.map} +0 -0
  102. /package/dist/{status-ANZPRZJJ.js.map → status-CEHZKHBU.js.map} +0 -0
  103. /package/dist/{status-line-J3TUWVRQ.js.map → status-line-QRAO3Y2E.js.map} +0 -0
  104. /package/dist/{status-line-wiring-HSV7DXO5.js.map → status-line-wiring-XKUVI5UW.js.map} +0 -0
  105. /package/dist/{uninstall-GUU34YKP.js.map → uninstall-SJ6R2W2M.js.map} +0 -0
  106. /package/dist/{update-KO2NZRJ5.js.map → update-N2NZS3AA.js.map} +0 -0
  107. /package/dist/{wallet-3URC5QPK.js.map → wallet-IB2EFAUP.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  inspectHooksFile
4
- } from "./chunk-5FYKPQNX.js";
4
+ } from "./chunk-3Q3UBMVB.js";
5
5
  import {
6
6
  CliError,
7
7
  writeFileAtomic
@@ -169,4 +169,4 @@ export {
169
169
  removeStatusLine,
170
170
  inspectStatusLine
171
171
  };
172
- //# sourceMappingURL=chunk-LN2HISWU.js.map
172
+ //# sourceMappingURL=chunk-TU3IK7KK.js.map
@@ -2,10 +2,10 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  fetchFailureToCliError,
4
4
  httpRequest
5
- } from "./chunk-3BS55ANY.js";
5
+ } from "./chunk-AG4DWNHO.js";
6
6
  import {
7
7
  external_exports
8
- } from "./chunk-CCDOV45D.js";
8
+ } from "./chunk-SAN5PFTL.js";
9
9
 
10
10
  // src/router/decision.ts
11
11
  var ROUTER_PATH = "/api/x402-router";
@@ -45,6 +45,69 @@ var CapabilityFields = {
45
45
  * 402 above it; `gateSpend` still caps the amount actually signed. */
46
46
  providerPriceAtomic: external_exports.string().regex(/^\d+$/)
47
47
  };
48
+ function checkHint(decision, ctx) {
49
+ if (/[\p{Cc}\p{Cf}]/u.test(decision.hint)) {
50
+ ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint is one plain line" });
51
+ }
52
+ if (!decision.hint.includes("request({")) {
53
+ ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint names the call to make" });
54
+ }
55
+ if (!decision.hint.includes(decision.id)) {
56
+ ctx.addIssue({
57
+ code: "custom",
58
+ path: ["hint"],
59
+ message: "a hint carries this answer's own id"
60
+ });
61
+ }
62
+ }
63
+ var DiscoveredCandidateSchema = external_exports.strictObject({
64
+ source: external_exports.string().min(1).max(64),
65
+ provider: external_exports.string().min(1).max(120),
66
+ url: external_exports.string().min(1).max(2048),
67
+ method: external_exports.enum(["GET", "POST"]),
68
+ description: external_exports.string().max(500),
69
+ providerPriceAtomic: external_exports.string().regex(/^\d+$/),
70
+ network: external_exports.string().min(1).max(64),
71
+ payTo: external_exports.string().min(1).max(200),
72
+ input: external_exports.strictObject({
73
+ location: external_exports.enum(["body", "query"]),
74
+ schema: external_exports.record(external_exports.string(), external_exports.unknown())
75
+ })
76
+ });
77
+ var ToolSpecSchema = external_exports.strictObject({
78
+ capabilityId: external_exports.string().min(1).max(200),
79
+ provider: external_exports.string().min(1).max(120),
80
+ description: external_exports.string().min(1).max(500),
81
+ priceAtomic: external_exports.string().regex(/^\d+$/),
82
+ priceVaries: external_exports.boolean(),
83
+ maxAmountAtomic: external_exports.string().regex(/^\d+$/),
84
+ payTo: external_exports.string().min(1).max(200),
85
+ network: external_exports.string().min(1).max(64),
86
+ asset: external_exports.string().min(1).max(200),
87
+ request: external_exports.strictObject({
88
+ method: external_exports.enum(["GET", "POST"]),
89
+ url: external_exports.string().min(1).max(2048),
90
+ fields: external_exports.record(external_exports.string(), external_exports.enum(["path", "query", "body"])),
91
+ location: external_exports.enum(["query", "body"])
92
+ }),
93
+ input: external_exports.record(external_exports.string(), external_exports.unknown()),
94
+ pinned: external_exports.record(external_exports.string(), external_exports.unknown()),
95
+ example: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
96
+ returns: external_exports.string().min(1).max(200).optional(),
97
+ returnsExample: external_exports.unknown().optional(),
98
+ resultSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
99
+ });
100
+ var OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });
101
+ var SpecsSchema = external_exports.array(OfferSpecSchema).min(1).max(4).optional();
102
+ var DiscoveredSchema = external_exports.strictObject({
103
+ action: external_exports.literal("discovered"),
104
+ id: IdSchema,
105
+ candidate: DiscoveredCandidateSchema,
106
+ /** THE LINE, FINISHED, as on `execute`: it carries the seller's
107
+ * description and the input it takes. */
108
+ hint: external_exports.string().min(1).max(2e3),
109
+ specs: SpecsSchema
110
+ }).superRefine(checkHint);
48
111
  var HookDecisionSchema = external_exports.discriminatedUnion("action", [
49
112
  external_exports.strictObject({
50
113
  action: external_exports.literal("execute"),
@@ -58,24 +121,13 @@ var HookDecisionSchema = external_exports.discriminatedUnion("action", [
58
121
  * THE LINE, FINISHED. The server writes it with the real id in it and, on a
59
122
  * native call, the exact search or URL that was denied. The client injects
60
123
  * it and composes nothing, which is why there is no hint builder here any
61
- * more: two sides writing the same sentence is how they drift.
124
+ * more: two sides writing the same sentence is how they drift. The same
125
+ * bound as a discovered line's.
62
126
  */
63
- hint: external_exports.string().min(1).max(1e3)
64
- }).superRefine((decision, ctx) => {
65
- if (/[\p{Cc}\p{Cf}]/u.test(decision.hint)) {
66
- ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint is one plain line" });
67
- }
68
- if (!decision.hint.includes("request({")) {
69
- ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint names the call to make" });
70
- }
71
- if (!decision.hint.includes(decision.id)) {
72
- ctx.addIssue({
73
- code: "custom",
74
- path: ["hint"],
75
- message: "a hint carries this answer's own id"
76
- });
77
- }
78
- }),
127
+ hint: external_exports.string().min(1).max(2e3),
128
+ specs: SpecsSchema
129
+ }).superRefine(checkHint),
130
+ DiscoveredSchema,
79
131
  RefusedSchema.extend({ action: external_exports.literal("native") }),
80
132
  RefusedSchema.extend({ action: external_exports.literal("needs_input") })
81
133
  ]);
@@ -85,6 +137,23 @@ var ToolDecisionSchema = external_exports.discriminatedUnion("action", [
85
137
  ...CapabilityFields,
86
138
  contract: ContractSchema
87
139
  }),
140
+ /**
141
+ * A query with no id, answered with the spec of the service the server
142
+ * picked under a fresh `id`: kept like a hook's. `input` is there only when
143
+ * the query, as written, was a valid value for the spec's query field (a
144
+ * free-text field, or one whose format or pattern it satisfies), and the
145
+ * tool then runs it in the same call, checked again like any input.
146
+ * Otherwise the agent fills the skeleton. `hint` is the line, with the skeleton of the call:
147
+ * `request({id, input: {...}})` with the required fields, or the bound one.
148
+ */
149
+ external_exports.strictObject({
150
+ action: external_exports.literal("spec"),
151
+ id: IdSchema,
152
+ spec: ToolSpecSchema,
153
+ hint: external_exports.string().min(1).max(2e3),
154
+ input: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
155
+ }).superRefine(checkHint),
156
+ DiscoveredSchema,
88
157
  RefusedSchema.extend({ action: external_exports.literal("native") }),
89
158
  RefusedSchema.extend({ action: external_exports.literal("needs_input") })
90
159
  ]);
@@ -101,15 +170,27 @@ function envelope(decision) {
101
170
  }
102
171
  var HookResponseSchema = envelope(HookDecisionSchema);
103
172
  var ToolResponseSchema = envelope(ToolDecisionSchema);
104
- function buildHookBody(packet) {
105
- return { schemaVersion: 1, packet };
173
+ var CLIENT_ACCEPTS = ["discovered", "spec"];
174
+ var BAZAAR_ACCEPT = "bazaar";
175
+ function acceptsFor(bazaar) {
176
+ return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];
177
+ }
178
+ function buildHookBody(packet, extras = {}) {
179
+ return {
180
+ schemaVersion: 1,
181
+ ...extras.sessionId !== void 0 ? { sessionId: extras.sessionId } : {},
182
+ ...extras.accepts !== void 0 ? { accepts: [...extras.accepts] } : {},
183
+ packet
184
+ };
106
185
  }
107
186
  function buildToolBody(request) {
108
187
  return {
109
188
  schemaVersion: 1,
110
- query: request.query,
189
+ ...request.query !== void 0 ? { query: request.query } : {},
111
190
  ...request.id !== void 0 ? { id: request.id } : {},
112
- ...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {}
191
+ ...request.input !== void 0 ? { input: request.input } : {},
192
+ ...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {},
193
+ ...request.accepts !== void 0 ? { accepts: [...request.accepts] } : {}
113
194
  };
114
195
  }
115
196
  async function requestDecision(kind, request, deps) {
@@ -118,10 +199,15 @@ async function requestDecision(kind, request, deps) {
118
199
  method: "POST",
119
200
  timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,
120
201
  blockRedirects: true,
121
- jsonBody: kind === "hook" ? buildHookBody(request.packet) : buildToolBody({
122
- query: request.query,
202
+ jsonBody: kind === "hook" ? buildHookBody(request.packet, {
203
+ ...request.sessionId !== void 0 ? { sessionId: request.sessionId } : {},
204
+ accepts: acceptsFor(deps.acceptsBazaar === true)
205
+ }) : buildToolBody({
206
+ ...request.query !== void 0 ? { query: request.query } : {},
123
207
  ...request.id !== void 0 ? { id: request.id } : {},
124
- ...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {}
208
+ ...request.input !== void 0 ? { input: request.input } : {},
209
+ ...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {},
210
+ accepts: acceptsFor(deps.acceptsBazaar === true)
125
211
  }),
126
212
  ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
127
213
  };
@@ -130,6 +216,28 @@ async function requestDecision(kind, request, deps) {
130
216
  kind === "hook" ? HookResponseSchema : ToolResponseSchema
131
217
  );
132
218
  }
219
+ var OUTCOME_TIMEOUT_MS = 3e3;
220
+ async function reportSpecOutcome(outcome, deps) {
221
+ try {
222
+ await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {
223
+ method: "POST",
224
+ timeoutMs: OUTCOME_TIMEOUT_MS,
225
+ blockRedirects: true,
226
+ jsonBody: buildOutcomeBody(outcome),
227
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
228
+ });
229
+ } catch {
230
+ }
231
+ }
232
+ function buildOutcomeBody(outcome) {
233
+ return {
234
+ schemaVersion: 1,
235
+ id: outcome.id,
236
+ status: outcome.status,
237
+ ...outcome.httpStatus !== void 0 ? { httpStatus: outcome.httpStatus } : {},
238
+ ...outcome.ms !== void 0 ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}
239
+ };
240
+ }
133
241
  function readDecision(response, schema) {
134
242
  if (!response.ok) return { status: "failed", reason: fetchFailureToCliError(response).message };
135
243
  if (response.status < 200 || response.status >= 300) {
@@ -160,6 +268,8 @@ function errorOf(body) {
160
268
 
161
269
  export {
162
270
  ROUTER_PATH,
163
- requestDecision
271
+ OfferSpecSchema,
272
+ requestDecision,
273
+ reportSpecOutcome
164
274
  };
165
- //# sourceMappingURL=chunk-4AS52HUG.js.map
275
+ //# sourceMappingURL=chunk-U5FFVIIF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE FREE DECISION PER LOOKUP.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * NOTHING IS STORED LOCALLY. The bounded packet travels with the request and\n * the backend keeps it against the decision id until that id expires, which is\n * how `request({query})` reaches the same calibrated input with no session\n * file, no timestamp latch and no guess about which window this process serves.\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When no capability in the catalog fits\n * but a listed x402 service could do the step, the server names that one\n * service: who sells it, where, for how much, and the input it takes. The\n * candidate is the seller's own listing, so every field is data for the host\n * to judge, never an instruction; the host builds the `input` and the tool\n * call pays through the same `runPay` path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.strictObject({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.strictObject({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.strictObject({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer and any alternative. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(4).optional();\n\n/** The same answer on both calls: the hook's offer, and the tool's fallback\n * when a query with no id found no curated capability. */\nconst DiscoveredSchema = z\n .strictObject({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n })\n .superRefine(checkHint);\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's. `input` is there only when\n * the query, as written, was a valid value for the spec's query field (a\n * free-text field, or one whose format or pattern it satisfies), and the\n * tool then runs it in the same call, checked again like any input.\n * Otherwise the agent fills the skeleton. `hint` is the line, with the skeleton of the call:\n * `request({id, input: {...}})` with the required fields, or the bound one.\n */\n z\n .strictObject({\n action: z.literal('spec'),\n id: IdSchema,\n spec: ToolSpecSchema,\n hint: z.string().min(1).max(2_000),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool';\n\n/**\n * What this client can act on beyond the curated answers, sent on both calls.\n * `discovered` is Tenjin's reviewed list of third-party services, on for every\n * build that parses it; the server answers that arm only to a request that\n * lists it, so an older build never sees one. `spec` asks for each offered\n * service's request spec beside its line, and for the picked service's spec in\n * place of a decision on a query with no id, which only a build that parses\n * them can take: the decision schemas are strict. `bazaar` widens discovery\n * to the open Bazaar and is sent only while `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = ['discovered', 'spec'];\nexport const BAZAAR_ACCEPT = 'bazaar';\n\n/** The `accepts` this build sends, with the open Bazaar or without it. */\nexport function acceptsFor(bazaar: boolean): string[] {\n return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: { sessionId?: string; accepts?: readonly string[] } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n packet,\n };\n}\n\n/** The exact body the tool call sends. `id` is the turn whose packet decides\n * with this query; `gateHint` is evidence, never authority. `input` is the\n * host's own input for a discovered service, and stands in for `query`. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n input?: Record<string, unknown>;\n gateHint?: GateHint;\n accepts?: readonly string[];\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.input !== undefined ? { input: request.input } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n return { success: schema.safeParse(value).success };\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n}\n\nexport type DecisionOutcome<T> =\n | { status: 'decided'; decision: T }\n /** Nothing was paid and nothing could be: the endpoint is free, so a failure\n * here costs the turn a routing answer and nothing else. */\n | { status: 'failed'; reason: string; errorCode?: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id. The tool sends\n * `{ query, id? }`: the backend makes THE decision from that query plus the\n * packet it stored, and answers with the contract to run. A discovered\n * service's id is sent with the host's own `{ input }` instead of a query.\n *\n * The tool never sends a packet of its own. The turn's context lives on the\n * backend against the id, and the query the model wrote is what the routing\n * corpus is calibrated against: 55 of 56 for query plus packet, 53 of 56 for\n * the raw prompt, measured on jev-1.13.0.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query?: string; id?: string; input?: Record<string, unknown>; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n input?: Record<string, unknown>;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.input !== undefined ? { input: request.input } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n return readDecision(\n await httpRequest(url, options),\n kind === 'hook' ? HookResponseSchema : ToolResponseSchema,\n );\n}\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval';\n httpStatus?: number;\n ms?: number;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken.\n * Never throws and never waits on anything the caller needs: a lost report\n * costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/** The exact body of an outcome report, pinned to the shared fixtures. */\nexport function buildOutcomeBody(outcome: SpecOutcome): Record<string, unknown> {\n return {\n schemaVersion: 1,\n id: outcome.id,\n status: outcome.status,\n ...(outcome.httpStatus !== undefined ? { httpStatus: outcome.httpStatus } : {}),\n ...(outcome.ms !== undefined ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}),\n };\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) return { status: 'failed', reason: fetchFailureToCliError(response).message };\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n"],"mappings":";;;;;;;;;;AAuBO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAAM,IAAI,EACd,SAAS;AACd,CAAC;AAED,IAAM,iBAAiB,iBAAE,OAAO;AAAA;AAAA;AAAA,EAG9B,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACtD,cAAc,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACzD,SAAS;AACX,CAAC;AAQD,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACjC,YAAY,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAAA,EACpC,OAAO,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAAA,E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,OAAO,UAAU,SAAU,QAAO;AACxD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAS,GAAI,QAAO;AAC9E,QAAM,OAAO,OAAO,YAAY,WAAW,QAAQ,MAAM,GAAG,GAAG,IAAI;AACnE,SAAO,EAAE,MAAM,SAAS,KAAK;AAC/B;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  assertPublicDestination
4
- } from "./chunk-2G2WLVHB.js";
4
+ } from "./chunk-LAIZ2AQA.js";
5
5
  import {
6
6
  HTTPFacilitatorClient,
7
7
  PaymentRequirementsV2Schema,
@@ -30,39 +30,37 @@ import {
30
30
  } from "./chunk-LHHMV4GU.js";
31
31
  import {
32
32
  USDC_ADDRESS
33
- } from "./chunk-BTX2QE2Y.js";
34
- import {
35
- readUsdcBalance
36
- } from "./chunk-3KKKB2AQ.js";
33
+ } from "./chunk-F4IJQBGP.js";
37
34
  import {
38
35
  describeWallet,
39
36
  resolveSpendAuthorizer,
40
37
  resolveWalletProvider
41
- } from "./chunk-YEBNE5NW.js";
38
+ } from "./chunk-DHCOGDJB.js";
42
39
  import {
43
40
  getAddress
44
41
  } from "./chunk-EGELTSPU.js";
45
42
  import {
46
43
  sanitizeForTerminal
47
- } from "./chunk-72UHZRG6.js";
44
+ } from "./chunk-UGLTSPXQ.js";
48
45
  import {
49
46
  mask
50
47
  } from "./chunk-7QKHZQKW.js";
51
48
  import {
52
49
  fetchFailureToCliError,
53
50
  httpRequest
54
- } from "./chunk-3BS55ANY.js";
51
+ } from "./chunk-AG4DWNHO.js";
55
52
  import {
56
53
  resolveContextSettings
57
- } from "./chunk-5KD5HRAJ.js";
54
+ } from "./chunk-UHEMZEGW.js";
58
55
  import {
59
56
  parseUsdToAtomic,
60
57
  toMoney
61
58
  } from "./chunk-O2JYBOUO.js";
62
59
  import {
63
60
  external_exports,
64
- isSameDeployment
65
- } from "./chunk-CCDOV45D.js";
61
+ isSameDeployment,
62
+ readUsdcBalanceWithFallback
63
+ } from "./chunk-SAN5PFTL.js";
66
64
  import {
67
65
  CliError
68
66
  } from "./chunk-JLEF5WHM.js";
@@ -8617,18 +8615,18 @@ function walk(value, schemaMode, depth = 0) {
8617
8615
  if (schemaMode && key === "$ref" && typeof entry === "string" && !entry.startsWith("#/")) {
8618
8616
  throw new Error("Remote or recursive schema references are unsupported.");
8619
8617
  }
8620
- if (schemaMode && (key === "pattern" || key === "patternProperties")) {
8618
+ if (schemaMode && (key === "pattern" && typeof entry === "string" || key === "patternProperties")) {
8621
8619
  throw new Error("Regular-expression schema constraints are unsupported.");
8622
8620
  }
8623
8621
  walk(entry, schemaMode, depth + 1);
8624
8622
  }
8625
8623
  }
8626
8624
  var validators = /* @__PURE__ */ new Map();
8627
- function compile(schema) {
8625
+ function compile(schema, { allErrors = false, ignoreUnknown = false } = {}) {
8628
8626
  if (Buffer.byteLength(stable(schema)) > MAX_SCHEMA_BYTES) {
8629
8627
  throw new Error("Schema exceeds its size limit.");
8630
8628
  }
8631
- const key = canonicalHash(schema);
8629
+ const key = `${canonicalHash(schema)}${allErrors ? ":all" : ""}${ignoreUnknown ? ":lenient" : ""}`;
8632
8630
  const cached = validators.get(key);
8633
8631
  if (cached !== void 0) return cached;
8634
8632
  walk(schema, true);
@@ -8637,7 +8635,8 @@ function compile(schema) {
8637
8635
  strictTypes: false,
8638
8636
  strictTuples: false,
8639
8637
  strictRequired: false,
8640
- allErrors: false,
8638
+ ...ignoreUnknown ? { strictSchema: false, logger: false } : {},
8639
+ allErrors,
8641
8640
  validateFormats: true,
8642
8641
  coerceTypes: false,
8643
8642
  useDefaults: false,
@@ -8676,6 +8675,58 @@ function validateAgainstSchema(schema, value) {
8676
8675
  return { valid: false, errors: [err instanceof Error ? err.message : String(err)] };
8677
8676
  }
8678
8677
  }
8678
+ function withoutPatterns(value) {
8679
+ if (Array.isArray(value)) return value.map(withoutPatterns);
8680
+ if (value === null || typeof value !== "object") return value;
8681
+ return Object.fromEntries(
8682
+ Object.entries(value).filter(
8683
+ ([key, entry]) => !(key === "pattern" && typeof entry === "string") && key !== "patternProperties"
8684
+ ).map(([key, entry]) => [key, withoutPatterns(entry)])
8685
+ );
8686
+ }
8687
+ function describeProblem(error) {
8688
+ const at = error.instancePath.replace(/^\//, "").replaceAll("/", ".");
8689
+ const field = (name) => at ? `${at}.${name}` : name;
8690
+ const subject = at || "the input";
8691
+ const { params } = error;
8692
+ switch (error.keyword) {
8693
+ case "required":
8694
+ return `${field(String(params.missingProperty))} is required`;
8695
+ case "additionalProperties":
8696
+ return `${subject} has no field ${JSON.stringify(params.additionalProperty)}`;
8697
+ case "enum":
8698
+ return `${subject} must be one of ${params.allowedValues.map((v) => JSON.stringify(v)).join(", ")}`;
8699
+ case "const":
8700
+ return `${subject} must be ${JSON.stringify(params.allowedValue)}`;
8701
+ case "type":
8702
+ return `${subject} must be ${String(params.type)}`;
8703
+ default:
8704
+ return `${subject} ${error.message ?? "is invalid"}`;
8705
+ }
8706
+ }
8707
+ function inputProblems(schema, value) {
8708
+ if (schema === null || typeof schema !== "object" || Array.isArray(schema)) return void 0;
8709
+ let validate;
8710
+ try {
8711
+ validate = compile(withoutPatterns(schema), {
8712
+ allErrors: true,
8713
+ ignoreUnknown: true
8714
+ });
8715
+ } catch {
8716
+ return void 0;
8717
+ }
8718
+ try {
8719
+ const json = JSON.stringify(value);
8720
+ if (json === void 0 || Buffer.byteLength(json) > MAX_VALUE_BYTES) {
8721
+ return ["the input is not JSON, or exceeds its size limit"];
8722
+ }
8723
+ walk(value, false);
8724
+ } catch (err) {
8725
+ return [err instanceof Error ? err.message : String(err)];
8726
+ }
8727
+ if (validate(value)) return [];
8728
+ return [...new Set((validate.errors ?? []).map(describeProblem))];
8729
+ }
8679
8730
  function assertResultSchema(schema) {
8680
8731
  if (schema === null || typeof schema !== "object" || Array.isArray(schema)) {
8681
8732
  throw new Error("A result success schema must be a JSON Schema object.");
@@ -9852,6 +9903,17 @@ var BuilderCodeClientExtension = class {
9852
9903
  };
9853
9904
 
9854
9905
  // src/lib/x402-pay.ts
9906
+ function authorizationOf(payload) {
9907
+ const inner = payload?.payload;
9908
+ const auth = inner?.authorization;
9909
+ if (auth === null || typeof auth !== "object") return void 0;
9910
+ const { from, nonce, validBefore } = auth;
9911
+ if (typeof from !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(from)) return void 0;
9912
+ if (typeof nonce !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(nonce)) return void 0;
9913
+ const before = typeof validBefore === "number" ? String(validBefore) : validBefore;
9914
+ if (typeof before !== "string" || !/^\d+$/.test(before)) return void 0;
9915
+ return { from, nonce, validBefore: before };
9916
+ }
9855
9917
  var ALLOWED_USDC_BY_NETWORK = {
9856
9918
  "eip155:8453": USDC_ADDRESS,
9857
9919
  "eip155:84532": "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
@@ -9941,21 +10003,28 @@ async function buildExactPayment(paymentRequired, signer, only) {
9941
10003
  extensions: withoutSellerServiceCodes(paymentRequired.extensions, builderCodeKey)
9942
10004
  };
9943
10005
  let headers;
10006
+ let authorization;
9944
10007
  try {
9945
10008
  const payload = await http2.createPaymentPayload(bound);
9946
10009
  headers = http2.encodePaymentSignatureHeader(payload);
10010
+ authorization = authorizationOf(payload);
9947
10011
  } catch (err) {
9948
10012
  throw new CliError("PAYMENT_FAILED", "Could not build the x402 payment authorization.", {
9949
10013
  fix: "Confirm the wallet is a supported EVM account on the advertised network.",
9950
10014
  cause: err
9951
10015
  });
9952
10016
  }
9953
- return { headers, amountAtomic: BigInt(requirement.amount) };
10017
+ return {
10018
+ headers,
10019
+ amountAtomic: BigInt(requirement.amount),
10020
+ ...authorization !== void 0 ? { authorization } : {}
10021
+ };
9954
10022
  }
9955
10023
 
9956
10024
  // src/commands/pay.ts
9957
10025
  var PAYMENT_REQUIRED_HEADER = "PAYMENT-REQUIRED";
9958
10026
  var PAYMENT_RESPONSE_HEADER = "PAYMENT-RESPONSE";
10027
+ var PAYMENT_RESPONSE_HEADER_V1 = "X-PAYMENT-RESPONSE";
9959
10028
  var BODY_PREVIEW_CHARS = 1200;
9960
10029
  async function runPay(args, ctx, deps = {}) {
9961
10030
  const warnings = [];
@@ -10009,6 +10078,9 @@ async function executePay(args, ctx, deps, warnings) {
10009
10078
  ...jsonBody !== void 0 ? { jsonBody } : {},
10010
10079
  ...jsonBody === void 0 && args.rawBody !== void 0 ? { rawBody: args.rawBody } : {},
10011
10080
  ...Object.keys(headers).length > 0 ? { headers } : {},
10081
+ // A router lookup can buy a file (a sound, an image): its bytes are kept
10082
+ // whole for the tool to save, never decoded as text.
10083
+ ...router ? { binaryBody: true } : {},
10012
10084
  method
10013
10085
  };
10014
10086
  const probe = await httpRequest(url, fetchOpts);
@@ -10161,7 +10233,7 @@ async function executePay(args, ctx, deps, warnings) {
10161
10233
  try {
10162
10234
  if (amountAtomic > 0n) {
10163
10235
  const deadline = Date.now() + ctx.flags.timeout;
10164
- const readBalance = deps.readBalance ?? readUsdcBalance;
10236
+ const readBalance = deps.readBalance ?? readUsdcBalanceWithFallback;
10165
10237
  let balance = await readBalance(signer.address, settings.rpcUrl, {
10166
10238
  timeoutMs: Math.max(1, Math.floor(ctx.flags.timeout / 2))
10167
10239
  });
@@ -10203,11 +10275,18 @@ async function executePay(args, ctx, deps, warnings) {
10203
10275
  timeoutMs: paidLegTimeoutMs(effectiveRequirement, ctx.flags.timeout),
10204
10276
  headers: { ...headers, ...payment.headers }
10205
10277
  });
10206
- await authorizer.commit(reservationId, payment.amountAtomic, { mode });
10278
+ await authorizer.commit(reservationId, payment.amountAtomic, {
10279
+ mode,
10280
+ ...payment.authorization !== void 0 ? { nonce: payment.authorization.nonce } : {}
10281
+ });
10207
10282
  if (!paid.ok) {
10208
10283
  throw fetchFailureToCliError(paid, {
10209
10284
  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)}`,
10210
- details: { amountAtomic: payment.amountAtomic.toString(), settlement: "unknown" }
10285
+ details: {
10286
+ amountAtomic: payment.amountAtomic.toString(),
10287
+ settlement: "unknown",
10288
+ ...payment.authorization !== void 0 ? { authorization: payment.authorization } : {}
10289
+ }
10211
10290
  });
10212
10291
  }
10213
10292
  if (paid.status >= 200 && paid.status < 300) {
@@ -10222,6 +10301,7 @@ async function executePay(args, ctx, deps, warnings) {
10222
10301
  warnings,
10223
10302
  amountAtomic: payment.amountAtomic,
10224
10303
  requirement: effectiveRequirement,
10304
+ ...payment.authorization !== void 0 ? { authorization: payment.authorization } : {},
10225
10305
  ...registry !== void 0 ? { registry } : {},
10226
10306
  ...caveat !== void 0 ? { caveat } : {},
10227
10307
  printBody: args.printBody === true
@@ -10239,7 +10319,8 @@ async function executePay(args, ctx, deps, warnings) {
10239
10319
  body: paid.json,
10240
10320
  ...providerError(paid.text),
10241
10321
  amountAtomic: payment.amountAtomic.toString(),
10242
- settlement: "unknown"
10322
+ settlement: "unknown",
10323
+ ...payment.authorization !== void 0 ? { authorization: payment.authorization } : {}
10243
10324
  }
10244
10325
  }
10245
10326
  );
@@ -10470,6 +10551,7 @@ function deliver(url, lane, res, opts) {
10470
10551
  payTo: opts.requirement.payTo,
10471
10552
  network: opts.requirement.network,
10472
10553
  asset: opts.requirement.asset,
10554
+ ...opts.authorization !== void 0 ? { authorization: opts.authorization } : {},
10473
10555
  ...opts.registry !== void 0 ? { registry: opts.registry } : {}
10474
10556
  } : opts.entitled === true ? { entitled: true } : {},
10475
10557
  ...settlementTxHash !== void 0 ? { settlementTxHash } : {},
@@ -10478,9 +10560,11 @@ function deliver(url, lane, res, opts) {
10478
10560
  // a caller branching on a delivery must not have to match on prose, which
10479
10561
  // is how an unchecked body passed for a checked one one layer up.
10480
10562
  ...opts.caveat !== void 0 ? { resultUnverified: true, resultCaveat: opts.caveat } : {},
10481
- // The body is the product: JSON when the endpoint spoke it, raw text always.
10563
+ // The body is the product: JSON when the endpoint spoke it, raw text always,
10564
+ // and the bytes themselves when it was a file.
10482
10565
  ...res.json !== void 0 ? { body: res.json } : {},
10483
- bodyText: res.text
10566
+ bodyText: res.text,
10567
+ ...res.bytes !== void 0 ? { bodyBytes: res.bytes, contentType: res.header("content-type") ?? "" } : {}
10484
10568
  };
10485
10569
  const headline = opts.paid ? `paid ${toMoney(opts.amountAtomic.toString()).usd} USD to ${sanitizeForTerminal(new URL(url).host)}` + (settlementTxHash !== void 0 ? ` (tx ${settlementTxHash})` : "") : opts.entitled === true ? `free (entitled, no charge)` : `free (${res.status}, no charge)`;
10486
10570
  const body = sanitizeForTerminal(res.text);
@@ -10499,12 +10583,12 @@ function deliver(url, lane, res, opts) {
10499
10583
  };
10500
10584
  }
10501
10585
  function settlementTx(res) {
10502
- const header = res.header(PAYMENT_RESPONSE_HEADER);
10586
+ const header = res.header(PAYMENT_RESPONSE_HEADER) ?? res.header(PAYMENT_RESPONSE_HEADER_V1);
10503
10587
  if (header === void 0) return void 0;
10504
10588
  try {
10505
10589
  const settle = decodePaymentResponseHeader(header);
10506
10590
  const tx = settle.transaction;
10507
- return typeof tx === "string" ? tx : void 0;
10591
+ return typeof tx === "string" && /^0x[0-9a-fA-F]{64}$/.test(tx) ? tx : void 0;
10508
10592
  } catch {
10509
10593
  return void 0;
10510
10594
  }
@@ -10520,9 +10604,11 @@ export {
10520
10604
  require_ajv,
10521
10605
  require_dist,
10522
10606
  canonicalHash,
10607
+ inputProblems,
10523
10608
  assertResultSchema,
10524
10609
  runPay,
10525
10610
  MAX_PAID_LEG_TIMEOUT_MS,
10526
- paidLegTimeoutMs
10611
+ paidLegTimeoutMs,
10612
+ settlementTx
10527
10613
  };
10528
- //# sourceMappingURL=chunk-PO4HAXAW.js.map
10614
+ //# sourceMappingURL=chunk-UAT3Q7VF.js.map