agentcash 0.6.4 → 0.6.6

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 (47) hide show
  1. package/dist/cjs/run-server.cjs +689 -648
  2. package/dist/esm/{check-endpoint-Df0YnKdr.d.ts → check-endpoint-UD2Ycr-4.d.ts} +1 -0
  3. package/dist/esm/chunk-33JE5MUU.js +7 -0
  4. package/dist/esm/{chunk-RN73GKUU.js → chunk-6OZUZZIH.js} +5 -5
  5. package/dist/esm/chunk-6OZUZZIH.js.map +1 -0
  6. package/dist/esm/{chunk-KFYFGEC4.js → chunk-NQ5BLLN7.js} +17 -6
  7. package/dist/esm/chunk-NQ5BLLN7.js.map +1 -0
  8. package/dist/esm/{chunk-3STID4ZW.js → chunk-P666EAQ2.js} +7 -6
  9. package/dist/esm/chunk-P666EAQ2.js.map +1 -0
  10. package/dist/esm/{chunk-LOEINYA7.js → chunk-RFFZRGKI.js} +3 -4
  11. package/dist/esm/chunk-RFFZRGKI.js.map +1 -0
  12. package/dist/esm/{chunk-KPHAAIVC.js → chunk-SDQV56RE.js} +10 -2
  13. package/dist/esm/chunk-SDQV56RE.js.map +1 -0
  14. package/dist/esm/{chunk-NFGTXPUD.js → chunk-TIP56JAT.js} +42 -6
  15. package/dist/esm/chunk-TIP56JAT.js.map +1 -0
  16. package/dist/esm/{chunk-UFSCGP67.js → chunk-YUCA2PQT.js} +23 -19
  17. package/dist/esm/chunk-YUCA2PQT.js.map +1 -0
  18. package/dist/esm/{chunk-YXENPVZ4.js → chunk-Z453AIOR.js} +2 -2
  19. package/dist/esm/{commands-D3PD4CNW.js → commands-JV2Z4T2M.js} +350 -12
  20. package/dist/esm/commands-JV2Z4T2M.js.map +1 -0
  21. package/dist/esm/{fund-BVBH76XD.js → fund-RGWDV2M5.js} +4 -4
  22. package/dist/esm/index.js +26 -14
  23. package/dist/esm/index.js.map +1 -1
  24. package/dist/esm/{install-KD7XNKVI.js → install-IZ2IITSQ.js} +7 -7
  25. package/dist/esm/install-IZ2IITSQ.js.map +1 -0
  26. package/dist/esm/lib.d.ts +1 -1
  27. package/dist/esm/lib.js +5 -12
  28. package/dist/esm/lib.js.map +1 -1
  29. package/dist/esm/{server-NX7XT2F6.js → server-SMGMX4NA.js} +17 -29
  30. package/dist/esm/server-SMGMX4NA.js.map +1 -0
  31. package/dist/esm/shared/operations/index.d.ts +1 -1
  32. package/dist/esm/shared/operations/index.js +5 -5
  33. package/package.json +1 -1
  34. package/dist/esm/chunk-3STID4ZW.js.map +0 -1
  35. package/dist/esm/chunk-KFYFGEC4.js.map +0 -1
  36. package/dist/esm/chunk-KPHAAIVC.js.map +0 -1
  37. package/dist/esm/chunk-L3LTEB5B.js +0 -7
  38. package/dist/esm/chunk-LOEINYA7.js.map +0 -1
  39. package/dist/esm/chunk-NFGTXPUD.js.map +0 -1
  40. package/dist/esm/chunk-RN73GKUU.js.map +0 -1
  41. package/dist/esm/chunk-UFSCGP67.js.map +0 -1
  42. package/dist/esm/commands-D3PD4CNW.js.map +0 -1
  43. package/dist/esm/install-KD7XNKVI.js.map +0 -1
  44. package/dist/esm/server-NX7XT2F6.js.map +0 -1
  45. /package/dist/esm/{chunk-L3LTEB5B.js.map → chunk-33JE5MUU.js.map} +0 -0
  46. /package/dist/esm/{chunk-YXENPVZ4.js.map → chunk-Z453AIOR.js.map} +0 -0
  47. /package/dist/esm/{fund-BVBH76XD.js.map → fund-RGWDV2M5.js.map} +0 -0
@@ -34,10 +34,10 @@ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__
34
34
  ));
35
35
  var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
36
36
 
37
- // ../../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js
37
+ // ../../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3_yaml@2.8.2/node_modules/tsup/assets/cjs_shims.js
38
38
  var getImportMetaUrl, importMetaUrl;
