agentcash 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/cjs/run-server.cjs +1158 -1099
  2. package/dist/esm/{check-endpoint-BGFpMl2m.d.ts → check-endpoint-Df0YnKdr.d.ts} +8 -3
  3. package/dist/esm/{chunk-VU4O2YQU.js → chunk-5MGZ3UGG.js} +90 -44
  4. package/dist/esm/chunk-5MGZ3UGG.js.map +1 -0
  5. package/dist/esm/{chunk-2RSGMWFW.js → chunk-EYF7JMMC.js} +5 -5
  6. package/dist/esm/chunk-EYF7JMMC.js.map +1 -0
  7. package/dist/esm/chunk-F5ZDNWEA.js +7 -0
  8. package/dist/esm/{chunk-KFYFGEC4.js → chunk-PLBNJ647.js} +2 -2
  9. package/dist/esm/{chunk-XVQ7S42P.js → chunk-VUTE3VTW.js} +7 -6
  10. package/dist/esm/chunk-VUTE3VTW.js.map +1 -0
  11. package/dist/esm/{chunk-FJNT5GH6.js → chunk-W3V4VWAR.js} +2 -2
  12. package/dist/esm/{chunk-LOEINYA7.js → chunk-WBLOSD2E.js} +3 -3
  13. package/dist/esm/{chunk-UFSCGP67.js → chunk-YUCA2PQT.js} +23 -19
  14. package/dist/esm/chunk-YUCA2PQT.js.map +1 -0
  15. package/dist/esm/{commands-JAPV6DQL.js → commands-5GTG7HKC.js} +17 -12
  16. package/dist/esm/{commands-JAPV6DQL.js.map → commands-5GTG7HKC.js.map} +1 -1
  17. package/dist/esm/{fund-BVBH76XD.js → fund-WZGVUR2S.js} +4 -4
  18. package/dist/esm/index.js +21 -13
  19. package/dist/esm/index.js.map +1 -1
  20. package/dist/esm/{install-DTZT2V7I.js → install-A6TREGKW.js} +7 -6
  21. package/dist/esm/{install-DTZT2V7I.js.map → install-A6TREGKW.js.map} +1 -1
  22. package/dist/esm/lib.d.ts +1 -1
  23. package/dist/esm/lib.js +2 -2
  24. package/dist/esm/lib.js.map +1 -1
  25. package/dist/esm/{server-I6GY7YDA.js → server-4CN2V4WJ.js} +27 -17
  26. package/dist/esm/server-4CN2V4WJ.js.map +1 -0
  27. package/dist/esm/shared/operations/index.d.ts +1 -1
  28. package/dist/esm/shared/operations/index.js +5 -5
  29. package/dist/esm/shared/operations/index.js.map +1 -1
  30. package/package.json +3 -3
  31. package/dist/esm/chunk-2RSGMWFW.js.map +0 -1
  32. package/dist/esm/chunk-UFSCGP67.js.map +0 -1
  33. package/dist/esm/chunk-VU4O2YQU.js.map +0 -1
  34. package/dist/esm/chunk-XVQ7S42P.js.map +0 -1
  35. package/dist/esm/chunk-ZPI2XP7U.js +0 -7
  36. package/dist/esm/server-I6GY7YDA.js.map +0 -1
  37. /package/dist/esm/{chunk-ZPI2XP7U.js.map → chunk-F5ZDNWEA.js.map} +0 -0
  38. /package/dist/esm/{chunk-KFYFGEC4.js.map → chunk-PLBNJ647.js.map} +0 -0
  39. /package/dist/esm/{chunk-FJNT5GH6.js.map → chunk-W3V4VWAR.js.map} +0 -0
  40. /package/dist/esm/{chunk-LOEINYA7.js.map → chunk-WBLOSD2E.js.map} +0 -0
  41. /package/dist/esm/{fund-BVBH76XD.js.map → fund-WZGVUR2S.js.map} +0 -0
@@ -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.3";
104306
+ return "0.6.5";
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.3".includes("-mpp");
104469
+ var isMppEnabled = () => "0.6.5".includes("-mpp");
104470
104470
 
104471
104471
  // src/shared/operations/fetch-with-payment.ts
104472
104472
  init_cjs_shims();
@@ -108877,1152 +108877,1157 @@ 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
108880
 
108899
- // src/shared/tempo-balance.ts
108881
+ // src/shared/utils.ts
108900
108882
  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
108883
 
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
- };
108884
+ // ../../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
108885
+ init_cjs_shims();
108886
+ var import_node_process8 = __toESM(require("process"), 1);
108887
+ var import_node_path = __toESM(require("path"), 1);
108888
+ var import_node_url = require("url");
108889
+ var import_node_child_process7 = __toESM(require("child_process"), 1);
108890
+ var import_promises4 = __toESM(require("fs/promises"), 1);
108891
+
108892
+ // ../../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js
108893
+ init_cjs_shims();
108894
+ var import_node_util2 = require("util");
108895
+ var import_node_child_process2 = __toESM(require("child_process"), 1);
108896
+ var import_promises3 = __toESM(require("fs/promises"), 1);
108897
+
108898
+ // ../../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
108899
+ init_cjs_shims();
108900
+ var import_node_process2 = __toESM(require("process"), 1);
108901
+ var import_node_os = __toESM(require("os"), 1);
108902
+ var import_node_fs3 = __toESM(require("fs"), 1);
108903
+
108904
+ // ../../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
108905
+ init_cjs_shims();
108906
+ var import_node_fs2 = __toESM(require("fs"), 1);
108907
+
108908
+ // ../../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
108909
+ init_cjs_shims();
108910
+ var import_node_fs = __toESM(require("fs"), 1);
108911
+ var isDockerCached;
108912
+ function hasDockerEnv() {
108913
+ try {
108914
+ import_node_fs.default.statSync("/.dockerenv");
108915
+ return true;
108916
+ } catch {
108917
+ return false;
108918
+ }
108980
108919
  }
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";
108920
+ function hasDockerCGroup() {
108921
+ try {
108922
+ return import_node_fs.default.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
108923
+ } catch {
108924
+ return false;
108998
108925
  }
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
- }
108926
+ }
108927
+ function isDocker() {
108928
+ if (isDockerCached === void 0) {
108929
+ isDockerCached = hasDockerEnv() || hasDockerCGroup();
109022
108930
  }
109023
- log.info(`Protocol selection \u2014 x402: $${x402Balance}, mpp: $${mppBalance}`);
109024
- return x402Balance >= mppBalance ? "x402" : "mpp";
108931
+ return isDockerCached;
109025
108932
  }
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;
108933
+
108934
+ // ../../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
108935
+ var cachedResult;
108936
+ var hasContainerEnv = () => {
108937
+ try {
108938
+ import_node_fs2.default.statSync("/run/.containerenv");
108939
+ return true;
108940
+ } catch {
108941
+ return false;
109034
108942
  }
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
- }
108943
+ };
108944
+ function isInsideContainer() {
108945
+ if (cachedResult === void 0) {
108946
+ cachedResult = hasContainerEnv() || isDocker();
109058
108947
  }
109059
- const paymentPayloadResult = await safeCreatePaymentPayload(
109060
- surface2,
109061
- client,
109062
- paymentRequired
109063
- );
109064
- if (paymentPayloadResult.isErr()) {
109065
- return paymentPayloadResult;
108948
+ return cachedResult;
108949
+ }
108950
+
108951
+ // ../../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
108952
+ var isWsl = () => {
108953
+ if (import_node_process2.default.platform !== "linux") {
108954
+ return false;
109066
108955
  }
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
- });
108956
+ if (import_node_os.default.release().toLowerCase().includes("microsoft")) {
108957
+ if (isInsideContainer()) {
108958
+ return false;
108959
+ }
108960
+ return true;
109074
108961
  }
