All files / src index.ts

56.37% Statements 420/745
47.87% Branches 271/566
65.34% Functions 66/101
58.53% Lines 408/697

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131                                                                                                3x   3x                                                       3x                                                                                                                                                                                                                                     3x       1x 1x       3x                   9x           9x           9x                     9x 9x                         9x     9x       9x               3x                       1x     1x 1x         1x       1x                                           2x 2x     2x 2x 2x 2x 1x     2x 1x   2x     2x           2x 2x 2x 2x 2x                     2x 2x 2x 2x         1x         1x 1x           1x 1x                 1x 1x 1x   1x             1x 1x 1x                       1x         1x                             1x         1x                                                                   3x                                                                 2x 2x 2x 2x 2x 2x                                       14x 6x 6x                       3x 3x 3x     6x 2x 2x       4x 4x 4x 4x 3x         1x       4x 4x       4x 4x 4x                   6x 6x 6x 6x 6x 6x 4x 4x 4x       6x   6x     6x 6x 6x     6x     6x 4x 4x 4x 4x         4x 4x 1x 1x 1x       4x 4x 4x 4x 4x   4x 3x   1x 1x     4x 4x     5x               6x     6x     6x             6x 6x 2x 2x 1x     1x     4x         4x 2x 2x 2x     2x 2x 4x 2x     2x 2x       2x 2x     4x 2x 2x 2x 2x             2x 2x 2x 2x   2x 2x 2x     2x     2x 2x           2x           2x                                                                 2x             2x     1x       1x   1x 1x 1x                 1x       1x 1x         1x                           4x 2x       2x                     3x 1x 1x   2x 2x 2x               2x                             2x 2x 2x 2x   2x 2x           2x         2x                                                       3x 3x                   2x 2x 832x 832x 832x 1x 1x   831x 830x         830x   831x   1x                       1x   1x 1x     1x 1x 1x 1x     1x 1x 1x         1x   1x 1x 1x 1x                         1x                               1x     1x         1x 1x   1x 1x 1x     1x     1x         1x 1x 1x     1x 1x                             2x 2x   2x       2x 2x     2x 1x                   1x   1x   1x 1x       1x       1x 1x                 1x   1x   1x   1x       1x       1x 1x                   2x 2x     1x     2x                                             1x 1x               1x   1x 1x 1x 1x 1x 1x 1x     1x             1x                   1x     1x         1x         1x                     2x 1x 1x   1x     1x 1x       1x     1x   1x         1x         1x                                     1x 1x 1x 1x       1x 1x         1x                       2x 2x 2x 2x         2x   2x                       1x 1x 1x 1x       1x 1x 1x         1x                             1x 1x     1x 1x                       1x       1x 1x 1x 1x                                                         1x                                                                                                                                                                                   3x 3x 3x 3x 3x 3x 3x               2x 2x     2x 2x 1x                     1x 1x 1x   1x 1x   1x       1x 1x 1x         1x 1x           1x 1x 1x 1x           1x 1x             1x 1x 1x 1x 1x 1x 1x 1x           1x 1x                     1x     1x     1x   1x                     1x 1x 1x 1x                     1x         1x             1x                                                                                                                                                                                                                                                                                                                                           3x 3x 3x 7x 6x 6x   3x       3x 3x 3x 3x         1x   1x         1x   1x     1x   1x 1x               2x 2x 2x 2x     2x 2x         2x           2x 4x                         2x     3x         3x                           3x                                       2x 2x 2x             3x                                                       3x                                 3x                                               3x                                                           3x                                                                                   3x                                                                                                                                                                   3x   3x      
#!/usr/bin/env node
import { execFile, spawn } from "node:child_process";
import crypto from "node:crypto";
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import process, { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
 
import bodyParser from "body-parser";
import chalk from "chalk";
import { Command } from "commander";
import dotenv from "dotenv";
import express, { type Request, type Response } from "express";
import JSON5 from "json5";
import Twilio from "twilio";
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message.js";
import { z } from "zod";
 
import {
	danger,
	info,
	isVerbose,
	isYes,
	logVerbose,
	setVerbose,
	setYes,
	success,
	warn,
} from "./globals.js";
import { loginWeb, monitorWebInbox, sendMessageWeb } from "./provider-web.js";
import { sendCommand } from "./commands/send.js";
import { statusCommand } from "./commands/status.js";
import { webhookCommand } from "./commands/webhook.js";
import { upCommand } from "./commands/up.js";
import {
	assertProvider,
	CONFIG_DIR,
	normalizeE164,
	normalizePath,
	sleep,
	toWhatsappJid,
	withWhatsAppPrefix,
} from "./utils.js";
 
dotenv.config({ quiet: true });
 
const program = new Command();
 
type AuthMode =
	| { accountSid: string; authToken: string }
	| { accountSid: string; apiKey: string; apiSecret: string };
 
type CliDeps = {
	sendMessage: typeof sendMessage;
	sendMessageWeb: typeof sendMessageWeb;
	waitForFinalStatus: typeof waitForFinalStatus;
	assertProvider: typeof assertProvider;
	createClient?: typeof createClient;
	monitor: typeof monitor;
	listRecentMessages: typeof listRecentMessages;
	ensurePortAvailable: typeof ensurePortAvailable;
	startWebhook: typeof startWebhook;
	waitForever: typeof waitForever;
	ensureBinary: typeof ensureBinary;
	ensureFunnel: typeof ensureFunnel;
	getTailnetHostname: typeof getTailnetHostname;
	readEnv: typeof readEnv;
	findWhatsappSenderSid: typeof findWhatsappSenderSid;
	updateWebhook: typeof updateWebhook;
	handlePortError: typeof handlePortError;
	monitorWebProvider: typeof monitorWebProvider;
};
 
function createDefaultDeps(): CliDeps {
	return {
		sendMessage,
		sendMessageWeb,
		waitForFinalStatus,
		assertProvider,
		createClient,
		monitor,
		listRecentMessages,
		ensurePortAvailable,
		startWebhook,
		waitForever,
		ensureBinary,
		ensureFunnel,
		getTailnetHostname,
		readEnv,
		findWhatsappSenderSid,
		updateWebhook,
		handlePortError,
		monitorWebProvider,
	};
}
 
type TwilioRequestOptions = {
	method: "get" | "post";
	uri: string;
	params?: Record<string, string | number>;
	form?: Record<string, string>;
	body?: unknown;
	contentType?: string;
};
 
type TwilioSender = { sid: string; sender_id: string };
 
type TwilioRequestResponse = {
	data?: {
		senders?: TwilioSender[];
	};
};
 
type IncomingNumber = {
	sid: string;
	phoneNumber: string;
	smsUrl?: string;
};
 
type TwilioChannelsSender = {
	sid?: string;
	senderId?: string;
	sender_id?: string;
	webhook?: {
		callback_url?: string;
		callback_method?: string;
		fallback_url?: string;
		fallback_method?: string;
	};
};
 
type ChannelSenderUpdater = {
	update: (params: Record<string, string>) => Promise<unknown>;
};
 
type IncomingPhoneNumberUpdater = {
	update: (params: Record<string, string>) => Promise<unknown>;
};
 
type IncomingPhoneNumbersClient = {
	list: (params: {
		phoneNumber: string;
		limit?: number;
	}) => Promise<IncomingNumber[]>;
	get: (sid: string) => IncomingPhoneNumberUpdater;
} & ((sid: string) => IncomingPhoneNumberUpdater);
 
type TwilioSenderListClient = {
	messaging: {
		v2: {
			channelsSenders: {
				list: (params: {
					channel: string;
					pageSize: number;
				}) => Promise<TwilioChannelsSender[]>;
				(
					sid: string,
				): ChannelSenderUpdater & {
					fetch: () => Promise<TwilioChannelsSender>;
				};
			};
		};
		v1: {
			services: (sid: string) => {
				update: (params: Record<string, string>) => Promise<unknown>;
				fetch: () => Promise<{ inboundRequestUrl?: string }>;
			};
		};
	};
	incomingPhoneNumbers: IncomingPhoneNumbersClient;
};
 
type TwilioRequester = {
	request: (options: TwilioRequestOptions) => Promise<TwilioRequestResponse>;
};
 
type EnvConfig = {
	accountSid: string;
	whatsappFrom: string;
	whatsappSenderSid?: string;
	auth: AuthMode;
};
 
type RuntimeEnv = {
	log: typeof console.log;
	error: typeof console.error;
	exit: (code: number) => never;
};
 
const defaultRuntime: RuntimeEnv = {
	log: console.log,
	error: console.error,
	exit: (code) => {
		process.exit(code);
		throw new Error("unreachable"); // satisfies tests when mocked
	},
};
 
const EnvSchema = z
	.object({
		TWILIO_ACCOUNT_SID: z.string().min(1, "TWILIO_ACCOUNT_SID required"),
		TWILIO_WHATSAPP_FROM: z.string().min(1, "TWILIO_WHATSAPP_FROM required"),
		TWILIO_SENDER_SID: z.string().optional(),
		TWILIO_AUTH_TOKEN: z.string().optional(),
		TWILIO_API_KEY: z.string().optional(),
		TWILIO_API_SECRET: z.string().optional(),
	})
	.superRefine((val, ctx) => {
		Iif (val.TWILIO_API_KEY && !val.TWILIO_API_SECRET) {
			ctx.addIssue({
				code: "custom",
				message: "TWILIO_API_SECRET required when TWILIO_API_KEY is set",
			});
		}
		Iif (val.TWILIO_API_SECRET && !val.TWILIO_API_KEY) {
			ctx.addIssue({
				code: "custom",
				message: "TWILIO_API_KEY required when TWILIO_API_SECRET is set",
			});
		}
		Iif (!val.TWILIO_AUTH_TOKEN && !(val.TWILIO_API_KEY && val.TWILIO_API_SECRET)) {
			ctx.addIssue({
				code: "custom",
				message:
					"Provide TWILIO_AUTH_TOKEN or both TWILIO_API_KEY and TWILIO_API_SECRET",
			});
		}
	});
 
function readEnv(runtime: RuntimeEnv = defaultRuntime): EnvConfig {
	// Load and validate Twilio auth + sender configuration from env.
	const parsed = EnvSchema.safeParse(process.env);
	Iif (!parsed.success) {
		runtime.error("Invalid environment configuration:");
		parsed.error.issues.forEach((iss) => runtime.error(`- ${iss.message}`));
		runtime.exit(1);
	}
 
	const {
		TWILIO_ACCOUNT_SID: accountSid,
		TWILIO_WHATSAPP_FROM: whatsappFrom,
		TWILIO_SENDER_SID: whatsappSenderSid,
		TWILIO_AUTH_TOKEN: authToken,
		TWILIO_API_KEY: apiKey,
		TWILIO_API_SECRET: apiSecret,
	} = parsed.data;
 
	const auth: AuthMode =
		apiKey && apiSecret
			? { accountSid, apiKey, apiSecret }
			: { accountSid, authToken: authToken! };
 
	return {
		accountSid,
		whatsappFrom,
		whatsappSenderSid,
		auth,
	};
}
 
const execFileAsync = promisify(execFile);
 
type ExecResult = { stdout: string; stderr: string };
 
type ExecOptions = { maxBuffer?: number; timeoutMs?: number };
 
async function runExec(
	command: string,
	args: string[],
	{ maxBuffer = 2_000_000, timeoutMs }: ExecOptions = {},
): Promise<ExecResult> {
	// Thin wrapper around execFile with utf8 output.
	Iif (isVerbose()) {
		console.log(`$ ${command} ${args.join(" ")}`);
	}
	try {
		const { stdout, stderr } = await execFileAsync(command, args, {
			maxBuffer,
			encoding: "utf8",
			timeout: timeoutMs,
		});
		Iif (isVerbose()) {
			if (stdout.trim()) console.log(stdout.trim());
			if (stderr.trim()) console.error(stderr.trim());
		}
		return { stdout, stderr };
	} catch (err) {
		if (isVerbose()) {
			console.error(danger(`Command failed: ${command} ${args.join(" ")}`));
		}
		throw err;
	}
}
 
type SpawnResult = {
	stdout: string;
	stderr: string;
	code: number | null;
	signal: NodeJS.Signals | null;
	killed: boolean;
};
 
async function runCommandWithTimeout(
	argv: string[],
	timeoutMs: number,
): Promise<SpawnResult> {
	// Spawn with inherited stdin (TTY) so tools like `claude` don't hang.
	return await new Promise((resolve, reject) => {
		const child = spawn(argv[0], argv.slice(1), {
			stdio: ["inherit", "pipe", "pipe"],
		});
		let stdout = "";
		let stderr = "";
		let settled = false;
		const timer = setTimeout(() => {
			child.kill("SIGKILL");
		}, timeoutMs);
 
		child.stdout?.on("data", (d) => {
			stdout += d.toString();
		});
		child.stderr?.on("data", (d) => {
			stderr += d.toString();
		});
		child.on("error", (err) => {
			if (settled) return;
			settled = true;
			clearTimeout(timer);
			reject(err);
		});
		child.on("close", (code, signal) => {
			Iif (settled) return;
			settled = true;
			clearTimeout(timer);
			resolve({ stdout, stderr, code, signal, killed: child.killed });
		});
	});
}
 
class PortInUseError extends Error {
	port: number;
 
	details?: string;
 
	constructor(port: number, details?: string) {
		super(`Port ${port} is already in use.`);
		this.name = "PortInUseError";
		this.port = port;
		this.details = details;
	}
}
 
function isErrno(err: unknown): err is NodeJS.ErrnoException {
	return Boolean(err && typeof err === "object" && "code" in err);
}
 
async function describePortOwner(port: number): Promise<string | undefined> {
	// Best-effort process info for a listening port (macOS/Linux).
	try {
		const { stdout } = await runExec("lsof", [
			"-i",
			`tcp:${port}`,
			"-sTCP:LISTEN",
			"-nP",
		]);
		const trimmed = stdout.trim();
		Eif (trimmed) return trimmed;
	} catch (err) {
		logVerbose(`lsof unavailable: ${String(err)}`);
	}
	return undefined;
}
 
async function ensurePortAvailable(port: number): Promise<void> {
	// Detect EADDRINUSE early with a friendly message.
	try {
		await new Promise<void>((resolve, reject) => {
			const tester = net
				.createServer()
				.once("error", (err) => reject(err))
				.once("listening", () => {
					tester.close(() => resolve());
				})
				.listen(port);
		});
	} catch (err) {
		Eif (isErrno(err) && err.code === "EADDRINUSE") {
			const details = await describePortOwner(port);
			throw new PortInUseError(port, details);
		}
		throw err;
	}
}
 
async function handlePortError(
	err: unknown,
	port: number,
	context: string,
	runtime: RuntimeEnv = defaultRuntime,
): Promise<never> {
	Eif (
		err instanceof PortInUseError ||
		(isErrno(err) && err.code === "EADDRINUSE")
	) {
		const details =
			err instanceof PortInUseError
				? err.details
				: await describePortOwner(port);
		runtime.error(danger(`${context} failed: port ${port} is already in use.`));
		if (details) {
			runtime.error(info("Port listener details:"));
			runtime.error(details);
			if (/warelay|src\/index\.ts|dist\/index\.js/.test(details)) {
				runtime.error(
					warn(
						"It looks like another warelay instance is already running. Stop it or pick a different port.",
					),
				);
			}
		}
		runtime.error(
			info(
				"Resolve by stopping the process using the port or passing --port <free-port>.",
			),
		);
		runtime.exit(1);
	}
	runtime.error(danger(`${context} failed: ${String(err)}`));
	return runtime.exit(1);
}
 
async function ensureBinary(
	name: string,
	exec: typeof runExec = runExec,
	runtime: RuntimeEnv = defaultRuntime,
): Promise<void> {
	// Abort early if a required CLI tool is missing.
	await exec("which", [name]).catch(() => {
		runtime.error(`Missing required binary: ${name}. Please install it.`);
		runtime.exit(1);
	});
}
 
async function promptYesNo(
	question: string,
	defaultYes = false,
): Promise<boolean> {
	if (isVerbose() && isYes()) return true; // redundant guard when both flags set
	if (isYes()) return true;
	const rl = readline.createInterface({ input, output });
	const suffix = defaultYes ? " [Y/n] " : " [y/N] ";
	const answer = (await rl.question(`${question}${suffix}`))
		.trim()
		.toLowerCase();
	rl.close();
	if (!answer) return defaultYes;
	return answer.startsWith("y");
}
 
const CONFIG_PATH = path.join(os.homedir(), ".warelay", "warelay.json");
 
type ReplyMode = "text" | "command";
 
type WarelayConfig = {
	inbound?: {
		allowFrom?: string[]; // E.164 numbers allowed to trigger auto-reply (without whatsapp:)
		reply?: {
			mode: ReplyMode;
			text?: string; // for mode=text, can contain {{Body}}
			command?: string[]; // for mode=command, argv with templates
			template?: string; // prepend template string when building command/prompt
			timeoutSeconds?: number; // optional command timeout; defaults to 600s
			bodyPrefix?: string; // optional string prepended to Body before templating
			session?: SessionConfig;
		};
	};
};
 
type SessionScope = "per-sender" | "global";
 
type SessionConfig = {
	scope?: SessionScope;
	resetTriggers?: string[];
	idleMinutes?: number;
	store?: string;
	sessionArgNew?: string[];
	sessionArgResume?: string[];
	sessionArgBeforeBody?: boolean;
};
 
function loadConfig(): WarelayConfig {
	// Read ~/.warelay/warelay.json (JSON5) if present.
	try {
		Iif (!fs.existsSync(CONFIG_PATH)) return {};
		const raw = fs.readFileSync(CONFIG_PATH, "utf-8");
		const parsed = JSON5.parse(raw);
		Iif (typeof parsed !== "object" || parsed === null) return {};
		return parsed as WarelayConfig;
	} catch (err) {
		console.error(`Failed to read config at ${CONFIG_PATH}`, err);
		return {};
	}
}
 
type MsgContext = {
	Body?: string;
	From?: string;
	To?: string;
	MessageSid?: string;
};
 
type GetReplyOptions = {
	onReplyStart?: () => Promise<void> | void;
};
 
function applyTemplate(str: string, ctx: TemplateContext) {
	// Simple {{Placeholder}} interpolation using inbound message context.
	return str.replace(/{{\s*(\w+)\s*}}/g, (_, key) => {
		const value = (ctx as Record<string, unknown>)[key];
		return value == null ? "" : String(value);
	});
}
 
type TemplateContext = MsgContext & {
	BodyStripped?: string;
	SessionId?: string;
	IsNewSession?: string;
};
 
type SessionEntry = { sessionId: string; updatedAt: number };
 
const SESSION_STORE_DEFAULT = path.join(CONFIG_DIR, "sessions.json");
const DEFAULT_RESET_TRIGGER = "/new";
const DEFAULT_IDLE_MINUTES = 60;
 
function resolveStorePath(store?: string) {
	if (!store) return SESSION_STORE_DEFAULT;
	Iif (store.startsWith("~")) return path.resolve(store.replace("~", os.homedir()));
	return path.resolve(store);
}
 
function loadSessionStore(storePath: string): Record<string, SessionEntry> {
	try {
		const raw = fs.readFileSync(storePath, "utf-8");
		const parsed = JSON5.parse(raw);
		if (parsed && typeof parsed === "object") {
			return parsed as Record<string, SessionEntry>;
		}
	} catch {
		// ignore missing/invalid store; we'll recreate it
	}
	return {};
}
 
async function saveSessionStore(storePath: string, store: Record<string, SessionEntry>) {
	await fs.promises.mkdir(path.dirname(storePath), { recursive: true });
	await fs.promises.writeFile(storePath, JSON.stringify(store, null, 2), "utf-8");
}
 
function deriveSessionKey(scope: SessionScope, ctx: MsgContext) {
	Iif (scope === "global") return "global";
	const from = ctx.From ? normalizeE164(ctx.From) : "";
	return from || "unknown";
}
 
async function getReplyFromConfig(
	ctx: MsgContext,
	opts?: GetReplyOptions,
	configOverride?: WarelayConfig,
	commandRunner: typeof runCommandWithTimeout = runCommandWithTimeout,
): Promise<string | undefined> {
	// Choose reply from config: static text or external command stdout.
	const cfg = configOverride ?? loadConfig();
	const reply = cfg.inbound?.reply;
	const timeoutSeconds = Math.max(reply?.timeoutSeconds ?? 600, 1);
	const timeoutMs = timeoutSeconds * 1000;
	let started = false;
	const onReplyStart = async () => {
		Iif (started) return;
		started = true;
		await opts?.onReplyStart?.();
	};
 
	// Optional session handling (conversation reuse + /new resets)
	const sessionCfg = reply?.session;
	const resetTriggers =
		sessionCfg?.resetTriggers?.length
			? sessionCfg.resetTriggers
			: [DEFAULT_RESET_TRIGGER];
	const idleMinutes = Math.max(sessionCfg?.idleMinutes ?? DEFAULT_IDLE_MINUTES, 1);
	const sessionScope = sessionCfg?.scope ?? "per-sender";
	const storePath = resolveStorePath(sessionCfg?.store);
 
	let sessionId: string | undefined;
	let isNewSession = false;
	let bodyStripped: string | undefined;
 
	if (sessionCfg) {
		const trimmedBody = (ctx.Body ?? "").trim();
		for (const trigger of resetTriggers) {
			Iif (!trigger) continue;
			Iif (trimmedBody === trigger) {
				isNewSession = true;
				bodyStripped = "";
				break;
			}
			const triggerPrefix = `${trigger} `;
			if (trimmedBody.startsWith(triggerPrefix)) {
				isNewSession = true;
				bodyStripped = trimmedBody.slice(trigger.length).trimStart();
				break;
			}
		}
 
		const sessionKey = deriveSessionKey(sessionScope, ctx);
		const store = loadSessionStore(storePath);
		const entry = store[sessionKey];
		const idleMs = idleMinutes * 60_000;
		const freshEntry = entry && Date.now() - entry.updatedAt <= idleMs;
 
		if (!isNewSession && freshEntry) {
			sessionId = entry.sessionId;
		} else {
			sessionId = crypto.randomUUID();
			isNewSession = true;
		}
 
		store[sessionKey] = { sessionId, updatedAt: Date.now() };
		await saveSessionStore(storePath, store);
	}
 
	const sessionCtx: TemplateContext = {
		...ctx,
		BodyStripped: bodyStripped ?? ctx.Body,
		SessionId: sessionId,
		IsNewSession: isNewSession ? "true" : "false",
	};
 
	// Optional prefix injected before Body for templating/command prompts.
	const bodyPrefix = reply?.bodyPrefix
		? applyTemplate(reply.bodyPrefix, sessionCtx)
		: "";
	const prefixedBody = bodyPrefix
		? `${bodyPrefix}${sessionCtx.BodyStripped ?? sessionCtx.Body ?? ""}`
		: sessionCtx.BodyStripped ?? sessionCtx.Body;
	const templatingCtx: TemplateContext = {
		...sessionCtx,
		Body: prefixedBody,
		BodyStripped: prefixedBody,
	};
 
	// Optional allowlist by origin number (E.164 without whatsapp: prefix)
	const allowFrom = cfg.inbound?.allowFrom;
	if (Array.isArray(allowFrom) && allowFrom.length > 0) {
		const from = (ctx.From ?? "").replace(/^whatsapp:/, "");
		if (!allowFrom.includes(from)) {
			logVerbose(
				`Skipping auto-reply: sender ${from || "<unknown>"} not in allowFrom list`,
			);
			return undefined;
		}
	}
	Iif (!reply) {
		logVerbose("No inbound.reply configured; skipping auto-reply");
		return undefined;
	}
 
	if (reply.mode === "text" && reply.text) {
		await onReplyStart();
		logVerbose("Using text auto-reply from config");
		return applyTemplate(reply.text, templatingCtx);
	}
 
	Eif (reply.mode === "command" && reply.command?.length) {
		await onReplyStart();
		let argv = reply.command.map((part) => applyTemplate(part, templatingCtx));
		const templatePrefix = reply.template
			? applyTemplate(reply.template, templatingCtx)
			: "";
		Eif (templatePrefix && argv.length > 0) {
			argv = [argv[0], templatePrefix, ...argv.slice(1)];
		}
 
		// Inject session args if configured (use resume for existing, session-id for new)
		Eif (reply.session) {
			const sessionArgList = (isNewSession
				? reply.session.sessionArgNew ?? ["--session-id", "{{SessionId}}"]
				: reply.session.sessionArgResume ?? ["--resume", "{{SessionId}}"]
			).map((part) => applyTemplate(part, templatingCtx));
			Eif (sessionArgList.length) {
				const insertBeforeBody = reply.session.sessionArgBeforeBody ?? true;
				const insertAt = insertBeforeBody && argv.length > 1 ? argv.length - 1 : argv.length;
				argv = [
					...argv.slice(0, insertAt),
					...sessionArgList,
					...argv.slice(insertAt),
				];
			}
		}
		const finalArgv = argv;
		logVerbose(`Running command auto-reply: ${finalArgv.join(" ")}`);
		const started = Date.now();
		try {
			const { stdout, stderr, code, signal, killed } =
				await commandRunner(finalArgv, timeoutMs);
			const trimmed = stdout.trim();
			Iif (stderr?.trim()) {
				logVerbose(`Command auto-reply stderr: ${stderr.trim()}`);
			}
			logVerbose(
				`Command auto-reply stdout (trimmed): ${trimmed || "<empty>"}`,
			);
			logVerbose(`Command auto-reply finished in ${Date.now() - started}ms`);
			Iif ((code ?? 0) !== 0) {
				console.error(
					`Command auto-reply exited with code ${code ?? "unknown"} (signal: ${signal ?? "none"})`,
				);
				return undefined;
			}
			Iif (killed && !signal) {
				console.error(
					`Command auto-reply process killed before completion (exit code ${code ?? "unknown"})`,
				);
				return undefined;
			}
			return trimmed || undefined;
		} catch (err) {
			const elapsed = Date.now() - started;
			const anyErr = err as { killed?: boolean; signal?: string };
			const timeoutHit = anyErr.killed === true || anyErr.signal === "SIGKILL";
			const errorObj = err as {
				stdout?: string;
				stderr?: string;
			};
			if (errorObj.stderr?.trim()) {
				logVerbose(`Command auto-reply stderr: ${errorObj.stderr.trim()}`);
			}
			if (timeoutHit) {
				console.error(
					`Command auto-reply timed out after ${elapsed}ms (limit ${timeoutMs}ms)`,
				);
			} else {
				console.error(`Command auto-reply failed after ${elapsed}ms`, err);
			}
			return undefined;
		}
	}
 
	return undefined;
}
 
async function autoReplyIfConfigured(
	client: ReturnType<typeof createClient>,
	message: MessageInstance,
	configOverride?: WarelayConfig,
	runtime: RuntimeEnv = defaultRuntime,
): Promise<void> {
	// Fire a config-driven reply (text or command) for the inbound message, if configured.
	const ctx: MsgContext = {
		Body: message.body ?? undefined,
		From: message.from ?? undefined,
		To: message.to ?? undefined,
		MessageSid: message.sid,
	};
 
	const replyText = await getReplyFromConfig(
		ctx,
		{
			onReplyStart: () => sendTypingIndicator(client, message.sid, runtime),
		},
		configOverride,
	);
	Iif (!replyText) return;
 
	const replyFrom = message.to;
	const replyTo = message.from;
	Iif (!replyFrom || !replyTo) {
	if (isVerbose())
		console.error(
			"Skipping auto-reply: missing to/from on inbound message",
			ctx,
			);
		return;
	}
 
	logVerbose(
		`Auto-replying via Twilio: from ${replyFrom} to ${replyTo}, body length ${replyText.length}`,
	);
 
	try {
		await client.messages.create({
			from: replyFrom,
			to: replyTo,
			body: replyText,
		});
		Iif (isVerbose()) {
			console.log(
				success(
					`↩️  Auto-replied to ${replyTo} (sid ${message.sid ?? "no-sid"})`,
				),
			);
		}
	} catch (err) {
		logTwilioSendError(err, replyTo ?? undefined, runtime);
	}
}
 
function createClient(env: EnvConfig) {
	// Twilio client using either auth token or API key/secret.
	if ("authToken" in env.auth) {
		return Twilio(env.accountSid, env.auth.authToken, {
			accountSid: env.accountSid,
		});
	}
	return Twilio(env.auth.apiKey, env.auth.apiSecret, {
		accountSid: env.accountSid,
	});
}
 
async function sendTypingIndicator(
	client: ReturnType<typeof createClient>,
	messageSid?: string,
	runtime: RuntimeEnv = defaultRuntime,
) {
	// Best-effort WhatsApp typing indicator (public beta as of Nov 2025).
	if (!messageSid) {
		logVerbose("Skipping typing indicator: missing MessageSid");
		return;
	}
	try {
		const requester = client as unknown as TwilioRequester;
		await requester.request({
			method: "post",
			uri: "https://messaging.twilio.com/v2/Indicators/Typing.json",
			form: {
				messageId: messageSid,
				channel: "whatsapp",
			},
		});
		logVerbose(`Sent typing indicator for inbound ${messageSid}`);
	} catch (err) {
		if (isVerbose()) {
			runtime.error(warn("Typing indicator failed (continuing without it)"));
			runtime.error(err as Error);
		}
	}
}
 
async function sendMessage(
	to: string,
	body: string,
	runtime: RuntimeEnv = defaultRuntime,
) {
	// Send outbound WhatsApp message; exit non-zero on API failure.
	const env = readEnv(runtime);
	const client = createClient(env);
	const from = withWhatsAppPrefix(env.whatsappFrom);
	const toNumber = withWhatsAppPrefix(to);
 
	try {
		const message = await client.messages.create({
			from,
			to: toNumber,
			body,
		});
 
		console.log(
			success(
				`✅ Request accepted. Message SID: ${message.sid} -> ${toNumber}`,
			),
		);
		return { client, sid: message.sid };
	} catch (err) {
		const anyErr = err as {
			code?: string | number;
			message?: unknown;
			moreInfo?: unknown;
			status?: string | number;
			response?: { body?: unknown };
		};
		const { code, status } = anyErr;
		const msg =
			typeof anyErr?.message === "string"
				? anyErr.message
			: (anyErr?.message ?? err);
		const more = anyErr?.moreInfo;
		runtime.error(
			`❌ Twilio send failed${code ? ` (code ${code})` : ""}${status ? ` status ${status}` : ""}: ${msg}`,
		);
		if (more) console.error(`More info: ${more}`);
		// Some Twilio errors include response.body with more context.
		const responseBody = anyErr?.response?.body;
		if (responseBody) {
			console.error("Response body:", JSON.stringify(responseBody, null, 2));
		}
		runtime.exit(1);
	}
}
 
const successTerminalStatuses = new Set(["delivered", "read"]);
const failureTerminalStatuses = new Set(["failed", "undelivered", "canceled"]);
 
async function waitForFinalStatus(
	client: ReturnType<typeof createClient>,
	sid: string,
	timeoutSeconds: number,
	pollSeconds: number,
	runtime: RuntimeEnv = defaultRuntime,
) {
	// Poll message status until delivered/failed or timeout.
	const deadline = Date.now() + timeoutSeconds * 1000;
	while (Date.now() < deadline) {
		const m = await client.messages(sid).fetch();
		const status = m.status ?? "unknown";
		if (successTerminalStatuses.has(status)) {
			console.log(success(`✅ Delivered (status: ${status})`));
			return;
		}
		if (failureTerminalStatuses.has(status)) {
			runtime.error(
				`❌ Delivery failed (status: ${status}${
					m.errorCode ? `, code ${m.errorCode}` : ""
				})${m.errorMessage ? `: ${m.errorMessage}` : ""}`,
			);
			runtime.exit(1);
		}
		await sleep(pollSeconds * 1000);
	}
	console.log(
		"ℹ️  Timed out waiting for final status; message may still be in flight.",
	);
}
 
async function startWebhook(
	port: number,
	path = "/webhook/whatsapp",
	autoReply: string | undefined,
	verbose: boolean,
	runtime: RuntimeEnv = defaultRuntime,
): Promise<import("http").Server> {
	const normalizedPath = normalizePath(path);
	// Start Express webhook; generate replies via config or CLI flag.
	const env = readEnv(runtime);
	const app = express();
 
	// Twilio sends application/x-www-form-urlencoded
	app.use(bodyParser.urlencoded({ extended: false }));
	app.use((req, _res, next) => {
		runtime.log(chalk.gray(`REQ ${req.method} ${req.url}`));
		next();
	});
 
	app.post(normalizedPath, async (req: Request, res: Response) => {
		const { From, To, Body, MessageSid } = req.body ?? {};
		console.log(
			`[INBOUND] ${From ?? "unknown"} -> ${To ?? "unknown"} (${
				MessageSid ?? "no-sid"
			})`,
		);
		Iif (verbose) runtime.log(chalk.gray(`Body: ${Body ?? ""}`));
 
		const client = createClient(env);
		let replyText = autoReply;
		Eif (!replyText) {
			replyText = await getReplyFromConfig(
				{
					Body,
					From,
					To,
					MessageSid,
				},
				{
					onReplyStart: () => sendTypingIndicator(client, MessageSid, runtime),
				},
			);
		}
 
		Iif (replyText) {
			try {
				await client.messages.create({
					from: To,
					to: From,
					body: replyText,
				});
				if (verbose) {
					runtime.log(success(`↩️  Auto-replied to ${From}`));
				}
			} catch (err) {
				logTwilioSendError(err, From ?? undefined, runtime);
			}
		}
 
		// Respond 200 OK to Twilio
		res.type("text/xml").send("<Response></Response>");
	});
 
	app.use((_req, res) => {
		if (verbose) runtime.log(chalk.yellow(`404 ${_req.method} ${_req.url}`));
		res.status(404).send("warelay webhook: not found");
	});
 
	return await new Promise((resolve, reject) => {
		const server = app.listen(port);
 
		const onListening = () => {
			cleanup();
			runtime.log(
				`📥 Webhook listening on http://localhost:${port}${normalizedPath}`,
			);
			resolve(server);
		};
 
		const onError = (err: NodeJS.ErrnoException) => {
			cleanup();
			reject(err);
		};
 
		const cleanup = () => {
			server.off("listening", onListening);
			server.off("error", onError);
		};
 
		server.once("listening", onListening);
		server.once("error", onError);
	});
}
 
function waitForever() {
	// Keep event loop alive via an unref'ed interval plus a pending promise.
	const interval = setInterval(() => {}, 1_000_000);
	interval.unref();
	return new Promise<void>(() => {
		/* never resolve */
	});
}
 
async function getTailnetHostname(exec: typeof runExec = runExec) {
	// Derive tailnet hostname (or IP fallback) from tailscale status JSON.
	const { stdout } = await exec("tailscale", ["status", "--json"]);
	const parsed = stdout ? (JSON.parse(stdout) as Record<string, unknown>) : {};
	const self =
		typeof parsed.Self === "object" && parsed.Self !== null
			? (parsed.Self as Record<string, unknown>)
			: undefined;
	const dns =
		typeof self?.DNSName === "string" ? (self.DNSName as string) : undefined;
	const ips = Array.isArray(self?.TailscaleIPs)
		? (self.TailscaleIPs as string[])
		: [];
	if (dns && dns.length > 0) return dns.replace(/\.$/, "");
	Eif (ips.length > 0) return ips[0];
	throw new Error("Could not determine Tailscale DNS or IP");
}
 
async function ensureGoInstalled(
	exec: typeof runExec = runExec,
	prompt: typeof promptYesNo = promptYesNo,
	runtime: RuntimeEnv = defaultRuntime,
) {
	// Ensure Go toolchain is present; offer Homebrew install if missing.
	const hasGo = await exec("go", ["version"]).then(
		() => true,
		() => false,
	);
	Iif (hasGo) return;
	const install = await prompt(
		"Go is not installed. Install via Homebrew (brew install go)?",
		true,
	);
	Iif (!install) {
		runtime.error("Go is required to build tailscaled from source. Aborting.");
		runtime.exit(1);
	}
	logVerbose("Installing Go via Homebrew…");
	await exec("brew", ["install", "go"]);
}
 
async function ensureTailscaledInstalled(
	exec: typeof runExec = runExec,
	prompt: typeof promptYesNo = promptYesNo,
	runtime: RuntimeEnv = defaultRuntime,
) {
	// Ensure tailscaled binary exists; install via Homebrew tailscale if missing.
	const hasTailscaled = await exec("tailscaled", ["--version"]).then(
		() => true,
		() => false,
	);
	Iif (hasTailscaled) return;
 
	const install = await prompt(
		"tailscaled not found. Install via Homebrew (tailscale package)?",
		true,
	);
	Iif (!install) {
		runtime.error("tailscaled is required for user-space funnel. Aborting.");
		runtime.exit(1);
	}
	logVerbose("Installing tailscaled via Homebrew…");
	await exec("brew", ["install", "tailscale"]);
}
 
async function ensureFunnel(
	port: number,
	exec: typeof runExec = runExec,
	runtime: RuntimeEnv = defaultRuntime,
	prompt: typeof promptYesNo = promptYesNo,
) {
	// Ensure Funnel is enabled and publish the webhook port.
	try {
		const statusOut = (
			await exec("tailscale", ["funnel", "status", "--json"])
		).stdout.trim();
		const parsed = statusOut
			? (JSON.parse(statusOut) as Record<string, unknown>)
			: {};
		Iif (!parsed || Object.keys(parsed).length === 0) {
			runtime.error(
				danger("Tailscale Funnel is not enabled on this tailnet/device."),
			);
			runtime.error(
				info(
					"Enable in admin console: https://login.tailscale.com/admin (see https://tailscale.com/kb/1223/funnel)",
				),
			);
			runtime.error(
				info(
					"macOS user-space tailscaled docs: https://github.com/tailscale/tailscale/wiki/Tailscaled-on-macOS",
				),
			);
			const proceed = await prompt(
				"Attempt local setup with user-space tailscaled?",
				true,
			);
			if (!proceed) runtime.exit(1);
			await ensureGoInstalled(exec, prompt, runtime);
			await ensureTailscaledInstalled(exec, prompt, runtime);
		}
 
		logVerbose(`Enabling funnel on port ${port}…`);
		const { stdout } = await exec(
			"tailscale",
			["funnel", "--yes", "--bg", `${port}`],
			{
				maxBuffer: 200_000,
				timeoutMs: 15_000,
			},
		);
		Eif (stdout.trim()) console.log(stdout.trim());
	} catch (err) {
		const errOutput = err as { stdout?: unknown; stderr?: unknown };
		const stdout = typeof errOutput.stdout === "string" ? errOutput.stdout : "";
		const stderr = typeof errOutput.stderr === "string" ? errOutput.stderr : "";
		Eif (stdout.includes("Funnel is not enabled")) {
			console.error(danger("Funnel is not enabled on this tailnet/device."));
			const linkMatch = stdout.match(/https?:\/\/\S+/);
			Iif (linkMatch) {
				console.error(info(`Enable it here: ${linkMatch[0]}`));
			} else {
				console.error(
					info(
						"Enable in admin console: https://login.tailscale.com/admin (see https://tailscale.com/kb/1223/funnel)",
					),
				);
			}
		}
		Iif (
			stderr.includes("client version") ||
			stdout.includes("client version")
		) {
			console.error(
				warn(
					"Tailscale client/server version mismatch detected; try updating tailscale/tailscaled.",
				),
			);
		}
		runtime.error(
			"Failed to enable Tailscale Funnel. Is it allowed on your tailnet?",
		);
		runtime.error(
			info(
				"Tip: you can fall back to polling (no webhooks needed): `pnpm warelay poll --interval 5 --lookback 10`",
			),
		);
		Iif (isVerbose()) {
			if (stdout.trim()) runtime.error(chalk.gray(`stdout: ${stdout.trim()}`));
			if (stderr.trim()) runtime.error(chalk.gray(`stderr: ${stderr.trim()}`));
			runtime.error(err as Error);
		}
		runtime.exit(1);
	}
}
 
async function findWhatsappSenderSid(
	client: ReturnType<typeof createClient>,
	from: string,
	explicitSenderSid?: string,
	runtime: RuntimeEnv = defaultRuntime,
) {
	// Use explicit sender SID if provided, otherwise list and match by sender_id.
	if (explicitSenderSid) {
		logVerbose(`Using TWILIO_SENDER_SID from env: ${explicitSenderSid}`);
		return explicitSenderSid;
	}
	try {
		// Prefer official SDK list helper to avoid request-shape mismatches.
		// Twilio helper types are broad; we narrow to expected shape.
		const senderClient = client as unknown as TwilioSenderListClient;
		const senders = await senderClient.messaging.v2.channelsSenders.list({
			channel: "whatsapp",
			pageSize: 50,
		});
		Iif (!senders) {
			throw new Error('List senders response missing "senders" array');
		}
		const match = senders.find(
			(s) =>
				(typeof s.senderId === "string" &&
					s.senderId === withWhatsAppPrefix(from)) ||
				(typeof s.sender_id === "string" &&
					s.sender_id === withWhatsAppPrefix(from)),
		);
		Iif (!match || typeof match.sid !== "string") {
			throw new Error(
				`Could not find sender ${withWhatsAppPrefix(from)} in Twilio account`,
			);
		}
		return match.sid;
	} catch (err) {
		runtime.error(danger("Unable to list WhatsApp senders via Twilio API."));
		if (isVerbose()) {
			runtime.error(err as Error);
		}
		runtime.error(
			info(
				"Set TWILIO_SENDER_SID in .env to skip discovery (Twilio Console → Messaging → Senders → WhatsApp).",
			),
		);
		runtime.exit(1);
	}
}
 
async function findIncomingNumberSid(
	client: TwilioSenderListClient,
): Promise<string | null> {
	// Try to locate the underlying phone number and return its SID for webhook fallback.
	const env = readEnv();
	const phone = env.whatsappFrom.replace("whatsapp:", "");
	try {
		const list = await client.incomingPhoneNumbers.list({
			phoneNumber: phone,
			limit: 2,
		});
		Iif (!list || list.length === 0) return null;
		Iif (list.length > 1 && isVerbose()) {
			console.error(
				warn("Multiple incoming numbers matched; using the first."),
			);
		}
		return list[0]?.sid ?? null;
	} catch (err) {
		if (isVerbose()) console.error("incomingPhoneNumbers.list failed", err);
		return null;
	}
}
 
async function findMessagingServiceSid(
	client: TwilioSenderListClient,
): Promise<string | null> {
	// Attempt to locate a messaging service tied to the WA phone number (webhook fallback).
	type IncomingNumberWithService = { messagingServiceSid?: string };
	try {
		const env = readEnv();
		const phone = env.whatsappFrom.replace("whatsapp:", "");
		const list = await client.incomingPhoneNumbers.list({
			phoneNumber: phone,
			limit: 1,
		});
		const msid =
			(list?.[0] as IncomingNumberWithService | undefined)
				?.messagingServiceSid ?? null;
		return msid;
	} catch (err) {
		if (isVerbose()) console.error("findMessagingServiceSid failed", err);
		return null;
	}
}
 
async function setMessagingServiceWebhook(
	client: TwilioSenderListClient,
	url: string,
	method: "POST" | "GET",
): Promise<boolean> {
	const msid = await findMessagingServiceSid(client);
	Iif (!msid) return false;
	try {
		await client.messaging.v1.services(msid).update({
			InboundRequestUrl: url,
			InboundRequestMethod: method,
		});
		const fetched = await client.messaging.v1.services(msid).fetch();
		const stored = fetched?.inboundRequestUrl;
		console.log(
			success(
				`✅ Messaging Service webhook set to ${stored ?? url} (service ${msid})`,
			),
		);
		return true;
	} catch (err) {
		if (isVerbose()) console.error("Messaging Service update failed", err);
		return false;
	}
}
 
async function updateWebhook(
	client: ReturnType<typeof createClient>,
	senderSid: string,
	url: string,
	method: "POST" | "GET" = "POST",
	runtime: RuntimeEnv = defaultRuntime,
) {
	// Point Twilio sender webhook at the provided URL.
	const requester = client as unknown as TwilioRequester;
	const clientTyped = client as unknown as TwilioSenderListClient;
 
	// 1) Raw request (Channels/Senders) with JSON webhook payload — most reliable for WA
	try {
		await requester.request({
			method: "post",
			uri: `https://messaging.twilio.com/v2/Channels/Senders/${senderSid}`,
			body: {
				webhook: {
					callback_url: url,
					callback_method: method,
				},
			},
			contentType: "application/json",
		});
		// Fetch to verify what Twilio stored
		const fetched = await clientTyped.messaging.v2
			.channelsSenders(senderSid)
			.fetch();
		const storedUrl =
			fetched?.webhook?.callback_url || fetched?.webhook?.fallback_url;
		Eif (storedUrl) {
			console.log(success(`✅ Twilio sender webhook set to ${storedUrl}`));
			return;
		}
		if (isVerbose())
			console.error(
				"Sender updated but webhook callback_url missing; will try fallbacks",
			);
	} catch (err) {
		if (isVerbose())
			console.error(
				"channelsSenders request update failed, will try client helpers",
				err,
			);
	}
 
	// 1b) Form-encoded fallback for older Twilio stacks
	try {
		await requester.request({
			method: "post",
			uri: `https://messaging.twilio.com/v2/Channels/Senders/${senderSid}`,
			form: {
				"Webhook.CallbackUrl": url,
				"Webhook.CallbackMethod": method,
			},
		});
		const fetched = await clientTyped.messaging.v2
			.channelsSenders(senderSid)
			.fetch();
		const storedUrl =
			fetched?.webhook?.callback_url || fetched?.webhook?.fallback_url;
		Iif (storedUrl) {
			console.log(success(`✅ Twilio sender webhook set to ${storedUrl}`));
			return;
		}
		if (isVerbose())
			console.error(
				"Form update succeeded but callback_url missing; will try helper fallback",
			);
	} catch (err) {
		if (isVerbose())
			console.error(
				"Form channelsSenders update failed, will try helper fallback",
				err,
			);
	}
 
	// 2) SDK helper fallback (if supported by this client)
	try {
		if (clientTyped.messaging?.v2?.channelsSenders) {
			await clientTyped.messaging.v2.channelsSenders(senderSid).update({
				callbackUrl: url,
				callbackMethod: method,
			});
			const fetched = await clientTyped.messaging.v2
				.channelsSenders(senderSid)
				.fetch();
			const storedUrl =
				fetched?.webhook?.callback_url || fetched?.webhook?.fallback_url;
			console.log(
				success(
					`✅ Twilio sender webhook set to ${storedUrl ?? url} (helper API)`,
				),
			);
			return;
		}
	} catch (err) {
		if (isVerbose())
			console.error(
				"channelsSenders helper update failed, will try phone number fallback",
				err,
			);
	}
 
	// 3) Incoming phone number fallback (works for many WA senders)
	try {
		const phoneSid = await findIncomingNumberSid(clientTyped);
		if (phoneSid) {
			const phoneNumberUpdater = clientTyped.incomingPhoneNumbers(phoneSid);
			await phoneNumberUpdater.update({
				smsUrl: url,
				smsMethod: method,
			});
			console.log(success(`✅ Twilio phone webhook set to ${url}`));
			return;
		}
	} catch (err) {
		if (isVerbose()) console.error("Incoming number update failed", err);
	}
 
	// 4) Messaging Service fallback (some WA senders are tied to a service)
	const messagingServiceUpdated = await setMessagingServiceWebhook(
		clientTyped,
		url,
		method,
	);
	if (messagingServiceUpdated) return;
 
	runtime.error(danger("Failed to set Twilio webhook."));
	runtime.error(
		info(
			"Double-check your sender SID and credentials; you can set TWILIO_SENDER_SID to force a specific sender.",
		),
	);
	runtime.error(
		info(
			"Tip: if webhooks are blocked, use polling instead: `pnpm warelay poll --interval 5 --lookback 10`",
		),
	);
	runtime.exit(1);
}
 
type TwilioApiError = {
	code?: number | string;
	status?: number | string;
	message?: string;
	moreInfo?: string;
	response?: { body?: unknown };
};
 
function formatTwilioError(err: unknown): string {
	const e = err as TwilioApiError;
	const pieces = [];
	if (e.code != null) pieces.push(`code ${e.code}`);
	if (e.status != null) pieces.push(`status ${e.status}`);
	if (e.message) pieces.push(e.message);
	if (e.moreInfo) pieces.push(`more: ${e.moreInfo}`);
	return pieces.length ? pieces.join(" | ") : String(err);
}
 
function logTwilioSendError(
	err: unknown,
	destination?: string,
	runtime: RuntimeEnv = defaultRuntime,
) {
	const prefix = destination ? `to ${destination}: ` : "";
	runtime.error(
		danger(`❌ Twilio send failed ${prefix}${formatTwilioError(err)}`),
	);
	const body = (err as TwilioApiError)?.response?.body;
	if (body) {
		runtime.error(info("Response body:"), JSON.stringify(body, null, 2));
	}
}
 
async function monitor(
	intervalSeconds: number,
	lookbackMinutes: number,
	clientOverride?: ReturnType<typeof createClient>,
	maxIterations = Infinity,
) {
	// Poll Twilio for inbound messages and stream them with de-dupe.
	const env = readEnv();
	const client = clientOverride ?? createClient(env);
	const from = withWhatsAppPrefix(env.whatsappFrom);
 
	let since = new Date(Date.now() - lookbackMinutes * 60_000);
	const seen = new Set<string>();
 
	console.log(
		`📡 Monitoring inbound messages to ${from} (poll ${intervalSeconds}s, lookback ${lookbackMinutes}m)`,
	);
 
	const updateSince = (date?: Date | null) => {
		Iif (!date) return;
		Iif (date.getTime() > since.getTime()) {
			since = date;
		}
	};
 
	let keepRunning = true;
	process.once("SIGINT", () => {
		if (!keepRunning) return;
		keepRunning = false;
		console.log("\n👋 Stopping monitor");
	});
 
	let iterations = 0;
	while (keepRunning && iterations < maxIterations) {
		try {
			const messages = await client.messages.list({
				to: from,
				dateSentAfter: since,
				limit: 50,
			});
 
			const inboundMessages = messages
				.filter((m: MessageInstance) => m.direction === "inbound")
				.sort((a: MessageInstance, b: MessageInstance) => {
					const da = a.dateCreated?.getTime() ?? 0;
					const db = b.dateCreated?.getTime() ?? 0;
					return da - db;
				});
 
			for (const m of inboundMessages) {
				Iif (seen.has(m.sid)) continue;
				seen.add(m.sid);
				const time = m.dateCreated?.toISOString() ?? "unknown time";
				const fromNum = m.from ?? "unknown sender";
				console.log(`\n[${time}] ${fromNum} -> ${m.to}: ${m.body ?? ""}`);
				updateSince(m.dateCreated);
				void autoReplyIfConfigured(client, m);
			}
		} catch (err) {
			console.error("Error while polling messages", err);
		}
 
		await sleep(intervalSeconds * 1000);
		iterations += 1;
	}
}
 
async function monitorWebProvider(
	verbose: boolean,
	listenerFactory = monitorWebInbox,
	keepAlive = true,
	replyResolver: typeof getReplyFromConfig = getReplyFromConfig,
) {
	// Listen for inbound personal WhatsApp Web messages and auto-reply if configured.
	const listener = await listenerFactory({
		verbose,
		onMessage: async (msg) => {
			const ts = msg.timestamp
				? new Date(msg.timestamp).toISOString()
				: new Date().toISOString();
			console.log(`\n[${ts}] ${msg.from} -> ${msg.to}: ${msg.body}`);
 
			const replyText = await replyResolver(
				{
					Body: msg.body,
					From: msg.from,
					To: msg.to,
					MessageSid: msg.id,
				},
				{
					onReplyStart: msg.sendComposing,
				},
			);
			Iif (!replyText) return;
			try {
				await msg.reply(replyText);
				Iif (isVerbose()) {
					console.log(success(`↩️  Auto-replied to ${msg.from} (web)`));
				}
			} catch (err) {
				console.error(
					danger(`Failed sending web auto-reply to ${msg.from}: ${String(err)}`),
				);
			}
		},
	});
 
	console.log(
		info(
			"📡 Listening for personal WhatsApp Web inbound messages. Leave this running; Ctrl+C to stop.",
		),
	);
	process.on("SIGINT", () => {
		void listener.close().finally(() => {
			console.log("\n👋 Web monitor stopped");
			defaultRuntime.exit(0);
		});
	});
 
	Iif (keepAlive) {
		await waitForever();
	}
}
 
async function performSend(
	opts: {
		to: string;
		message: string;
		wait: string;
		poll: string;
		provider: Provider;
	},
	deps: CliDeps,
	exitFn: (code: number) => never = defaultRuntime.exit,
	runtime: RuntimeEnv = defaultRuntime,
) {
	deps.assertProvider(opts.provider);
	const waitSeconds = Number.parseInt(opts.wait, 10);
	const pollSeconds = Number.parseInt(opts.poll, 10);
 
	if (Number.isNaN(waitSeconds) || waitSeconds < 0) {
		throw new Error("Wait must be >= 0 seconds");
	}
	if (Number.isNaN(pollSeconds) || pollSeconds <= 0) {
		throw new Error("Poll must be > 0 seconds");
	}
 
	if (opts.provider === "web") {
		if (waitSeconds !== 0) {
			console.log(info("Wait/poll are Twilio-only; ignored for provider=web."));
		}
		await deps.sendMessageWeb(opts.to, opts.message, { verbose: isVerbose() });
		return;
	}
 
	const result = await deps.sendMessage(opts.to, opts.message, runtime);
	if (!result) return;
	if (waitSeconds === 0) return;
	await deps.waitForFinalStatus(
		result.client,
		result.sid,
		waitSeconds,
		pollSeconds,
	);
}
 
async function performStatus(
	opts: { limit: string; lookback: string; json?: boolean },
	deps: CliDeps,
	exitFn: (code: number) => never = defaultRuntime.exit,
	runtime: RuntimeEnv = defaultRuntime,
) {
	const limit = Number.parseInt(opts.limit, 10);
	const lookbackMinutes = Number.parseInt(opts.lookback, 10);
	if (Number.isNaN(limit) || limit <= 0 || limit > 200) {
		throw new Error("limit must be between 1 and 200");
	}
	if (Number.isNaN(lookbackMinutes) || lookbackMinutes <= 0) {
		throw new Error("lookback must be > 0 minutes");
	}
 
	const messages = await deps.listRecentMessages(lookbackMinutes, limit);
	if (opts.json) {
		console.log(JSON.stringify(messages, null, 2));
		return;
	}
	if (messages.length === 0) {
		console.log("No messages found in the requested window.");
		return;
	}
	for (const m of messages) {
		console.log(formatMessageLine(m));
	}
}
 
async function performWebhookSetup(
	opts: {
		port: string;
		path: string;
		reply?: string;
		verbose?: boolean;
	},
	deps: CliDeps,
	exitFn: (code: number) => never = defaultRuntime.exit,
	runtime: RuntimeEnv = defaultRuntime,
) {
	const port = Number.parseInt(opts.port, 10);
	if (Number.isNaN(port) || port <= 0 || port >= 65536) {
		throw new Error("Port must be between 1 and 65535");
	}
	await deps.ensurePortAvailable(port);
 
	const server = await deps.startWebhook(
		port,
		opts.path,
		opts.reply,
		Boolean(opts.verbose),
	);
	return server;
}
 
async function performUp(
	opts: {
		port: string;
		path: string;
		verbose?: boolean;
		yes?: boolean;
	},
	deps: CliDeps,
	exitFn: (code: number) => never = defaultRuntime.exit,
	runtime: RuntimeEnv = defaultRuntime,
) {
	const port = Number.parseInt(opts.port, 10);
	if (Number.isNaN(port) || port <= 0 || port >= 65536) {
		throw new Error("Port must be between 1 and 65535");
	}
 
	await deps.ensurePortAvailable(port);
 
	// Validate env and binaries
	const env = deps.readEnv(runtime);
	await deps.ensureBinary("tailscale", runExec, runtime);
 
	// Enable Funnel first so we don't keep a webhook running on failure
	await deps.ensureFunnel(port, runExec, runtime, promptYesNo);
	const host = await deps.getTailnetHostname(runExec);
	const publicUrl = `https://${host}${opts.path}`;
	console.log(`🌐 Public webhook URL (via Funnel): ${publicUrl}`);
 
	// Start webhook locally (after funnel success)
	const server = await deps.startWebhook(
		port,
		opts.path,
		undefined,
		Boolean(opts.verbose),
	);
 
	// Configure Twilio sender webhook
	const client = createClient(env);
	const senderSid = await deps.findWhatsappSenderSid(
		client,
		env.whatsappFrom,
		env.whatsappSenderSid,
	);
	await deps.updateWebhook(client, senderSid, publicUrl, "POST", runtime);
 
	console.log(
		"\nSetup complete. Leave this process running to keep the webhook online. Ctrl+C to stop.",
	);
	return { server, publicUrl, senderSid };
}
 
type ListedMessage = {
	sid: string;
	status: string | null;
	direction: string | null;
	dateCreated?: Date | null;
	from?: string | null;
	to?: string | null;
	body?: string | null;
	errorCode?: number | null;
	errorMessage?: string | null;
};
 
function uniqueBySid(messages: ListedMessage[]): ListedMessage[] {
	const seen = new Set<string>();
	const deduped: ListedMessage[] = [];
	for (const m of messages) {
		if (seen.has(m.sid)) continue;
		seen.add(m.sid);
		deduped.push(m);
	}
	return deduped;
}
 
function sortByDateDesc(messages: ListedMessage[]): ListedMessage[] {
	return [...messages].sort((a, b) => {
		const da = a.dateCreated?.getTime() ?? 0;
		const db = b.dateCreated?.getTime() ?? 0;
		return db - da;
	});
}
 
function formatMessageLine(m: ListedMessage): string {
	const ts = m.dateCreated?.toISOString() ?? "unknown-time";
	const dir =
		m.direction === "inbound"
			? "⬅️ "
			: m.direction === "outbound-api" || m.direction === "outbound-reply"
				? "➡️ "
				: "↔️ ";
	const status = m.status ?? "unknown";
	const err =
		m.errorCode != null
			? ` error ${m.errorCode}${m.errorMessage ? ` (${m.errorMessage})` : ""}`
			: "";
	const body = (m.body ?? "").replace(/\s+/g, " ").trim();
	const bodyPreview =
		body.length > 140 ? `${body.slice(0, 137)}…` : body || "<empty>";
	return `[${ts}] ${dir}${m.from ?? "?"} -> ${m.to ?? "?"} | ${status}${err} | ${bodyPreview} (sid ${m.sid})`;
}
 
async function listRecentMessages(
	lookbackMinutes: number,
	limit: number,
	clientOverride?: ReturnType<typeof createClient>,
): Promise<ListedMessage[]> {
	const env = readEnv();
	const client = clientOverride ?? createClient(env);
	const from = withWhatsAppPrefix(env.whatsappFrom);
	const since = new Date(Date.now() - lookbackMinutes * 60_000);
 
	// Fetch inbound (to our WA number) and outbound (from our WA number), merge, sort, limit.
	const fetchLimit = Math.min(Math.max(limit * 2, limit + 10), 100);
	const inbound = await client.messages.list({
		to: from,
		dateSentAfter: since,
		limit: fetchLimit,
	});
	const outbound = await client.messages.list({
		from,
		dateSentAfter: since,
		limit: fetchLimit,
	});
 
	const combined = uniqueBySid(
		[...inbound, ...outbound].map((m) => ({
			sid: m.sid,
			status: m.status ?? null,
			direction: m.direction ?? null,
			dateCreated: m.dateCreated,
			from: m.from,
			to: m.to,
			body: m.body,
			errorCode: m.errorCode ?? null,
			errorMessage: m.errorMessage ?? null,
		})),
	);
 
	return sortByDateDesc(combined).slice(0, limit);
}
 
program
	.name("warelay")
	.description("WhatsApp relay CLI (Twilio or WhatsApp Web session)")
	.version("1.0.0");
 
program
	.command("web:login")
	.description("Link your personal WhatsApp via QR (web provider)")
	.option("--verbose", "Verbose connection logs", false)
	.action(async (opts) => {
		setVerbose(Boolean(opts.verbose));
		try {
			await loginWeb(Boolean(opts.verbose));
		} catch (err) {
			defaultRuntime.error(danger(`Web login failed: ${String(err)}`));
			defaultRuntime.exit(1);
		}
	});
 
program
	.command("send")
	.description("Send a WhatsApp message")
	.requiredOption(
		"-t, --to <number>",
		"Recipient number in E.164 (e.g. +15551234567)",
	)
	.requiredOption("-m, --message <text>", "Message body")
	.option("-w, --wait <seconds>", "Wait for delivery status (0 to skip)", "20")
	.option("-p, --poll <seconds>", "Polling interval while waiting", "2")
	.option("--provider <provider>", "Provider: twilio | web", "twilio")
	.addHelpText(
		"after",
		`
Examples:
  warelay send --to +15551234567 --message "Hi"                # wait 20s for delivery (default)
  warelay send --to +15551234567 --message "Hi" --wait 0       # fire-and-forget
  warelay send --to +15551234567 --message "Hi" --wait 60 --poll 3`,
	)
	.action(async (opts) => {
		const deps = createDefaultDeps();
		try {
			await sendCommand(opts, deps, defaultRuntime);
		} catch (err) {
			defaultRuntime.error(String(err));
			defaultRuntime.exit(1);
		}
	});
 
program
	.command("monitor")
	.description("Poll Twilio for inbound WhatsApp messages")
	.option("-i, --interval <seconds>", "Polling interval in seconds", "5")
	.option("-l, --lookback <minutes>", "Initial lookback window in minutes", "5")
	.addHelpText(
		"after",
		`
Examples:
  warelay monitor                         # poll every 5s, look back 5 minutes
  warelay monitor --interval 2 --lookback 30`,
	)
	.action(async (opts) => {
		const intervalSeconds = Number.parseInt(opts.interval, 10);
		const lookbackMinutes = Number.parseInt(opts.lookback, 10);
 
		if (Number.isNaN(intervalSeconds) || intervalSeconds <= 0) {
			defaultRuntime.error("Interval must be a positive integer");
			defaultRuntime.exit(1);
		}
		if (Number.isNaN(lookbackMinutes) || lookbackMinutes < 0) {
			defaultRuntime.error("Lookback must be >= 0 minutes");
			defaultRuntime.exit(1);
		}
 
		await monitor(intervalSeconds, lookbackMinutes);
	});
 
program
	.command("web:monitor")
	.description("Listen for inbound messages via personal WhatsApp Web and auto-reply")
	.option("--verbose", "Verbose logging", false)
	.addHelpText(
		"after",
		`
Examples:
  warelay web:monitor            # start auto-replies on your linked web session
  warelay web:monitor --verbose  # show low-level Baileys logs
`,
	)
	.action(async (opts) => {
		setVerbose(Boolean(opts.verbose));
		await monitorWebProvider(Boolean(opts.verbose));
	});
 
program
	.command("status")
	.description("Show recent WhatsApp messages (sent and received)")
	.option("-l, --limit <count>", "Number of messages to show", "20")
	.option("-b, --lookback <minutes>", "How far back to fetch messages", "240")
	.option("--json", "Output JSON instead of text", false)
	.addHelpText(
		"after",
		`
Examples:
  warelay status                            # last 20 msgs in past 4h
  warelay status --limit 5 --lookback 30    # last 5 msgs in past 30m
  warelay status --json --limit 50          # machine-readable output`,
	)
	.action(async (opts) => {
		const deps = createDefaultDeps();
		try {
			await statusCommand(opts, deps, defaultRuntime);
		} catch (err) {
			defaultRuntime.error(String(err));
			defaultRuntime.exit(1);
		}
	});
 
program
	.command("poll")
	.description("Poll Twilio for inbound WhatsApp messages (non-webhook mode)")
	.option("-i, --interval <seconds>", "Polling interval in seconds", "5")
	.option("-l, --lookback <minutes>", "Initial lookback window in minutes", "5")
	.option("--verbose", "Verbose logging during polling", false)
	.addHelpText(
		"after",
		`
Examples:
  warelay poll                         # poll every 5s, look back 5 minutes
  warelay poll --interval 2 --lookback 30 --verbose`,
	)
	.action(async (opts) => {
		setVerbose(Boolean(opts.verbose));
		const intervalSeconds = Number.parseInt(opts.interval, 10);
		const lookbackMinutes = Number.parseInt(opts.lookback, 10);
 
		if (Number.isNaN(intervalSeconds) || intervalSeconds <= 0) {
			defaultRuntime.error("Interval must be a positive integer");
			defaultRuntime.exit(1);
		}
		if (Number.isNaN(lookbackMinutes) || lookbackMinutes < 0) {
			defaultRuntime.error("Lookback must be >= 0 minutes");
			defaultRuntime.exit(1);
		}
 
		await monitor(intervalSeconds, lookbackMinutes);
	});
 
program
	.command("webhook")
	.description(
		"Run a local webhook server for inbound WhatsApp (works with Tailscale/port forward)",
	)
	.option("-p, --port <port>", "Port to listen on", "42873")
	.option("-r, --reply <text>", "Optional auto-reply text")
	.option("--path <path>", "Webhook path", "/webhook/whatsapp")
	.option("--verbose", "Log inbound and auto-replies", false)
	.option("-y, --yes", "Auto-confirm prompts when possible", false)
	.addHelpText(
		"after",
		`
Examples:
  warelay webhook                       # listen on 42873
  warelay webhook --port 45000          # pick a high, less-colliding port
  warelay webhook --reply "Got it!"     # static auto-reply; otherwise use config file
 
With Tailscale:
  tailscale serve tcp 42873 127.0.0.1:42873
  (then set Twilio webhook URL to your tailnet IP:42873/webhook/whatsapp)`,
	)
	// istanbul ignore next
	.action(async (opts) => {
		setVerbose(Boolean(opts.verbose));
		setYes(Boolean(opts.yes));
		const deps = createDefaultDeps();
		try {
			const server = await webhookCommand(opts, deps, defaultRuntime);
			process.on("SIGINT", () => {
				server.close(() => {
					console.log("\n👋 Webhook stopped");
					defaultRuntime.exit(0);
				});
			});
			await deps.waitForever();
		} catch (err) {
			defaultRuntime.error(String(err));
			defaultRuntime.exit(1);
		}
	});
 
program
	.command("up")
	.description(
		"Bring up webhook + Tailscale Funnel + Twilio callback (default webhook mode)",
	)
	.option("-p, --port <port>", "Port to listen on", "42873")
	.option("--path <path>", "Webhook path", "/webhook/whatsapp")
	.option("--verbose", "Verbose logging during setup/webhook", false)
	.option("-y, --yes", "Auto-confirm prompts when possible", false)
	// istanbul ignore next
	.action(async (opts) => {
		setVerbose(Boolean(opts.verbose));
		setYes(Boolean(opts.yes));
		const deps = createDefaultDeps();
		try {
			const { server } = await upCommand(opts, deps, defaultRuntime);
			process.on("SIGINT", () => {
				server.close(() => {
					console.log("\n👋 Webhook stopped");
					defaultRuntime.exit(0);
				});
			});
			await deps.waitForever();
		} catch (err) {
			defaultRuntime.error(String(err));
			defaultRuntime.exit(1);
		}
	});
 
export {
	assertProvider,
	autoReplyIfConfigured,
	applyTemplate,
	createClient,
	deriveSessionKey,
	describePortOwner,
	ensureBinary,
	ensureFunnel,
	ensureGoInstalled,
	ensurePortAvailable,
	ensureTailscaledInstalled,
	findIncomingNumberSid,
	findMessagingServiceSid,
	findWhatsappSenderSid,
	formatMessageLine,
	formatTwilioError,
	getReplyFromConfig,
	getTailnetHostname,
	handlePortError,
	logTwilioSendError,
	listRecentMessages,
	loadConfig,
	loadSessionStore,
	monitor,
	monitorWebProvider,
	normalizeE164,
	PortInUseError,
	promptYesNo,
	createDefaultDeps,
	performSend,
	performStatus,
	performUp,
	performWebhookSetup,
	readEnv,
	resolveStorePath,
	runCommandWithTimeout,
	runExec,
	saveSessionStore,
	sendMessage,
	sendTypingIndicator,
	setMessagingServiceWebhook,
	sortByDateDesc,
	startWebhook,
	updateWebhook,
	uniqueBySid,
	waitForFinalStatus,
	waitForever,
	toWhatsappJid,
	program,
};
 
const isMain =
	process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
 
Iif (isMain) {
	program.parseAsync(process.argv);
}