39
39
  var init_cjs_shims = __esm({
40
- "../../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js"() {
40
+ "../../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3_yaml@2.8.2/node_modules/tsup/assets/cjs_shims.js"() {
41
41
  "use strict";
42
42
  getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
43
43
  importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
@@ -104303,7 +104303,7 @@ var import_path2 = require("path");
104303
104303
  var import_url = require("url");
104304
104304
  function getVersion2() {
104305
104305
  if (true) {
104306
- return "0.6.4";
104306
+ return "0.6.6";
104307
104307
  }
104308
104308
  const __dirname3 = (0, import_path2.dirname)((0, import_url.fileURLToPath)(importMetaUrl));
104309
104309
  const pkg = JSON.parse(
@@ -104466,7 +104466,7 @@ var TEMPO_TOKEN_ADDRESS = "0x20c0000000000000000000000000000000000000";
104466
104466
 
104467
104467
  // src/shared/mpp-enabled.ts
104468
104468
  init_cjs_shims();
104469
- var isMppEnabled = () => "0.6.4".includes("-mpp");
104469
+ var isMppEnabled = () => "0.6.6".includes("-mpp");
104470
104470
 
104471
104471
  // src/shared/operations/fetch-with-payment.ts
104472
104472
  init_cjs_shims();
@@ -108877,505 +108877,6 @@ var tokenStringToNumber = (amount2, decimals2 = 6) => {
108877
108877
 
108878
108878
  // src/shared/balance.ts
108879
108879
  init_cjs_shims();
108880
- var X402SCAN_BASE = "https://x402scan.com";
108881
- var getBalance3 = async ({ address, surface: surface2 }) => {
108882
- const url3 = `${X402SCAN_BASE}/api/rpc/balance/${address}`;
108883
- const res = await safeFetchJson(
108884
- surface2,
108885
- new Request(url3, {
108886
- method: "GET",
108887
- headers: {
108888
- accept: "application/json"
108889
- }
108890
- }),
108891
- zod_default.object({
108892
- chain: zod_default.number(),
108893
- balance: zod_default.coerce.number()
108894
- })
108895
- );
108896
- return res;
108897
- };
108898
-
108899
- // src/shared/tempo-balance.ts
108900
- init_cjs_shims();
108901
- var MPPSCAN_BASE = "https://mppscan.com";
108902
- async function getTempoBalance({
108903
- address,
108904
- tokenAddress
108905
- }) {
108906
- const url3 = `${MPPSCAN_BASE}/api/balance/${address}`;
108907
- const res = await fetch(url3, {
108908
- method: "GET",
108909
- headers: { accept: "application/json" }
108910
- });
108911
- if (!res.ok) {
108912
- throw new Error(`mppscan balance request failed: ${res.status}`);
108913
- }
108914
- const data = await res.json();
108915
- return {
108916
- chainId: tempo.id,
108917
- chainName: tempo.name,
108918
- balance: BigInt(data.balance),
108919
- tokenAddress
108920
- };
108921
- }
108922
-
108923
- // src/shared/operations/fetch-with-payment.ts
108924
- function createFetchWithPayment(options) {
108925
- const { surface: surface2, clients, paymentMethod, beforePayment, timeout } = options;
108926
- return async (request) => {
108927
- const clonedRequest = request.clone();
108928
- const fallbackRequest = request.clone();
108929
- const probeResult = await safeFetch(surface2, request, timeout);
108930
- if (probeResult.isErr()) {
108931
- return fetchErr(surface2, probeResult.error);
108932
- }
108933
- if (probeResult.value.status !== 402) {
108934
- return probeResult.andThen(
108935
- (response2) => fetchOk({ response: response2, paymentInfo: null })
108936
- );
108937
- }
108938
- const response = probeResult.value;
108939
- if (paymentMethod !== "auto") {
108940
- if (paymentMethod === "mpp") {
108941
- return handleMppPayment(surface2, response, clonedRequest, options);
108942
- }
108943
- return handleX402Payment(
108944
- surface2,
108945
- response,
108946
- clonedRequest,
108947
- clients.x402,
108948
- beforePayment,
108949
- timeout
108950
- );
108951
- }
108952
- const available = detectPaymentProtocols(response);
108953
- let preferred;
108954
- if (available.length === 1) {
108955
- preferred = available[0];
108956
- } else {
108957
- preferred = await pickByBalance(surface2, response, options);
108958
- }
108959
- const fallback = available.length > 1 ? preferred === "mpp" ? "x402" : "mpp" : null;
108960
- const result = preferred === "mpp" ? await handleMppPayment(surface2, response, clonedRequest, options) : await handleX402Payment(
108961
- surface2,
108962
- response,
108963
- clonedRequest,
108964
- clients.x402,
108965
- beforePayment,
108966
- timeout
108967
- );
108968
- if (result.isErr() && fallback) {
108969
- return fallback === "mpp" ? handleMppPayment(surface2, response, fallbackRequest, options) : handleX402Payment(
108970
- surface2,
108971
- response,
108972
- fallbackRequest,
108973
- clients.x402,
108974
- beforePayment,
108975
- timeout
108976
- );
108977
- }
108978
- return result;
108979
- };
108980
- }
108981
- async function pickByBalance(surface2, response, options) {
108982
- const { account } = options;
108983
- const x402BalanceResult = await resultFromPromise(
108984
- "balance",
108985
- surface2,
108986
- getBalance3({
108987
- address: account.address,
108988
- surface: surface2
108989
- }).then((r) => r.isOk() ? r.value.balance : 0),
108990
- () => ({
108991
- cause: "x402_balance",
108992
- message: "Failed to get x402 balance"
108993
- })
108994
- );
108995
- if (x402BalanceResult.isErr()) {
108996
- log.debug("Balance comparison failed, defaulting to mpp");
108997
- return "mpp";
108998
- }
108999
- const x402Balance = x402BalanceResult.value;
109000
- let mppBalance = 0;
109001
- const challengeResult = safeGetMppChallenge(surface2, response);
109002
- if (challengeResult.isOk()) {
109003
- const currency = challengeResult.value.request.currency;
109004
- const decimals2 = challengeResult.value.request.decimals ?? 6;
109005
- if (currency) {
109006
- const tempoResult = await resultFromPromise(
109007
- "tempo",
109008
- surface2,
109009
- getTempoBalance({
109010
- address: account.address,
109011
- tokenAddress: currency
109012
- }),
109013
- () => ({
109014
- cause: "tempo_balance",
109015
- message: "Tempo balance check failed"
109016
- })
109017
- );
109018
- if (tempoResult.isOk()) {
109019
- mppBalance = Number(formatUnits(tempoResult.value.balance, decimals2));
109020
- }
109021
- }
109022
- }
109023
- log.info(`Protocol selection \u2014 x402: $${x402Balance}, mpp: $${mppBalance}`);
109024
- return x402Balance >= mppBalance ? "x402" : "mpp";
109025
- }
109026
- async function handleX402Payment(surface2, response, clonedRequest, client, beforePayment, timeout) {
109027
- const paymentRequiredResult = await safeGetPaymentRequired(
109028
- surface2,
109029
- client,
109030
- response
109031
- );
109032
- if (paymentRequiredResult.isErr()) {
109033
- return paymentRequiredResult;
109034
- }
109035
- const paymentRequired = paymentRequiredResult.value;
109036
- if (beforePayment) {
109037
- const accept = paymentRequired.accepts[0];
109038
- if (accept) {
109039
- const amount2 = tokenStringToNumber(accept.amount);
109040
- const hookResult = await resultFromPromise(
109041
- "x402",
109042
- surface2,
109043
- beforePayment({
109044
- protocol: "x402",
109045
- amount: amount2,
109046
- currency: "USDC",
109047
- network: accept.network
109048
- }),
109049
- (e) => ({
109050
- cause: "payment_already_attempted",
109051
- message: e instanceof Error ? e.message : "Before-payment hook failed"
109052
- })
109053
- );
109054
- if (hookResult.isErr()) {
109055
- return x402Err(surface2, hookResult.error);
109056
- }
109057
- }
109058
- }
109059
- const paymentPayloadResult = await safeCreatePaymentPayload(
109060
- surface2,
109061
- client,
109062
- paymentRequired
109063
- );
109064
- if (paymentPayloadResult.isErr()) {
109065
- return paymentPayloadResult;
109066
- }
109067
- const paymentPayload = paymentPayloadResult.value;
109068
- const paymentHeaders = client.encodePaymentSignatureHeader(paymentPayload);
109069
- if (clonedRequest.headers.has("PAYMENT-SIGNATURE") || clonedRequest.headers.has("X-PAYMENT")) {
109070
- return x402Err(surface2, {
109071
- cause: "payment_already_attempted",
109072
- message: "Payment already attempted"
109073
- });
109074
- }
109075
- for (const [key, value] of Object.entries(paymentHeaders)) {
109076
- clonedRequest.headers.set(key, value);
109077
- }
109078
- clonedRequest.headers.set(
109079
- "Access-Control-Expose-Headers",
109080
- "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE"
109081
- );
109082
- return await safeFetch(surface2, clonedRequest, timeout).andThen(
109083
- (paidResponse) => {
109084
- const settlementResult = safeGetPaymentSettlement(
109085
- surface2,
109086
- client,
109087
- paidResponse
109088
- );
109089
- return x402Ok({
109090
- response: paidResponse,
109091
- paymentInfo: {
109092
- protocol: "x402",
109093
- price: tokenStringToNumber(
109094
- paymentPayload.accepted.amount
109095
- ).toLocaleString("en-US", {
109096
- style: "currency",
109097
- currency: "USD"
109098
- }),
109099
- ...settlementResult.isOk() ? {
109100
- payment: {
109101
- success: settlementResult.value.success,
109102
- transactionHash: settlementResult.value.transaction
109103
- }
109104
- } : {}
109105
- }
109106
- });
109107
- }
109108
- );
109109
- }
109110
- async function handleMppPayment(surface2, response, clonedRequest, options) {
109111
- const { clients, beforePayment, timeout } = options;
109112
- const mppxClient = clients.mpp;
109113
- if (clonedRequest.headers.has("Authorization")) {
109114
- return mppErr(surface2, {
109115
- cause: "mpp_payment_already_attempted",
109116
- message: "MPP payment already attempted"
109117
- });
109118
- }
109119
- const challengeResult = safeGetMppChallenge(surface2, response);
109120
- if (challengeResult.isErr()) {
109121
- return challengeResult;
109122
- }
109123
- const challenge2 = challengeResult.value;
109124
- const amount2 = challenge2.request.amount;
109125
- const decimals2 = challenge2.request.decimals ?? 6;
109126
- const currency = challenge2.request.currency;
109127
- if (beforePayment && amount2 && currency) {
109128
- const numericAmount = Number(formatUnits(BigInt(amount2), decimals2));
109129
- const hookResult = await resultFromPromise(
109130
- "mpp",
109131
- surface2,
109132
- beforePayment({
109133
- protocol: "mpp",
109134
- amount: numericAmount,
109135
- currency,
109136
- network: `tempo:${challenge2.method}`
109137
- }),
109138
- (e) => ({
109139
- cause: "mpp_payment_already_attempted",
109140
- message: e instanceof Error ? e.message : "Before-payment hook failed"
109141
- })
109142
- );
109143
- if (hookResult.isErr()) {
109144
- return mppErr(surface2, hookResult.error);
109145
- }
109146
- }
109147
- const credentialResult = await safeCreateMppCredential(
109148
- surface2,
109149
- mppxClient,
109150
- response
109151
- );
109152
- if (credentialResult.isErr()) {
109153
- return credentialResult;
109154
- }
109155
- const credential = credentialResult.value;
109156
- clonedRequest.headers.set("Authorization", credential);
109157
- return await safeFetch(surface2, clonedRequest, timeout).andThen(
109158
- (paidResponse) => {
109159
- const receiptResult = safeGetMppReceipt(surface2, paidResponse);
109160
- const priceDisplay = amount2 ? Number(formatUnits(BigInt(amount2), decimals2)).toLocaleString(
109161
- "en-US",
109162
- {
109163
- style: "currency",
109164
- currency: "USD"
109165
- }
109166
- ) : void 0;
109167
- return mppOk({
109168
- response: paidResponse,
109169
- paymentInfo: {
109170
- protocol: "mpp",
109171
- ...priceDisplay ? { price: priceDisplay } : {},
109172
- ...receiptResult.isOk() ? {
109173
- payment: {
109174
- success: true,
109175
- transactionHash: receiptResult.value.reference
109176
- }
109177
- } : {}
109178
- }
109179
- });
109180
- }
109181
- );
109182
- }
109183
-
109184
- // src/server/tools/response/index.ts
109185
- init_cjs_shims();
109186
-
109187
- // src/server/tools/response/success.ts
109188
- init_cjs_shims();
109189
-
109190
- // src/shared/neverthrow/json/index.ts
109191
- init_cjs_shims();
109192
- var type3 = "json";
109193
- var jsonErr = (surface2, error48) => {
109194
- return err2(type3, surface2, error48);
109195
- };
109196
- var safeStringifyJson = (surface2, value) => {
109197
- return resultFromThrowable(
109198
- type3,
109199
- surface2,
109200
- () => JSON.stringify(value, null, 2),
109201
- () => ({
109202
- cause: "stringify",
109203
- message: "Could not stringify JSON"
109204
- })
109205
- );
109206
- };
109207
- var toJsonObject = (value) => JSON.parse(JSON.stringify(value));
109208
- var safeParseJson = (surface2, value) => {
109209
- return resultFromThrowable(
109210
- type3,
109211
- surface2,
109212
- () => JSON.parse(value),
109213
- (e) => ({
109214
- cause: "parse",
109215
- message: e instanceof Error ? e.message : "Could not parse JSON"
109216
- })
109217
- );
109218
- };
109219
-
109220
- // src/server/tools/response/error.ts
109221
- init_cjs_shims();
109222
-
109223
- // src/server/tools/response/lib.ts
109224
- init_cjs_shims();
109225
- var parsedResponseToToolContentPart = (data) => {
109226
- switch (data.type) {
109227
- case "json":
109228
- return {
109229
- type: "text",
109230
- text: JSON.stringify(data.data)
109231
- };
109232
- case "image":
109233
- return {
109234
- type: "image",
109235
- mimeType: data.mimeType,
109236
- data: Buffer.from(data.data).toString("base64")
109237
- };
109238
- case "audio":
109239
- return {
109240
- type: "audio",
109241
- mimeType: data.mimeType,
109242
- data: Buffer.from(data.data).toString("base64")
109243
- };
109244
- case "text":
109245
- return { type: "text", text: data.data };
109246
- default:
109247
- return {
109248
- type: "text",
109249
- text: `Unsupported response type: ${data.type}`
109250
- };
109251
- }
109252
- };
109253
-
109254
- // src/server/tools/response/error.ts
109255
- var buildMcpError = (content, options) => {
109256
- return {
109257
- content,
109258
- // Default: omit isError so siblings survive parallel calls.
109259
- // Tools with outputSchema MUST pass isError: true so the SDK
109260
- // skips output validation on error paths.
109261
- ...options?.isError ? { isError: true } : {}
109262
- };
109263
- };
109264
- var mcpErrorJson = (error48, options) => {
109265
- return safeStringifyJson("mcp-error-json", error48).match(
109266
- (success3) => buildMcpError([{ type: "text", text: success3 }], options),
109267
- (error49) => buildMcpError(
109268
- [{ type: "text", text: JSON.stringify(error49, null, 2) }],
109269
- options
109270
- )
109271
- );
109272
- };
109273
- var mcpError = async (err3, options) => {
109274
- const { error: error48 } = err3;
109275
- if (isFetchError(error48)) {
109276
- switch (error48.cause) {
109277
- case "network":
109278
- case "parse":
109279
- return mcpErrorJson({ ...error48 }, options);
109280
- case "http":
109281
- const { response, ...rest } = error48;
109282
- const parseResponseResult = await safeParseResponse(
109283
- "mcp-error-fetch-parse-response",
109284
- response
109285
- );
109286
- const httpContent = [
109287
- { type: "text", text: JSON.stringify(rest, null, 2) },
109288
- ...parseResponseResult.match(
109289
- (success3) => [parsedResponseToToolContentPart(success3)],
109290
- () => []
109291
- )
109292
- ];
109293
- return buildMcpError(httpContent, options);
109294
- }
109295
- }
109296
- return mcpErrorJson({ ...error48 }, options);
109297
- };
109298
- var mcpErrorFetch = async (surface2, response) => {
109299
- return mcpError(fetchHttpErr(surface2, response));
109300
- };
109301
-
109302
- // src/server/tools/response/success.ts
109303
- var buildMcpSuccess = (content) => {
109304
- return {
109305
- content
109306
- };
109307
- };
109308
- var mcpSuccessJson = (data) => {
109309
- return safeStringifyJson("mcp-success-text", data).match(
109310
- (success3) => buildMcpSuccess([{ type: "text", text: success3 }]),
109311
- (error48) => mcpErrorJson(error48)
109312
- );
109313
- };
109314
- var mcpSuccessStructuredJson = (data) => {
109315
- return safeStringifyJson("mcp-success-structured", data).match(
109316
- (success3) => ({
109317
- content: [{ type: "text", text: success3 }],
109318
- structuredContent: data
109319
- }),
109320
- (error48) => mcpErrorJson(error48)
109321
- );
109322
- };
109323
- var mcpSuccessResponse = (data, extra) => {
109324
- const parsedExtra = extra ? safeStringifyJson("mcp-success-extra", extra).match(
109325
- (success3) => success3,
109326
- () => void 0
109327
- ) : void 0;
109328
- return buildMcpSuccess([
109329
- parsedResponseToToolContentPart(data),
109330
- ...parsedExtra ? [{ type: "text", text: parsedExtra }] : []
109331
- ]);
109332
- };
109333
-
109334
- // src/server/tools/response/safe-handler.ts
109335
- init_cjs_shims();
109336
- function safeHandler(handler) {
109337
- return async (input) => {
109338
- try {
109339
- return await handler(input);
109340
- } catch (e) {
109341
- log.error("Unhandled tool error", e);
109342
- return mcpErrorJson({
109343
- error: e instanceof Error ? e.message : String(e),
109344
- cause: "unhandled_exception"
109345
- });
109346
- }
109347
- };
109348
- }
109349
-
109350
- // src/server/tools/lib/request.ts
109351
- init_cjs_shims();
109352
- var requestSchema = zod_default.object({
109353
- url: zod_default.string().describe("The endpoint URL"),
109354
- method: zod_default.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).optional().describe("HTTP method. Defaults to GET for fetch operations."),
109355
- body: zod_default.unknown().optional().describe("Request body for POST/PUT/PATCH methods"),
109356
- headers: zod_default.record(zod_default.string(), zod_default.string()).optional().describe("Additional headers to include").default({}),
109357
- timeout: zod_default.number().int().positive().optional().describe("Request timeout in milliseconds")
109358
- });
109359
- var buildRequest2 = ({
109360
- input,
109361
- address,
109362
- sessionId,
109363
- provider
109364
- }) => {
109365
- return new Request(input.url, {
109366
- method: input.method ?? "GET",
109367
- body: input.body ? typeof input.body === "string" ? input.body : JSON.stringify(input.body) : void 0,
109368
- headers: {
109369
- ...input.body ? { "Content-Type": "application/json" } : {},
109370
- ...input.headers,
109371
- ...address ? { "X-Wallet-Address": address, "X-Client-ID": provider } : {},
109372
- ...sessionId ? { "X-Session-ID": sessionId } : {}
109373
- }
109374
- });
109375
- };
109376
-
109377
- // src/server/tools/lib/check-balance.ts
109378
- init_cjs_shims();
109379
108880
 
109380
108881
  // src/shared/utils.ts
109381
108882
  init_cjs_shims();
@@ -109883,146 +109384,650 @@ var baseOpen = async (options) => {
109883
109384
  exeLocalXdgOpen = true;
109884
109385
  } catch {
109885
109386
  }
109886
- const useSystemXdgOpen = import_node_process8.default.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
109887
- command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
109888
- }
109889
- if (appArguments.length > 0) {
109890
- cliArguments.push(...appArguments);
109891
- }
109892
- if (!options.wait) {
109893
- childProcessOptions.stdio = "ignore";
109894
- childProcessOptions.detached = true;
109387
+ const useSystemXdgOpen = import_node_process8.default.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
109388
+ command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
109389
+ }
109390
+ if (appArguments.length > 0) {
109391
+ cliArguments.push(...appArguments);
109392
+ }
109393
+ if (!options.wait) {
109394
+ childProcessOptions.stdio = "ignore";
109395
+ childProcessOptions.detached = true;
109396
+ }
109397
+ }
109398
+ if (platform === "darwin" && appArguments.length > 0) {
109399
+ cliArguments.push("--args", ...appArguments);
109400
+ }
109401
+ if (options.target) {
109402
+ cliArguments.push(options.target);
109403
+ }
109404
+ const subprocess = import_node_child_process7.default.spawn(command, cliArguments, childProcessOptions);
109405
+ if (options.wait) {
109406
+ return new Promise((resolve, reject) => {
109407
+ subprocess.once("error", reject);
109408
+ subprocess.once("close", (exitCode) => {
109409
+ if (!options.allowNonzeroExitCode && exitCode !== 0) {
109410
+ reject(new Error(`Exited with code ${exitCode}`));
109411
+ return;
109412
+ }
109413
+ resolve(subprocess);
109414
+ });
109415
+ });
109416
+ }
109417
+ if (isFallbackAttempt) {
109418
+ return new Promise((resolve, reject) => {
109419
+ subprocess.once("error", reject);
109420
+ subprocess.once("spawn", () => {
109421
+ subprocess.once("close", (exitCode) => {
109422
+ subprocess.off("error", reject);
109423
+ if (exitCode !== 0) {
109424
+ reject(new Error(`Exited with code ${exitCode}`));
109425
+ return;
109426
+ }
109427
+ subprocess.unref();
109428
+ resolve(subprocess);
109429
+ });
109430
+ });
109431
+ });
109432
+ }
109433
+ subprocess.unref();
109434
+ return new Promise((resolve, reject) => {
109435
+ subprocess.once("error", reject);
109436
+ subprocess.once("spawn", () => {
109437
+ subprocess.off("error", reject);
109438
+ resolve(subprocess);
109439
+ });
109440
+ });
109441
+ };
109442
+ var open = (target, options) => {
109443
+ if (typeof target !== "string") {
109444
+ throw new TypeError("Expected a `target`");
109445
+ }
109446
+ return baseOpen({
109447
+ ...options,
109448
+ target
109449
+ });
109450
+ };
109451
+ function detectArchBinary(binary) {
109452
+ if (typeof binary === "string" || Array.isArray(binary)) {
109453
+ return binary;
109454
+ }
109455
+ const { [arch]: archBinary } = binary;
109456
+ if (!archBinary) {
109457
+ throw new Error(`${arch} is not supported`);
109458
+ }
109459
+ return archBinary;
109460
+ }
109461
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
109462
+ if (wsl && is_wsl_default) {
109463
+ return detectArchBinary(wsl);
109464
+ }
109465
+ if (!platformBinary) {
109466
+ throw new Error(`${platform} is not supported`);
109467
+ }
109468
+ return detectArchBinary(platformBinary);
109469
+ }
109470
+ var apps = {
109471
+ browser: "browser",
109472
+ browserPrivate: "browserPrivate"
109473
+ };
109474
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
109475
+ darwin: "google chrome",
109476
+ win32: "chrome",
109477
+ // `chromium-browser` is the older deb package name used by Ubuntu/Debian before snap.
109478
+ linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
109479
+ }, {
109480
+ wsl: {
109481
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
109482
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
109483
+ }
109484
+ }));
109485
+ defineLazyProperty(apps, "brave", () => detectPlatformBinary({
109486
+ darwin: "brave browser",
109487
+ win32: "brave",
109488
+ linux: ["brave-browser", "brave"]
109489
+ }, {
109490
+ wsl: {
109491
+ ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
109492
+ x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
109493
+ }
109494
+ }));
109495
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
109496
+ darwin: "firefox",
109497
+ win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
109498
+ linux: "firefox"
109499
+ }, {
109500
+ wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
109501
+ }));
109502
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
109503
+ darwin: "microsoft edge",
109504
+ win32: "msedge",
109505
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
109506
+ }, {
109507
+ wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
109508
+ }));
109509
+ defineLazyProperty(apps, "safari", () => detectPlatformBinary({
109510
+ darwin: "Safari"
109511
+ }));
109512
+ var open_default = open;
109513
+
109514
+ // src/shared/utils.ts
109515
+ var getBaseUrl = (dev) => {
109516
+ return dev ? "http://localhost:3000" : "https://agentcash.dev";
109517
+ };
109518
+ var getDepositLink = (address, flags) => {
109519
+ return `${getBaseUrl(flags.dev)}/deposit/${address}`;
109520
+ };
109521
+ var openDepositLink = async (address, flags) => {
109522
+ const depositLink = getDepositLink(address, flags);
109523
+ await open_default(depositLink);
109524
+ };
109525
+
109526
+ // src/shared/balance.ts
109527
+ var getBalance3 = async ({
109528
+ address,
109529
+ surface: surface2,
109530
+ dev = false
109531
+ }) => {
109532
+ const baseUrl = getBaseUrl(dev);
109533
+ const url3 = `${baseUrl}/api/balance/${address}`;
109534
+ const res = await safeFetchJson(
109535
+ surface2,
109536
+ new Request(url3, {
109537
+ method: "GET",
109538
+ headers: {
109539
+ accept: "application/json"
109540
+ }
109541
+ }),
109542
+ zod_default.object({
109543
+ chain: zod_default.number(),
109544
+ balance: zod_default.coerce.number()
109545
+ })
109546
+ );
109547
+ return res;
109548
+ };
109549
+
109550
+ // src/shared/tempo-balance.ts
109551
+ init_cjs_shims();
109552
+ var MPPSCAN_BASE = "https://mppscan.com";
109553
+ async function getTempoBalance({
109554
+ address,
109555
+ tokenAddress
109556
+ }) {
109557
+ const url3 = `${MPPSCAN_BASE}/api/balance/${address}`;
109558
+ const res = await fetch(url3, {
109559
+ method: "GET",
109560
+ headers: { accept: "application/json" }
109561
+ });
109562
+ if (!res.ok) {
109563
+ throw new Error(`mppscan balance request failed: ${res.status}`);
109564
+ }
109565
+ const data = await res.json();
109566
+ return {
109567
+ chainId: tempo.id,
109568
+ chainName: tempo.name,
109569
+ balance: BigInt(data.balance),
109570
+ tokenAddress
109571
+ };
109572
+ }
109573
+
109574
+ // src/shared/operations/fetch-with-payment.ts
109575
+ function createFetchWithPayment(options) {
109576
+ const { surface: surface2, clients, paymentMethod, beforePayment, timeout } = options;
109577
+ return async (request) => {
109578
+ const clonedRequest = request.clone();
109579
+ const fallbackRequest = request.clone();
109580
+ const probeResult = await safeFetch(surface2, request, timeout);
109581
+ if (probeResult.isErr()) {
109582
+ return fetchErr(surface2, probeResult.error);
109583
+ }
109584
+ if (probeResult.value.status !== 402) {
109585
+ return probeResult.andThen(
109586
+ (response2) => fetchOk({ response: response2, paymentInfo: null })
109587
+ );
109588
+ }
109589
+ const response = probeResult.value;
109590
+ if (paymentMethod !== "auto") {
109591
+ if (paymentMethod === "mpp") {
109592
+ return handleMppPayment(surface2, response, clonedRequest, options);
109593
+ }
109594
+ return handleX402Payment(
109595
+ surface2,
109596
+ response,
109597
+ clonedRequest,
109598
+ clients.x402,
109599
+ beforePayment,
109600
+ timeout
109601
+ );
109602
+ }
109603
+ const available = detectPaymentProtocols(response);
109604
+ let preferred;
109605
+ if (available.length === 1) {
109606
+ preferred = available[0];
109607
+ } else {
109608
+ preferred = await pickByBalance(surface2, response, options);
109609
+ }
109610
+ const fallback = available.length > 1 ? preferred === "mpp" ? "x402" : "mpp" : null;
109611
+ const result = preferred === "mpp" ? await handleMppPayment(surface2, response, clonedRequest, options) : await handleX402Payment(
109612
+ surface2,
109613
+ response,
109614
+ clonedRequest,
109615
+ clients.x402,
109616
+ beforePayment,
109617
+ timeout
109618
+ );
109619
+ if (result.isErr() && fallback) {
109620
+ return fallback === "mpp" ? handleMppPayment(surface2, response, fallbackRequest, options) : handleX402Payment(
109621
+ surface2,
109622
+ response,
109623
+ fallbackRequest,
109624
+ clients.x402,
109625
+ beforePayment,
109626
+ timeout
109627
+ );
109628
+ }
109629
+ return result;
109630
+ };
109631
+ }
109632
+ async function pickByBalance(surface2, response, options) {
109633
+ const { account, flags } = options;
109634
+ const x402BalanceResult = await resultFromPromise(
109635
+ "balance",
109636
+ surface2,
109637
+ getBalance3({
109638
+ address: account.address,
109639
+ surface: surface2,
109640
+ dev: flags.dev
109641
+ }).then((r) => r.isOk() ? r.value.balance : 0),
109642
+ () => ({
109643
+ cause: "x402_balance",
109644
+ message: "Failed to get x402 balance"
109645
+ })
109646
+ );
109647
+ if (x402BalanceResult.isErr()) {
109648
+ log.debug("Balance comparison failed, defaulting to mpp");
109649
+ return "mpp";
109650
+ }
109651
+ const x402Balance = x402BalanceResult.value;
109652
+ let mppBalance = 0;
109653
+ const challengeResult = safeGetMppChallenge(surface2, response);
109654
+ if (challengeResult.isOk()) {
109655
+ const currency = challengeResult.value.request.currency;
109656
+ const decimals2 = challengeResult.value.request.decimals ?? 6;
109657
+ if (currency) {
109658
+ const tempoResult = await resultFromPromise(
109659
+ "tempo",
109660
+ surface2,
109661
+ getTempoBalance({
109662
+ address: account.address,
109663
+ tokenAddress: currency
109664
+ }),
109665
+ () => ({
109666
+ cause: "tempo_balance",
109667
+ message: "Tempo balance check failed"
109668
+ })
109669
+ );
109670
+ if (tempoResult.isOk()) {
109671
+ mppBalance = Number(formatUnits(tempoResult.value.balance, decimals2));
109672
+ }
109895
109673
  }
109896
109674
  }
109897
- if (platform === "darwin" && appArguments.length > 0) {
109898
- cliArguments.push("--args", ...appArguments);
109675
+ log.info(`Protocol selection \u2014 x402: $${x402Balance}, mpp: $${mppBalance}`);
109676
+ return x402Balance >= mppBalance ? "x402" : "mpp";
109677
+ }
109678
+ async function handleX402Payment(surface2, response, clonedRequest, client, beforePayment, timeout) {
109679
+ const paymentRequiredResult = await safeGetPaymentRequired(
109680
+ surface2,
109681
+ client,
109682
+ response
109683
+ );
109684
+ if (paymentRequiredResult.isErr()) {
109685
+ return paymentRequiredResult;
109899
109686
  }
109900
- if (options.target) {
109901
- cliArguments.push(options.target);
109687
+ const paymentRequired = paymentRequiredResult.value;
109688
+ if (beforePayment) {
109689
+ const accept = paymentRequired.accepts[0];
109690
+ if (accept) {
109691
+ const amount2 = tokenStringToNumber(accept.amount);
109692
+ const hookResult = await resultFromPromise(
109693
+ "x402",
109694
+ surface2,
109695
+ beforePayment({
109696
+ protocol: "x402",
109697
+ amount: amount2,
109698
+ currency: "USDC",
109699
+ network: accept.network
109700
+ }),
109701
+ (e) => ({
109702
+ cause: "payment_already_attempted",
109703
+ message: e instanceof Error ? e.message : "Before-payment hook failed"
109704
+ })
109705
+ );
109706
+ if (hookResult.isErr()) {
109707
+ return x402Err(surface2, hookResult.error);
109708
+ }
109709
+ }
109902
109710
  }
109903
- const subprocess = import_node_child_process7.default.spawn(command, cliArguments, childProcessOptions);
109904
- if (options.wait) {
109905
- return new Promise((resolve, reject) => {
109906
- subprocess.once("error", reject);
109907
- subprocess.once("close", (exitCode) => {
109908
- if (!options.allowNonzeroExitCode && exitCode !== 0) {
109909
- reject(new Error(`Exited with code ${exitCode}`));
109910
- return;
109911
- }
109912
- resolve(subprocess);
109913
- });
109914
- });
109711
+ const paymentPayloadResult = await safeCreatePaymentPayload(
109712
+ surface2,
109713
+ client,
109714
+ paymentRequired
109715
+ );
109716
+ if (paymentPayloadResult.isErr()) {
109717
+ return paymentPayloadResult;
109915
109718
  }
109916
- if (isFallbackAttempt) {
109917
- return new Promise((resolve, reject) => {
109918
- subprocess.once("error", reject);
109919
- subprocess.once("spawn", () => {
109920
- subprocess.once("close", (exitCode) => {
109921
- subprocess.off("error", reject);
109922
- if (exitCode !== 0) {
109923
- reject(new Error(`Exited with code ${exitCode}`));
109924
- return;
109925
- }
109926
- subprocess.unref();
109927
- resolve(subprocess);
109928
- });
109929
- });
109719
+ const paymentPayload = paymentPayloadResult.value;
109720
+ const paymentHeaders = client.encodePaymentSignatureHeader(paymentPayload);
109721
+ if (clonedRequest.headers.has("PAYMENT-SIGNATURE") || clonedRequest.headers.has("X-PAYMENT")) {
109722
+ return x402Err(surface2, {
109723
+ cause: "payment_already_attempted",
109724
+ message: "Payment already attempted"
109930
109725
  });
109931
109726
  }
109932
- subprocess.unref();
109933
- return new Promise((resolve, reject) => {
109934
- subprocess.once("error", reject);
109935
- subprocess.once("spawn", () => {
109936
- subprocess.off("error", reject);
109937
- resolve(subprocess);
109938
- });
109939
- });
109940
- };
109941
- var open = (target, options) => {
109942
- if (typeof target !== "string") {
109943
- throw new TypeError("Expected a `target`");
109727
+ for (const [key, value] of Object.entries(paymentHeaders)) {
109728
+ clonedRequest.headers.set(key, value);
109944
109729
  }
109945
- return baseOpen({
109946
- ...options,
109947
- target
109948
- });
109949
- };
109950
- function detectArchBinary(binary) {
109951
- if (typeof binary === "string" || Array.isArray(binary)) {
109952
- return binary;
109730
+ clonedRequest.headers.set(
109731
+ "Access-Control-Expose-Headers",
109732
+ "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE"
109733
+ );
109734
+ return await safeFetch(surface2, clonedRequest, timeout).andThen(
109735
+ (paidResponse) => {
109736
+ const settlementResult = safeGetPaymentSettlement(
109737
+ surface2,
109738
+ client,
109739
+ paidResponse
109740
+ );
109741
+ return x402Ok({
109742
+ response: paidResponse,
109743
+ paymentInfo: {
109744
+ protocol: "x402",
109745
+ price: tokenStringToNumber(
109746
+ paymentPayload.accepted.amount
109747
+ ).toLocaleString("en-US", {
109748
+ style: "currency",
109749
+ currency: "USD"
109750
+ }),
109751
+ ...settlementResult.isOk() ? {
109752
+ payment: {
109753
+ success: settlementResult.value.success,
109754
+ transactionHash: settlementResult.value.transaction
109755
+ }
109756
+ } : {}
109757
+ }
109758
+ });
109759
+ }
109760
+ );
109761
+ }
109762
+ async function handleMppPayment(surface2, response, clonedRequest, options) {
109763
+ const { clients, beforePayment, timeout } = options;
109764
+ const mppxClient = clients.mpp;
109765
+ if (clonedRequest.headers.has("Authorization")) {
109766
+ return mppErr(surface2, {
109767
+ cause: "mpp_payment_already_attempted",
109768
+ message: "MPP payment already attempted"
109769
+ });
109953
109770
  }
109954
- const { [arch]: archBinary } = binary;
109955
- if (!archBinary) {
109956
- throw new Error(`${arch} is not supported`);
109771
+ const challengeResult = safeGetMppChallenge(surface2, response);
109772
+ if (challengeResult.isErr()) {
109773
+ return challengeResult;
109957
109774
  }
109958
- return archBinary;
109959
- }
109960
- function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
109961
- if (wsl && is_wsl_default) {
109962
- return detectArchBinary(wsl);
109775
+ const challenge2 = challengeResult.value;
109776
+ const amount2 = challenge2.request.amount;
109777
+ const decimals2 = challenge2.request.decimals ?? 6;
109778
+ const currency = challenge2.request.currency;
109779
+ if (beforePayment && amount2 && currency) {
109780
+ const numericAmount = Number(formatUnits(BigInt(amount2), decimals2));
109781
+ const hookResult = await resultFromPromise(
109782
+ "mpp",
109783
+ surface2,
109784
+ beforePayment({
109785
+ protocol: "mpp",
109786
+ amount: numericAmount,
109787
+ currency,
109788
+ network: `tempo:${challenge2.method}`
109789
+ }),
109790
+ (e) => ({
109791
+ cause: "mpp_payment_already_attempted",
109792
+ message: e instanceof Error ? e.message : "Before-payment hook failed"
109793
+ })
109794
+ );
109795
+ if (hookResult.isErr()) {
109796
+ return mppErr(surface2, hookResult.error);
109797
+ }
109963
109798
  }
109964
- if (!platformBinary) {
109965
- throw new Error(`${platform} is not supported`);
109799
+ const credentialResult = await safeCreateMppCredential(
109800
+ surface2,
109801
+ mppxClient,
109802
+ response
109803
+ );
109804
+ if (credentialResult.isErr()) {
109805
+ return credentialResult;
109966
109806
  }
109967
- return detectArchBinary(platformBinary);
109807
+ const credential = credentialResult.value;
109808
+ clonedRequest.headers.set("Authorization", credential);
109809
+ return await safeFetch(surface2, clonedRequest, timeout).andThen(
109810
+ (paidResponse) => {
109811
+ const receiptResult = safeGetMppReceipt(surface2, paidResponse);
109812
+ const priceDisplay = amount2 ? Number(formatUnits(BigInt(amount2), decimals2)).toLocaleString(
109813
+ "en-US",
109814
+ {
109815
+ style: "currency",
109816
+ currency: "USD"
109817
+ }
109818
+ ) : void 0;
109819
+ return mppOk({
109820
+ response: paidResponse,
109821
+ paymentInfo: {
109822
+ protocol: "mpp",
109823
+ ...priceDisplay ? { price: priceDisplay } : {},
109824
+ ...receiptResult.isOk() ? {
109825
+ payment: {
109826
+ success: true,
109827
+ transactionHash: receiptResult.value.reference
109828
+ }
109829
+ } : {}
109830
+ }
109831
+ });
109832
+ }
109833
+ );
109968
109834
  }
109969
- var apps = {
109970
- browser: "browser",
109971
- browserPrivate: "browserPrivate"
109835
+
109836
+ // src/server/tools/response/index.ts
109837
+ init_cjs_shims();
109838
+
109839
+ // src/server/tools/response/success.ts
109840
+ init_cjs_shims();
109841
+
109842
+ // src/shared/neverthrow/json/index.ts
109843
+ init_cjs_shims();
109844
+ var type3 = "json";
109845
+ var jsonErr = (surface2, error48) => {
109846
+ return err2(type3, surface2, error48);
109972
109847
  };
109973
- defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
109974
- darwin: "google chrome",
109975
- win32: "chrome",
109976
- // `chromium-browser` is the older deb package name used by Ubuntu/Debian before snap.
109977
- linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
109978
- }, {
109979
- wsl: {
109980
- ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
109981
- x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
109848
+ var safeStringifyJson = (surface2, value) => {
109849
+ return resultFromThrowable(
109850
+ type3,
109851
+ surface2,
109852
+ () => JSON.stringify(value, null, 2),
109853
+ () => ({
109854
+ cause: "stringify",
109855
+ message: "Could not stringify JSON"
109856
+ })
109857
+ );
109858
+ };
109859
+ var toJsonObject = (value) => JSON.parse(JSON.stringify(value));
109860
+ var safeParseJson = (surface2, value) => {
109861
+ return resultFromThrowable(
109862
+ type3,
109863
+ surface2,
109864
+ () => JSON.parse(value),
109865
+ (e) => ({
109866
+ cause: "parse",
109867
+ message: e instanceof Error ? e.message : "Could not parse JSON"
109868
+ })
109869
+ );
109870
+ };
109871
+
109872
+ // src/server/tools/response/error.ts
109873
+ init_cjs_shims();
109874
+
109875
+ // src/server/tools/response/lib.ts
109876
+ init_cjs_shims();
109877
+ var parsedResponseToToolContentPart = (data) => {
109878
+ switch (data.type) {
109879
+ case "json":
109880
+ return {
109881
+ type: "text",
109882
+ text: JSON.stringify(data.data)
109883
+ };
109884
+ case "image":
109885
+ return {
109886
+ type: "image",
109887
+ mimeType: data.mimeType,
109888
+ data: Buffer.from(data.data).toString("base64")
109889
+ };
109890
+ case "audio":
109891
+ return {
109892
+ type: "audio",
109893
+ mimeType: data.mimeType,
109894
+ data: Buffer.from(data.data).toString("base64")
109895
+ };
109896
+ case "text":
109897
+ return { type: "text", text: data.data };
109898
+ default:
109899
+ return {
109900
+ type: "text",
109901
+ text: `Unsupported response type: ${data.type}`
109902
+ };
109982
109903
  }
109983
- }));
109984
- defineLazyProperty(apps, "brave", () => detectPlatformBinary({
109985
- darwin: "brave browser",
109986
- win32: "brave",
109987
- linux: ["brave-browser", "brave"]
109988
- }, {
109989
- wsl: {
109990
- ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
109991
- x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
109904
+ };
109905
+
109906
+ // src/server/tools/response/error.ts
109907
+ var buildMcpError = (content, options) => {
109908
+ return {
109909
+ content,
109910
+ // Default: omit isError so siblings survive parallel calls.
109911
+ // Tools with outputSchema MUST pass isError: true so the SDK
109912
+ // skips output validation on error paths.
109913
+ ...options?.isError ? { isError: true } : {}
109914
+ };
109915
+ };
109916
+ var mcpErrorJson = (error48, options) => {
109917
+ return safeStringifyJson("mcp-error-json", error48).match(
109918
+ (success3) => buildMcpError([{ type: "text", text: success3 }], options),
109919
+ (error49) => buildMcpError(
109920
+ [{ type: "text", text: JSON.stringify(error49, null, 2) }],
109921
+ options
109922
+ )
109923
+ );
109924
+ };
109925
+ var mcpError = async (err3, options) => {
109926
+ const { error: error48 } = err3;
109927
+ if (isFetchError(error48)) {
109928
+ switch (error48.cause) {
109929
+ case "network":
109930
+ case "parse":
109931
+ return mcpErrorJson({ ...error48 }, options);
109932
+ case "http":
109933
+ const { response, ...rest } = error48;
109934
+ const parseResponseResult = await safeParseResponse(
109935
+ "mcp-error-fetch-parse-response",
109936
+ response
109937
+ );
109938
+ const httpContent = [
109939
+ { type: "text", text: JSON.stringify(rest, null, 2) },
109940
+ ...parseResponseResult.match(
109941
+ (success3) => [parsedResponseToToolContentPart(success3)],
109942
+ () => []
109943
+ )
109944
+ ];
109945
+ return buildMcpError(httpContent, options);
109946
+ }
109992
109947
  }
109993
- }));
109994
- defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
109995
- darwin: "firefox",
109996
- win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
109997
- linux: "firefox"
109998
- }, {
109999
- wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
110000
- }));
110001
- defineLazyProperty(apps, "edge", () => detectPlatformBinary({
110002
- darwin: "microsoft edge",
110003
- win32: "msedge",
110004
- linux: ["microsoft-edge", "microsoft-edge-dev"]
110005
- }, {
110006
- wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
110007
- }));
110008
- defineLazyProperty(apps, "safari", () => detectPlatformBinary({
110009
- darwin: "Safari"
110010
- }));
110011
- var open_default = open;
109948
+ return mcpErrorJson({ ...error48 }, options);
109949
+ };
109950
+ var mcpErrorFetch = async (surface2, response) => {
109951
+ return mcpError(fetchHttpErr(surface2, response));
109952
+ };
110012
109953
 
110013
- // src/shared/utils.ts
110014
- var getBaseUrl = (dev) => {
110015
- return dev ? "http://localhost:3000" : "https://agentcash.dev";
109954
+ // src/server/tools/response/success.ts
109955
+ var buildMcpSuccess = (content) => {
109956
+ return {
109957
+ content
109958
+ };
110016
109959
  };
110017
- var getDepositLink = (address, flags) => {
110018
- return `${getBaseUrl(flags.dev)}/deposit/${address}`;
109960
+ var mcpSuccessJson = (data) => {
109961
+ return safeStringifyJson("mcp-success-text", data).match(
109962
+ (success3) => buildMcpSuccess([{ type: "text", text: success3 }]),
109963
+ (error48) => mcpErrorJson(error48)
109964
+ );
110019
109965
  };
110020
- var openDepositLink = async (address, flags) => {
110021
- const depositLink = getDepositLink(address, flags);
110022
- await open_default(depositLink);
109966
+ var mcpSuccessStructuredJson = (data) => {
109967
+ return safeStringifyJson("mcp-success-structured", data).match(
109968
+ (success3) => ({
109969
+ content: [{ type: "text", text: success3 }],
109970
+ structuredContent: data
109971
+ }),
109972
+ (error48) => mcpErrorJson(error48)
109973
+ );
109974
+ };
109975
+ var mcpSuccessResponse = (data, extra) => {
109976
+ const parsedExtra = extra ? safeStringifyJson("mcp-success-extra", extra).match(
109977
+ (success3) => success3,
109978
+ () => void 0
109979
+ ) : void 0;
109980
+ return buildMcpSuccess([
109981
+ parsedResponseToToolContentPart(data),
109982
+ ...parsedExtra ? [{ type: "text", text: parsedExtra }] : []
109983
+ ]);
109984
+ };
109985
+
109986
+ // src/server/tools/response/safe-handler.ts
109987
+ init_cjs_shims();
109988
+ function safeHandler(handler) {
109989
+ return async (input) => {
109990
+ try {
109991
+ return await handler(input);
109992
+ } catch (e) {
109993
+ log.error("Unhandled tool error", e);
109994
+ return mcpErrorJson({
109995
+ error: e instanceof Error ? e.message : String(e),
109996
+ cause: "unhandled_exception"
109997
+ });
109998
+ }
109999
+ };
110000
+ }
110001
+
110002
+ // src/server/tools/lib/request.ts
110003
+ init_cjs_shims();
110004
+ var requestSchema = zod_default.object({
110005
+ url: zod_default.string().describe("The endpoint URL"),
110006
+ method: zod_default.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).optional().describe("HTTP method. Defaults to GET for fetch operations."),
110007
+ body: zod_default.unknown().optional().describe("Request body for POST/PUT/PATCH methods"),
110008
+ headers: zod_default.record(zod_default.string(), zod_default.string()).optional().describe("Additional headers to include").default({}),
110009
+ timeout: zod_default.number().int().positive().optional().describe("Request timeout in milliseconds")
110010
+ });
110011
+ var buildRequest2 = ({
110012
+ input,
110013
+ address,
110014
+ sessionId,
110015
+ provider
110016
+ }) => {
110017
+ return new Request(input.url, {
110018
+ method: input.method ?? "GET",
110019
+ body: input.body ? typeof input.body === "string" ? input.body : JSON.stringify(input.body) : void 0,
110020
+ headers: {
110021
+ ...input.body ? { "Content-Type": "application/json" } : {},
110022
+ ...input.headers,
110023
+ ...address ? { "X-Wallet-Address": address, "X-Client-ID": provider } : {},
110024
+ ...sessionId ? { "X-Session-ID": sessionId } : {}
110025
+ }
110026
+ });
110023
110027
  };
110024
110028
 
110025
110029
  // src/server/tools/lib/check-balance.ts
110030
+ init_cjs_shims();
110026
110031
  var checkBalance = async ({
110027
110032
  server,
110028
110033
  address,
@@ -110031,7 +110036,11 @@ var checkBalance = async ({
110031
110036
  flags,
110032
110037
  surface: surface2
110033
110038
  }) => {
110034
- const balanceResult = await getBalance3({ address, surface: surface2 });
110039
+ const balanceResult = await getBalance3({
110040
+ address,
110041
+ surface: surface2,
110042
+ dev: flags.dev
110043
+ });
110035
110044
  if (balanceResult.isErr()) {
110036
110045
  log.error(JSON.stringify(balanceResult.error, null, 2));
110037
110046
  return;
@@ -110345,7 +110354,7 @@ init_cjs_shims();
110345
110354
  init_cjs_shims();
110346
110355
  async function getWalletInfo(surface2, address, flags) {
110347
110356
  const balancePromises = [
110348
- getBalance3({ address, surface: surface2 }),
110357
+ getBalance3({ address, surface: surface2, dev: flags.dev }),
110349
110358
  isMppEnabled() ? getTempoBalance({ address, tokenAddress: TEMPO_TOKEN_ADDRESS }).then((r) => Number(formatUnits(r.balance, 6))).catch((e) => {
110350
110359
  log.info(`Failed to fetch Tempo balance: ${e}`);
110351
110360
  return null;
@@ -110646,6 +110655,33 @@ var SUPPORTED_METHODS = [
110646
110655
  "DELETE",
110647
110656
  "PATCH"
110648
110657
  ];
110658
+ function derivePaymentRequirement(protocols, paymentOptions, hasSiwxExtension) {
110659
+ const hasPaymentOptions = paymentOptions.length > 0;
110660
+ const isSiwxOnly = hasSiwxExtension && !hasPaymentOptions;
110661
+ if (isSiwxOnly) {
110662
+ return {
110663
+ requiresPayment: false,
110664
+ protocols: []
110665
+ };
110666
+ }
110667
+ return {
110668
+ requiresPayment: true,
110669
+ protocols
110670
+ };
110671
+ }
110672
+ function deriveSpecFallbackPaymentRequirement(schema, estimatedPrice) {
110673
+ if (!schema || typeof schema !== "object") return true;
110674
+ const op = schema;
110675
+ const hasPaymentInfo = Boolean(op["x-payment-info"]);
110676
+ const security = op.security;
110677
+ const hasSiwxSecurity = Array.isArray(security) && security.some(
110678
+ (entry) => entry != null && typeof entry === "object" && "siwx" in entry
110679
+ );
110680
+ if (hasSiwxSecurity && !hasPaymentInfo && !estimatedPrice) {
110681
+ return false;
110682
+ }
110683
+ return true;
110684
+ }
110649
110685
  async function checkEndpoint({
110650
110686
  surface: surface2,
110651
110687
  url: url3,
@@ -110731,12 +110767,16 @@ async function probeMethod({
110731
110767
  protocols2 = indexResult2.value.protocols;
110732
110768
  }
110733
110769
  }
110770
+ const requiresPayment = deriveSpecFallbackPaymentRequirement(
110771
+ schema2,
110772
+ estimatedPrice2
110773
+ );
110734
110774
  return {
110735
110775
  method,
110736
- requiresPayment: true,
110776
+ requiresPayment,
110737
110777
  statusCode: 402,
110738
110778
  schema: schema2,
110739
- ...protocols2 ? { protocols: protocols2 } : {},
110779
+ ...requiresPayment && protocols2 ? { protocols: protocols2 } : {},
110740
110780
  ...estimatedPrice2 ? { estimatedPrice: estimatedPrice2 } : {},
110741
110781
  ...summary2 ? { summary: summary2 } : {}
110742
110782
  };
@@ -110768,6 +110808,7 @@ async function probeMethod({
110768
110808
  }
110769
110809
  const protocols = detectPaymentProtocols(response);
110770
110810
  const paymentOptions = [];
110811
+ let hasSiwxExtension = false;
110771
110812
  let schema;
110772
110813
  const endpointSchemaResult = await schemaPromise;
110773
110814
  if (endpointSchemaResult.isOk() && endpointSchemaResult.value) {
@@ -110809,6 +110850,7 @@ async function probeMethod({
110809
110850
  );
110810
110851
  if (paymentRequiredResult.isOk()) {
110811
110852
  const { resource, extensions, accepts } = paymentRequiredResult.value;
110853
+ hasSiwxExtension = !!extensions && typeof extensions === "object" && "sign-in-with-x" in extensions;
110812
110854
  if (!schema) {
110813
110855
  const inputSchema = getInputSchema(extensions);
110814
110856
  if (inputSchema) schema = inputSchema;
@@ -110847,9 +110889,8 @@ async function probeMethod({
110847
110889
  }
110848
110890
  return {
110849
110891
  method,
110850
- requiresPayment: true,
110892
+ ...derivePaymentRequirement(protocols, paymentOptions, hasSiwxExtension),
110851
110893
  statusCode: response.status,
110852
- protocols,
110853
110894
  paymentOptions,
110854
110895
  ...schema ? { schema } : {},
110855
110896
  ...estimatedPrice ? { estimatedPrice } : {},
@@ -110950,6 +110991,19 @@ init_cjs_shims();
110950
110991
  // src/shared/redeem-invite.ts
110951
110992
  init_cjs_shims();
110952
110993
 
110994
+ // src/shared/origins.ts
110995
+ init_cjs_shims();
110996
+ var ORIGINS = [
110997
+ "https://stableenrich.dev" /* StableEnrich */,
110998
+ "https://stablesocial.dev" /* StableSocial */,
110999
+ "https://stablestudio.dev" /* StableStudio */,
111000
+ "https://stableupload.dev" /* StableUpload */,
111001
+ "https://stableemail.dev" /* StableEmail */,
111002
+ "https://x402scan.com" /* X402Scan */,
111003
+ "https://shirt.sh" /* Shirt */,
111004
+ "https://x402puppet.com" /* X402Puppet */
111005
+ ];
111006
+
110953
111007
  // src/shared/state.ts
110954
111008
  init_cjs_shims();
110955
111009
  var import_fs4 = __toESM(require("fs"), 1);
@@ -110979,7 +111033,6 @@ var setState = (state) => {
110979
111033
  // src/shared/redeem-invite.ts
110980
111034
  var redeemInviteCode = async ({
110981
111035
  code,
110982
- dev,
110983
111036
  address,
110984
111037
  surface: surface2
110985
111038
  }) => {
@@ -110992,7 +111045,7 @@ var redeemInviteCode = async ({
110992
111045
  }
110993
111046
  const result = await safeFetchJson(
110994
111047
  surface2,
110995
- new Request(`${getBaseUrl(dev)}/api/invite/redeem`, {
111048
+ new Request(`${"https://x402scan.com" /* X402Scan */}/api/invite/redeem`, {
110996
111049
  method: "POST",
110997
111050
  headers: {
110998
111051
  "Content-Type": "application/json"
@@ -111019,8 +111072,7 @@ var redeemInviteCode = async ({
111019
111072
  // src/server/tools/redeem-invite.ts
111020
111073
  var registerRedeemInviteTool = ({
111021
111074
  server,
111022
- account: { address },
111023
- flags
111075
+ account: { address }
111024
111076
  }) => {
111025
111077
  server.registerTool(
111026
111078
  "redeem_invite",
@@ -111048,7 +111100,6 @@ var registerRedeemInviteTool = ({
111048
111100
  async ({ code }) => {
111049
111101
  const result = await redeemInviteCode({
111050
111102
  code,
111051
- dev: flags.dev,
111052
111103
  address,
111053
111104
  surface: "redeem_invite"
111054
111105
  });
@@ -111175,19 +111226,6 @@ var registerTelemetryTools = ({
111175
111226
  // src/server/tools/discover-resources.ts
111176
111227
  init_cjs_shims();
111177
111228
 
111178
- // src/shared/origins.ts
111179
- init_cjs_shims();
111180
- var ORIGINS = [
111181
- "https://stableenrich.dev" /* StableEnrich */,
111182
- "https://stablesocial.dev" /* StableSocial */,
111183
- "https://stablestudio.dev" /* StableStudio */,
111184
- "https://stableupload.dev" /* StableUpload */,
111185
- "https://stableemail.dev" /* StableEmail */,
111186
- "https://x402scan.com" /* X402Scan */,
111187
- "https://shirt.sh" /* Shirt */,
111188
- "https://x402puppet.com" /* X402Puppet */
111189
- ];
111190
-
111191
111229
  // src/shared/operations/discover.ts
111192
111230
  init_cjs_shims();
111193
111231
  async function fetchLlmsTxt(surface2, origin) {
@@ -111205,6 +111243,9 @@ async function fetchLlmsTxt(surface2, origin) {
111205
111243
  return parseResult.value.data;
111206
111244
  }
111207
111245
  async function discoverResources(surface2, url3) {
111246
+ if (!/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(url3)) {
111247
+ url3 = `https://${url3}`;
111248
+ }
111208
111249
  const origin = URL.canParse(url3) ? new URL(url3).origin : url3;
111209
111250
  log.info(`Discovering resources for origin: ${origin}`);
111210
111251
  const [specResult, instructions] = await Promise.all([
@@ -111233,6 +111274,7 @@ async function discoverResources(surface2, url3) {
111233
111274
  ...typeof rawInfo.description === "string" ? { description: rawInfo.description } : {}
111234
111275
  } : void 0;
111235
111276
  return {
111277
+ found: true,
111236
111278
  origin,
111237
111279
  source: "openapi",
111238
111280
  ...info ? { info } : {},
@@ -111820,7 +111862,7 @@ var import_path3 = require("path");
111820
111862
  var import_url2 = require("url");
111821
111863
  function getVersion3() {
111822
111864
  if (true) {
111823
- return "0.6.4";
111865
+ return "0.6.6";
111824
111866
  }
111825
111867
  const __dirname3 = (0, import_path3.dirname)((0, import_url2.fileURLToPath)(importMetaUrl));
111826
111868
  const pkg = JSON.parse(
@@ -112007,7 +112049,7 @@ async function getWallet() {
112007
112049
  // src/server/index.ts
112008
112050
  var startServer = async (flags) => {
112009
112051
  log.info("Starting agentcash...");
112010
- const { dev, invite } = flags;
112052
+ const { invite } = flags;
112011
112053
  let { sessionId } = flags;
112012
112054
  sessionId ??= (0, import_crypto2.randomBytes)(16).toString("hex");
112013
112055
  const walletResult = await getWallet();
@@ -112021,7 +112063,6 @@ var startServer = async (flags) => {
112021
112063
  if (code) {
112022
112064
  await redeemInviteCode({
112023
112065
  code,
112024
- dev,
112025
112066
  address: account.address,
112026
112067
  surface: "startServer"
112027
112068
  });