109075
- for (const [key, value] of Object.entries(paymentHeaders)) {
109076
- clonedRequest.headers.set(key, value);
108962
+ try {
108963
+ return import_node_fs3.default.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
108964
+ } catch {
108965
+ return false;
109077
108966
  }
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
- });
108967
+ };
108968
+ var is_wsl_default = import_node_process2.default.env.__IS_WSL_TEST__ ? isWsl : isWsl();
108969
+
108970
+ // ../../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js
108971
+ init_cjs_shims();
108972
+ var import_node_process3 = __toESM(require("process"), 1);
108973
+ var import_node_buffer = require("buffer");
108974
+ var import_node_util = require("util");
108975
+ var import_node_child_process = __toESM(require("child_process"), 1);
108976
+ var import_promises2 = __toESM(require("fs/promises"), 1);
108977
+ var execFile = (0, import_node_util.promisify)(import_node_child_process.default.execFile);
108978
+ var powerShellPath = () => `${import_node_process3.default.env.SYSTEMROOT || import_node_process3.default.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
108979
+ var executePowerShell = async (command, options = {}) => {
108980
+ const {
108981
+ powerShellPath: psPath,
108982
+ ...execFileOptions
108983
+ } = options;
108984
+ const encodedCommand = executePowerShell.encodeCommand(command);
108985
+ return execFile(
108986
+ psPath ?? powerShellPath(),
108987
+ [
108988
+ ...executePowerShell.argumentsPrefix,
108989
+ encodedCommand
108990
+ ],
108991
+ {
108992
+ encoding: "utf8",
108993
+ ...execFileOptions
109107
108994
  }
109108
108995
  );
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;
108996
+ };
108997
+ executePowerShell.argumentsPrefix = [
108998
+ "-NoProfile",
108999
+ "-NonInteractive",
109000
+ "-ExecutionPolicy",
109001
+ "Bypass",
109002
+ "-EncodedCommand"
109003
+ ];
109004
+ executePowerShell.encodeCommand = (command) => import_node_buffer.Buffer.from(command, "utf16le").toString("base64");
109005
+ executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
109006
+
109007
+ // ../../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/utilities.js
109008
+ init_cjs_shims();
109009
+ function parseMountPointFromConfig(content) {
109010
+ for (const line of content.split("\n")) {
109011
+ if (/^\s*#/.test(line)) {
109012
+ continue;
109013
+ }
109014
+ const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
109015
+ if (!match) {
109016
+ continue;
109017
+ }
109018
+ return match.groups.mountPoint.trim().replaceAll(/^["']|["']$/g, "");
109122
109019
  }
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);
109020
+ }
109021
+
109022
+ // ../../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js
109023
+ var execFile2 = (0, import_node_util2.promisify)(import_node_child_process2.default.execFile);
109024
+ var wslDrivesMountPoint = /* @__PURE__ */ (() => {
109025
+ const defaultMountPoint = "/mnt/";
109026
+ let mountPoint;
109027
+ return async function() {
109028
+ if (mountPoint) {
109029
+ return mountPoint;
109030
+ }
109031
+ const configFilePath = "/etc/wsl.conf";
109032
+ let isConfigFileExists = false;
109033
+ try {
109034
+ await import_promises3.default.access(configFilePath, import_promises3.constants.F_OK);
109035
+ isConfigFileExists = true;
109036
+ } catch {
109037
+ }
109038
+ if (!isConfigFileExists) {
109039
+ return defaultMountPoint;
109040
+ }
109041
+ const configContent = await import_promises3.default.readFile(configFilePath, { encoding: "utf8" });
109042
+ const parsedMountPoint = parseMountPointFromConfig(configContent);
109043
+ if (parsedMountPoint === void 0) {
109044
+ return defaultMountPoint;
109045
+ }
109046
+ mountPoint = parsedMountPoint;
109047
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
109048
+ return mountPoint;
109049
+ };
109050
+ })();
109051
+ var powerShellPathFromWsl = async () => {
109052
+ const mountPoint = await wslDrivesMountPoint();
109053
+ return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
109054
+ };
109055
+ var powerShellPath2 = is_wsl_default ? powerShellPathFromWsl : powerShellPath;
109056
+ var canAccessPowerShellPromise;
109057
+ var canAccessPowerShell = async () => {
109058
+ canAccessPowerShellPromise ??= (async () => {
109059
+ try {
109060
+ const psPath = await powerShellPath2();
109061
+ await import_promises3.default.access(psPath, import_promises3.constants.X_OK);
109062
+ return true;
109063
+ } catch {
109064
+ return false;
109145
109065
  }
109066
+ })();
109067
+ return canAccessPowerShellPromise;
109068
+ };
109069
+ var wslDefaultBrowser = async () => {
109070
+ const psPath = await powerShellPath2();
109071
+ const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
109072
+ const { stdout } = await executePowerShell(command, { powerShellPath: psPath });
109073
+ return stdout.trim();
109074
+ };
109075
+ var convertWslPathToWindows = async (path2) => {
109076
+ if (/^[a-z]+:\/\//i.test(path2)) {
109077
+ return path2;
109146
109078
  }
109147
- const credentialResult = await safeCreateMppCredential(
109148
- surface2,
109149
- mppxClient,
109150
- response
109151
- );
109152
- if (credentialResult.isErr()) {
109153
- return credentialResult;
109079
+ try {
109080
+ const { stdout } = await execFile2("wslpath", ["-aw", path2], { encoding: "utf8" });
109081
+ return stdout.trim();
109082
+ } catch {
109083
+ return path2;
109154
109084
  }
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
- });
109085
+ };
109086
+
109087
+ // ../../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
109088
+ init_cjs_shims();
109089
+ function defineLazyProperty(object3, propertyName, valueGetter) {
109090
+ const define = (value) => Object.defineProperty(object3, propertyName, { value, enumerable: true, writable: true });
109091
+ Object.defineProperty(object3, propertyName, {
109092
+ configurable: true,
109093
+ enumerable: true,
109094
+ get() {
109095
+ const result = valueGetter();
109096
+ define(result);
109097
+ return result;
109098
+ },
109099
+ set(value) {
109100
+ define(value);
109180
109101
  }
109181
- );
109102
+ });
109103
+ return object3;
109182
109104
  }
109183
109105
 
109184
- // src/server/tools/response/index.ts
109106
+ // ../../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
109185
109107
  init_cjs_shims();
109108
+ var import_node_util6 = require("util");
109109
+ var import_node_process6 = __toESM(require("process"), 1);
109110
+ var import_node_child_process6 = require("child_process");
109186
109111
 
109187
- // src/server/tools/response/success.ts
109112
+ // ../../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
109188
109113
  init_cjs_shims();
109114
+ var import_node_util3 = require("util");
109115
+ var import_node_process4 = __toESM(require("process"), 1);
109116
+ var import_node_child_process3 = require("child_process");
109117
+ var execFileAsync = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
109118
+ async function defaultBrowserId() {
109119
+ if (import_node_process4.default.platform !== "darwin") {
109120
+ throw new Error("macOS only");
109121
+ }
109122
+ const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
109123
+ const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
109124
+ const browserId = match?.groups.id ?? "com.apple.Safari";
109125
+ if (browserId === "com.apple.safari") {
109126
+ return "com.apple.Safari";
109127
+ }
109128
+ return browserId;
109129
+ }
109189
109130
 
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
109131
+ // ../../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
109221
109132
  init_cjs_shims();
109222
109133
 
109223
- // src/server/tools/response/lib.ts
109134
+ // ../../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
109224
109135
  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
- };
109136
+ var import_node_process5 = __toESM(require("process"), 1);
109137
+ var import_node_util4 = require("util");
109138
+ var import_node_child_process4 = require("child_process");
109139
+ var execFileAsync2 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
109140
+ async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
109141
+ if (import_node_process5.default.platform !== "darwin") {
109142
+ throw new Error("macOS only");
109251
109143
  }
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
- }
109144
+ const outputArguments = humanReadableOutput ? [] : ["-ss"];
109145
+ const execOptions = {};
109146
+ if (signal) {
109147
+ execOptions.signal = signal;
109295
109148
  }
109296
- return mcpErrorJson({ ...error48 }, options);
109297
- };
109298
- var mcpErrorFetch = async (surface2, response) => {
109299
- return mcpError(fetchHttpErr(surface2, response));
109300
- };
109149
+ const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
109150
+ return stdout.trim();
109151
+ }
109301
109152
 
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
- );
109153
+ // ../../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
109154
+ async function bundleName(bundleId) {
109155
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
109156
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
109157
+ }
109158
+
109159
+ // ../../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
109160
+ init_cjs_shims();
109161
+ var import_node_util5 = require("util");
109162
+ var import_node_child_process5 = require("child_process");
109163
+ var execFileAsync3 = (0, import_node_util5.promisify)(import_node_child_process5.execFile);
109164
+ var windowsBrowserProgIds = {
109165
+ MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
109166
+ // The missing `L` is correct.
109167
+ MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
109168
+ MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
109169
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
109170
+ ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
109171
+ ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
109172
+ ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
109173
+ ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
109174
+ BraveHTML: { name: "Brave", id: "com.brave.Browser" },
109175
+ BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
109176
+ BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
109177
+ BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
109178
+ FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
109179
+ OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
109180
+ VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
109181
+ "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
109313
109182
  };
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
- );
109183
+ var _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
109184
+ var UnknownBrowserError = class extends Error {
109322
109185
  };
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 }] : []
109186
+ async function defaultBrowser(_execFileAsync = execFileAsync3) {
109187
+ const { stdout } = await _execFileAsync("reg", [
109188
+ "QUERY",
109189
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
109190
+ "/v",
109191
+ "ProgId"
109331
109192
  ]);
109332
- };
109193
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
109194
+ if (!match) {
109195
+ throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
109196
+ }
109197
+ const { id } = match.groups;
109198
+ const dotIndex = id.lastIndexOf(".");
109199
+ const hyphenIndex = id.lastIndexOf("-");
109200
+ const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
109201
+ const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
109202
+ return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? { name: id, id };
109203
+ }
109333
109204
 
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
- };
109205
+ // ../../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
109206
+ var execFileAsync4 = (0, import_node_util6.promisify)(import_node_child_process6.execFile);
109207
+ var titleize = (string6) => string6.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
109208
+ async function defaultBrowser2() {
109209
+ if (import_node_process6.default.platform === "darwin") {
109210
+ const id = await defaultBrowserId();
109211
+ const name = await bundleName(id);
109212
+ return { name, id };
109213
+ }
109214
+ if (import_node_process6.default.platform === "linux") {
109215
+ const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
109216
+ const id = stdout.trim();
109217
+ const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
109218
+ return { name, id };
109219
+ }
109220
+ if (import_node_process6.default.platform === "win32") {
109221
+ return defaultBrowser();
109222
+ }
109223
+ throw new Error("Only macOS, Linux, and Windows are supported");
109348
109224
  }
109349
109225
 
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
-
109380
- // src/shared/utils.ts
109226
+ // ../../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js
109381
109227
  init_cjs_shims();
109228
+ var import_node_process7 = __toESM(require("process"), 1);
109229
+ var isInSsh = Boolean(import_node_process7.default.env.SSH_CONNECTION || import_node_process7.default.env.SSH_CLIENT || import_node_process7.default.env.SSH_TTY);
109230
+ var is_in_ssh_default = isInSsh;
109382
109231
 
109383
109232
  // ../../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
109384
- init_cjs_shims();
109385
- var import_node_process8 = __toESM(require("process"), 1);
109386
- var import_node_path = __toESM(require("path"), 1);
109387
- var import_node_url = require("url");
109388
- var import_node_child_process7 = __toESM(require("child_process"), 1);
109389
- var import_promises4 = __toESM(require("fs/promises"), 1);
109390
-
109391
- // ../../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js
109392
- init_cjs_shims();
109393
- var import_node_util2 = require("util");
109394
- var import_node_child_process2 = __toESM(require("child_process"), 1);
109395
- var import_promises3 = __toESM(require("fs/promises"), 1);
109396
-
109397
- // ../../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
109398
- init_cjs_shims();
109399
- var import_node_process2 = __toESM(require("process"), 1);
109400
- var import_node_os = __toESM(require("os"), 1);
109401
- var import_node_fs3 = __toESM(require("fs"), 1);
109402
-
109403
- // ../../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
109404
- init_cjs_shims();
109405
- var import_node_fs2 = __toESM(require("fs"), 1);
109406
-
109407
- // ../../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
109408
- init_cjs_shims();
109409
- var import_node_fs = __toESM(require("fs"), 1);
109410
- var isDockerCached;
109411
- function hasDockerEnv() {
109412
- try {
109413
- import_node_fs.default.statSync("/.dockerenv");
109414
- return true;
109415
- } catch {
109416
- return false;
109417
- }
109418
- }
109419
- function hasDockerCGroup() {
109420
- try {
109421
- return import_node_fs.default.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
109422
- } catch {
109423
- return false;
109424
- }
109425
- }
109426
- function isDocker() {
109427
- if (isDockerCached === void 0) {
109428
- isDockerCached = hasDockerEnv() || hasDockerCGroup();
109233
+ var fallbackAttemptSymbol = /* @__PURE__ */ Symbol("fallbackAttempt");
109234
+ var __dirname2 = importMetaUrl ? import_node_path.default.dirname((0, import_node_url.fileURLToPath)(importMetaUrl)) : "";
109235
+ var localXdgOpenPath = import_node_path.default.join(__dirname2, "xdg-open");
109236
+ var { platform, arch } = import_node_process8.default;
109237
+ var tryEachApp = async (apps2, opener) => {
109238
+ if (apps2.length === 0) {
109239
+ return;
109429
109240
  }
109430
- return isDockerCached;
109431
- }
109432
-
109433
- // ../../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
109434
- var cachedResult;
109435
- var hasContainerEnv = () => {
109436
- try {
109437
- import_node_fs2.default.statSync("/run/.containerenv");
109438
- return true;
109439
- } catch {
109440
- return false;
109241
+ const errors = [];
109242
+ for (const app of apps2) {
109243
+ try {
109244
+ return await opener(app);
109245
+ } catch (error48) {
109246
+ errors.push(error48);
109247
+ }
109441
109248
  }
109249
+ throw new AggregateError(errors, "Failed to open in all supported apps");
109442
109250
  };
109443
- function isInsideContainer() {
109444
- if (cachedResult === void 0) {
109445
- cachedResult = hasContainerEnv() || isDocker();
109251
+ var baseOpen = async (options) => {
109252
+ options = {
109253
+ wait: false,
109254
+ background: false,
109255
+ newInstance: false,
109256
+ allowNonzeroExitCode: false,
109257
+ ...options
109258
+ };
109259
+ const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
109260
+ delete options[fallbackAttemptSymbol];
109261
+ if (Array.isArray(options.app)) {
109262
+ return tryEachApp(options.app, (singleApp) => baseOpen({
109263
+ ...options,
109264
+ app: singleApp,
109265
+ [fallbackAttemptSymbol]: true
109266
+ }));
109446
109267
  }
109447
- return cachedResult;
109448
- }
109449
-
109450
- // ../../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
109451
- var isWsl = () => {
109452
- if (import_node_process2.default.platform !== "linux") {
109453
- return false;
109268
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
109269
+ appArguments = [...appArguments];
109270
+ if (Array.isArray(app)) {
109271
+ return tryEachApp(app, (appName) => baseOpen({
109272
+ ...options,
109273
+ app: {
109274
+ name: appName,
109275
+ arguments: appArguments
109276
+ },
109277
+ [fallbackAttemptSymbol]: true
109278
+ }));
109454
109279
  }
109455
- if (import_node_os.default.release().toLowerCase().includes("microsoft")) {
109456
- if (isInsideContainer()) {
109457
- return false;
109280
+ if (app === "browser" || app === "browserPrivate") {
109281
+ const ids = {
109282
+ "com.google.chrome": "chrome",
109283
+ "google-chrome.desktop": "chrome",
109284
+ "com.brave.browser": "brave",
109285
+ "org.mozilla.firefox": "firefox",
109286
+ "firefox.desktop": "firefox",
109287
+ "com.microsoft.msedge": "edge",
109288
+ "com.microsoft.edge": "edge",
109289
+ "com.microsoft.edgemac": "edge",
109290
+ "microsoft-edge.desktop": "edge",
109291
+ "com.apple.safari": "safari"
109292
+ };
109293
+ const flags = {
109294
+ chrome: "--incognito",
109295
+ brave: "--incognito",
109296
+ firefox: "--private-window",
109297
+ edge: "--inPrivate"
109298
+ // Safari doesn't support private mode via command line
109299
+ };
109300
+ let browser;
109301
+ if (is_wsl_default) {
109302
+ const progId = await wslDefaultBrowser();
109303
+ const browserInfo = _windowsBrowserProgIdMap.get(progId);
109304
+ browser = browserInfo ?? {};
109305
+ } else {
109306
+ browser = await defaultBrowser2();
109458
109307
  }
109459
- return true;
109308
+ if (browser.id in ids) {
109309
+ const browserName = ids[browser.id.toLowerCase()];
109310
+ if (app === "browserPrivate") {
109311
+ if (browserName === "safari") {
109312
+ throw new Error("Safari doesn't support opening in private mode via command line");
109313
+ }
109314
+ appArguments.push(flags[browserName]);
109315
+ }
109316
+ return baseOpen({
109317
+ ...options,
109318
+ app: {
109319
+ name: apps[browserName],
109320
+ arguments: appArguments
109321
+ }
109322
+ });
109323
+ }
109324
+ throw new Error(`${browser.name} is not supported as a default browser`);
109460
109325
  }
109461
- try {
109462
- return import_node_fs3.default.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
109463
- } catch {
109464
- return false;
109326
+ let command;
109327
+ const cliArguments = [];
109328
+ const childProcessOptions = {};
109329
+ let shouldUseWindowsInWsl = false;
109330
+ if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) {
109331
+ shouldUseWindowsInWsl = await canAccessPowerShell();
109465
109332
  }
109466
- };
109467
- var is_wsl_default = import_node_process2.default.env.__IS_WSL_TEST__ ? isWsl : isWsl();
109468
-
109469
- // ../../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js
109470
- init_cjs_shims();
109471
- var import_node_process3 = __toESM(require("process"), 1);
109472
- var import_node_buffer = require("buffer");
109473
- var import_node_util = require("util");
109474
- var import_node_child_process = __toESM(require("child_process"), 1);
109475
- var import_promises2 = __toESM(require("fs/promises"), 1);
109476
- var execFile = (0, import_node_util.promisify)(import_node_child_process.default.execFile);
109477
- var powerShellPath = () => `${import_node_process3.default.env.SYSTEMROOT || import_node_process3.default.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
109478
- var executePowerShell = async (command, options = {}) => {
109479
- const {
109480
- powerShellPath: psPath,
109481
- ...execFileOptions
109482
- } = options;
109483
- const encodedCommand = executePowerShell.encodeCommand(command);
109484
- return execFile(
109485
- psPath ?? powerShellPath(),
109486
- [
109487
- ...executePowerShell.argumentsPrefix,
109488
- encodedCommand
109489
- ],
109490
- {
109491
- encoding: "utf8",
109492
- ...execFileOptions
109333
+ if (platform === "darwin") {
109334
+ command = "open";
109335
+ if (options.wait) {
109336
+ cliArguments.push("--wait-apps");
109493
109337
  }
109494
- );
109495
- };
109496
- executePowerShell.argumentsPrefix = [
109497
- "-NoProfile",
109498
- "-NonInteractive",
109499
- "-ExecutionPolicy",
109500
- "Bypass",
109501
- "-EncodedCommand"
109502
- ];
109503
- executePowerShell.encodeCommand = (command) => import_node_buffer.Buffer.from(command, "utf16le").toString("base64");
109504
- executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
109505
-
109506
- // ../../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/utilities.js
109507
- init_cjs_shims();
109508
- function parseMountPointFromConfig(content) {
109509
- for (const line of content.split("\n")) {
109510
- if (/^\s*#/.test(line)) {
109511
- continue;
109338
+ if (options.background) {
109339
+ cliArguments.push("--background");
109512
109340
  }
109513
- const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
109514
- if (!match) {
109515
- continue;
109341
+ if (options.newInstance) {
109342
+ cliArguments.push("--new");
109516
109343
  }
109517
- return match.groups.mountPoint.trim().replaceAll(/^["']|["']$/g, "");
109518
- }
109519
- }
109520
-
109521
- // ../../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js
109522
- var execFile2 = (0, import_node_util2.promisify)(import_node_child_process2.default.execFile);
109523
- var wslDrivesMountPoint = /* @__PURE__ */ (() => {
109524
- const defaultMountPoint = "/mnt/";
109525
- let mountPoint;
109526
- return async function() {
109527
- if (mountPoint) {
109528
- return mountPoint;
109344
+ if (app) {
109345
+ cliArguments.push("-a", app);
109529
109346
  }
109530
- const configFilePath = "/etc/wsl.conf";
109531
- let isConfigFileExists = false;
109532
- try {
109533
- await import_promises3.default.access(configFilePath, import_promises3.constants.F_OK);
109534
- isConfigFileExists = true;
109535
- } catch {
109347
+ } else if (platform === "win32" || shouldUseWindowsInWsl) {
109348
+ command = await powerShellPath2();
109349
+ cliArguments.push(...executePowerShell.argumentsPrefix);
109350
+ if (!is_wsl_default) {
109351
+ childProcessOptions.windowsVerbatimArguments = true;
109536
109352
  }
109537
- if (!isConfigFileExists) {
109538
- return defaultMountPoint;
109353
+ if (is_wsl_default && options.target) {
109354
+ options.target = await convertWslPathToWindows(options.target);
109539
109355
  }
109540
- const configContent = await import_promises3.default.readFile(configFilePath, { encoding: "utf8" });
109541
- const parsedMountPoint = parseMountPointFromConfig(configContent);
109542
- if (parsedMountPoint === void 0) {
109543
- return defaultMountPoint;
109356
+ const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
109357
+ if (options.wait) {
109358
+ encodedArguments.push("-Wait");
109544
109359
  }
109545
- mountPoint = parsedMountPoint;
109546
- mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
109547
- return mountPoint;
109548
- };
109549
- })();
109550
- var powerShellPathFromWsl = async () => {
109551
- const mountPoint = await wslDrivesMountPoint();
109552
- return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
109553
- };
109554
- var powerShellPath2 = is_wsl_default ? powerShellPathFromWsl : powerShellPath;
109555
- var canAccessPowerShellPromise;
109556
- var canAccessPowerShell = async () => {
109557
- canAccessPowerShellPromise ??= (async () => {
109558
- try {
109559
- const psPath = await powerShellPath2();
109560
- await import_promises3.default.access(psPath, import_promises3.constants.X_OK);
109561
- return true;
109562
- } catch {
109563
- return false;
109360
+ if (app) {
109361
+ encodedArguments.push(executePowerShell.escapeArgument(app));
109362
+ if (options.target) {
109363
+ appArguments.push(options.target);
109364
+ }
109365
+ } else if (options.target) {
109366
+ encodedArguments.push(executePowerShell.escapeArgument(options.target));
109367
+ }
109368
+ if (appArguments.length > 0) {
109369
+ appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
109370
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
109371
+ }
109372
+ options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
109373
+ if (!options.wait) {
109374
+ childProcessOptions.stdio = "ignore";
109375
+ }
109376
+ } else {
109377
+ if (app) {
109378
+ command = app;
109379
+ } else {
109380
+ const isBundled = !__dirname2 || __dirname2 === "/";
109381
+ let exeLocalXdgOpen = false;
109382
+ try {
109383
+ await import_promises4.default.access(localXdgOpenPath, import_promises4.constants.X_OK);
109384
+ exeLocalXdgOpen = true;
109385
+ } catch {
109386
+ }
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;
109564
109396
  }
109565
- })();
109566
- return canAccessPowerShellPromise;
109567
- };
109568
- var wslDefaultBrowser = async () => {
109569
- const psPath = await powerShellPath2();
109570
- const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
109571
- const { stdout } = await executePowerShell(command, { powerShellPath: psPath });
109572
- return stdout.trim();
109573
- };
109574
- var convertWslPathToWindows = async (path2) => {
109575
- if (/^[a-z]+:\/\//i.test(path2)) {
109576
- return path2;
109577
109397
  }
109578
- try {
109579
- const { stdout } = await execFile2("wslpath", ["-aw", path2], { encoding: "utf8" });
109580
- return stdout.trim();
109581
- } catch {
109582
- return path2;
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
+ });
109583
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
+ });
109584
109441
  };
109585
-
109586
- // ../../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
109587
- init_cjs_shims();
109588
- function defineLazyProperty(object3, propertyName, valueGetter) {
109589
- const define = (value) => Object.defineProperty(object3, propertyName, { value, enumerable: true, writable: true });
109590
- Object.defineProperty(object3, propertyName, {
109591
- configurable: true,
109592
- enumerable: true,
109593
- get() {
109594
- const result = valueGetter();
109595
- define(result);
109596
- return result;
109597
- },
109598
- set(value) {
109599
- define(value);
109600
- }
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
109601
109449
  });
109602
- return object3;
109603
- }
109604
-
109605
- // ../../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
109606
- init_cjs_shims();
109607
- var import_node_util6 = require("util");
109608
- var import_node_process6 = __toESM(require("process"), 1);
109609
- var import_node_child_process6 = require("child_process");
109610
-
109611
- // ../../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
109612
- init_cjs_shims();
109613
- var import_node_util3 = require("util");
109614
- var import_node_process4 = __toESM(require("process"), 1);
109615
- var import_node_child_process3 = require("child_process");
109616
- var execFileAsync = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
109617
- async function defaultBrowserId() {
109618
- if (import_node_process4.default.platform !== "darwin") {
109619
- throw new Error("macOS only");
109450
+ };
109451
+ function detectArchBinary(binary) {
109452
+ if (typeof binary === "string" || Array.isArray(binary)) {
109453
+ return binary;
109620
109454
  }
109621
- const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
109622
- const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
109623
- const browserId = match?.groups.id ?? "com.apple.Safari";
109624
- if (browserId === "com.apple.safari") {
109625
- return "com.apple.Safari";
109455
+ const { [arch]: archBinary } = binary;
109456
+ if (!archBinary) {
109457
+ throw new Error(`${arch} is not supported`);
109626
109458
  }
109627
- return browserId;
109459
+ return archBinary;
109628
109460
  }
109629
-
109630
- // ../../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
109631
- init_cjs_shims();
109632
-
109633
- // ../../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
109634
- init_cjs_shims();
109635
- var import_node_process5 = __toESM(require("process"), 1);
109636
- var import_node_util4 = require("util");
109637
- var import_node_child_process4 = require("child_process");
109638
- var execFileAsync2 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
109639
- async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
109640
- if (import_node_process5.default.platform !== "darwin") {
109641
- throw new Error("macOS only");
109461
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
109462
+ if (wsl && is_wsl_default) {
109463
+ return detectArchBinary(wsl);
109642
109464
  }
109643
- const outputArguments = humanReadableOutput ? [] : ["-ss"];
109644
- const execOptions = {};
109645
- if (signal) {
109646
- execOptions.signal = signal;
109465
+ if (!platformBinary) {
109466
+ throw new Error(`${platform} is not supported`);
109647
109467
  }
109648
- const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
109649
- return stdout.trim();
109650
- }
109651
-
109652
- // ../../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
109653
- async function bundleName(bundleId) {
109654
- return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
109655
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
109468
+ return detectArchBinary(platformBinary);
109656
109469
  }
109657
-
109658
- // ../../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
109659
- init_cjs_shims();
109660
- var import_node_util5 = require("util");
109661
- var import_node_child_process5 = require("child_process");
109662
- var execFileAsync3 = (0, import_node_util5.promisify)(import_node_child_process5.execFile);
109663
- var windowsBrowserProgIds = {
109664
- MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
109665
- // The missing `L` is correct.
109666
- MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
109667
- MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
109668
- AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
109669
- ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
109670
- ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
109671
- ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
109672
- ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
109673
- BraveHTML: { name: "Brave", id: "com.brave.Browser" },
109674
- BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
109675
- BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
109676
- BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
109677
- FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
109678
- OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
109679
- VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
109680
- "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
109681
- };
109682
- var _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
109683
- var UnknownBrowserError = class extends Error {
109470
+ var apps = {
109471
+ browser: "browser",
109472
+ browserPrivate: "browserPrivate"
109684
109473
  };
109685
- async function defaultBrowser(_execFileAsync = execFileAsync3) {
109686
- const { stdout } = await _execFileAsync("reg", [
109687
- "QUERY",
109688
- " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
109689
- "/v",
109690
- "ProgId"
109691
- ]);
109692
- const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
109693
- if (!match) {
109694
- throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
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"]
109695
109483
  }
109696
- const { id } = match.groups;
109697
- const dotIndex = id.lastIndexOf(".");
109698
- const hyphenIndex = id.lastIndexOf("-");
109699
- const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
109700
- const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
109701
- return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? { name: id, id };
109702
- }
109703
-
109704
- // ../../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
109705
- var execFileAsync4 = (0, import_node_util6.promisify)(import_node_child_process6.execFile);
109706
- var titleize = (string6) => string6.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
109707
- async function defaultBrowser2() {
109708
- if (import_node_process6.default.platform === "darwin") {
109709
- const id = await defaultBrowserId();
109710
- const name = await bundleName(id);
109711
- return { name, id };
109712
- }
109713
- if (import_node_process6.default.platform === "linux") {
109714
- const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
109715
- const id = stdout.trim();
109716
- const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
109717
- return { name, id };
109718
- }
109719
- if (import_node_process6.default.platform === "win32") {
109720
- return defaultBrowser();
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"]
109721
109493
  }
109722
- throw new Error("Only macOS, Linux, and Windows are supported");
109723
- }
109724
-
109725
- // ../../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js
109726
- init_cjs_shims();
109727
- var import_node_process7 = __toESM(require("process"), 1);
109728
- var isInSsh = Boolean(import_node_process7.default.env.SSH_CONNECTION || import_node_process7.default.env.SSH_CLIENT || import_node_process7.default.env.SSH_TTY);
109729
- var is_in_ssh_default = isInSsh;
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;
109730
109513
 
109731
- // ../../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
109732
- var fallbackAttemptSymbol = /* @__PURE__ */ Symbol("fallbackAttempt");
109733
- var __dirname2 = importMetaUrl ? import_node_path.default.dirname((0, import_node_url.fileURLToPath)(importMetaUrl)) : "";
109734
- var localXdgOpenPath = import_node_path.default.join(__dirname2, "xdg-open");
109735
- var { platform, arch } = import_node_process8.default;
109736
- var tryEachApp = async (apps2, opener) => {
109737
- if (apps2.length === 0) {
109738
- return;
109739
- }
109740
- const errors = [];
109741
- for (const app of apps2) {
109742
- try {
109743
- return await opener(app);
109744
- } catch (error48) {
109745
- errors.push(error48);
109746
- }
109747
- }
109748
- throw new AggregateError(errors, "Failed to open in all supported apps");
109514
+ // src/shared/utils.ts
109515
+ var getBaseUrl = (dev) => {
109516
+ return dev ? "http://localhost:3000" : "https://agentcash.dev";
109749
109517
  };
109750
- var baseOpen = async (options) => {
109751
- options = {
109752
- wait: false,
109753
- background: false,
109754
- newInstance: false,
109755
- allowNonzeroExitCode: false,
109756
- ...options
109757
- };
109758
- const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
109759
- delete options[fallbackAttemptSymbol];
109760
- if (Array.isArray(options.app)) {
109761
- return tryEachApp(options.app, (singleApp) => baseOpen({
109762
- ...options,
109763
- app: singleApp,
109764
- [fallbackAttemptSymbol]: true
109765
- }));
109766
- }
109767
- let { name: app, arguments: appArguments = [] } = options.app ?? {};
109768
- appArguments = [...appArguments];
109769
- if (Array.isArray(app)) {
109770
- return tryEachApp(app, (appName) => baseOpen({
109771
- ...options,
109772
- app: {
109773
- name: appName,
109774
- arguments: appArguments
109775
- },
109776
- [fallbackAttemptSymbol]: true
109777
- }));
109778
- }
109779
- if (app === "browser" || app === "browserPrivate") {
109780
- const ids = {
109781
- "com.google.chrome": "chrome",
109782
- "google-chrome.desktop": "chrome",
109783
- "com.brave.browser": "brave",
109784
- "org.mozilla.firefox": "firefox",
109785
- "firefox.desktop": "firefox",
109786
- "com.microsoft.msedge": "edge",
109787
- "com.microsoft.edge": "edge",
109788
- "com.microsoft.edgemac": "edge",
109789
- "microsoft-edge.desktop": "edge",
109790
- "com.apple.safari": "safari"
109791
- };
109792
- const flags = {
109793
- chrome: "--incognito",
109794
- brave: "--incognito",
109795
- firefox: "--private-window",
109796
- edge: "--inPrivate"
109797
- // Safari doesn't support private mode via command line
109798
- };
109799
- let browser;
109800
- if (is_wsl_default) {
109801
- const progId = await wslDefaultBrowser();
109802
- const browserInfo = _windowsBrowserProgIdMap.get(progId);
109803
- browser = browserInfo ?? {};
109804
- } else {
109805
- browser = await defaultBrowser2();
109806
- }
109807
- if (browser.id in ids) {
109808
- const browserName = ids[browser.id.toLowerCase()];
109809
- if (app === "browserPrivate") {
109810
- if (browserName === "safari") {
109811
- throw new Error("Safari doesn't support opening in private mode via command line");
109812
- }
109813
- appArguments.push(flags[browserName]);
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"
109814
109540
  }
109815
- return baseOpen({
109816
- ...options,
109817
- app: {
109818
- name: apps[browserName],
109819
- arguments: appArguments
109820
- }
109821
- });
109822
- }
109823
- throw new Error(`${browser.name} is not supported as a default browser`);
109824
- }
109825
- let command;
109826
- const cliArguments = [];
109827
- const childProcessOptions = {};
109828
- let shouldUseWindowsInWsl = false;
109829
- if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) {
109830
- shouldUseWindowsInWsl = await canAccessPowerShell();
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}`);
109831
109564
  }
109832
- if (platform === "darwin") {
109833
- command = "open";
109834
- if (options.wait) {
109835
- cliArguments.push("--wait-apps");
109836
- }
109837
- if (options.background) {
109838
- cliArguments.push("--background");
109839
- }
109840
- if (options.newInstance) {
109841
- cliArguments.push("--new");
109842
- }
109843
- if (app) {
109844
- cliArguments.push("-a", app);
109845
- }
109846
- } else if (platform === "win32" || shouldUseWindowsInWsl) {
109847
- command = await powerShellPath2();
109848
- cliArguments.push(...executePowerShell.argumentsPrefix);
109849
- if (!is_wsl_default) {
109850
- childProcessOptions.windowsVerbatimArguments = true;
109851
- }
109852
- if (is_wsl_default && options.target) {
109853
- options.target = await convertWslPathToWindows(options.target);
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);
109854
109583
  }
109855
- const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
109856
- if (options.wait) {
109857
- encodedArguments.push("-Wait");
109584
+ if (probeResult.value.status !== 402) {
109585
+ return probeResult.andThen(
109586
+ (response2) => fetchOk({ response: response2, paymentInfo: null })
109587
+ );
109858
109588
  }
109859
- if (app) {
109860
- encodedArguments.push(executePowerShell.escapeArgument(app));
109861
- if (options.target) {
109862
- appArguments.push(options.target);
109589
+ const response = probeResult.value;
109590
+ if (paymentMethod !== "auto") {
109591
+ if (paymentMethod === "mpp") {
109592
+ return handleMppPayment(surface2, response, clonedRequest, options);
109863
109593
  }
109864
- } else if (options.target) {
109865
- encodedArguments.push(executePowerShell.escapeArgument(options.target));
109594
+ return handleX402Payment(
109595
+ surface2,
109596
+ response,
109597
+ clonedRequest,
109598
+ clients.x402,
109599
+ beforePayment,
109600
+ timeout
109601
+ );
109866
109602
  }
109867
- if (appArguments.length > 0) {
109868
- appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
109869
- encodedArguments.push("-ArgumentList", appArguments.join(","));
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);
109870
109609
  }
109871
- options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
109872
- if (!options.wait) {
109873
- childProcessOptions.stdio = "ignore";
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
+ );
109874
109628
  }
109875
- } else {
109876
- if (app) {
109877
- command = app;
109878
- } else {
109879
- const isBundled = !__dirname2 || __dirname2 === "/";
109880
- let exeLocalXdgOpen = false;
109881
- try {
109882
- await import_promises4.default.access(localXdgOpenPath, import_promises4.constants.X_OK);
109883
- exeLocalXdgOpen = true;
109884
- } catch {
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));
109885
109672
  }
109886
- const useSystemXdgOpen = import_node_process8.default.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
109887
- command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
109888
109673
  }
109889
- if (appArguments.length > 0) {
109890
- cliArguments.push(...appArguments);
109891
- }
109892
- if (!options.wait) {
109893
- childProcessOptions.stdio = "ignore";
109894
- childProcessOptions.detached = true;
109674
+ }
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;
109686
+ }
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
+ }
109895
109709
  }
109896
109710
  }
109897
- if (platform === "darwin" && appArguments.length > 0) {
109898
- cliArguments.push("--args", ...appArguments);
109711
+ const paymentPayloadResult = await safeCreatePaymentPayload(
109712
+ surface2,
109713
+ client,
109714
+ paymentRequired
109715
+ );
109716
+ if (paymentPayloadResult.isErr()) {
109717
+ return paymentPayloadResult;
109899
109718
  }
109900
- if (options.target) {
109901
- cliArguments.push(options.target);
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"
109725
+ });
109902
109726
  }
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;
109727
+ for (const [key, value] of Object.entries(paymentHeaders)) {
109728
+ clonedRequest.headers.set(key, value);
109729
+ }
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
+ } : {}
109911
109757
  }
109912
- resolve(subprocess);
109913
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"
109914
109769
  });
109915
109770
  }
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
- });
109771
+ const challengeResult = safeGetMppChallenge(surface2, response);
109772
+ if (challengeResult.isErr()) {
109773
+ return challengeResult;
109774
+ }
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
+ }
109798
+ }
109799
+ const credentialResult = await safeCreateMppCredential(
109800
+ surface2,
109801
+ mppxClient,
109802
+ response
109803
+ );
109804
+ if (credentialResult.isErr()) {
109805
+ return credentialResult;
109806
+ }
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
+ }
109929
109831
  });
109930
- });
109832
+ }
109833
+ );
109834
+ }
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);
109847
+ };
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
+ };
109931
109903
  }
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
109904
  };
109941
- var open = (target, options) => {
109942
- if (typeof target !== "string") {
109943
- throw new TypeError("Expected a `target`");
109944
- }
109945
- return baseOpen({
109946
- ...options,
109947
- target
109948
- });
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
+ };
109949
109915
  };
109950
- function detectArchBinary(binary) {
109951
- if (typeof binary === "string" || Array.isArray(binary)) {
109952
- return binary;
109953
- }
109954
- const { [arch]: archBinary } = binary;
109955
- if (!archBinary) {
109956
- throw new Error(`${arch} is not supported`);
109957
- }
109958
- return archBinary;
109959
- }
109960
- function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
109961
- if (wsl && is_wsl_default) {
109962
- return detectArchBinary(wsl);
109963
- }
109964
- if (!platformBinary) {
109965
- throw new Error(`${platform} is not supported`);
109966
- }
109967
- return detectArchBinary(platformBinary);
109968
- }
109969
- var apps = {
109970
- browser: "browser",
109971
- browserPrivate: "browserPrivate"
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
+ );
109972
109924
  };
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"]
109982
- }
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"]
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;
@@ -110427,14 +110436,16 @@ init_cjs_shims();
110427
110436
 
110428
110437
  // src/shared/openapi-cache.ts
110429
110438
  init_cjs_shims();
110430
- var specCache = /* @__PURE__ */ new Map();
110439
+ var OPENAPI_SPEC_PATHS = [
110440
+ "/openapi.json",
110441
+ "/.well-known/openapi.json"
110442
+ ];
110431
110443
  async function fetchOpenApiSpec(origin) {
110432
- const cached2 = specCache.get(origin);
110433
- if (cached2) return cached2;
110434
- const uniqueUrls = [
110435
- `${origin}/openapi.json`,
110436
- `${origin}/.well-known/openapi.json`
110437
- ];
110444
+ const uniqueUrls = OPENAPI_SPEC_PATHS.map((p) => `${origin}${p}`);
110445
+ let failure = {
110446
+ ok: false,
110447
+ cause: "not_found"
110448
+ };
110438
110449
  for (const url3 of uniqueUrls) {
110439
110450
  log.debug(`Fetching OpenAPI spec from: ${url3}`);
110440
110451
  const fetchResult = await safeFetch(
@@ -110443,6 +110454,10 @@ async function fetchOpenApiSpec(origin) {
110443
110454
  DEFAULT_FETCH_TIMEOUT
110444
110455
  );
110445
110456
  if (fetchResult.isErr()) {
110457
+ const { cause, message } = fetchResult.error;
110458
+ if (cause === "network" || cause === "timeout") {
110459
+ failure = { ok: false, cause, message };
110460
+ }
110446
110461
  log.debug(`Failed to fetch OpenAPI spec from: ${url3}`);
110447
110462
  continue;
110448
110463
  }
@@ -110458,18 +110473,24 @@ async function fetchOpenApiSpec(origin) {
110458
110473
  })
110459
110474
  );
110460
110475
  if (jsonResult.isErr()) {
110461
- log.debug(`Failed to fetch OpenAPI spec from: ${url3}`);
110476
+ if (failure.cause === "not_found") {
110477
+ failure = {
110478
+ ok: false,
110479
+ cause: "parse",
110480
+ message: `Failed to parse JSON from: ${url3}`
110481
+ };
110482
+ }
110483
+ log.debug(`Failed to parse OpenAPI spec from: ${url3}`);
110462
110484
  continue;
110463
110485
  }
110464
110486
  const spec = jsonResult.value;
110465
110487
  if (spec && typeof spec === "object" && spec.paths) {
110466
- specCache.set(origin, spec);
110467
- log.info(`Cached OpenAPI spec for origin: ${origin}`);
110468
- return spec;
110488
+ log.info(`Fetched OpenAPI spec for origin: ${origin}`);
110489
+ return { ok: true, spec };
110469
110490
  }
110470
110491
  }
110471
110492
  log.debug(`No OpenAPI spec found for origin: ${origin}`);
110472
- return null;
110493
+ return failure;
110473
110494
  }
110474
110495
  function resolveRef2(spec, ref, seen) {
110475
110496
  if (!ref.startsWith("#/")) return void 0;
@@ -110524,8 +110545,9 @@ function extractPath(url3, origin) {
110524
110545
  async function getEndpointSchema(endpointUrl, method) {
110525
110546
  if (!URL.canParse(endpointUrl)) return null;
110526
110547
  const origin = new URL(endpointUrl).origin;
110527
- const spec = await fetchOpenApiSpec(origin);
110528
- if (!spec) return null;
110548
+ const result = await fetchOpenApiSpec(origin);
110549
+ if (!result.ok) return null;
110550
+ const spec = result.spec;
110529
110551
  const paths = spec.paths;
110530
110552
  if (!paths) return null;
110531
110553
  const path2 = extractPath(endpointUrl, origin);
@@ -110556,12 +110578,10 @@ async function getEndpointSchema(endpointUrl, method) {
110556
110578
  const resolved = resolveRefs(spec, operation, /* @__PURE__ */ new Set());
110557
110579
  return { path: path2, method: httpMethod, ...resolved };
110558
110580
  }
110559
- var indexCache = /* @__PURE__ */ new Map();
110560
110581
  async function getOriginIndex(origin) {
110561
- const cached2 = indexCache.get(origin);
110562
- if (cached2) return cached2;
110563
- const spec = await fetchOpenApiSpec(origin);
110564
- if (!spec?.paths) return null;
110582
+ const result = await fetchOpenApiSpec(origin);
110583
+ if (!result.ok) return null;
110584
+ const spec = result.spec;
110565
110585
  const endpoints = [];
110566
110586
  for (const [path2, methods] of Object.entries(
110567
110587
  spec.paths
@@ -110585,7 +110605,6 @@ async function getOriginIndex(origin) {
110585
110605
  }
110586
110606
  }
110587
110607
  }
110588
- indexCache.set(origin, endpoints);
110589
110608
  return endpoints;
110590
110609
  }
110591
110610
  var OPENAPI_HTTP_METHODS = /* @__PURE__ */ new Set([
@@ -110601,9 +110620,9 @@ var OPENAPI_HTTP_METHODS = /* @__PURE__ */ new Set([
110601
110620
  async function getSpecMethods(endpointUrl) {
110602
110621
  if (!URL.canParse(endpointUrl)) return null;
110603
110622
  const origin = new URL(endpointUrl).origin;
110604
- const spec = await fetchOpenApiSpec(origin);
110605
- if (!spec?.paths) return null;
110606
- const paths = spec.paths;
110623
+ const result = await fetchOpenApiSpec(origin);
110624
+ if (!result.ok) return null;
110625
+ const paths = result.spec.paths;
110607
110626
  const path2 = extractPath(endpointUrl, origin);
110608
110627
  let pathEntry = paths[path2];
110609
110628
  if (!pathEntry) {
@@ -110620,8 +110639,8 @@ async function getSpecMethods(endpointUrl) {
110620
110639
  if (!pathEntry) return null;
110621
110640
  return Object.keys(pathEntry).filter((k) => OPENAPI_HTTP_METHODS.has(k)).map((k) => k.toUpperCase());
110622
110641
  }
110623
- function getIndexEntry(origin, path2, method) {
110624
- const entries = indexCache.get(origin);
110642
+ async function getIndexEntry(origin, path2, method) {
110643
+ const entries = await getOriginIndex(origin);
110625
110644
  if (!entries) return void 0;
110626
110645
  const m = method.toUpperCase();
110627
110646
  return entries.find((e) => e.path === path2 && e.method === m);
@@ -110636,6 +110655,33 @@ var SUPPORTED_METHODS = [
110636
110655
  "DELETE",
110637
110656
  "PATCH"
110638
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
+ }
110639
110685
  async function checkEndpoint({
110640
110686
  surface: surface2,
110641
110687
  url: url3,
@@ -110700,14 +110746,14 @@ async function probeMethod({
110700
110746
  if (!schema2) return null;
110701
110747
  let estimatedPrice2;
110702
110748
  let summary2;
110703
- const indexResult2 = resultFromThrowable(
110749
+ const indexResult2 = await resultFromPromise(
110704
110750
  "openapi",
110705
110751
  surface2,
110706
- () => {
110752
+ (async () => {
110707
110753
  const origin = new URL(url3).origin;
110708
110754
  const path2 = new URL(url3).pathname || "/";
110709
110755
  return getIndexEntry(origin, path2, method);
110710
- },
110756
+ })(),
110711
110757
  (e) => ({
110712
110758
  cause: "index_lookup",
110713
110759
  message: e instanceof Error ? e.message : String(e)
@@ -110721,12 +110767,16 @@ async function probeMethod({
110721
110767
  protocols2 = indexResult2.value.protocols;
110722
110768
  }
110723
110769
  }
110770
+ const requiresPayment = deriveSpecFallbackPaymentRequirement(
110771
+ schema2,
110772
+ estimatedPrice2
110773
+ );
110724
110774
  return {
110725
110775
  method,
110726
- requiresPayment: true,
110776
+ requiresPayment,
110727
110777
  statusCode: 402,
110728
110778
  schema: schema2,
110729
- ...protocols2 ? { protocols: protocols2 } : {},
110779
+ ...requiresPayment && protocols2 ? { protocols: protocols2 } : {},
110730
110780
  ...estimatedPrice2 ? { estimatedPrice: estimatedPrice2 } : {},
110731
110781
  ...summary2 ? { summary: summary2 } : {}
110732
110782
  };
@@ -110758,6 +110808,7 @@ async function probeMethod({
110758
110808
  }
110759
110809
  const protocols = detectPaymentProtocols(response);
110760
110810
  const paymentOptions = [];
110811
+ let hasSiwxExtension = false;
110761
110812
  let schema;
110762
110813
  const endpointSchemaResult = await schemaPromise;
110763
110814
  if (endpointSchemaResult.isOk() && endpointSchemaResult.value) {
@@ -110799,6 +110850,7 @@ async function probeMethod({
110799
110850
  );
110800
110851
  if (paymentRequiredResult.isOk()) {
110801
110852
  const { resource, extensions, accepts } = paymentRequiredResult.value;
110853
+ hasSiwxExtension = !!extensions && typeof extensions === "object" && "sign-in-with-x" in extensions;
110802
110854
  if (!schema) {
110803
110855
  const inputSchema = getInputSchema(extensions);
110804
110856
  if (inputSchema) schema = inputSchema;
@@ -110818,14 +110870,14 @@ async function probeMethod({
110818
110870
  }
110819
110871
  let estimatedPrice;
110820
110872
  let summary;
110821
- const indexResult = resultFromThrowable(
110873
+ const indexResult = await resultFromPromise(
110822
110874
  "openapi",
110823
110875
  surface2,
110824
- () => {
110876
+ (async () => {
110825
110877
  const origin = new URL(url3).origin;
110826
110878
  const path2 = new URL(url3).pathname || "/";
110827
110879
  return getIndexEntry(origin, path2, method);
110828
- },
110880
+ })(),
110829
110881
  (e) => ({
110830
110882
  cause: "index_lookup",
110831
110883
  message: e instanceof Error ? e.message : String(e)
@@ -110837,9 +110889,8 @@ async function probeMethod({
110837
110889
  }
110838
110890
  return {
110839
110891
  method,
110840
- requiresPayment: true,
110892
+ ...derivePaymentRequirement(protocols, paymentOptions, hasSiwxExtension),
110841
110893
  statusCode: response.status,
110842
- protocols,
110843
110894
  paymentOptions,
110844
110895
  ...schema ? { schema } : {},
110845
110896
  ...estimatedPrice ? { estimatedPrice } : {},
@@ -111173,7 +111224,6 @@ var ORIGINS = [
111173
111224
  "https://stablestudio.dev" /* StableStudio */,
111174
111225
  "https://stableupload.dev" /* StableUpload */,
111175
111226
  "https://stableemail.dev" /* StableEmail */,
111176
- "https://stablejobs.dev" /* StableJobs */,
111177
111227
  "https://x402scan.com" /* X402Scan */,
111178
111228
  "https://shirt.sh" /* Shirt */,
111179
111229
  "https://x402puppet.com" /* X402Puppet */
@@ -111198,20 +111248,23 @@ async function fetchLlmsTxt(surface2, origin) {
111198
111248
  async function discoverResources(surface2, url3) {
111199
111249
  const origin = URL.canParse(url3) ? new URL(url3).origin : url3;
111200
111250
  log.info(`Discovering resources for origin: ${origin}`);
111201
- const [spec, instructions] = await Promise.all([
111251
+ const [specResult, instructions] = await Promise.all([
111202
111252
  fetchOpenApiSpec(origin),
111203
111253
  fetchLlmsTxt(surface2, origin)
111204
111254
  ]);
111205
- if (!spec?.paths) {
111206
- log.debug(
111207
- `No OpenAPI spec found for ${origin}. Tried: /openapi.json, /.well-known/openapi.json`
111208
- );
111209
- return null;
111255
+ if (!specResult.ok) {
111256
+ log.debug(`No OpenAPI spec found for ${origin}: ${specResult.cause}`);
111257
+ return {
111258
+ found: false,
111259
+ cause: specResult.cause,
111260
+ ..."message" in specResult ? { message: specResult.message } : {}
111261
+ };
111210
111262
  }
111263
+ const spec = specResult.spec;
111211
111264
  const endpoints = await getOriginIndex(origin);
111212
111265
  if (!endpoints || endpoints.length === 0) {
111213
111266
  log.debug(`OpenAPI spec found for ${origin} but no endpoints extracted`);
111214
- return null;
111267
+ return { found: false, cause: "not_found" };
111215
111268
  }
111216
111269
  log.info(`Found ${endpoints.length} endpoints for: ${origin}`);
111217
111270
  const rawInfo = spec.info;
@@ -111295,7 +111348,7 @@ function registerDiscoveryTools(server) {
111295
111348
  return mcpError(discoverResult);
111296
111349
  }
111297
111350
  const result = discoverResult.value;
111298
- if (result) {
111351
+ if ("endpoints" in result) {
111299
111352
  return mcpSuccessJson({
111300
111353
  found: true,
111301
111354
  origin: result.origin,
@@ -111307,10 +111360,20 @@ function registerDiscoveryTools(server) {
111307
111360
  });
111308
111361
  }
111309
111362
  const origin = URL.canParse(url3) ? new URL(url3).origin : url3;
111363
+ const tried = OPENAPI_SPEC_PATHS.join(", ");
111364
+ if (result.cause === "not_found") {
111365
+ return mcpSuccessJson({
111366
+ found: false,
111367
+ origin,
111368
+ error: `No OpenAPI spec found. Tried: ${tried}`
111369
+ });
111370
+ }
111310
111371
  return mcpSuccessJson({
111311
111372
  found: false,
111312
111373
  origin,
111313
- error: "No OpenAPI spec found. Tried: /openapi.json, /.well-known/openapi.json"
111374
+ cause: result.cause,
111375
+ error: result.message ?? `Failed to fetch OpenAPI spec (${result.cause})`,
111376
+ hint: result.cause === "timeout" ? "The server may be slow or unreachable. Try again later." : result.cause === "network" ? "Could not reach the server. Check the network connection and try again." : `The server returned an unparseable response. Tried: ${tried}`
111314
111377
  });
111315
111378
  })
111316
111379
  );
@@ -111339,10 +111402,6 @@ var ORIGIN_METADATA = {
111339
111402
  title: "StableEmail",
111340
111403
  description: "Send emails"
111341
111404
  },
111342
- ["https://stablejobs.dev" /* StableJobs */]: {
111343
- title: "StableJobs",
111344
- description: "Search job postings"
111345
- },
111346
111405
  ["https://x402scan.com" /* X402Scan */]: {
111347
111406
  title: "X402 Scan",
111348
111407
  description: "x402 protocol explorer"
@@ -111802,7 +111861,7 @@ var import_path3 = require("path");
111802
111861
  var import_url2 = require("url");
111803
111862
  function getVersion3() {
111804
111863
  if (true) {
111805
- return "0.6.3";
111864
+ return "0.6.5";
111806
111865
  }
111807
111866
  const __dirname3 = (0, import_path3.dirname)((0, import_url2.fileURLToPath)(importMetaUrl));
111808
111867
  const pkg = JSON.parse(