privateer-agent 0.15.4 → 0.15.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/README.md +11 -0
  2. package/bin/boot-bundle.d.mts +2 -0
  3. package/bin/boot-bundle.mjs +44 -0
  4. package/bin/fresh-supervisor.d.mts +5 -1
  5. package/bin/fresh-supervisor.mjs +47 -10
  6. package/bin/privateer-launch.mjs +27 -3
  7. package/bin/privateer-subagent.mjs +5 -2
  8. package/bin/privateer-verify.mjs +12 -0
  9. package/bin/session-recovery.d.mts +53 -0
  10. package/bin/session-recovery.mjs +240 -0
  11. package/bin/session-seal-preload.mjs +17 -0
  12. package/bin/session-seal.d.mts +25 -0
  13. package/bin/session-seal.mjs +242 -0
  14. package/dist-boot/boot.mjs +3 -0
  15. package/dist-boot/c-27JKSMWL.mjs +1460 -0
  16. package/dist-boot/c-2BMRFV24.mjs +269 -0
  17. package/dist-boot/c-2CTF6JA3.mjs +166 -0
  18. package/dist-boot/c-2G3BBHRJ.mjs +84 -0
  19. package/dist-boot/c-2IDLKXX6.mjs +250 -0
  20. package/dist-boot/c-2NJD5VYM.mjs +8 -0
  21. package/dist-boot/c-2S5EEQPW.mjs +1602 -0
  22. package/dist-boot/c-2WRDCUVI.mjs +25 -0
  23. package/dist-boot/c-2YN3M256.mjs +14 -0
  24. package/dist-boot/c-37GM3GMU.mjs +187 -0
  25. package/dist-boot/c-3STKRSVO.mjs +2480 -0
  26. package/dist-boot/c-3TPV6TQQ.mjs +2320 -0
  27. package/dist-boot/c-3UVHLQDJ.mjs +225 -0
  28. package/dist-boot/c-42PUUZYC.mjs +697 -0
  29. package/dist-boot/c-4D5UMWVW.mjs +683 -0
  30. package/dist-boot/c-4ETZRMTA.mjs +46 -0
  31. package/dist-boot/c-4QT25BD5.mjs +1482 -0
  32. package/dist-boot/c-4WVR32AP.mjs +2579 -0
  33. package/dist-boot/c-5EMM567G.mjs +152 -0
  34. package/dist-boot/c-5FA4CV63.mjs +145 -0
  35. package/dist-boot/c-5GV3X3RB.mjs +14 -0
  36. package/dist-boot/c-5JCEPRIY.mjs +52 -0
  37. package/dist-boot/c-5NDKIIWT.mjs +16 -0
  38. package/dist-boot/c-5QL3AR26.mjs +4665 -0
  39. package/dist-boot/c-5XY6MFKN.mjs +5142 -0
  40. package/dist-boot/c-65UZIZC7.mjs +2897 -0
  41. package/dist-boot/c-6FUXKHOK.mjs +1969 -0
  42. package/dist-boot/c-6JHWQE4V.mjs +18242 -0
  43. package/dist-boot/c-6LOBR4I6.mjs +5280 -0
  44. package/dist-boot/c-6QHOZXKQ.mjs +14394 -0
  45. package/dist-boot/c-6ZO2SADQ.mjs +178 -0
  46. package/dist-boot/c-6ZORVVZP.mjs +1449 -0
  47. package/dist-boot/c-76QH4UCP.mjs +2441 -0
  48. package/dist-boot/c-77GO5L5Y.mjs +20982 -0
  49. package/dist-boot/c-7M23XFTN.mjs +5052 -0
  50. package/dist-boot/c-7TC367E2.mjs +32 -0
  51. package/dist-boot/c-7UOG7POX.mjs +1524 -0
  52. package/dist-boot/c-7VHP3FLN.mjs +376 -0
  53. package/dist-boot/c-A73JHZP2.mjs +13207 -0
  54. package/dist-boot/c-ABXULAFL.mjs +71 -0
  55. package/dist-boot/c-ANDD2AQO.mjs +74 -0
  56. package/dist-boot/c-AOY77AZL.mjs +1430 -0
  57. package/dist-boot/c-AXEPZ22I.mjs +108 -0
  58. package/dist-boot/c-B2Y7VNHU.mjs +427 -0
  59. package/dist-boot/c-B7VJUH73.mjs +77 -0
  60. package/dist-boot/c-BFW6CDVL.mjs +24 -0
  61. package/dist-boot/c-BHNIF2AR.mjs +188 -0
  62. package/dist-boot/c-BKF2O6BL.mjs +23 -0
  63. package/dist-boot/c-BOZXFTZN.mjs +8 -0
  64. package/dist-boot/c-BRNYJWZL.mjs +28 -0
  65. package/dist-boot/c-C3N4Z2HO.mjs +93 -0
  66. package/dist-boot/c-C4IV7ZFG.mjs +717 -0
  67. package/dist-boot/c-C5NK6UYV.mjs +793 -0
  68. package/dist-boot/c-C67644MB.mjs +1659 -0
  69. package/dist-boot/c-C6S2YB53.mjs +620 -0
  70. package/dist-boot/c-CDBEJSBF.mjs +37 -0
  71. package/dist-boot/c-CG47HBKU.mjs +435 -0
  72. package/dist-boot/c-CKCTWCT5.mjs +51 -0
  73. package/dist-boot/c-CN77DCGF.mjs +60 -0
  74. package/dist-boot/c-CRBXNKFO.mjs +1795 -0
  75. package/dist-boot/c-CRIHASQ6.mjs +973 -0
  76. package/dist-boot/c-CU4NGAUO.mjs +3786 -0
  77. package/dist-boot/c-CWRFLGQU.mjs +1883 -0
  78. package/dist-boot/c-CYQB2USO.mjs +32 -0
  79. package/dist-boot/c-DEE67DJO.mjs +379 -0
  80. package/dist-boot/c-DIFDBYOP.mjs +1258 -0
  81. package/dist-boot/c-DOSGVXDZ.mjs +34879 -0
  82. package/dist-boot/c-DR7XQI32.mjs +381 -0
  83. package/dist-boot/c-DTGPSB46.mjs +14666 -0
  84. package/dist-boot/c-DTHDNA4P.mjs +320 -0
  85. package/dist-boot/c-E4Z3Y5B5.mjs +3864 -0
  86. package/dist-boot/c-E66Z2TI7.mjs +203 -0
  87. package/dist-boot/c-EBU6RLRV.mjs +1527 -0
  88. package/dist-boot/c-EBZZNGSF.mjs +432 -0
  89. package/dist-boot/c-EC3LJ2KF.mjs +1032 -0
  90. package/dist-boot/c-EQBKXWNX.mjs +15829 -0
  91. package/dist-boot/c-EUEPIW4S.mjs +574 -0
  92. package/dist-boot/c-EX4YVWAT.mjs +378 -0
  93. package/dist-boot/c-EYZGSAJU.mjs +98 -0
  94. package/dist-boot/c-F75VRKY4.mjs +172 -0
  95. package/dist-boot/c-FH4NXKHV.mjs +177 -0
  96. package/dist-boot/c-FHNUCTEM.mjs +140 -0
  97. package/dist-boot/c-FJ5T42DS.mjs +5349 -0
  98. package/dist-boot/c-FPCNRL7G.mjs +1728 -0
  99. package/dist-boot/c-G4DLN7Q4.mjs +8 -0
  100. package/dist-boot/c-G56GYQFZ.mjs +2507 -0
  101. package/dist-boot/c-GLIOERDQ.mjs +1200 -0
  102. package/dist-boot/c-GMJ5HUBM.mjs +14 -0
  103. package/dist-boot/c-H3HSGMAQ.mjs +461 -0
  104. package/dist-boot/c-HIKTO6P7.mjs +275 -0
  105. package/dist-boot/c-I2MCJ34O.mjs +464 -0
  106. package/dist-boot/c-I3C6LBW4.mjs +765 -0
  107. package/dist-boot/c-I54OKQHW.mjs +387 -0
  108. package/dist-boot/c-IFSP3R4D.mjs +80 -0
  109. package/dist-boot/c-IZK77VB7.mjs +171 -0
  110. package/dist-boot/c-J3Y25UGE.mjs +54 -0
  111. package/dist-boot/c-J5IESS7W.mjs +27750 -0
  112. package/dist-boot/c-JJWZBY7L.mjs +254 -0
  113. package/dist-boot/c-JKTFXTGF.mjs +463 -0
  114. package/dist-boot/c-JN57AXQ4.mjs +77 -0
  115. package/dist-boot/c-KFIO6LUW.mjs +1096 -0
  116. package/dist-boot/c-KIEMEFWW.mjs +478 -0
  117. package/dist-boot/c-KIVXWBYD.mjs +28 -0
  118. package/dist-boot/c-KP6CRIP4.mjs +580 -0
  119. package/dist-boot/c-L26VOJX4.mjs +11558 -0
  120. package/dist-boot/c-L5GHWG5G.mjs +5988 -0
  121. package/dist-boot/c-M7NSQAKK.mjs +353 -0
  122. package/dist-boot/c-MCEWOPBW.mjs +56 -0
  123. package/dist-boot/c-MGPIEG7I.mjs +20 -0
  124. package/dist-boot/c-NREXJV3M.mjs +393 -0
  125. package/dist-boot/c-O5PP6CTX.mjs +162 -0
  126. package/dist-boot/c-OBQDHSXM.mjs +1774 -0
  127. package/dist-boot/c-OLQHHDD4.mjs +21 -0
  128. package/dist-boot/c-OXW4JQQH.mjs +319 -0
  129. package/dist-boot/c-P3D7ZUWN.mjs +1288 -0
  130. package/dist-boot/c-P4PQZVV5.mjs +948 -0
  131. package/dist-boot/c-P63T3XL2.mjs +26373 -0
  132. package/dist-boot/c-P6N5DQGZ.mjs +194 -0
  133. package/dist-boot/c-P7MLKQFC.mjs +58 -0
  134. package/dist-boot/c-PB3PZJL5.mjs +1276 -0
  135. package/dist-boot/c-PTN4S6G2.mjs +1259 -0
  136. package/dist-boot/c-PYCE5J7U.mjs +1083 -0
  137. package/dist-boot/c-Q4HYCRLB.mjs +19410 -0
  138. package/dist-boot/c-QUXMETGG.mjs +68 -0
  139. package/dist-boot/c-RDMJZCOX.mjs +356 -0
  140. package/dist-boot/c-ROGJK76M.mjs +17 -0
  141. package/dist-boot/c-RQJJ26T4.mjs +708 -0
  142. package/dist-boot/c-RSKCUPJF.mjs +7559 -0
  143. package/dist-boot/c-RVJU4O6P.mjs +37 -0
  144. package/dist-boot/c-S2RVHR3M.mjs +165 -0
  145. package/dist-boot/c-SKMK3PEE.mjs +91120 -0
  146. package/dist-boot/c-TI7SM4EG.mjs +20 -0
  147. package/dist-boot/c-TILJ6GXD.mjs +1235 -0
  148. package/dist-boot/c-TT6BCUJD.mjs +114 -0
  149. package/dist-boot/c-U4ITOXAN.mjs +2107 -0
  150. package/dist-boot/c-UGERXVO2.mjs +7120 -0
  151. package/dist-boot/c-UPBH5AXY.mjs +1363 -0
  152. package/dist-boot/c-US2PUNZL.mjs +597 -0
  153. package/dist-boot/c-UU4WZPPE.mjs +20 -0
  154. package/dist-boot/c-UWVIYPQS.mjs +39 -0
  155. package/dist-boot/c-V4RHQBPQ.mjs +17683 -0
  156. package/dist-boot/c-V5MRVK47.mjs +351 -0
  157. package/dist-boot/c-V6CL266R.mjs +1755 -0
  158. package/dist-boot/c-VJTMFKYE.mjs +14975 -0
  159. package/dist-boot/c-VJTRUKIB.mjs +773 -0
  160. package/dist-boot/c-W4IFSHPW.mjs +43 -0
  161. package/dist-boot/c-WETGB2CF.mjs +113 -0
  162. package/dist-boot/c-WO3QSZUU.mjs +1337 -0
  163. package/dist-boot/c-WQLH73TY.mjs +242 -0
  164. package/dist-boot/c-XL735JW5.mjs +500 -0
  165. package/dist-boot/c-Y7HADL5B.mjs +1107 -0
  166. package/dist-boot/c-YGQHSVSK.mjs +41 -0
  167. package/dist-boot/c-YMP2AMEB.mjs +10350 -0
  168. package/dist-boot/c-YRDO2WEF.mjs +12012 -0
  169. package/dist-boot/c-YUSTRATJ.mjs +8 -0
  170. package/dist-boot/c-Z2262R22.mjs +2697 -0
  171. package/dist-boot/c-Z4ALQMJC.mjs +709 -0
  172. package/dist-boot/c-Z5ZUQVUY.mjs +62 -0
  173. package/dist-boot/c-ZDZUKXF7.mjs +874 -0
  174. package/dist-boot/c-ZJYLGIC3.mjs +32 -0
  175. package/dist-boot/c-ZNA5CDMI.mjs +77 -0
  176. package/dist-boot/c-ZSO6DI3M.mjs +204 -0
  177. package/dist-boot/c-ZWUVHKMK.mjs +100 -0
  178. package/dist-boot/c-ZY4MESEW.mjs +832 -0
  179. package/dist-boot/c-ZZ5REI4L.mjs +329 -0
  180. package/dist-boot/cli.mjs +51 -0
  181. package/dist-boot/ext-anthropic-attribution.mjs +207 -0
  182. package/dist-boot/ext-pi-background-tasks.mjs +7234 -0
  183. package/dist-boot/ext-pi-subagents.mjs +37 -0
  184. package/dist-boot/ext-privateer-account.mjs +4426 -0
  185. package/dist-boot/ext-privateer-brand.mjs +5274 -0
  186. package/dist-boot/ext-privateer-codemode.mjs +37 -0
  187. package/dist-boot/ext-privateer-computer.mjs +626 -0
  188. package/dist-boot/ext-privateer-connect.mjs +1862 -0
  189. package/dist-boot/ext-privateer-context.mjs +323 -0
  190. package/dist-boot/ext-privateer-desktop.mjs +92 -0
  191. package/dist-boot/ext-privateer-final-audit.mjs +48 -0
  192. package/dist-boot/ext-privateer-fresh.mjs +81 -0
  193. package/dist-boot/ext-privateer-gate.mjs +5959 -0
  194. package/dist-boot/ext-privateer-hints.mjs +236 -0
  195. package/dist-boot/ext-privateer-media.mjs +2626 -0
  196. package/dist-boot/ext-privateer-models.mjs +3397 -0
  197. package/dist-boot/ext-privateer-posture.mjs +3006 -0
  198. package/dist-boot/ext-privateer-privacy.mjs +4578 -0
  199. package/dist-boot/ext-privateer-recovery.mjs +287 -0
  200. package/dist-boot/ext-privateer-speak.mjs +4754 -0
  201. package/dist-boot/ext-privateer-terminals.mjs +725 -0
  202. package/dist-boot/ext-privateer-tools.mjs +528 -0
  203. package/dist-boot/ext-privateer-truncation.mjs +74 -0
  204. package/dist-boot/ext-privateer-update.mjs +210 -0
  205. package/dist-boot/ext-privateer-vision.mjs +148 -0
  206. package/dist-boot/ext-privateer-web.mjs +543 -0
  207. package/dist-boot/ext-rpiv-ask-user-question.mjs +710 -0
  208. package/dist-boot/manifest.json +9 -0
  209. package/extensions/privateer-brand.ts +3 -1
  210. package/extensions/privateer-context.ts +4 -2
  211. package/extensions/privateer-final-audit.ts +17 -0
  212. package/extensions/privateer-gate.ts +55 -9
  213. package/extensions/privateer-recovery.ts +175 -0
  214. package/extensions/privateer-web.ts +4 -4
  215. package/package.json +3 -1
  216. package/patches/@earendil-works+pi-coding-agent+1.3.0.patch +199 -2
  217. package/patches/pi-background-tasks+2.6.10.patch +91 -7
  218. package/src/cli/chat.ts +7 -1
  219. package/src/config/moatManifest.json +2 -0
  220. package/src/config/whatsNew.json +4 -4
  221. package/src/context.ts +33 -5
  222. package/src/engine/finalAudit.ts +38 -0
  223. package/src/engine/stallWatchdog.ts +8 -1
  224. package/src/providers/account.ts +34 -3
  225. package/src/remote/attentionPush.ts +40 -0
  226. package/src/remote/liveTaskSession.ts +7 -1
  227. package/src/remote/relayClient.ts +38 -4
  228. package/src/remote/remoteBridge.ts +17 -0
  229. package/src/remote/transcriptSnapshot.ts +104 -0
@@ -0,0 +1,3864 @@
1
+ import{createRequire as __pvCR}from"node:module";import{fileURLToPath as __pvF}from"node:url";import{dirname as __pvD}from"node:path";const require=__pvCR(import.meta.url);const __pvUrl=(r)=>new URL(r,import.meta.url).href;const __pvFile=(r)=>__pvF(new URL(r,import.meta.url));
2
+ import {
3
+ getShellConfig
4
+ } from "./c-6ZO2SADQ.mjs";
5
+ import {
6
+ getAgentDir,
7
+ getFileRevision,
8
+ normalizePath,
9
+ require_cross_spawn,
10
+ stripBom
11
+ } from "./c-PTN4S6G2.mjs";
12
+ import {
13
+ __commonJS,
14
+ __name,
15
+ __require,
16
+ __toESM
17
+ } from "./c-CN77DCGF.mjs";
18
+
19
+ // node_modules/graceful-fs/polyfills.js
20
+ var require_polyfills = __commonJS({
21
+ "node_modules/graceful-fs/polyfills.js"(exports, module) {
22
+ var constants = __require("constants");
23
+ var origCwd = process.cwd;
24
+ var cwd = null;
25
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
26
+ process.cwd = function() {
27
+ if (!cwd)
28
+ cwd = origCwd.call(process);
29
+ return cwd;
30
+ };
31
+ try {
32
+ process.cwd();
33
+ } catch (er) {
34
+ }
35
+ if (typeof process.chdir === "function") {
36
+ chdir = process.chdir;
37
+ process.chdir = function(d) {
38
+ cwd = null;
39
+ chdir.call(process, d);
40
+ };
41
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
42
+ }
43
+ var chdir;
44
+ module.exports = patch;
45
+ function patch(fs) {
46
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
47
+ patchLchmod(fs);
48
+ }
49
+ if (!fs.lutimes) {
50
+ patchLutimes(fs);
51
+ }
52
+ fs.chown = chownFix(fs.chown);
53
+ fs.fchown = chownFix(fs.fchown);
54
+ fs.lchown = chownFix(fs.lchown);
55
+ fs.chmod = chmodFix(fs.chmod);
56
+ fs.fchmod = chmodFix(fs.fchmod);
57
+ fs.lchmod = chmodFix(fs.lchmod);
58
+ fs.chownSync = chownFixSync(fs.chownSync);
59
+ fs.fchownSync = chownFixSync(fs.fchownSync);
60
+ fs.lchownSync = chownFixSync(fs.lchownSync);
61
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
62
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
63
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
64
+ fs.stat = statFix(fs.stat);
65
+ fs.fstat = statFix(fs.fstat);
66
+ fs.lstat = statFix(fs.lstat);
67
+ fs.statSync = statFixSync(fs.statSync);
68
+ fs.fstatSync = statFixSync(fs.fstatSync);
69
+ fs.lstatSync = statFixSync(fs.lstatSync);
70
+ if (fs.chmod && !fs.lchmod) {
71
+ fs.lchmod = function(path, mode, cb) {
72
+ if (cb) process.nextTick(cb);
73
+ };
74
+ fs.lchmodSync = function() {
75
+ };
76
+ }
77
+ if (fs.chown && !fs.lchown) {
78
+ fs.lchown = function(path, uid, gid, cb) {
79
+ if (cb) process.nextTick(cb);
80
+ };
81
+ fs.lchownSync = function() {
82
+ };
83
+ }
84
+ if (platform === "win32") {
85
+ fs.rename = typeof fs.rename !== "function" ? fs.rename : (function(fs$rename) {
86
+ function rename(from, to, cb) {
87
+ var start = Date.now();
88
+ var backoff = 0;
89
+ fs$rename(from, to, /* @__PURE__ */ __name(function CB(er) {
90
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) {
91
+ setTimeout(function() {
92
+ fs.stat(to, function(stater, st) {
93
+ if (stater && stater.code === "ENOENT")
94
+ fs$rename(from, to, CB);
95
+ else
96
+ cb(er);
97
+ });
98
+ }, backoff);
99
+ if (backoff < 100)
100
+ backoff += 10;
101
+ return;
102
+ }
103
+ if (cb) cb(er);
104
+ }, "CB"));
105
+ }
106
+ __name(rename, "rename");
107
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
108
+ return rename;
109
+ })(fs.rename);
110
+ }
111
+ fs.read = typeof fs.read !== "function" ? fs.read : (function(fs$read) {
112
+ function read(fd, buffer, offset, length, position, callback_) {
113
+ var callback;
114
+ if (callback_ && typeof callback_ === "function") {
115
+ var eagCounter = 0;
116
+ callback = /* @__PURE__ */ __name(function(er, _, __) {
117
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
118
+ eagCounter++;
119
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
120
+ }
121
+ callback_.apply(this, arguments);
122
+ }, "callback");
123
+ }
124
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
125
+ }
126
+ __name(read, "read");
127
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
128
+ return read;
129
+ })(fs.read);
130
+ fs.readSync = typeof fs.readSync !== "function" ? fs.readSync : /* @__PURE__ */ (function(fs$readSync) {
131
+ return function(fd, buffer, offset, length, position) {
132
+ var eagCounter = 0;
133
+ while (true) {
134
+ try {
135
+ return fs$readSync.call(fs, fd, buffer, offset, length, position);
136
+ } catch (er) {
137
+ if (er.code === "EAGAIN" && eagCounter < 10) {
138
+ eagCounter++;
139
+ continue;
140
+ }
141
+ throw er;
142
+ }
143
+ }
144
+ };
145
+ })(fs.readSync);
146
+ function patchLchmod(fs2) {
147
+ fs2.lchmod = function(path, mode, callback) {
148
+ fs2.open(
149
+ path,
150
+ constants.O_WRONLY | constants.O_SYMLINK,
151
+ mode,
152
+ function(err, fd) {
153
+ if (err) {
154
+ if (callback) callback(err);
155
+ return;
156
+ }
157
+ fs2.fchmod(fd, mode, function(err2) {
158
+ fs2.close(fd, function(err22) {
159
+ if (callback) callback(err2 || err22);
160
+ });
161
+ });
162
+ }
163
+ );
164
+ };
165
+ fs2.lchmodSync = function(path, mode) {
166
+ var fd = fs2.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
167
+ var threw = true;
168
+ var ret;
169
+ try {
170
+ ret = fs2.fchmodSync(fd, mode);
171
+ threw = false;
172
+ } finally {
173
+ if (threw) {
174
+ try {
175
+ fs2.closeSync(fd);
176
+ } catch (er) {
177
+ }
178
+ } else {
179
+ fs2.closeSync(fd);
180
+ }
181
+ }
182
+ return ret;
183
+ };
184
+ }
185
+ __name(patchLchmod, "patchLchmod");
186
+ function patchLutimes(fs2) {
187
+ if (constants.hasOwnProperty("O_SYMLINK") && fs2.futimes) {
188
+ fs2.lutimes = function(path, at, mt, cb) {
189
+ fs2.open(path, constants.O_SYMLINK, function(er, fd) {
190
+ if (er) {
191
+ if (cb) cb(er);
192
+ return;
193
+ }
194
+ fs2.futimes(fd, at, mt, function(er2) {
195
+ fs2.close(fd, function(er22) {
196
+ if (cb) cb(er2 || er22);
197
+ });
198
+ });
199
+ });
200
+ };
201
+ fs2.lutimesSync = function(path, at, mt) {
202
+ var fd = fs2.openSync(path, constants.O_SYMLINK);
203
+ var ret;
204
+ var threw = true;
205
+ try {
206
+ ret = fs2.futimesSync(fd, at, mt);
207
+ threw = false;
208
+ } finally {
209
+ if (threw) {
210
+ try {
211
+ fs2.closeSync(fd);
212
+ } catch (er) {
213
+ }
214
+ } else {
215
+ fs2.closeSync(fd);
216
+ }
217
+ }
218
+ return ret;
219
+ };
220
+ } else if (fs2.futimes) {
221
+ fs2.lutimes = function(_a, _b, _c, cb) {
222
+ if (cb) process.nextTick(cb);
223
+ };
224
+ fs2.lutimesSync = function() {
225
+ };
226
+ }
227
+ }
228
+ __name(patchLutimes, "patchLutimes");
229
+ function chmodFix(orig) {
230
+ if (!orig) return orig;
231
+ return function(target, mode, cb) {
232
+ return orig.call(fs, target, mode, function(er) {
233
+ if (chownErOk(er)) er = null;
234
+ if (cb) cb.apply(this, arguments);
235
+ });
236
+ };
237
+ }
238
+ __name(chmodFix, "chmodFix");
239
+ function chmodFixSync(orig) {
240
+ if (!orig) return orig;
241
+ return function(target, mode) {
242
+ try {
243
+ return orig.call(fs, target, mode);
244
+ } catch (er) {
245
+ if (!chownErOk(er)) throw er;
246
+ }
247
+ };
248
+ }
249
+ __name(chmodFixSync, "chmodFixSync");
250
+ function chownFix(orig) {
251
+ if (!orig) return orig;
252
+ return function(target, uid, gid, cb) {
253
+ return orig.call(fs, target, uid, gid, function(er) {
254
+ if (chownErOk(er)) er = null;
255
+ if (cb) cb.apply(this, arguments);
256
+ });
257
+ };
258
+ }
259
+ __name(chownFix, "chownFix");
260
+ function chownFixSync(orig) {
261
+ if (!orig) return orig;
262
+ return function(target, uid, gid) {
263
+ try {
264
+ return orig.call(fs, target, uid, gid);
265
+ } catch (er) {
266
+ if (!chownErOk(er)) throw er;
267
+ }
268
+ };
269
+ }
270
+ __name(chownFixSync, "chownFixSync");
271
+ function statFix(orig) {
272
+ if (!orig) return orig;
273
+ return function(target, options, cb) {
274
+ if (typeof options === "function") {
275
+ cb = options;
276
+ options = null;
277
+ }
278
+ function callback(er, stats) {
279
+ if (stats) {
280
+ if (stats.uid < 0) stats.uid += 4294967296;
281
+ if (stats.gid < 0) stats.gid += 4294967296;
282
+ }
283
+ if (cb) cb.apply(this, arguments);
284
+ }
285
+ __name(callback, "callback");
286
+ return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback);
287
+ };
288
+ }
289
+ __name(statFix, "statFix");
290
+ function statFixSync(orig) {
291
+ if (!orig) return orig;
292
+ return function(target, options) {
293
+ var stats = options ? orig.call(fs, target, options) : orig.call(fs, target);
294
+ if (stats) {
295
+ if (stats.uid < 0) stats.uid += 4294967296;
296
+ if (stats.gid < 0) stats.gid += 4294967296;
297
+ }
298
+ return stats;
299
+ };
300
+ }
301
+ __name(statFixSync, "statFixSync");
302
+ function chownErOk(er) {
303
+ if (!er)
304
+ return true;
305
+ if (er.code === "ENOSYS")
306
+ return true;
307
+ var nonroot = !process.getuid || process.getuid() !== 0;
308
+ if (nonroot) {
309
+ if (er.code === "EINVAL" || er.code === "EPERM")
310
+ return true;
311
+ }
312
+ return false;
313
+ }
314
+ __name(chownErOk, "chownErOk");
315
+ }
316
+ __name(patch, "patch");
317
+ }
318
+ });
319
+
320
+ // node_modules/graceful-fs/legacy-streams.js
321
+ var require_legacy_streams = __commonJS({
322
+ "node_modules/graceful-fs/legacy-streams.js"(exports, module) {
323
+ var Stream = __require("stream").Stream;
324
+ module.exports = legacy;
325
+ function legacy(fs) {
326
+ return {
327
+ ReadStream,
328
+ WriteStream
329
+ };
330
+ function ReadStream(path, options) {
331
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
332
+ Stream.call(this);
333
+ var self = this;
334
+ this.path = path;
335
+ this.fd = null;
336
+ this.readable = true;
337
+ this.paused = false;
338
+ this.flags = "r";
339
+ this.mode = 438;
340
+ this.bufferSize = 64 * 1024;
341
+ options = options || {};
342
+ var keys = Object.keys(options);
343
+ for (var index = 0, length = keys.length; index < length; index++) {
344
+ var key = keys[index];
345
+ this[key] = options[key];
346
+ }
347
+ if (this.encoding) this.setEncoding(this.encoding);
348
+ if (this.start !== void 0) {
349
+ if ("number" !== typeof this.start) {
350
+ throw TypeError("start must be a Number");
351
+ }
352
+ if (this.end === void 0) {
353
+ this.end = Infinity;
354
+ } else if ("number" !== typeof this.end) {
355
+ throw TypeError("end must be a Number");
356
+ }
357
+ if (this.start > this.end) {
358
+ throw new Error("start must be <= end");
359
+ }
360
+ this.pos = this.start;
361
+ }
362
+ if (this.fd !== null) {
363
+ process.nextTick(function() {
364
+ self._read();
365
+ });
366
+ return;
367
+ }
368
+ fs.open(this.path, this.flags, this.mode, function(err, fd) {
369
+ if (err) {
370
+ self.emit("error", err);
371
+ self.readable = false;
372
+ return;
373
+ }
374
+ self.fd = fd;
375
+ self.emit("open", fd);
376
+ self._read();
377
+ });
378
+ }
379
+ __name(ReadStream, "ReadStream");
380
+ function WriteStream(path, options) {
381
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
382
+ Stream.call(this);
383
+ this.path = path;
384
+ this.fd = null;
385
+ this.writable = true;
386
+ this.flags = "w";
387
+ this.encoding = "binary";
388
+ this.mode = 438;
389
+ this.bytesWritten = 0;
390
+ options = options || {};
391
+ var keys = Object.keys(options);
392
+ for (var index = 0, length = keys.length; index < length; index++) {
393
+ var key = keys[index];
394
+ this[key] = options[key];
395
+ }
396
+ if (this.start !== void 0) {
397
+ if ("number" !== typeof this.start) {
398
+ throw TypeError("start must be a Number");
399
+ }
400
+ if (this.start < 0) {
401
+ throw new Error("start must be >= zero");
402
+ }
403
+ this.pos = this.start;
404
+ }
405
+ this.busy = false;
406
+ this._queue = [];
407
+ if (this.fd === null) {
408
+ this._open = fs.open;
409
+ this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
410
+ this.flush();
411
+ }
412
+ }
413
+ __name(WriteStream, "WriteStream");
414
+ }
415
+ __name(legacy, "legacy");
416
+ }
417
+ });
418
+
419
+ // node_modules/graceful-fs/clone.js
420
+ var require_clone = __commonJS({
421
+ "node_modules/graceful-fs/clone.js"(exports, module) {
422
+ "use strict";
423
+ module.exports = clone;
424
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
425
+ return obj.__proto__;
426
+ };
427
+ function clone(obj) {
428
+ if (obj === null || typeof obj !== "object")
429
+ return obj;
430
+ if (obj instanceof Object)
431
+ var copy = { __proto__: getPrototypeOf(obj) };
432
+ else
433
+ var copy = /* @__PURE__ */ Object.create(null);
434
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
435
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
436
+ });
437
+ return copy;
438
+ }
439
+ __name(clone, "clone");
440
+ }
441
+ });
442
+
443
+ // node_modules/graceful-fs/graceful-fs.js
444
+ var require_graceful_fs = __commonJS({
445
+ "node_modules/graceful-fs/graceful-fs.js"(exports, module) {
446
+ var fs = __require("fs");
447
+ var polyfills = require_polyfills();
448
+ var legacy = require_legacy_streams();
449
+ var clone = require_clone();
450
+ var util = __require("util");
451
+ var gracefulQueue;
452
+ var previousSymbol;
453
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
454
+ gracefulQueue = /* @__PURE__ */ Symbol.for("graceful-fs.queue");
455
+ previousSymbol = /* @__PURE__ */ Symbol.for("graceful-fs.previous");
456
+ } else {
457
+ gracefulQueue = "___graceful-fs.queue";
458
+ previousSymbol = "___graceful-fs.previous";
459
+ }
460
+ function noop() {
461
+ }
462
+ __name(noop, "noop");
463
+ function publishQueue(context, queue2) {
464
+ Object.defineProperty(context, gracefulQueue, {
465
+ get: /* @__PURE__ */ __name(function() {
466
+ return queue2;
467
+ }, "get")
468
+ });
469
+ }
470
+ __name(publishQueue, "publishQueue");
471
+ var debug = noop;
472
+ if (util.debuglog)
473
+ debug = util.debuglog("gfs4");
474
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
475
+ debug = /* @__PURE__ */ __name(function() {
476
+ var m = util.format.apply(util, arguments);
477
+ m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
478
+ console.error(m);
479
+ }, "debug");
480
+ if (!fs[gracefulQueue]) {
481
+ queue = global[gracefulQueue] || [];
482
+ publishQueue(fs, queue);
483
+ fs.close = (function(fs$close) {
484
+ function close(fd, cb) {
485
+ return fs$close.call(fs, fd, function(err) {
486
+ if (!err) {
487
+ resetQueue();
488
+ }
489
+ if (typeof cb === "function")
490
+ cb.apply(this, arguments);
491
+ });
492
+ }
493
+ __name(close, "close");
494
+ Object.defineProperty(close, previousSymbol, {
495
+ value: fs$close
496
+ });
497
+ return close;
498
+ })(fs.close);
499
+ fs.closeSync = (function(fs$closeSync) {
500
+ function closeSync(fd) {
501
+ fs$closeSync.apply(fs, arguments);
502
+ resetQueue();
503
+ }
504
+ __name(closeSync, "closeSync");
505
+ Object.defineProperty(closeSync, previousSymbol, {
506
+ value: fs$closeSync
507
+ });
508
+ return closeSync;
509
+ })(fs.closeSync);
510
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
511
+ process.on("exit", function() {
512
+ debug(fs[gracefulQueue]);
513
+ __require("assert").equal(fs[gracefulQueue].length, 0);
514
+ });
515
+ }
516
+ }
517
+ var queue;
518
+ if (!global[gracefulQueue]) {
519
+ publishQueue(global, fs[gracefulQueue]);
520
+ }
521
+ module.exports = patch(clone(fs));
522
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
523
+ module.exports = patch(fs);
524
+ fs.__patched = true;
525
+ }
526
+ function patch(fs2) {
527
+ polyfills(fs2);
528
+ fs2.gracefulify = patch;
529
+ fs2.createReadStream = createReadStream;
530
+ fs2.createWriteStream = createWriteStream;
531
+ var fs$readFile = fs2.readFile;
532
+ fs2.readFile = readFile;
533
+ function readFile(path, options, cb) {
534
+ if (typeof options === "function")
535
+ cb = options, options = null;
536
+ return go$readFile(path, options, cb);
537
+ function go$readFile(path2, options2, cb2, startTime) {
538
+ return fs$readFile(path2, options2, function(err) {
539
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
540
+ enqueue([go$readFile, [path2, options2, cb2], err, startTime || Date.now(), Date.now()]);
541
+ else {
542
+ if (typeof cb2 === "function")
543
+ cb2.apply(this, arguments);
544
+ }
545
+ });
546
+ }
547
+ __name(go$readFile, "go$readFile");
548
+ }
549
+ __name(readFile, "readFile");
550
+ var fs$writeFile = fs2.writeFile;
551
+ fs2.writeFile = writeFile;
552
+ function writeFile(path, data, options, cb) {
553
+ if (typeof options === "function")
554
+ cb = options, options = null;
555
+ return go$writeFile(path, data, options, cb);
556
+ function go$writeFile(path2, data2, options2, cb2, startTime) {
557
+ return fs$writeFile(path2, data2, options2, function(err) {
558
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
559
+ enqueue([go$writeFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
560
+ else {
561
+ if (typeof cb2 === "function")
562
+ cb2.apply(this, arguments);
563
+ }
564
+ });
565
+ }
566
+ __name(go$writeFile, "go$writeFile");
567
+ }
568
+ __name(writeFile, "writeFile");
569
+ var fs$appendFile = fs2.appendFile;
570
+ if (fs$appendFile)
571
+ fs2.appendFile = appendFile;
572
+ function appendFile(path, data, options, cb) {
573
+ if (typeof options === "function")
574
+ cb = options, options = null;
575
+ return go$appendFile(path, data, options, cb);
576
+ function go$appendFile(path2, data2, options2, cb2, startTime) {
577
+ return fs$appendFile(path2, data2, options2, function(err) {
578
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
579
+ enqueue([go$appendFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
580
+ else {
581
+ if (typeof cb2 === "function")
582
+ cb2.apply(this, arguments);
583
+ }
584
+ });
585
+ }
586
+ __name(go$appendFile, "go$appendFile");
587
+ }
588
+ __name(appendFile, "appendFile");
589
+ var fs$copyFile = fs2.copyFile;
590
+ if (fs$copyFile)
591
+ fs2.copyFile = copyFile;
592
+ function copyFile(src, dest, flags, cb) {
593
+ if (typeof flags === "function") {
594
+ cb = flags;
595
+ flags = 0;
596
+ }
597
+ return go$copyFile(src, dest, flags, cb);
598
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
599
+ return fs$copyFile(src2, dest2, flags2, function(err) {
600
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
601
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
602
+ else {
603
+ if (typeof cb2 === "function")
604
+ cb2.apply(this, arguments);
605
+ }
606
+ });
607
+ }
608
+ __name(go$copyFile, "go$copyFile");
609
+ }
610
+ __name(copyFile, "copyFile");
611
+ var fs$readdir = fs2.readdir;
612
+ fs2.readdir = readdir;
613
+ var noReaddirOptionVersions = /^v[0-5]\./;
614
+ function readdir(path, options, cb) {
615
+ if (typeof options === "function")
616
+ cb = options, options = null;
617
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? /* @__PURE__ */ __name(function go$readdir2(path2, options2, cb2, startTime) {
618
+ return fs$readdir(path2, fs$readdirCallback(
619
+ path2,
620
+ options2,
621
+ cb2,
622
+ startTime
623
+ ));
624
+ }, "go$readdir") : /* @__PURE__ */ __name(function go$readdir2(path2, options2, cb2, startTime) {
625
+ return fs$readdir(path2, options2, fs$readdirCallback(
626
+ path2,
627
+ options2,
628
+ cb2,
629
+ startTime
630
+ ));
631
+ }, "go$readdir");
632
+ return go$readdir(path, options, cb);
633
+ function fs$readdirCallback(path2, options2, cb2, startTime) {
634
+ return function(err, files) {
635
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
636
+ enqueue([
637
+ go$readdir,
638
+ [path2, options2, cb2],
639
+ err,
640
+ startTime || Date.now(),
641
+ Date.now()
642
+ ]);
643
+ else {
644
+ if (files && files.sort)
645
+ files.sort();
646
+ if (typeof cb2 === "function")
647
+ cb2.call(this, err, files);
648
+ }
649
+ };
650
+ }
651
+ __name(fs$readdirCallback, "fs$readdirCallback");
652
+ }
653
+ __name(readdir, "readdir");
654
+ if (process.version.substr(0, 4) === "v0.8") {
655
+ var legStreams = legacy(fs2);
656
+ ReadStream = legStreams.ReadStream;
657
+ WriteStream = legStreams.WriteStream;
658
+ }
659
+ var fs$ReadStream = fs2.ReadStream;
660
+ if (fs$ReadStream) {
661
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
662
+ ReadStream.prototype.open = ReadStream$open;
663
+ }
664
+ var fs$WriteStream = fs2.WriteStream;
665
+ if (fs$WriteStream) {
666
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
667
+ WriteStream.prototype.open = WriteStream$open;
668
+ }
669
+ Object.defineProperty(fs2, "ReadStream", {
670
+ get: /* @__PURE__ */ __name(function() {
671
+ return ReadStream;
672
+ }, "get"),
673
+ set: /* @__PURE__ */ __name(function(val) {
674
+ ReadStream = val;
675
+ }, "set"),
676
+ enumerable: true,
677
+ configurable: true
678
+ });
679
+ Object.defineProperty(fs2, "WriteStream", {
680
+ get: /* @__PURE__ */ __name(function() {
681
+ return WriteStream;
682
+ }, "get"),
683
+ set: /* @__PURE__ */ __name(function(val) {
684
+ WriteStream = val;
685
+ }, "set"),
686
+ enumerable: true,
687
+ configurable: true
688
+ });
689
+ var FileReadStream = ReadStream;
690
+ Object.defineProperty(fs2, "FileReadStream", {
691
+ get: /* @__PURE__ */ __name(function() {
692
+ return FileReadStream;
693
+ }, "get"),
694
+ set: /* @__PURE__ */ __name(function(val) {
695
+ FileReadStream = val;
696
+ }, "set"),
697
+ enumerable: true,
698
+ configurable: true
699
+ });
700
+ var FileWriteStream = WriteStream;
701
+ Object.defineProperty(fs2, "FileWriteStream", {
702
+ get: /* @__PURE__ */ __name(function() {
703
+ return FileWriteStream;
704
+ }, "get"),
705
+ set: /* @__PURE__ */ __name(function(val) {
706
+ FileWriteStream = val;
707
+ }, "set"),
708
+ enumerable: true,
709
+ configurable: true
710
+ });
711
+ function ReadStream(path, options) {
712
+ if (this instanceof ReadStream)
713
+ return fs$ReadStream.apply(this, arguments), this;
714
+ else
715
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
716
+ }
717
+ __name(ReadStream, "ReadStream");
718
+ function ReadStream$open() {
719
+ var that = this;
720
+ open(that.path, that.flags, that.mode, function(err, fd) {
721
+ if (err) {
722
+ if (that.autoClose)
723
+ that.destroy();
724
+ that.emit("error", err);
725
+ } else {
726
+ that.fd = fd;
727
+ that.emit("open", fd);
728
+ that.read();
729
+ }
730
+ });
731
+ }
732
+ __name(ReadStream$open, "ReadStream$open");
733
+ function WriteStream(path, options) {
734
+ if (this instanceof WriteStream)
735
+ return fs$WriteStream.apply(this, arguments), this;
736
+ else
737
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
738
+ }
739
+ __name(WriteStream, "WriteStream");
740
+ function WriteStream$open() {
741
+ var that = this;
742
+ open(that.path, that.flags, that.mode, function(err, fd) {
743
+ if (err) {
744
+ that.destroy();
745
+ that.emit("error", err);
746
+ } else {
747
+ that.fd = fd;
748
+ that.emit("open", fd);
749
+ }
750
+ });
751
+ }
752
+ __name(WriteStream$open, "WriteStream$open");
753
+ function createReadStream(path, options) {
754
+ return new fs2.ReadStream(path, options);
755
+ }
756
+ __name(createReadStream, "createReadStream");
757
+ function createWriteStream(path, options) {
758
+ return new fs2.WriteStream(path, options);
759
+ }
760
+ __name(createWriteStream, "createWriteStream");
761
+ var fs$open = fs2.open;
762
+ fs2.open = open;
763
+ function open(path, flags, mode, cb) {
764
+ if (typeof mode === "function")
765
+ cb = mode, mode = null;
766
+ return go$open(path, flags, mode, cb);
767
+ function go$open(path2, flags2, mode2, cb2, startTime) {
768
+ return fs$open(path2, flags2, mode2, function(err, fd) {
769
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
770
+ enqueue([go$open, [path2, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
771
+ else {
772
+ if (typeof cb2 === "function")
773
+ cb2.apply(this, arguments);
774
+ }
775
+ });
776
+ }
777
+ __name(go$open, "go$open");
778
+ }
779
+ __name(open, "open");
780
+ return fs2;
781
+ }
782
+ __name(patch, "patch");
783
+ function enqueue(elem) {
784
+ debug("ENQUEUE", elem[0].name, elem[1]);
785
+ fs[gracefulQueue].push(elem);
786
+ retry();
787
+ }
788
+ __name(enqueue, "enqueue");
789
+ var retryTimer;
790
+ function resetQueue() {
791
+ var now = Date.now();
792
+ for (var i = 0; i < fs[gracefulQueue].length; ++i) {
793
+ if (fs[gracefulQueue][i].length > 2) {
794
+ fs[gracefulQueue][i][3] = now;
795
+ fs[gracefulQueue][i][4] = now;
796
+ }
797
+ }
798
+ retry();
799
+ }
800
+ __name(resetQueue, "resetQueue");
801
+ function retry() {
802
+ clearTimeout(retryTimer);
803
+ retryTimer = void 0;
804
+ if (fs[gracefulQueue].length === 0)
805
+ return;
806
+ var elem = fs[gracefulQueue].shift();
807
+ var fn = elem[0];
808
+ var args = elem[1];
809
+ var err = elem[2];
810
+ var startTime = elem[3];
811
+ var lastTime = elem[4];
812
+ if (startTime === void 0) {
813
+ debug("RETRY", fn.name, args);
814
+ fn.apply(null, args);
815
+ } else if (Date.now() - startTime >= 6e4) {
816
+ debug("TIMEOUT", fn.name, args);
817
+ var cb = args.pop();
818
+ if (typeof cb === "function")
819
+ cb.call(null, err);
820
+ } else {
821
+ var sinceAttempt = Date.now() - lastTime;
822
+ var sinceStart = Math.max(lastTime - startTime, 1);
823
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
824
+ if (sinceAttempt >= desiredDelay) {
825
+ debug("RETRY", fn.name, args);
826
+ fn.apply(null, args.concat([startTime]));
827
+ } else {
828
+ fs[gracefulQueue].push(elem);
829
+ }
830
+ }
831
+ if (retryTimer === void 0) {
832
+ retryTimer = setTimeout(retry, 0);
833
+ }
834
+ }
835
+ __name(retry, "retry");
836
+ }
837
+ });
838
+
839
+ // node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js
840
+ var require_retry_operation = __commonJS({
841
+ "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js"(exports, module) {
842
+ function RetryOperation(timeouts, options) {
843
+ if (typeof options === "boolean") {
844
+ options = { forever: options };
845
+ }
846
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
847
+ this._timeouts = timeouts;
848
+ this._options = options || {};
849
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
850
+ this._fn = null;
851
+ this._errors = [];
852
+ this._attempts = 1;
853
+ this._operationTimeout = null;
854
+ this._operationTimeoutCb = null;
855
+ this._timeout = null;
856
+ this._operationStart = null;
857
+ if (this._options.forever) {
858
+ this._cachedTimeouts = this._timeouts.slice(0);
859
+ }
860
+ }
861
+ __name(RetryOperation, "RetryOperation");
862
+ module.exports = RetryOperation;
863
+ RetryOperation.prototype.reset = function() {
864
+ this._attempts = 1;
865
+ this._timeouts = this._originalTimeouts;
866
+ };
867
+ RetryOperation.prototype.stop = function() {
868
+ if (this._timeout) {
869
+ clearTimeout(this._timeout);
870
+ }
871
+ this._timeouts = [];
872
+ this._cachedTimeouts = null;
873
+ };
874
+ RetryOperation.prototype.retry = function(err) {
875
+ if (this._timeout) {
876
+ clearTimeout(this._timeout);
877
+ }
878
+ if (!err) {
879
+ return false;
880
+ }
881
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
882
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
883
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
884
+ return false;
885
+ }
886
+ this._errors.push(err);
887
+ var timeout = this._timeouts.shift();
888
+ if (timeout === void 0) {
889
+ if (this._cachedTimeouts) {
890
+ this._errors.splice(this._errors.length - 1, this._errors.length);
891
+ this._timeouts = this._cachedTimeouts.slice(0);
892
+ timeout = this._timeouts.shift();
893
+ } else {
894
+ return false;
895
+ }
896
+ }
897
+ var self = this;
898
+ var timer = setTimeout(function() {
899
+ self._attempts++;
900
+ if (self._operationTimeoutCb) {
901
+ self._timeout = setTimeout(function() {
902
+ self._operationTimeoutCb(self._attempts);
903
+ }, self._operationTimeout);
904
+ if (self._options.unref) {
905
+ self._timeout.unref();
906
+ }
907
+ }
908
+ self._fn(self._attempts);
909
+ }, timeout);
910
+ if (this._options.unref) {
911
+ timer.unref();
912
+ }
913
+ return true;
914
+ };
915
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
916
+ this._fn = fn;
917
+ if (timeoutOps) {
918
+ if (timeoutOps.timeout) {
919
+ this._operationTimeout = timeoutOps.timeout;
920
+ }
921
+ if (timeoutOps.cb) {
922
+ this._operationTimeoutCb = timeoutOps.cb;
923
+ }
924
+ }
925
+ var self = this;
926
+ if (this._operationTimeoutCb) {
927
+ this._timeout = setTimeout(function() {
928
+ self._operationTimeoutCb();
929
+ }, self._operationTimeout);
930
+ }
931
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
932
+ this._fn(this._attempts);
933
+ };
934
+ RetryOperation.prototype.try = function(fn) {
935
+ console.log("Using RetryOperation.try() is deprecated");
936
+ this.attempt(fn);
937
+ };
938
+ RetryOperation.prototype.start = function(fn) {
939
+ console.log("Using RetryOperation.start() is deprecated");
940
+ this.attempt(fn);
941
+ };
942
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
943
+ RetryOperation.prototype.errors = function() {
944
+ return this._errors;
945
+ };
946
+ RetryOperation.prototype.attempts = function() {
947
+ return this._attempts;
948
+ };
949
+ RetryOperation.prototype.mainError = function() {
950
+ if (this._errors.length === 0) {
951
+ return null;
952
+ }
953
+ var counts = {};
954
+ var mainError = null;
955
+ var mainErrorCount = 0;
956
+ for (var i = 0; i < this._errors.length; i++) {
957
+ var error = this._errors[i];
958
+ var message = error.message;
959
+ var count = (counts[message] || 0) + 1;
960
+ counts[message] = count;
961
+ if (count >= mainErrorCount) {
962
+ mainError = error;
963
+ mainErrorCount = count;
964
+ }
965
+ }
966
+ return mainError;
967
+ };
968
+ }
969
+ });
970
+
971
+ // node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/node_modules/retry/lib/retry.js
972
+ var require_retry = __commonJS({
973
+ "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(exports) {
974
+ var RetryOperation = require_retry_operation();
975
+ exports.operation = function(options) {
976
+ var timeouts = exports.timeouts(options);
977
+ return new RetryOperation(timeouts, {
978
+ forever: options && options.forever,
979
+ unref: options && options.unref,
980
+ maxRetryTime: options && options.maxRetryTime
981
+ });
982
+ };
983
+ exports.timeouts = function(options) {
984
+ if (options instanceof Array) {
985
+ return [].concat(options);
986
+ }
987
+ var opts = {
988
+ retries: 10,
989
+ factor: 2,
990
+ minTimeout: 1 * 1e3,
991
+ maxTimeout: Infinity,
992
+ randomize: false
993
+ };
994
+ for (var key in options) {
995
+ opts[key] = options[key];
996
+ }
997
+ if (opts.minTimeout > opts.maxTimeout) {
998
+ throw new Error("minTimeout is greater than maxTimeout");
999
+ }
1000
+ var timeouts = [];
1001
+ for (var i = 0; i < opts.retries; i++) {
1002
+ timeouts.push(this.createTimeout(i, opts));
1003
+ }
1004
+ if (options && options.forever && !timeouts.length) {
1005
+ timeouts.push(this.createTimeout(i, opts));
1006
+ }
1007
+ timeouts.sort(function(a, b) {
1008
+ return a - b;
1009
+ });
1010
+ return timeouts;
1011
+ };
1012
+ exports.createTimeout = function(attempt, opts) {
1013
+ var random = opts.randomize ? Math.random() + 1 : 1;
1014
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
1015
+ timeout = Math.min(timeout, opts.maxTimeout);
1016
+ return timeout;
1017
+ };
1018
+ exports.wrap = function(obj, options, methods) {
1019
+ if (options instanceof Array) {
1020
+ methods = options;
1021
+ options = null;
1022
+ }
1023
+ if (!methods) {
1024
+ methods = [];
1025
+ for (var key in obj) {
1026
+ if (typeof obj[key] === "function") {
1027
+ methods.push(key);
1028
+ }
1029
+ }
1030
+ }
1031
+ for (var i = 0; i < methods.length; i++) {
1032
+ var method = methods[i];
1033
+ var original = obj[method];
1034
+ obj[method] = (/* @__PURE__ */ __name(function retryWrapper(original2) {
1035
+ var op = exports.operation(options);
1036
+ var args = Array.prototype.slice.call(arguments, 1);
1037
+ var callback = args.pop();
1038
+ args.push(function(err) {
1039
+ if (op.retry(err)) {
1040
+ return;
1041
+ }
1042
+ if (err) {
1043
+ arguments[0] = op.mainError();
1044
+ }
1045
+ callback.apply(this, arguments);
1046
+ });
1047
+ op.attempt(function() {
1048
+ original2.apply(obj, args);
1049
+ });
1050
+ }, "retryWrapper")).bind(obj, original);
1051
+ obj[method].options = options;
1052
+ }
1053
+ };
1054
+ }
1055
+ });
1056
+
1057
+ // node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/node_modules/retry/index.js
1058
+ var require_retry2 = __commonJS({
1059
+ "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/node_modules/retry/index.js"(exports, module) {
1060
+ module.exports = require_retry();
1061
+ }
1062
+ });
1063
+
1064
+ // node_modules/@earendil-works/pi-coding-agent/node_modules/signal-exit/signals.js
1065
+ var require_signals = __commonJS({
1066
+ "node_modules/@earendil-works/pi-coding-agent/node_modules/signal-exit/signals.js"(exports, module) {
1067
+ module.exports = [
1068
+ "SIGABRT",
1069
+ "SIGALRM",
1070
+ "SIGHUP",
1071
+ "SIGINT",
1072
+ "SIGTERM"
1073
+ ];
1074
+ if (process.platform !== "win32") {
1075
+ module.exports.push(
1076
+ "SIGVTALRM",
1077
+ "SIGXCPU",
1078
+ "SIGXFSZ",
1079
+ "SIGUSR2",
1080
+ "SIGTRAP",
1081
+ "SIGSYS",
1082
+ "SIGQUIT",
1083
+ "SIGIOT"
1084
+ // should detect profiler and enable/disable accordingly.
1085
+ // see #21
1086
+ // 'SIGPROF'
1087
+ );
1088
+ }
1089
+ if (process.platform === "linux") {
1090
+ module.exports.push(
1091
+ "SIGIO",
1092
+ "SIGPOLL",
1093
+ "SIGPWR",
1094
+ "SIGSTKFLT",
1095
+ "SIGUNUSED"
1096
+ );
1097
+ }
1098
+ }
1099
+ });
1100
+
1101
+ // node_modules/@earendil-works/pi-coding-agent/node_modules/signal-exit/index.js
1102
+ var require_signal_exit = __commonJS({
1103
+ "node_modules/@earendil-works/pi-coding-agent/node_modules/signal-exit/index.js"(exports, module) {
1104
+ var process3 = global.process;
1105
+ var processOk = /* @__PURE__ */ __name(function(process4) {
1106
+ return process4 && typeof process4 === "object" && typeof process4.removeListener === "function" && typeof process4.emit === "function" && typeof process4.reallyExit === "function" && typeof process4.listeners === "function" && typeof process4.kill === "function" && typeof process4.pid === "number" && typeof process4.on === "function";
1107
+ }, "processOk");
1108
+ if (!processOk(process3)) {
1109
+ module.exports = function() {
1110
+ return function() {
1111
+ };
1112
+ };
1113
+ } else {
1114
+ assert = __require("assert");
1115
+ signals = require_signals();
1116
+ isWin = /^win/i.test(process3.platform);
1117
+ EE = __require("events");
1118
+ if (typeof EE !== "function") {
1119
+ EE = EE.EventEmitter;
1120
+ }
1121
+ if (process3.__signal_exit_emitter__) {
1122
+ emitter = process3.__signal_exit_emitter__;
1123
+ } else {
1124
+ emitter = process3.__signal_exit_emitter__ = new EE();
1125
+ emitter.count = 0;
1126
+ emitter.emitted = {};
1127
+ }
1128
+ if (!emitter.infinite) {
1129
+ emitter.setMaxListeners(Infinity);
1130
+ emitter.infinite = true;
1131
+ }
1132
+ module.exports = function(cb, opts) {
1133
+ if (!processOk(global.process)) {
1134
+ return function() {
1135
+ };
1136
+ }
1137
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
1138
+ if (loaded === false) {
1139
+ load();
1140
+ }
1141
+ var ev = "exit";
1142
+ if (opts && opts.alwaysLast) {
1143
+ ev = "afterexit";
1144
+ }
1145
+ var remove = /* @__PURE__ */ __name(function() {
1146
+ emitter.removeListener(ev, cb);
1147
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
1148
+ unload();
1149
+ }
1150
+ }, "remove");
1151
+ emitter.on(ev, cb);
1152
+ return remove;
1153
+ };
1154
+ unload = /* @__PURE__ */ __name(function unload2() {
1155
+ if (!loaded || !processOk(global.process)) {
1156
+ return;
1157
+ }
1158
+ loaded = false;
1159
+ signals.forEach(function(sig) {
1160
+ try {
1161
+ process3.removeListener(sig, sigListeners[sig]);
1162
+ } catch (er) {
1163
+ }
1164
+ });
1165
+ process3.emit = originalProcessEmit;
1166
+ process3.reallyExit = originalProcessReallyExit;
1167
+ emitter.count -= 1;
1168
+ }, "unload");
1169
+ module.exports.unload = unload;
1170
+ emit = /* @__PURE__ */ __name(function emit2(event, code, signal) {
1171
+ if (emitter.emitted[event]) {
1172
+ return;
1173
+ }
1174
+ emitter.emitted[event] = true;
1175
+ emitter.emit(event, code, signal);
1176
+ }, "emit");
1177
+ sigListeners = {};
1178
+ signals.forEach(function(sig) {
1179
+ sigListeners[sig] = /* @__PURE__ */ __name(function listener() {
1180
+ if (!processOk(global.process)) {
1181
+ return;
1182
+ }
1183
+ var listeners = process3.listeners(sig);
1184
+ if (listeners.length === emitter.count) {
1185
+ unload();
1186
+ emit("exit", null, sig);
1187
+ emit("afterexit", null, sig);
1188
+ if (isWin && sig === "SIGHUP") {
1189
+ sig = "SIGINT";
1190
+ }
1191
+ process3.kill(process3.pid, sig);
1192
+ }
1193
+ }, "listener");
1194
+ });
1195
+ module.exports.signals = function() {
1196
+ return signals;
1197
+ };
1198
+ loaded = false;
1199
+ load = /* @__PURE__ */ __name(function load2() {
1200
+ if (loaded || !processOk(global.process)) {
1201
+ return;
1202
+ }
1203
+ loaded = true;
1204
+ emitter.count += 1;
1205
+ signals = signals.filter(function(sig) {
1206
+ try {
1207
+ process3.on(sig, sigListeners[sig]);
1208
+ return true;
1209
+ } catch (er) {
1210
+ return false;
1211
+ }
1212
+ });
1213
+ process3.emit = processEmit;
1214
+ process3.reallyExit = processReallyExit;
1215
+ }, "load");
1216
+ module.exports.load = load;
1217
+ originalProcessReallyExit = process3.reallyExit;
1218
+ processReallyExit = /* @__PURE__ */ __name(function processReallyExit2(code) {
1219
+ if (!processOk(global.process)) {
1220
+ return;
1221
+ }
1222
+ process3.exitCode = code || /* istanbul ignore next */
1223
+ 0;
1224
+ emit("exit", process3.exitCode, null);
1225
+ emit("afterexit", process3.exitCode, null);
1226
+ originalProcessReallyExit.call(process3, process3.exitCode);
1227
+ }, "processReallyExit");
1228
+ originalProcessEmit = process3.emit;
1229
+ processEmit = /* @__PURE__ */ __name(function processEmit2(ev, arg) {
1230
+ if (ev === "exit" && processOk(global.process)) {
1231
+ if (arg !== void 0) {
1232
+ process3.exitCode = arg;
1233
+ }
1234
+ var ret = originalProcessEmit.apply(this, arguments);
1235
+ emit("exit", process3.exitCode, null);
1236
+ emit("afterexit", process3.exitCode, null);
1237
+ return ret;
1238
+ } else {
1239
+ return originalProcessEmit.apply(this, arguments);
1240
+ }
1241
+ }, "processEmit");
1242
+ }
1243
+ var assert;
1244
+ var signals;
1245
+ var isWin;
1246
+ var EE;
1247
+ var emitter;
1248
+ var unload;
1249
+ var emit;
1250
+ var sigListeners;
1251
+ var loaded;
1252
+ var load;
1253
+ var originalProcessReallyExit;
1254
+ var processReallyExit;
1255
+ var originalProcessEmit;
1256
+ var processEmit;
1257
+ }
1258
+ });
1259
+
1260
+ // node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/lib/mtime-precision.js
1261
+ var require_mtime_precision = __commonJS({
1262
+ "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/lib/mtime-precision.js"(exports, module) {
1263
+ "use strict";
1264
+ var cacheSymbol = /* @__PURE__ */ Symbol();
1265
+ function probe(file, fs, callback) {
1266
+ const cachedPrecision = fs[cacheSymbol];
1267
+ if (cachedPrecision) {
1268
+ return fs.stat(file, (err, stat) => {
1269
+ if (err) {
1270
+ return callback(err);
1271
+ }
1272
+ callback(null, stat.mtime, cachedPrecision);
1273
+ });
1274
+ }
1275
+ const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
1276
+ fs.utimes(file, mtime, mtime, (err) => {
1277
+ if (err) {
1278
+ return callback(err);
1279
+ }
1280
+ fs.stat(file, (err2, stat) => {
1281
+ if (err2) {
1282
+ return callback(err2);
1283
+ }
1284
+ const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
1285
+ Object.defineProperty(fs, cacheSymbol, { value: precision });
1286
+ callback(null, stat.mtime, precision);
1287
+ });
1288
+ });
1289
+ }
1290
+ __name(probe, "probe");
1291
+ function getMtime(precision) {
1292
+ let now = Date.now();
1293
+ if (precision === "s") {
1294
+ now = Math.ceil(now / 1e3) * 1e3;
1295
+ }
1296
+ return new Date(now);
1297
+ }
1298
+ __name(getMtime, "getMtime");
1299
+ module.exports.probe = probe;
1300
+ module.exports.getMtime = getMtime;
1301
+ }
1302
+ });
1303
+
1304
+ // node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/lib/lockfile.js
1305
+ var require_lockfile = __commonJS({
1306
+ "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/lib/lockfile.js"(exports, module) {
1307
+ "use strict";
1308
+ var path = __require("path");
1309
+ var fs = require_graceful_fs();
1310
+ var retry = require_retry2();
1311
+ var onExit = require_signal_exit();
1312
+ var mtimePrecision = require_mtime_precision();
1313
+ var locks = {};
1314
+ function getLockFile(file, options) {
1315
+ return options.lockfilePath || `${file}.lock`;
1316
+ }
1317
+ __name(getLockFile, "getLockFile");
1318
+ function resolveCanonicalPath(file, options, callback) {
1319
+ if (!options.realpath) {
1320
+ return callback(null, path.resolve(file));
1321
+ }
1322
+ options.fs.realpath(file, callback);
1323
+ }
1324
+ __name(resolveCanonicalPath, "resolveCanonicalPath");
1325
+ function acquireLock(file, options, callback) {
1326
+ const lockfilePath = getLockFile(file, options);
1327
+ options.fs.mkdir(lockfilePath, (err) => {
1328
+ if (!err) {
1329
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
1330
+ if (err2) {
1331
+ options.fs.rmdir(lockfilePath, () => {
1332
+ });
1333
+ return callback(err2);
1334
+ }
1335
+ callback(null, mtime, mtimePrecision2);
1336
+ });
1337
+ }
1338
+ if (err.code !== "EEXIST") {
1339
+ return callback(err);
1340
+ }
1341
+ if (options.stale <= 0) {
1342
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1343
+ }
1344
+ options.fs.stat(lockfilePath, (err2, stat) => {
1345
+ if (err2) {
1346
+ if (err2.code === "ENOENT") {
1347
+ return acquireLock(file, { ...options, stale: 0 }, callback);
1348
+ }
1349
+ return callback(err2);
1350
+ }
1351
+ if (!isLockStale(stat, options)) {
1352
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1353
+ }
1354
+ removeLock(file, options, (err3) => {
1355
+ if (err3) {
1356
+ return callback(err3);
1357
+ }
1358
+ acquireLock(file, { ...options, stale: 0 }, callback);
1359
+ });
1360
+ });
1361
+ });
1362
+ }
1363
+ __name(acquireLock, "acquireLock");
1364
+ function isLockStale(stat, options) {
1365
+ return stat.mtime.getTime() < Date.now() - options.stale;
1366
+ }
1367
+ __name(isLockStale, "isLockStale");
1368
+ function removeLock(file, options, callback) {
1369
+ options.fs.rmdir(getLockFile(file, options), (err) => {
1370
+ if (err && err.code !== "ENOENT") {
1371
+ return callback(err);
1372
+ }
1373
+ callback();
1374
+ });
1375
+ }
1376
+ __name(removeLock, "removeLock");
1377
+ function updateLock(file, options) {
1378
+ const lock2 = locks[file];
1379
+ if (lock2.updateTimeout) {
1380
+ return;
1381
+ }
1382
+ lock2.updateDelay = lock2.updateDelay || options.update;
1383
+ lock2.updateTimeout = setTimeout(() => {
1384
+ lock2.updateTimeout = null;
1385
+ options.fs.stat(lock2.lockfilePath, (err, stat) => {
1386
+ const isOverThreshold = lock2.lastUpdate + options.stale < Date.now();
1387
+ if (err) {
1388
+ if (err.code === "ENOENT" || isOverThreshold) {
1389
+ return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" }));
1390
+ }
1391
+ lock2.updateDelay = 1e3;
1392
+ return updateLock(file, options);
1393
+ }
1394
+ const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime();
1395
+ if (!isMtimeOurs) {
1396
+ return setLockAsCompromised(
1397
+ file,
1398
+ lock2,
1399
+ Object.assign(
1400
+ new Error("Unable to update lock within the stale threshold"),
1401
+ { code: "ECOMPROMISED" }
1402
+ )
1403
+ );
1404
+ }
1405
+ const mtime = mtimePrecision.getMtime(lock2.mtimePrecision);
1406
+ options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => {
1407
+ const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now();
1408
+ if (lock2.released) {
1409
+ return;
1410
+ }
1411
+ if (err2) {
1412
+ if (err2.code === "ENOENT" || isOverThreshold2) {
1413
+ return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" }));
1414
+ }
1415
+ lock2.updateDelay = 1e3;
1416
+ return updateLock(file, options);
1417
+ }
1418
+ lock2.mtime = mtime;
1419
+ lock2.lastUpdate = Date.now();
1420
+ lock2.updateDelay = null;
1421
+ updateLock(file, options);
1422
+ });
1423
+ });
1424
+ }, lock2.updateDelay);
1425
+ if (lock2.updateTimeout.unref) {
1426
+ lock2.updateTimeout.unref();
1427
+ }
1428
+ }
1429
+ __name(updateLock, "updateLock");
1430
+ function setLockAsCompromised(file, lock2, err) {
1431
+ lock2.released = true;
1432
+ if (lock2.updateTimeout) {
1433
+ clearTimeout(lock2.updateTimeout);
1434
+ }
1435
+ if (locks[file] === lock2) {
1436
+ delete locks[file];
1437
+ }
1438
+ lock2.options.onCompromised(err);
1439
+ }
1440
+ __name(setLockAsCompromised, "setLockAsCompromised");
1441
+ function lock(file, options, callback) {
1442
+ options = {
1443
+ stale: 1e4,
1444
+ update: null,
1445
+ realpath: true,
1446
+ retries: 0,
1447
+ fs,
1448
+ onCompromised: /* @__PURE__ */ __name((err) => {
1449
+ throw err;
1450
+ }, "onCompromised"),
1451
+ ...options
1452
+ };
1453
+ options.retries = options.retries || 0;
1454
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
1455
+ options.stale = Math.max(options.stale || 0, 2e3);
1456
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
1457
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1e3);
1458
+ resolveCanonicalPath(file, options, (err, file2) => {
1459
+ if (err) {
1460
+ return callback(err);
1461
+ }
1462
+ const operation = retry.operation(options.retries);
1463
+ operation.attempt(() => {
1464
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
1465
+ if (operation.retry(err2)) {
1466
+ return;
1467
+ }
1468
+ if (err2) {
1469
+ return callback(operation.mainError());
1470
+ }
1471
+ const lock2 = locks[file2] = {
1472
+ lockfilePath: getLockFile(file2, options),
1473
+ mtime,
1474
+ mtimePrecision: mtimePrecision2,
1475
+ options,
1476
+ lastUpdate: Date.now()
1477
+ };
1478
+ updateLock(file2, options);
1479
+ callback(null, (releasedCallback) => {
1480
+ if (lock2.released) {
1481
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
1482
+ }
1483
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
1484
+ });
1485
+ });
1486
+ });
1487
+ });
1488
+ }
1489
+ __name(lock, "lock");
1490
+ function unlock(file, options, callback) {
1491
+ options = {
1492
+ fs,
1493
+ realpath: true,
1494
+ ...options
1495
+ };
1496
+ resolveCanonicalPath(file, options, (err, file2) => {
1497
+ if (err) {
1498
+ return callback(err);
1499
+ }
1500
+ const lock2 = locks[file2];
1501
+ if (!lock2) {
1502
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
1503
+ }
1504
+ lock2.updateTimeout && clearTimeout(lock2.updateTimeout);
1505
+ lock2.released = true;
1506
+ delete locks[file2];
1507
+ removeLock(file2, options, callback);
1508
+ });
1509
+ }
1510
+ __name(unlock, "unlock");
1511
+ function check(file, options, callback) {
1512
+ options = {
1513
+ stale: 1e4,
1514
+ realpath: true,
1515
+ fs,
1516
+ ...options
1517
+ };
1518
+ options.stale = Math.max(options.stale || 0, 2e3);
1519
+ resolveCanonicalPath(file, options, (err, file2) => {
1520
+ if (err) {
1521
+ return callback(err);
1522
+ }
1523
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
1524
+ if (err2) {
1525
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
1526
+ }
1527
+ return callback(null, !isLockStale(stat, options));
1528
+ });
1529
+ });
1530
+ }
1531
+ __name(check, "check");
1532
+ function getLocks() {
1533
+ return locks;
1534
+ }
1535
+ __name(getLocks, "getLocks");
1536
+ onExit(() => {
1537
+ for (const file in locks) {
1538
+ const options = locks[file].options;
1539
+ try {
1540
+ options.fs.rmdirSync(getLockFile(file, options));
1541
+ } catch (e) {
1542
+ }
1543
+ }
1544
+ });
1545
+ module.exports.lock = lock;
1546
+ module.exports.unlock = unlock;
1547
+ module.exports.check = check;
1548
+ module.exports.getLocks = getLocks;
1549
+ }
1550
+ });
1551
+
1552
+ // node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/lib/adapter.js
1553
+ var require_adapter = __commonJS({
1554
+ "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/lib/adapter.js"(exports, module) {
1555
+ "use strict";
1556
+ var fs = require_graceful_fs();
1557
+ function createSyncFs(fs2) {
1558
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1559
+ const newFs = { ...fs2 };
1560
+ methods.forEach((method) => {
1561
+ newFs[method] = (...args) => {
1562
+ const callback = args.pop();
1563
+ let ret;
1564
+ try {
1565
+ ret = fs2[`${method}Sync`](...args);
1566
+ } catch (err) {
1567
+ return callback(err);
1568
+ }
1569
+ callback(null, ret);
1570
+ };
1571
+ });
1572
+ return newFs;
1573
+ }
1574
+ __name(createSyncFs, "createSyncFs");
1575
+ function toPromise(method) {
1576
+ return (...args) => new Promise((resolve, reject) => {
1577
+ args.push((err, result) => {
1578
+ if (err) {
1579
+ reject(err);
1580
+ } else {
1581
+ resolve(result);
1582
+ }
1583
+ });
1584
+ method(...args);
1585
+ });
1586
+ }
1587
+ __name(toPromise, "toPromise");
1588
+ function toSync(method) {
1589
+ return (...args) => {
1590
+ let err;
1591
+ let result;
1592
+ args.push((_err, _result) => {
1593
+ err = _err;
1594
+ result = _result;
1595
+ });
1596
+ method(...args);
1597
+ if (err) {
1598
+ throw err;
1599
+ }
1600
+ return result;
1601
+ };
1602
+ }
1603
+ __name(toSync, "toSync");
1604
+ function toSyncOptions(options) {
1605
+ options = { ...options };
1606
+ options.fs = createSyncFs(options.fs || fs);
1607
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
1608
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
1609
+ }
1610
+ return options;
1611
+ }
1612
+ __name(toSyncOptions, "toSyncOptions");
1613
+ module.exports = {
1614
+ toPromise,
1615
+ toSync,
1616
+ toSyncOptions
1617
+ };
1618
+ }
1619
+ });
1620
+
1621
+ // node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/index.js
1622
+ var require_proper_lockfile = __commonJS({
1623
+ "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/index.js"(exports, module) {
1624
+ "use strict";
1625
+ var lockfile2 = require_lockfile();
1626
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
1627
+ async function lock(file, options) {
1628
+ const release = await toPromise(lockfile2.lock)(file, options);
1629
+ return toPromise(release);
1630
+ }
1631
+ __name(lock, "lock");
1632
+ function lockSync(file, options) {
1633
+ const release = toSync(lockfile2.lock)(file, toSyncOptions(options));
1634
+ return toSync(release);
1635
+ }
1636
+ __name(lockSync, "lockSync");
1637
+ function unlock(file, options) {
1638
+ return toPromise(lockfile2.unlock)(file, options);
1639
+ }
1640
+ __name(unlock, "unlock");
1641
+ function unlockSync(file, options) {
1642
+ return toSync(lockfile2.unlock)(file, toSyncOptions(options));
1643
+ }
1644
+ __name(unlockSync, "unlockSync");
1645
+ function check(file, options) {
1646
+ return toPromise(lockfile2.check)(file, options);
1647
+ }
1648
+ __name(check, "check");
1649
+ function checkSync(file, options) {
1650
+ return toSync(lockfile2.check)(file, toSyncOptions(options));
1651
+ }
1652
+ __name(checkSync, "checkSync");
1653
+ module.exports = lock;
1654
+ module.exports.lock = lock;
1655
+ module.exports.unlock = unlock;
1656
+ module.exports.lockSync = lockSync;
1657
+ module.exports.unlockSync = unlockSync;
1658
+ module.exports.check = check;
1659
+ module.exports.checkSync = checkSync;
1660
+ }
1661
+ });
1662
+
1663
+ // node_modules/@earendil-works/pi-coding-agent/dist/core/resolve-config-value.js
1664
+ import { execSync, spawnSync } from "child_process";
1665
+ var commandResultCache = /* @__PURE__ */ new Map();
1666
+ var ENV_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
1667
+ var ENV_VAR_NAME_PREFIX_RE = /^[A-Za-z_][A-Za-z0-9_]*/;
1668
+ function appendLiteral(parts, value) {
1669
+ if (!value)
1670
+ return;
1671
+ const previousPart = parts[parts.length - 1];
1672
+ if (previousPart?.type === "literal") {
1673
+ previousPart.value += value;
1674
+ return;
1675
+ }
1676
+ parts.push({ type: "literal", value });
1677
+ }
1678
+ __name(appendLiteral, "appendLiteral");
1679
+ function parseConfigValueTemplate(config) {
1680
+ const parts = [];
1681
+ let index = 0;
1682
+ while (index < config.length) {
1683
+ const dollarIndex = config.indexOf("$", index);
1684
+ if (dollarIndex < 0) {
1685
+ appendLiteral(parts, config.slice(index));
1686
+ break;
1687
+ }
1688
+ appendLiteral(parts, config.slice(index, dollarIndex));
1689
+ const nextChar = config[dollarIndex + 1];
1690
+ if (nextChar === "$" || nextChar === "!") {
1691
+ appendLiteral(parts, nextChar);
1692
+ index = dollarIndex + 2;
1693
+ continue;
1694
+ }
1695
+ if (nextChar === "{") {
1696
+ const endIndex = config.indexOf("}", dollarIndex + 2);
1697
+ if (endIndex < 0) {
1698
+ appendLiteral(parts, "$");
1699
+ index = dollarIndex + 1;
1700
+ continue;
1701
+ }
1702
+ const name = config.slice(dollarIndex + 2, endIndex);
1703
+ if (ENV_VAR_NAME_RE.test(name)) {
1704
+ parts.push({ type: "env", name });
1705
+ } else {
1706
+ appendLiteral(parts, config.slice(dollarIndex, endIndex + 1));
1707
+ }
1708
+ index = endIndex + 1;
1709
+ continue;
1710
+ }
1711
+ const match = config.slice(dollarIndex + 1).match(ENV_VAR_NAME_PREFIX_RE);
1712
+ if (match) {
1713
+ parts.push({ type: "env", name: match[0] });
1714
+ index = dollarIndex + 1 + match[0].length;
1715
+ continue;
1716
+ }
1717
+ appendLiteral(parts, "$");
1718
+ index = dollarIndex + 1;
1719
+ }
1720
+ return parts;
1721
+ }
1722
+ __name(parseConfigValueTemplate, "parseConfigValueTemplate");
1723
+ function parseConfigValueReference(config) {
1724
+ if (config.startsWith("!")) {
1725
+ return { type: "command", config };
1726
+ }
1727
+ return { type: "template", parts: parseConfigValueTemplate(config) };
1728
+ }
1729
+ __name(parseConfigValueReference, "parseConfigValueReference");
1730
+ function resolveEnvConfigValue(name, env) {
1731
+ return env?.[name] || process.env[name] || void 0;
1732
+ }
1733
+ __name(resolveEnvConfigValue, "resolveEnvConfigValue");
1734
+ function getTemplateEnvVarNames(parts) {
1735
+ const names = [];
1736
+ for (const part of parts) {
1737
+ if (part.type !== "env" || names.includes(part.name))
1738
+ continue;
1739
+ names.push(part.name);
1740
+ }
1741
+ return names;
1742
+ }
1743
+ __name(getTemplateEnvVarNames, "getTemplateEnvVarNames");
1744
+ function resolveTemplate(parts, env) {
1745
+ let resolved = "";
1746
+ for (const part of parts) {
1747
+ if (part.type === "literal") {
1748
+ resolved += part.value;
1749
+ continue;
1750
+ }
1751
+ const envValue = resolveEnvConfigValue(part.name, env);
1752
+ if (envValue === void 0)
1753
+ return void 0;
1754
+ resolved += envValue;
1755
+ }
1756
+ return resolved;
1757
+ }
1758
+ __name(resolveTemplate, "resolveTemplate");
1759
+ function getConfigValueEnvVarNames(config) {
1760
+ const reference = parseConfigValueReference(config);
1761
+ return reference.type === "template" ? getTemplateEnvVarNames(reference.parts) : [];
1762
+ }
1763
+ __name(getConfigValueEnvVarNames, "getConfigValueEnvVarNames");
1764
+ function getMissingConfigValueEnvVarNames(config, env) {
1765
+ return getConfigValueEnvVarNames(config).filter((name) => resolveEnvConfigValue(name, env) === void 0);
1766
+ }
1767
+ __name(getMissingConfigValueEnvVarNames, "getMissingConfigValueEnvVarNames");
1768
+ function isCommandConfigValue(config) {
1769
+ return parseConfigValueReference(config).type === "command";
1770
+ }
1771
+ __name(isCommandConfigValue, "isCommandConfigValue");
1772
+ function isConfigValueConfigured(config, env) {
1773
+ return getMissingConfigValueEnvVarNames(config, env).length === 0;
1774
+ }
1775
+ __name(isConfigValueConfigured, "isConfigValueConfigured");
1776
+ function resolveConfigValue(config, env) {
1777
+ const reference = parseConfigValueReference(config);
1778
+ if (reference.type === "command") {
1779
+ return executeCommand(reference.config);
1780
+ }
1781
+ return resolveTemplate(reference.parts, env);
1782
+ }
1783
+ __name(resolveConfigValue, "resolveConfigValue");
1784
+ function executeWithConfiguredShell(command) {
1785
+ try {
1786
+ const { shell, args, commandTransport } = getShellConfig();
1787
+ const commandFromStdin = commandTransport === "stdin";
1788
+ const result = spawnSync(shell, commandFromStdin ? args : [...args, command], {
1789
+ encoding: "utf-8",
1790
+ input: commandFromStdin ? command : void 0,
1791
+ timeout: 1e4,
1792
+ stdio: [commandFromStdin ? "pipe" : "ignore", "pipe", "ignore"],
1793
+ shell: false,
1794
+ windowsHide: true
1795
+ });
1796
+ if (result.error) {
1797
+ const error = result.error;
1798
+ if (error.code === "ENOENT") {
1799
+ return { executed: false, value: void 0 };
1800
+ }
1801
+ return { executed: true, value: void 0 };
1802
+ }
1803
+ if (result.status !== 0) {
1804
+ return { executed: true, value: void 0 };
1805
+ }
1806
+ const value = (result.stdout ?? "").trim();
1807
+ return { executed: true, value: value || void 0 };
1808
+ } catch {
1809
+ return { executed: false, value: void 0 };
1810
+ }
1811
+ }
1812
+ __name(executeWithConfiguredShell, "executeWithConfiguredShell");
1813
+ function executeWithDefaultShell(command) {
1814
+ try {
1815
+ const output = execSync(command, {
1816
+ encoding: "utf-8",
1817
+ timeout: 1e4,
1818
+ stdio: ["ignore", "pipe", "ignore"]
1819
+ });
1820
+ return output.trim() || void 0;
1821
+ } catch {
1822
+ return void 0;
1823
+ }
1824
+ }
1825
+ __name(executeWithDefaultShell, "executeWithDefaultShell");
1826
+ function executeCommandUncached(commandConfig) {
1827
+ const command = commandConfig.slice(1);
1828
+ return process.platform === "win32" ? (() => {
1829
+ const configuredResult = executeWithConfiguredShell(command);
1830
+ return configuredResult.executed ? configuredResult.value : executeWithDefaultShell(command);
1831
+ })() : executeWithDefaultShell(command);
1832
+ }
1833
+ __name(executeCommandUncached, "executeCommandUncached");
1834
+ function executeCommand(commandConfig) {
1835
+ if (commandResultCache.has(commandConfig)) {
1836
+ return commandResultCache.get(commandConfig);
1837
+ }
1838
+ const result = executeCommandUncached(commandConfig);
1839
+ commandResultCache.set(commandConfig, result);
1840
+ return result;
1841
+ }
1842
+ __name(executeCommand, "executeCommand");
1843
+ function resolveConfigValueUncached(config, env) {
1844
+ const reference = parseConfigValueReference(config);
1845
+ if (reference.type === "command") {
1846
+ return executeCommandUncached(reference.config);
1847
+ }
1848
+ return resolveTemplate(reference.parts, env);
1849
+ }
1850
+ __name(resolveConfigValueUncached, "resolveConfigValueUncached");
1851
+ function resolveConfigValueOrThrow(config, description, env) {
1852
+ const resolvedValue = resolveConfigValueUncached(config, env);
1853
+ if (resolvedValue !== void 0) {
1854
+ return resolvedValue;
1855
+ }
1856
+ const reference = parseConfigValueReference(config);
1857
+ if (reference.type === "command") {
1858
+ throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);
1859
+ }
1860
+ if (reference.type === "template") {
1861
+ const missingEnvVars = getMissingConfigValueEnvVarNames(config, env);
1862
+ if (missingEnvVars.length === 1) {
1863
+ throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);
1864
+ }
1865
+ if (missingEnvVars.length > 1) {
1866
+ throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`);
1867
+ }
1868
+ }
1869
+ throw new Error(`Failed to resolve ${description}`);
1870
+ }
1871
+ __name(resolveConfigValueOrThrow, "resolveConfigValueOrThrow");
1872
+ function resolveHeadersOrThrow(headers, description, env) {
1873
+ if (!headers)
1874
+ return void 0;
1875
+ const resolved = {};
1876
+ for (const [key, value] of Object.entries(headers)) {
1877
+ resolved[key] = resolveConfigValueOrThrow(value, `${description} header "${key}"`, env);
1878
+ }
1879
+ return Object.keys(resolved).length > 0 ? resolved : void 0;
1880
+ }
1881
+ __name(resolveHeadersOrThrow, "resolveHeadersOrThrow");
1882
+
1883
+ // node_modules/@earendil-works/pi-coding-agent/dist/core/auth-storage.js
1884
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
1885
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
1886
+ import { dirname, join } from "path";
1887
+ import { setTimeout as sleep } from "timers/promises";
1888
+
1889
+ // node_modules/@earendil-works/pi-coding-agent/dist/utils/abort.js
1890
+ function abortReason(signal) {
1891
+ if (signal.reason !== void 0)
1892
+ return signal.reason;
1893
+ const error = new Error("The operation was aborted");
1894
+ error.name = "AbortError";
1895
+ return error;
1896
+ }
1897
+ __name(abortReason, "abortReason");
1898
+ function operationSignal(signal) {
1899
+ return signal ?? new AbortController().signal;
1900
+ }
1901
+ __name(operationSignal, "operationSignal");
1902
+ function raceWithAbortSignal(operation, signal) {
1903
+ if (!signal)
1904
+ return operation;
1905
+ if (signal.aborted) {
1906
+ void operation.catch(() => {
1907
+ });
1908
+ return Promise.reject(abortReason(signal));
1909
+ }
1910
+ return new Promise((resolve, reject) => {
1911
+ let settled = false;
1912
+ const cleanup = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "cleanup");
1913
+ const onAbort = /* @__PURE__ */ __name(() => {
1914
+ if (settled)
1915
+ return;
1916
+ settled = true;
1917
+ cleanup();
1918
+ reject(abortReason(signal));
1919
+ }, "onAbort");
1920
+ signal.addEventListener("abort", onAbort, { once: true });
1921
+ void operation.then((value) => {
1922
+ if (settled)
1923
+ return;
1924
+ settled = true;
1925
+ cleanup();
1926
+ resolve(value);
1927
+ }, (error) => {
1928
+ if (settled)
1929
+ return;
1930
+ settled = true;
1931
+ cleanup();
1932
+ reject(error);
1933
+ });
1934
+ if (signal.aborted)
1935
+ onAbort();
1936
+ });
1937
+ }
1938
+ __name(raceWithAbortSignal, "raceWithAbortSignal");
1939
+
1940
+ // node_modules/@earendil-works/pi-coding-agent/dist/core/auth-storage.js
1941
+ var MAX_EPERM_RETRIES = 5;
1942
+ function getRetryableLockErrorCode(error) {
1943
+ const code = error instanceof Error && "code" in error ? error.code : void 0;
1944
+ if (code === "ELOCKED")
1945
+ return code;
1946
+ if (code === "EPERM" && process.platform === "win32")
1947
+ return code;
1948
+ return void 0;
1949
+ }
1950
+ __name(getRetryableLockErrorCode, "getRetryableLockErrorCode");
1951
+ var AUTH_FILE_WRITE_OPTIONS = { encoding: "utf-8", mode: 384 };
1952
+ var sharedAuthFileReadState;
1953
+ var FileAuthStorageBackend = class {
1954
+ static {
1955
+ __name(this, "FileAuthStorageBackend");
1956
+ }
1957
+ authPath;
1958
+ constructor(authPath = join(getAgentDir(), "auth.json")) {
1959
+ this.authPath = normalizePath(authPath);
1960
+ }
1961
+ ensureParentDir() {
1962
+ const dir = dirname(this.authPath);
1963
+ if (!existsSync(dir)) {
1964
+ mkdirSync(dir, { recursive: true, mode: 448 });
1965
+ }
1966
+ }
1967
+ ensureFileExists() {
1968
+ if (!existsSync(this.authPath)) {
1969
+ writeFileSync(this.authPath, "{}", AUTH_FILE_WRITE_OPTIONS);
1970
+ }
1971
+ }
1972
+ acquireLockSyncWithRetry(path) {
1973
+ const maxAttempts = 10;
1974
+ const delayMs = 20;
1975
+ for (let attempt = 1; ; attempt++) {
1976
+ try {
1977
+ return import_proper_lockfile.default.lockSync(path, { realpath: false });
1978
+ } catch (error) {
1979
+ if (!getRetryableLockErrorCode(error) || attempt === maxAttempts)
1980
+ throw error;
1981
+ const start = Date.now();
1982
+ while (Date.now() - start < delayMs) {
1983
+ }
1984
+ }
1985
+ }
1986
+ }
1987
+ withLock(fn) {
1988
+ this.ensureParentDir();
1989
+ this.ensureFileExists();
1990
+ let release;
1991
+ try {
1992
+ release = this.acquireLockSyncWithRetry(this.authPath);
1993
+ const current = existsSync(this.authPath) ? readFileSync(this.authPath, "utf-8") : void 0;
1994
+ const { result, next } = fn(current);
1995
+ if (next !== void 0) {
1996
+ writeFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);
1997
+ }
1998
+ return result;
1999
+ } finally {
2000
+ if (release) {
2001
+ release();
2002
+ }
2003
+ }
2004
+ }
2005
+ async acquireLockAsync(signal, onCompromised) {
2006
+ const staleMs = 3e4;
2007
+ const maxDelayMs = 2e3;
2008
+ const deadline = Date.now() + staleMs;
2009
+ let retry = 0;
2010
+ let epermRetries = 0;
2011
+ while (true) {
2012
+ signal?.throwIfAborted();
2013
+ let release;
2014
+ try {
2015
+ release = await import_proper_lockfile.default.lock(this.authPath, {
2016
+ realpath: false,
2017
+ retries: 0,
2018
+ stale: staleMs,
2019
+ onCompromised
2020
+ });
2021
+ } catch (error) {
2022
+ signal?.throwIfAborted();
2023
+ const code = getRetryableLockErrorCode(error);
2024
+ const remainingMs = deadline - Date.now();
2025
+ if (!code || remainingMs <= 0)
2026
+ throw error;
2027
+ if (code === "EPERM" && ++epermRetries > MAX_EPERM_RETRIES)
2028
+ throw error;
2029
+ const baseDelayMs = Math.min(10 * 2 ** retry, maxDelayMs / 2);
2030
+ retry++;
2031
+ const delayMs = Math.min(Math.round(baseDelayMs * (1 + Math.random())), remainingMs);
2032
+ if (signal)
2033
+ await sleep(delayMs, void 0, { signal });
2034
+ else
2035
+ await sleep(delayMs);
2036
+ continue;
2037
+ }
2038
+ if (signal?.aborted) {
2039
+ await release();
2040
+ signal.throwIfAborted();
2041
+ }
2042
+ return release;
2043
+ }
2044
+ }
2045
+ async withLockAsync(fn, options) {
2046
+ options?.signal?.throwIfAborted();
2047
+ this.ensureParentDir();
2048
+ this.ensureFileExists();
2049
+ let release;
2050
+ let lockCompromised = false;
2051
+ let lockCompromisedError;
2052
+ const throwIfCompromised = /* @__PURE__ */ __name(() => {
2053
+ if (lockCompromised) {
2054
+ throw lockCompromisedError ?? new Error("Auth storage lock was compromised");
2055
+ }
2056
+ }, "throwIfCompromised");
2057
+ try {
2058
+ release = await this.acquireLockAsync(options?.signal, (error) => {
2059
+ lockCompromised = true;
2060
+ lockCompromisedError = error;
2061
+ });
2062
+ throwIfCompromised();
2063
+ options?.signal?.throwIfAborted();
2064
+ const current = existsSync(this.authPath) ? readFileSync(this.authPath, "utf-8") : void 0;
2065
+ const { result, next } = await fn(current);
2066
+ throwIfCompromised();
2067
+ options?.signal?.throwIfAborted();
2068
+ if (next !== void 0) {
2069
+ writeFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);
2070
+ }
2071
+ throwIfCompromised();
2072
+ return result;
2073
+ } finally {
2074
+ if (release) {
2075
+ try {
2076
+ await release();
2077
+ } catch {
2078
+ }
2079
+ }
2080
+ }
2081
+ }
2082
+ };
2083
+ var ReadOnlyAuthStorage = class {
2084
+ static {
2085
+ __name(this, "ReadOnlyAuthStorage");
2086
+ }
2087
+ authPath;
2088
+ data;
2089
+ constructor(authPath = join(getAgentDir(), "auth.json")) {
2090
+ this.authPath = normalizePath(authPath);
2091
+ }
2092
+ load() {
2093
+ if (this.data)
2094
+ return this.data;
2095
+ let parsed;
2096
+ try {
2097
+ parsed = JSON.parse(stripBom(readFileSync(this.authPath, "utf-8")));
2098
+ } catch (error) {
2099
+ if (error.code === "ENOENT") {
2100
+ this.data = {};
2101
+ return this.data;
2102
+ }
2103
+ throw new Error(`Failed to read auth.json: ${error instanceof Error ? error.message : String(error)}`);
2104
+ }
2105
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
2106
+ throw new Error("Invalid auth.json: expected an object");
2107
+ }
2108
+ for (const [providerId, credential] of Object.entries(parsed)) {
2109
+ if (typeof credential !== "object" || credential === null || Array.isArray(credential)) {
2110
+ throw new Error(`Invalid auth.json credential for provider "${providerId}"`);
2111
+ }
2112
+ const value = credential;
2113
+ if (value.type === "api_key") {
2114
+ const validKey = value.key === void 0 || typeof value.key === "string";
2115
+ const validEnv = value.env === void 0 || typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) && Object.values(value.env).every((entry) => typeof entry === "string");
2116
+ if (validKey && validEnv)
2117
+ continue;
2118
+ } else if (value.type === "oauth" && typeof value.access === "string" && typeof value.refresh === "string" && typeof value.expires === "number" && Number.isFinite(value.expires)) {
2119
+ continue;
2120
+ }
2121
+ throw new Error(`Invalid auth.json credential for provider "${providerId}"`);
2122
+ }
2123
+ this.data = parsed;
2124
+ return this.data;
2125
+ }
2126
+ async read(providerId, options) {
2127
+ options?.signal?.throwIfAborted();
2128
+ const credential = this.load()[providerId];
2129
+ options?.signal?.throwIfAborted();
2130
+ if (!credential)
2131
+ return void 0;
2132
+ if (credential.type !== "api_key" || !credential.key || isCommandConfigValue(credential.key)) {
2133
+ return structuredClone(credential);
2134
+ }
2135
+ return { ...credential, key: resolveConfigValue(credential.key, credential.env) };
2136
+ }
2137
+ async list(options) {
2138
+ options?.signal?.throwIfAborted();
2139
+ const credentials = Object.entries(this.load()).map(([providerId, credential]) => ({
2140
+ providerId,
2141
+ type: credential.type
2142
+ }));
2143
+ options?.signal?.throwIfAborted();
2144
+ return credentials;
2145
+ }
2146
+ async modify(_providerId, _fn, _options) {
2147
+ throw new Error("Read-only credential storage cannot modify auth.json");
2148
+ }
2149
+ async delete(_providerId, _options) {
2150
+ throw new Error("Read-only credential storage cannot modify auth.json");
2151
+ }
2152
+ };
2153
+ var InMemoryAuthStorageBackend = class {
2154
+ static {
2155
+ __name(this, "InMemoryAuthStorageBackend");
2156
+ }
2157
+ value;
2158
+ asyncChain = Promise.resolve();
2159
+ withLock(fn) {
2160
+ const { result, next } = fn(this.value);
2161
+ if (next !== void 0) {
2162
+ this.value = next;
2163
+ }
2164
+ return result;
2165
+ }
2166
+ withLockAsync(fn, options) {
2167
+ const previous = this.asyncChain;
2168
+ const operation = (async () => {
2169
+ await previous.catch(() => {
2170
+ });
2171
+ options?.signal?.throwIfAborted();
2172
+ const { result, next } = await fn(this.value);
2173
+ options?.signal?.throwIfAborted();
2174
+ if (next !== void 0) {
2175
+ this.value = next;
2176
+ }
2177
+ return result;
2178
+ })();
2179
+ this.asyncChain = operation.catch(() => {
2180
+ });
2181
+ return raceWithAbortSignal(operation, options?.signal);
2182
+ }
2183
+ };
2184
+ var AuthStorage = class _AuthStorage {
2185
+ static {
2186
+ __name(this, "AuthStorage");
2187
+ }
2188
+ storage;
2189
+ authPath;
2190
+ readState;
2191
+ constructor(storage, authPath) {
2192
+ this.storage = storage;
2193
+ this.authPath = authPath;
2194
+ this.readState = authPath && sharedAuthFileReadState?.authPath === authPath ? sharedAuthFileReadState.readState : { data: {} };
2195
+ if (authPath && !sharedAuthFileReadState) {
2196
+ sharedAuthFileReadState = { authPath, readState: this.readState };
2197
+ }
2198
+ if (authPath) {
2199
+ const revision = getFileRevision(authPath);
2200
+ if (revision !== void 0 && revision === this.readState.revision)
2201
+ return;
2202
+ }
2203
+ this.reload();
2204
+ }
2205
+ static create(authPath = join(getAgentDir(), "auth.json")) {
2206
+ const normalizedAuthPath = normalizePath(authPath);
2207
+ return new _AuthStorage(new FileAuthStorageBackend(normalizedAuthPath), normalizedAuthPath);
2208
+ }
2209
+ static fromStorage(storage) {
2210
+ return new _AuthStorage(storage);
2211
+ }
2212
+ static inMemory(data = {}) {
2213
+ const storage = new InMemoryAuthStorageBackend();
2214
+ storage.withLock(() => ({ result: void 0, next: JSON.stringify(data, null, 2) }));
2215
+ return _AuthStorage.fromStorage(storage);
2216
+ }
2217
+ parseStorageData(content) {
2218
+ if (!content) {
2219
+ return {};
2220
+ }
2221
+ return JSON.parse(stripBom(content));
2222
+ }
2223
+ updateReadState(data, revision) {
2224
+ this.readState.data = data;
2225
+ this.readState.revision = revision;
2226
+ }
2227
+ /**
2228
+ * Reload credentials from storage.
2229
+ */
2230
+ reload() {
2231
+ let content;
2232
+ let revision;
2233
+ try {
2234
+ this.storage.withLock((current) => {
2235
+ content = current;
2236
+ revision = this.authPath ? getFileRevision(this.authPath) : void 0;
2237
+ return { result: void 0 };
2238
+ });
2239
+ this.updateReadState(this.parseStorageData(content), revision);
2240
+ } catch {
2241
+ }
2242
+ }
2243
+ async reloadFromStorageAsync(options) {
2244
+ return this.storage.withLockAsync(async (content) => {
2245
+ const currentData = this.parseStorageData(content);
2246
+ const revision = this.authPath ? getFileRevision(this.authPath) : void 0;
2247
+ this.updateReadState(currentData, revision);
2248
+ return { result: currentData };
2249
+ }, options);
2250
+ }
2251
+ async readLatestData(options) {
2252
+ options?.signal?.throwIfAborted();
2253
+ if (!this.authPath) {
2254
+ const reload2 = this.reloadFromStorageAsync(options);
2255
+ return options?.signal ? reload2 : reload2.catch(() => this.readState.data);
2256
+ }
2257
+ const revision = getFileRevision(this.authPath);
2258
+ if (revision !== void 0 && revision === this.readState.revision)
2259
+ return this.readState.data;
2260
+ if (!this.readState.reload) {
2261
+ const controller = new AbortController();
2262
+ const reload2 = {
2263
+ controller,
2264
+ promise: this.reloadFromStorageAsync({ signal: controller.signal }),
2265
+ readers: 0
2266
+ };
2267
+ this.readState.reload = reload2;
2268
+ void reload2.promise.then(() => {
2269
+ if (this.readState.reload === reload2)
2270
+ this.readState.reload = void 0;
2271
+ }, () => {
2272
+ if (this.readState.reload === reload2)
2273
+ this.readState.reload = void 0;
2274
+ });
2275
+ }
2276
+ const reload = this.readState.reload;
2277
+ reload.readers++;
2278
+ try {
2279
+ const result = raceWithAbortSignal(reload.promise, options?.signal);
2280
+ return options?.signal ? await result : await result.catch(() => this.readState.data);
2281
+ } finally {
2282
+ reload.readers--;
2283
+ if (reload.readers === 0 && this.readState.reload === reload) {
2284
+ this.readState.reload = void 0;
2285
+ reload.controller.abort();
2286
+ }
2287
+ }
2288
+ }
2289
+ async read(provider, options) {
2290
+ const credential = (await this.readLatestData(options))[provider];
2291
+ options?.signal?.throwIfAborted();
2292
+ if (credential?.type !== "api_key")
2293
+ return credential;
2294
+ if (credential.key === void 0)
2295
+ return credential;
2296
+ return { ...credential, key: resolveConfigValue(credential.key, credential.env) };
2297
+ }
2298
+ async modify(provider, fn, options) {
2299
+ let latestData = this.readState.data;
2300
+ let revision;
2301
+ const result = await this.storage.withLockAsync(async (content) => {
2302
+ const currentData = this.parseStorageData(content);
2303
+ const next = await fn(currentData[provider]);
2304
+ if (next === void 0) {
2305
+ latestData = currentData;
2306
+ revision = this.authPath ? getFileRevision(this.authPath) : void 0;
2307
+ return { result: currentData[provider] };
2308
+ }
2309
+ const merged = { ...currentData, [provider]: next };
2310
+ latestData = merged;
2311
+ return { result: next, next: JSON.stringify(merged, null, 2) };
2312
+ }, options);
2313
+ this.updateReadState(latestData, revision);
2314
+ return result;
2315
+ }
2316
+ async delete(provider, options) {
2317
+ let latestData = this.readState.data;
2318
+ await this.storage.withLockAsync(async (content) => {
2319
+ const currentData = this.parseStorageData(content);
2320
+ delete currentData[provider];
2321
+ latestData = currentData;
2322
+ return { result: void 0, next: JSON.stringify(currentData, null, 2) };
2323
+ }, options);
2324
+ this.updateReadState(latestData);
2325
+ }
2326
+ /** List credential metadata without resolving configured key values. */
2327
+ async list(options) {
2328
+ const entries = Object.entries(await this.readLatestData(options));
2329
+ options?.signal?.throwIfAborted();
2330
+ return entries.map(([providerId, credential]) => ({ providerId, type: credential.type }));
2331
+ }
2332
+ };
2333
+ function readStoredCredential(providerId, authPath = join(getAgentDir(), "auth.json")) {
2334
+ try {
2335
+ const data = JSON.parse(stripBom(readFileSync(normalizePath(authPath), "utf-8")));
2336
+ return data[providerId];
2337
+ } catch {
2338
+ return void 0;
2339
+ }
2340
+ }
2341
+ __name(readStoredCredential, "readStoredCredential");
2342
+
2343
+ // node_modules/@earendil-works/pi-coding-agent/dist/core/mcp-servers.js
2344
+ function toolPatternRegExp(pattern) {
2345
+ const source = pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
2346
+ return new RegExp(`^${source}$`);
2347
+ }
2348
+ __name(toolPatternRegExp, "toolPatternRegExp");
2349
+ function createToolNameMatcher(entries) {
2350
+ const names = new Set(entries.filter((entry) => !entry.includes("*")));
2351
+ const patterns = entries.filter((entry) => entry.includes("*")).map(toolPatternRegExp);
2352
+ return (name) => names.has(name) || patterns.some((pattern) => pattern.test(name));
2353
+ }
2354
+ __name(createToolNameMatcher, "createToolNameMatcher");
2355
+ var LIST_MCP_RESOURCES_TOOL = "list_mcp_resources";
2356
+ var LIST_MCP_RESOURCE_TEMPLATES_TOOL = "list_mcp_resource_templates";
2357
+ var READ_MCP_RESOURCE_TOOL = "read_mcp_resource";
2358
+ var MCP_RESOURCE_TOOLS = /* @__PURE__ */ new Set([
2359
+ LIST_MCP_RESOURCES_TOOL,
2360
+ LIST_MCP_RESOURCE_TEMPLATES_TOOL,
2361
+ READ_MCP_RESOURCE_TOOL
2362
+ ]);
2363
+ function isMcpToolName(name) {
2364
+ return name.startsWith("mcp__") || MCP_RESOURCE_TOOLS.has(name);
2365
+ }
2366
+ __name(isMcpToolName, "isMcpToolName");
2367
+ var MCP_EXPOSURES = ["codemode", "deferred", "direct", "hidden"];
2368
+ var MCP_EXPOSURE_ALIASES = { "codemode-deferred": "codemode" };
2369
+ var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
2370
+ function isLoopbackRedirectUri(value) {
2371
+ if (!URL.canParse(value))
2372
+ return false;
2373
+ const url = new URL(value);
2374
+ return url.protocol === "http:" && LOOPBACK_HOSTS.includes(url.hostname) && url.search === "" && url.hash === "";
2375
+ }
2376
+ __name(isLoopbackRedirectUri, "isLoopbackRedirectUri");
2377
+ var SERVER_NAME = /^[A-Za-z0-9_-]+$/;
2378
+ function mcpNamespace(server) {
2379
+ return `mcp__${server.replace(/-/g, "_")}`;
2380
+ }
2381
+ __name(mcpNamespace, "mcpNamespace");
2382
+ function isRecord(value) {
2383
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2384
+ }
2385
+ __name(isRecord, "isRecord");
2386
+ function isStringRecord(value) {
2387
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
2388
+ }
2389
+ __name(isStringRecord, "isStringRecord");
2390
+ function validateOAuth(value) {
2391
+ if (value === void 0)
2392
+ return void 0;
2393
+ if (!isRecord(value))
2394
+ return "oauth must be an object";
2395
+ if (value.clientId !== void 0 && typeof value.clientId !== "string")
2396
+ return "oauth.clientId must be a string";
2397
+ if (value.clientSecret !== void 0 && typeof value.clientSecret !== "string") {
2398
+ return "oauth.clientSecret must be a string";
2399
+ }
2400
+ const port = value.callbackPort;
2401
+ if (port !== void 0 && (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)) {
2402
+ return "oauth.callbackPort must be a port number";
2403
+ }
2404
+ if (value.callbackUrl !== void 0) {
2405
+ if (typeof value.callbackUrl !== "string" || !isLoopbackRedirectUri(value.callbackUrl)) {
2406
+ return "oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";
2407
+ }
2408
+ const urlPort = new URL(value.callbackUrl).port;
2409
+ if (urlPort && port !== void 0 && Number(urlPort) !== port) {
2410
+ return "oauth.callbackUrl and oauth.callbackPort name different ports";
2411
+ }
2412
+ }
2413
+ if (value.scope !== void 0 && typeof value.scope !== "string")
2414
+ return "oauth.scope must be a string";
2415
+ if (value.clientName !== void 0 && (typeof value.clientName !== "string" || !value.clientName.trim())) {
2416
+ return "oauth.clientName must be a non-empty string";
2417
+ }
2418
+ if (value.clientRegistration !== void 0 && value.clientRegistration !== "dcr") {
2419
+ if (value.clientRegistration !== "cimd")
2420
+ return 'oauth.clientRegistration must be "dcr" or "cimd"';
2421
+ if (value.clientId !== void 0 || value.clientName !== void 0) {
2422
+ return 'oauth.clientRegistration "cimd" cannot be combined with oauth.clientId or oauth.clientName';
2423
+ }
2424
+ const callback = typeof value.callbackUrl === "string" ? new URL(value.callbackUrl) : void 0;
2425
+ if (callback && (callback.hostname === "[::1]" || callback.pathname !== "/callback")) {
2426
+ return 'oauth.clientRegistration "cimd" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback';
2427
+ }
2428
+ }
2429
+ const metadataUrl = value.authServerMetadataUrl;
2430
+ if (metadataUrl !== void 0) {
2431
+ const url = typeof metadataUrl === "string" && URL.canParse(metadataUrl) ? new URL(metadataUrl) : void 0;
2432
+ if (!url || !(url.protocol === "https:" || url.protocol === "http:" && LOOPBACK_HOSTS.includes(url.hostname))) {
2433
+ return "oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]";
2434
+ }
2435
+ }
2436
+ return void 0;
2437
+ }
2438
+ __name(validateOAuth, "validateOAuth");
2439
+ function isExposure(value) {
2440
+ return typeof value === "string" && MCP_EXPOSURES.includes(value);
2441
+ }
2442
+ __name(isExposure, "isExposure");
2443
+ function resolveExposureAlias(value) {
2444
+ return typeof value === "string" ? MCP_EXPOSURE_ALIASES[value] ?? value : value;
2445
+ }
2446
+ __name(resolveExposureAlias, "resolveExposureAlias");
2447
+ function resolveExposureAliases(value) {
2448
+ const { exposure, toolExposure } = value;
2449
+ const resolved = { ...value };
2450
+ if (exposure !== void 0)
2451
+ resolved.exposure = resolveExposureAlias(exposure);
2452
+ if (isRecord(toolExposure)) {
2453
+ resolved.toolExposure = Object.fromEntries(Object.entries(toolExposure).map(([tool, entry]) => [tool, resolveExposureAlias(entry)]));
2454
+ }
2455
+ return resolved;
2456
+ }
2457
+ __name(resolveExposureAliases, "resolveExposureAliases");
2458
+ function getMcpToolExposure(config, toolName) {
2459
+ const overrides = config.toolExposure ?? {};
2460
+ const exact = overrides[toolName];
2461
+ if (exact !== void 0)
2462
+ return exact;
2463
+ for (const [pattern, exposure] of Object.entries(overrides)) {
2464
+ if (pattern.includes("*") && toolPatternRegExp(pattern).test(toolName))
2465
+ return exposure;
2466
+ }
2467
+ return config.exposure ?? "codemode";
2468
+ }
2469
+ __name(getMcpToolExposure, "getMcpToolExposure");
2470
+ function validateMcpServerConfig(name, raw) {
2471
+ if (!SERVER_NAME.test(name))
2472
+ return `invalid server name "${name}" (use letters, digits, "_" and "-")`;
2473
+ if (!isRecord(raw))
2474
+ return `server "${name}" must be an object`;
2475
+ const value = resolveExposureAliases(raw);
2476
+ const { type, exposure, enabled, timeout, toolExposure, description } = value;
2477
+ const exposures = MCP_EXPOSURES.map((value2) => `"${value2}"`).join(", ");
2478
+ if (exposure !== void 0 && !isExposure(exposure)) {
2479
+ return `server "${name}": exposure must be one of ${exposures}`;
2480
+ }
2481
+ if (toolExposure !== void 0) {
2482
+ if (!isRecord(toolExposure))
2483
+ return `server "${name}": toolExposure must map tool names to exposures`;
2484
+ for (const [tool, value2] of Object.entries(toolExposure)) {
2485
+ if (!isExposure(value2))
2486
+ return `server "${name}": toolExposure "${tool}" must be one of ${exposures}`;
2487
+ }
2488
+ }
2489
+ if (enabled !== void 0 && typeof enabled !== "boolean")
2490
+ return `server "${name}": enabled must be a boolean`;
2491
+ if (description !== void 0 && typeof description !== "string") {
2492
+ return `server "${name}": description must be a string`;
2493
+ }
2494
+ if (timeout !== void 0 && (typeof timeout !== "number" || !(timeout > 0))) {
2495
+ return `server "${name}": timeout must be a positive number of seconds`;
2496
+ }
2497
+ if (type === "sse")
2498
+ return `server "${name}": legacy SSE transport is not supported; use the streamable HTTP URL`;
2499
+ if (typeof value.url === "string" && (type === void 0 || type === "http" || type === "streamable-http")) {
2500
+ if (!URL.canParse(value.url) || !/^https?:$/.test(new URL(value.url).protocol)) {
2501
+ return `server "${name}": url must be an http or https URL`;
2502
+ }
2503
+ if (value.headers !== void 0 && !isStringRecord(value.headers)) {
2504
+ return `server "${name}": headers must map names to strings`;
2505
+ }
2506
+ const oauthError = validateOAuth(value.oauth);
2507
+ if (oauthError)
2508
+ return `server "${name}": ${oauthError}`;
2509
+ if (value.auth !== void 0) {
2510
+ if (!isRecord(value.auth) || typeof value.auth.provider !== "string" || !value.auth.provider) {
2511
+ return `server "${name}": auth.provider must be a provider name`;
2512
+ }
2513
+ const url = new URL(value.url);
2514
+ if (url.protocol !== "https:" && !LOOPBACK_HOSTS.includes(url.hostname)) {
2515
+ return `server "${name}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`;
2516
+ }
2517
+ }
2518
+ return value;
2519
+ }
2520
+ if (typeof value.command === "string" && (type === void 0 || type === "stdio")) {
2521
+ if (value.args !== void 0 && !(Array.isArray(value.args) && value.args.every((arg) => typeof arg === "string"))) {
2522
+ return `server "${name}": args must be an array of strings`;
2523
+ }
2524
+ if (value.env !== void 0 && !isStringRecord(value.env))
2525
+ return `server "${name}": env must map names to strings`;
2526
+ if (value.cwd !== void 0 && typeof value.cwd !== "string")
2527
+ return `server "${name}": cwd must be a string`;
2528
+ return value;
2529
+ }
2530
+ return `server "${name}" needs either "command" (stdio) or "url" (streamable HTTP)`;
2531
+ }
2532
+ __name(validateMcpServerConfig, "validateMcpServerConfig");
2533
+ var McpServerRegistry = class {
2534
+ static {
2535
+ __name(this, "McpServerRegistry");
2536
+ }
2537
+ servers = /* @__PURE__ */ new Map();
2538
+ changeListener;
2539
+ /** Register or replace a server. The caller checks ownership. */
2540
+ register(server) {
2541
+ this.servers.set(server.name, server);
2542
+ this.changeListener?.();
2543
+ }
2544
+ /** Remove a server registered by `extensionPath`. Servers of other extensions are left alone. */
2545
+ unregister(name, extensionPath) {
2546
+ if (this.servers.get(name)?.extensionPath !== extensionPath)
2547
+ return;
2548
+ this.servers.delete(name);
2549
+ this.changeListener?.();
2550
+ }
2551
+ get(name) {
2552
+ return this.servers.get(name);
2553
+ }
2554
+ /** Copies of the registered servers, in registration order. */
2555
+ list() {
2556
+ return [...this.servers.values()].map((server) => ({ ...server, config: structuredClone(server.config) }));
2557
+ }
2558
+ /** Called after every change. The runner sets it when it binds, to emit `mcp_servers_change`. */
2559
+ setChangeListener(listener) {
2560
+ this.changeListener = listener;
2561
+ }
2562
+ };
2563
+
2564
+ // node_modules/@earendil-works/pi-mcp/dist/protocol/jsonrpc.js
2565
+ var JSON_RPC_ERROR_CODES = {
2566
+ parseError: -32700,
2567
+ invalidRequest: -32600,
2568
+ methodNotFound: -32601,
2569
+ invalidParams: -32602,
2570
+ internalError: -32603
2571
+ };
2572
+ var McpError = class extends Error {
2573
+ static {
2574
+ __name(this, "McpError");
2575
+ }
2576
+ code;
2577
+ data;
2578
+ constructor(code, message, data) {
2579
+ super(message);
2580
+ this.name = "McpError";
2581
+ this.code = code;
2582
+ this.data = data;
2583
+ }
2584
+ };
2585
+ var McpConnectionClosedError = class extends Error {
2586
+ static {
2587
+ __name(this, "McpConnectionClosedError");
2588
+ }
2589
+ constructor(message = "MCP connection closed") {
2590
+ super(message);
2591
+ this.name = "McpConnectionClosedError";
2592
+ }
2593
+ };
2594
+ var McpTimeoutError = class extends Error {
2595
+ static {
2596
+ __name(this, "McpTimeoutError");
2597
+ }
2598
+ timeoutMs;
2599
+ constructor(timeoutMs) {
2600
+ super(`MCP request timed out after ${timeoutMs}ms`);
2601
+ this.name = "McpTimeoutError";
2602
+ this.timeoutMs = timeoutMs;
2603
+ }
2604
+ };
2605
+ var McpAbortError = class extends Error {
2606
+ static {
2607
+ __name(this, "McpAbortError");
2608
+ }
2609
+ constructor(message = "MCP request aborted") {
2610
+ super(message);
2611
+ this.name = "AbortError";
2612
+ }
2613
+ };
2614
+ function isObject(value) {
2615
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2616
+ }
2617
+ __name(isObject, "isObject");
2618
+ function toError(value) {
2619
+ return value instanceof Error ? value : new Error(String(value));
2620
+ }
2621
+ __name(toError, "toError");
2622
+ function isJsonRpcId(value) {
2623
+ return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
2624
+ }
2625
+ __name(isJsonRpcId, "isJsonRpcId");
2626
+ function isJsonRpcRequest(message) {
2627
+ return isObject(message) && message.jsonrpc === "2.0" && isJsonRpcId(message.id) && typeof message.method === "string";
2628
+ }
2629
+ __name(isJsonRpcRequest, "isJsonRpcRequest");
2630
+ function isJsonRpcNotification(message) {
2631
+ return isObject(message) && message.jsonrpc === "2.0" && !("id" in message) && typeof message.method === "string";
2632
+ }
2633
+ __name(isJsonRpcNotification, "isJsonRpcNotification");
2634
+ function isJsonRpcResponse(message) {
2635
+ if (!isObject(message) || message.jsonrpc !== "2.0" || !isJsonRpcId(message.id))
2636
+ return false;
2637
+ if ("result" in message)
2638
+ return !("error" in message);
2639
+ if (!("error" in message) || !isObject(message.error))
2640
+ return false;
2641
+ return typeof message.error.code === "number" && typeof message.error.message === "string";
2642
+ }
2643
+ __name(isJsonRpcResponse, "isJsonRpcResponse");
2644
+ function parseJsonRpcMessage(value) {
2645
+ if (isJsonRpcRequest(value) || isJsonRpcNotification(value) || isJsonRpcResponse(value))
2646
+ return value;
2647
+ throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid JSON-RPC message");
2648
+ }
2649
+ __name(parseJsonRpcMessage, "parseJsonRpcMessage");
2650
+
2651
+ // node_modules/@earendil-works/pi-mcp/dist/protocol/types.js
2652
+ var LATEST_PROTOCOL_VERSION = "2025-11-25";
2653
+ var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05"];
2654
+
2655
+ // node_modules/@earendil-works/pi-mcp/dist/client.js
2656
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
2657
+ var MAX_LIST_PAGES = 1e3;
2658
+ function validateInitializeResult(value) {
2659
+ if (!isObject(value) || typeof value.protocolVersion !== "string" || !isObject(value.capabilities) || !isObject(value.serverInfo) || typeof value.serverInfo.name !== "string" || typeof value.serverInfo.version !== "string" || value.instructions !== void 0 && typeof value.instructions !== "string") {
2660
+ throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP initialize result");
2661
+ }
2662
+ return value;
2663
+ }
2664
+ __name(validateInitializeResult, "validateInitializeResult");
2665
+ function invalid(message) {
2666
+ return new McpError(JSON_RPC_ERROR_CODES.invalidRequest, message);
2667
+ }
2668
+ __name(invalid, "invalid");
2669
+ function validateListPage(method, key, value, isItem) {
2670
+ const items = isObject(value) ? value[key] : void 0;
2671
+ if (!isObject(value) || !Array.isArray(items))
2672
+ throw invalid(`Invalid MCP ${method} result`);
2673
+ for (const item of items) {
2674
+ if (!isObject(item) || !isItem(item))
2675
+ throw invalid(`Invalid entry in MCP ${method} result`);
2676
+ }
2677
+ const nextCursor = value.nextCursor === null || value.nextCursor === "" ? void 0 : value.nextCursor;
2678
+ if (nextCursor !== void 0 && typeof nextCursor !== "string")
2679
+ throw invalid(`Invalid MCP ${method} cursor`);
2680
+ return { items, ...nextCursor === void 0 ? {} : { nextCursor } };
2681
+ }
2682
+ __name(validateListPage, "validateListPage");
2683
+ var isTool = /* @__PURE__ */ __name((tool) => typeof tool.name === "string" && isObject(tool.inputSchema), "isTool");
2684
+ var isResource = /* @__PURE__ */ __name((resource) => typeof resource.uri === "string" && (resource.name === void 0 || typeof resource.name === "string"), "isResource");
2685
+ var isResourceTemplate = /* @__PURE__ */ __name((template) => typeof template.uriTemplate === "string" && (template.name === void 0 || typeof template.name === "string"), "isResourceTemplate");
2686
+ function toResource(item) {
2687
+ return { ...item, name: item.name ?? item.uri };
2688
+ }
2689
+ __name(toResource, "toResource");
2690
+ function toResourceTemplate(item) {
2691
+ return { ...item, name: item.name ?? item.uriTemplate };
2692
+ }
2693
+ __name(toResourceTemplate, "toResourceTemplate");
2694
+ function pageCursor(page) {
2695
+ return page.nextCursor === void 0 ? {} : { nextCursor: page.nextCursor };
2696
+ }
2697
+ __name(pageCursor, "pageCursor");
2698
+ function validateReadResourceResult(value) {
2699
+ if (!isObject(value) || !Array.isArray(value.contents))
2700
+ throw invalid("Invalid MCP resources/read result");
2701
+ for (const contents of value.contents) {
2702
+ if (!isObject(contents) || typeof contents.uri !== "string" || typeof contents.text !== "string" && typeof contents.blob !== "string") {
2703
+ throw invalid("Invalid contents in MCP resources/read result");
2704
+ }
2705
+ }
2706
+ return value;
2707
+ }
2708
+ __name(validateReadResourceResult, "validateReadResourceResult");
2709
+ function validateCallToolResult(value) {
2710
+ if (!isObject(value) || value.content !== void 0 && !Array.isArray(value.content)) {
2711
+ throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP tools/call result");
2712
+ }
2713
+ return value.content === void 0 ? { ...value, content: [] } : value;
2714
+ }
2715
+ __name(validateCallToolResult, "validateCallToolResult");
2716
+ var McpClient = class {
2717
+ static {
2718
+ __name(this, "McpClient");
2719
+ }
2720
+ options;
2721
+ state = "idle";
2722
+ transport;
2723
+ nextRequestId = 1;
2724
+ serverInfoValue;
2725
+ serverCapabilitiesValue;
2726
+ instructionsValue;
2727
+ protocolVersionValue;
2728
+ pending = /* @__PURE__ */ new Map();
2729
+ progressRequests = /* @__PURE__ */ new Map();
2730
+ incoming = /* @__PURE__ */ new Map();
2731
+ requestHandlers = /* @__PURE__ */ new Map();
2732
+ notificationListeners = /* @__PURE__ */ new Map();
2733
+ errorListeners = /* @__PURE__ */ new Set();
2734
+ closeListeners = /* @__PURE__ */ new Set();
2735
+ disposers = [];
2736
+ constructor(options) {
2737
+ this.options = Object.freeze({ ...options });
2738
+ this.requestHandlers.set("ping", () => ({}));
2739
+ const roots = options.roots;
2740
+ if (roots) {
2741
+ this.requestHandlers.set("roots/list", async () => ({
2742
+ roots: [...typeof roots === "function" ? await roots() : roots]
2743
+ }));
2744
+ }
2745
+ }
2746
+ get connectionState() {
2747
+ return this.state;
2748
+ }
2749
+ get serverInfo() {
2750
+ return this.serverInfoValue;
2751
+ }
2752
+ get serverCapabilities() {
2753
+ return this.serverCapabilitiesValue;
2754
+ }
2755
+ get instructions() {
2756
+ return this.instructionsValue;
2757
+ }
2758
+ get protocolVersion() {
2759
+ return this.protocolVersionValue;
2760
+ }
2761
+ async connect(transport) {
2762
+ if (this.state !== "idle")
2763
+ throw new Error(`Cannot connect MCP client in ${this.state} state`);
2764
+ this.state = "connecting";
2765
+ this.transport = transport;
2766
+ this.disposers = [
2767
+ transport.onMessage((message) => this.handleMessage(message)),
2768
+ // Transport errors are reported only. Pending requests fail when the transport closes.
2769
+ transport.onError((error) => this.emitError(error)),
2770
+ transport.onClose(() => this.handleTransportClose())
2771
+ ];
2772
+ try {
2773
+ await transport.start();
2774
+ const capabilities = { ...this.options.capabilities };
2775
+ if (this.options.roots && capabilities.roots === void 0)
2776
+ capabilities.roots = {};
2777
+ const result = validateInitializeResult(await this.requestInternal("initialize", {
2778
+ protocolVersion: this.options.protocolVersion ?? LATEST_PROTOCOL_VERSION,
2779
+ capabilities,
2780
+ clientInfo: {
2781
+ name: this.options.name,
2782
+ version: this.options.version,
2783
+ ...this.options.title === void 0 ? {} : { title: this.options.title }
2784
+ }
2785
+ }, {}, true));
2786
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
2787
+ throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);
2788
+ }
2789
+ this.protocolVersionValue = result.protocolVersion;
2790
+ this.serverInfoValue = result.serverInfo;
2791
+ this.serverCapabilitiesValue = result.capabilities;
2792
+ this.instructionsValue = result.instructions;
2793
+ transport.setProtocolVersion?.(result.protocolVersion);
2794
+ await this.notifyInternal("notifications/initialized", void 0, true);
2795
+ this.state = "connected";
2796
+ return result;
2797
+ } catch (error) {
2798
+ await this.close().catch(() => {
2799
+ });
2800
+ throw error;
2801
+ }
2802
+ }
2803
+ request(method, params, options = {}) {
2804
+ return this.requestInternal(method, params, options, false);
2805
+ }
2806
+ notify(method, params) {
2807
+ return this.notifyInternal(method, params, false);
2808
+ }
2809
+ setRequestHandler(method, handler) {
2810
+ this.requestHandlers.set(method, handler);
2811
+ return () => {
2812
+ if (this.requestHandlers.get(method) === handler)
2813
+ this.requestHandlers.delete(method);
2814
+ };
2815
+ }
2816
+ onNotification(method, listener) {
2817
+ const listeners = this.notificationListeners.get(method) ?? /* @__PURE__ */ new Set();
2818
+ this.notificationListeners.set(method, listeners);
2819
+ listeners.add(listener);
2820
+ return () => {
2821
+ listeners.delete(listener);
2822
+ if (listeners.size === 0)
2823
+ this.notificationListeners.delete(method);
2824
+ };
2825
+ }
2826
+ onError(listener) {
2827
+ this.errorListeners.add(listener);
2828
+ return () => this.errorListeners.delete(listener);
2829
+ }
2830
+ /** Called once when the connection closes, whether the transport dropped or `close()` was called. */
2831
+ onClose(listener) {
2832
+ this.closeListeners.add(listener);
2833
+ return () => this.closeListeners.delete(listener);
2834
+ }
2835
+ async ping(options = {}) {
2836
+ await this.request("ping", void 0, options);
2837
+ }
2838
+ async listTools(options = {}) {
2839
+ return await this.listAll("tools/list", "tools", isTool, options);
2840
+ }
2841
+ /** Every resource, following `nextCursor` through all pages. */
2842
+ async listResources(options = {}) {
2843
+ return (await this.listAll("resources/list", "resources", isResource, options)).map(toResource);
2844
+ }
2845
+ /** One page of resources, starting at `cursor`. */
2846
+ async listResourcesPage(cursor, options = {}) {
2847
+ const page = await this.listPage("resources/list", "resources", isResource, cursor, options);
2848
+ return { resources: page.items.map(toResource), ...pageCursor(page) };
2849
+ }
2850
+ /** Every resource template, following `nextCursor` through all pages. */
2851
+ async listResourceTemplates(options = {}) {
2852
+ const templates = await this.listAll("resources/templates/list", "resourceTemplates", isResourceTemplate, options);
2853
+ return templates.map(toResourceTemplate);
2854
+ }
2855
+ /** One page of resource templates, starting at `cursor`. */
2856
+ async listResourceTemplatesPage(cursor, options = {}) {
2857
+ const page = await this.listPage("resources/templates/list", "resourceTemplates", isResourceTemplate, cursor, options);
2858
+ return { resourceTemplates: page.items.map(toResourceTemplate), ...pageCursor(page) };
2859
+ }
2860
+ async readResource(uri, options = {}) {
2861
+ return validateReadResourceResult(await this.request("resources/read", { uri }, options));
2862
+ }
2863
+ async listPage(method, key, isItem, cursor, options) {
2864
+ return validateListPage(method, key, await this.request(method, cursor === void 0 ? void 0 : { cursor }, options), isItem);
2865
+ }
2866
+ /** Every item of a paginated list method. */
2867
+ async listAll(method, key, isItem, options) {
2868
+ const items = [];
2869
+ const cursors = /* @__PURE__ */ new Set();
2870
+ let cursor;
2871
+ for (let pageNumber = 0; pageNumber < MAX_LIST_PAGES; pageNumber++) {
2872
+ const page = await this.listPage(method, key, isItem, cursor, options);
2873
+ items.push(...page.items);
2874
+ if (page.nextCursor === void 0)
2875
+ return items;
2876
+ if (cursors.has(page.nextCursor))
2877
+ throw new Error(`MCP ${method} returned duplicate cursor: ${page.nextCursor}`);
2878
+ cursors.add(page.nextCursor);
2879
+ cursor = page.nextCursor;
2880
+ }
2881
+ throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`);
2882
+ }
2883
+ async callTool(name, args, options = {}) {
2884
+ return validateCallToolResult(await this.request("tools/call", { name, ...args === void 0 ? {} : { arguments: args } }, options));
2885
+ }
2886
+ async close() {
2887
+ const transport = this.transport;
2888
+ this.transport = void 0;
2889
+ this.disposeTransportListeners();
2890
+ this.markClosed(new McpConnectionClosedError());
2891
+ await transport?.close();
2892
+ }
2893
+ async requestInternal(method, params, options, allowConnecting) {
2894
+ const transport = this.requireTransport(allowConnecting);
2895
+ if (options.signal?.aborted)
2896
+ throw new McpAbortError();
2897
+ const id = this.nextRequestId++;
2898
+ const progressToken = options.onProgress ? id : void 0;
2899
+ const requestParams = progressToken === void 0 ? params : { ...params, _meta: { ...isObject(params?._meta) ? params._meta : {}, progressToken } };
2900
+ const message = {
2901
+ jsonrpc: "2.0",
2902
+ id,
2903
+ method,
2904
+ ...requestParams === void 0 ? {} : { params: requestParams }
2905
+ };
2906
+ return new Promise((resolve, reject) => {
2907
+ const entry = {
2908
+ resolve,
2909
+ reject,
2910
+ timeoutMs: options.timeoutMs ?? this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
2911
+ timer: void 0,
2912
+ signal: options.signal,
2913
+ // The spec forbids cancelling `initialize`.
2914
+ onAbort: /* @__PURE__ */ __name(() => this.cancelPending(id, new McpAbortError(), method !== "initialize", String(options.signal?.reason ?? "Aborted")), "onAbort"),
2915
+ sendController: new AbortController(),
2916
+ cancellable: method !== "initialize",
2917
+ onProgress: options.onProgress,
2918
+ progressToken
2919
+ };
2920
+ this.pending.set(id, entry);
2921
+ if (progressToken !== void 0)
2922
+ this.progressRequests.set(progressToken, id);
2923
+ options.signal?.addEventListener("abort", entry.onAbort, { once: true });
2924
+ this.armTimeout(id, entry);
2925
+ transport.send(message, { signal: entry.sendController.signal }).catch((error) => this.cancelPending(id, error, false));
2926
+ });
2927
+ }
2928
+ async notifyInternal(method, params, allowConnecting) {
2929
+ await this.requireTransport(allowConnecting).send({
2930
+ jsonrpc: "2.0",
2931
+ method,
2932
+ ...params === void 0 ? {} : { params }
2933
+ });
2934
+ }
2935
+ requireTransport(allowConnecting) {
2936
+ if (this.transport && (this.state === "connected" || allowConnecting && this.state === "connecting")) {
2937
+ return this.transport;
2938
+ }
2939
+ throw new McpConnectionClosedError(`MCP client is ${this.state}`);
2940
+ }
2941
+ handleMessage(message) {
2942
+ if (isJsonRpcResponse(message)) {
2943
+ this.handleResponse(message);
2944
+ return;
2945
+ }
2946
+ if (isJsonRpcRequest(message)) {
2947
+ void this.handleRequest(message);
2948
+ return;
2949
+ }
2950
+ if (isJsonRpcNotification(message)) {
2951
+ this.handleNotification(message.method, message.params);
2952
+ return;
2953
+ }
2954
+ this.emitError(new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Received invalid JSON-RPC message"));
2955
+ }
2956
+ handleResponse(message) {
2957
+ const entry = this.pending.get(message.id);
2958
+ if (!entry) {
2959
+ this.emitError(new Error(`Received response for unknown MCP request ${String(message.id)}`));
2960
+ return;
2961
+ }
2962
+ this.removePending(message.id, entry);
2963
+ if ("error" in message)
2964
+ entry.reject(new McpError(message.error.code, message.error.message, message.error.data));
2965
+ else
2966
+ entry.resolve(message.result);
2967
+ }
2968
+ async handleRequest(message) {
2969
+ const transport = this.transport;
2970
+ if (!transport)
2971
+ return;
2972
+ const handler = this.requestHandlers.get(message.method);
2973
+ if (!handler) {
2974
+ await transport.send({
2975
+ jsonrpc: "2.0",
2976
+ id: message.id,
2977
+ error: { code: JSON_RPC_ERROR_CODES.methodNotFound, message: `Method not found: ${message.method}` }
2978
+ }).catch((error) => this.emitError(error));
2979
+ return;
2980
+ }
2981
+ const controller = new AbortController();
2982
+ this.incoming.set(message.id, controller);
2983
+ try {
2984
+ const result = await handler(message.params, { signal: controller.signal });
2985
+ await transport.send({ jsonrpc: "2.0", id: message.id, result: result ?? {} });
2986
+ } catch (error) {
2987
+ const responseError = error instanceof McpError ? { code: error.code, message: error.message, data: error.data } : { code: JSON_RPC_ERROR_CODES.internalError, message: toError(error).message };
2988
+ await transport.send({ jsonrpc: "2.0", id: message.id, error: responseError }).catch((sendError) => this.emitError(sendError));
2989
+ } finally {
2990
+ this.incoming.delete(message.id);
2991
+ }
2992
+ }
2993
+ handleNotification(method, params) {
2994
+ if (method === "notifications/progress")
2995
+ this.handleProgress(params);
2996
+ else if (method === "notifications/cancelled")
2997
+ this.handleCancelled(params);
2998
+ for (const listener of this.notificationListeners.get(method) ?? []) {
2999
+ try {
3000
+ listener(params);
3001
+ } catch (error) {
3002
+ this.emitError(error);
3003
+ }
3004
+ }
3005
+ }
3006
+ handleProgress(params) {
3007
+ if (!isObject(params) || !isJsonRpcId(params.progressToken) || typeof params.progress !== "number")
3008
+ return;
3009
+ const requestId = this.progressRequests.get(params.progressToken);
3010
+ const entry = requestId === void 0 ? void 0 : this.pending.get(requestId);
3011
+ if (requestId === void 0 || !entry)
3012
+ return;
3013
+ this.armTimeout(requestId, entry);
3014
+ try {
3015
+ entry.onProgress?.(params);
3016
+ } catch (error) {
3017
+ this.emitError(error);
3018
+ }
3019
+ }
3020
+ handleCancelled(params) {
3021
+ if (isObject(params) && isJsonRpcId(params.requestId))
3022
+ this.incoming.get(params.requestId)?.abort(params.reason);
3023
+ }
3024
+ armTimeout(id, entry) {
3025
+ if (entry.timer)
3026
+ clearTimeout(entry.timer);
3027
+ if (!Number.isFinite(entry.timeoutMs) || entry.timeoutMs <= 0)
3028
+ return;
3029
+ entry.timer = setTimeout(() => {
3030
+ this.cancelPending(id, new McpTimeoutError(entry.timeoutMs), entry.cancellable, "Request timed out");
3031
+ }, entry.timeoutMs);
3032
+ }
3033
+ cancelPending(id, error, notifyServer, reason) {
3034
+ const entry = this.pending.get(id);
3035
+ if (!entry)
3036
+ return;
3037
+ this.removePending(id, entry);
3038
+ entry.reject(error);
3039
+ if (notifyServer && this.transport) {
3040
+ void this.transport.send({
3041
+ jsonrpc: "2.0",
3042
+ method: "notifications/cancelled",
3043
+ params: { requestId: id, ...reason ? { reason } : {} }
3044
+ }).catch((sendError) => this.emitError(sendError));
3045
+ }
3046
+ }
3047
+ removePending(id, entry) {
3048
+ this.pending.delete(id);
3049
+ if (entry.timer)
3050
+ clearTimeout(entry.timer);
3051
+ if (entry.progressToken !== void 0)
3052
+ this.progressRequests.delete(entry.progressToken);
3053
+ entry.signal?.removeEventListener("abort", entry.onAbort);
3054
+ entry.sendController.abort();
3055
+ }
3056
+ rejectPending(error) {
3057
+ for (const [id, entry] of this.pending) {
3058
+ this.removePending(id, entry);
3059
+ entry.reject(error);
3060
+ }
3061
+ }
3062
+ handleTransportClose() {
3063
+ this.markClosed(new McpConnectionClosedError());
3064
+ }
3065
+ /** Idempotent: rejects in-flight requests, aborts server requests we are serving, and flips the state. */
3066
+ markClosed(error) {
3067
+ const wasClosed = this.state === "closed";
3068
+ this.state = "closed";
3069
+ this.rejectPending(error);
3070
+ for (const controller of this.incoming.values())
3071
+ controller.abort(error);
3072
+ this.incoming.clear();
3073
+ if (wasClosed)
3074
+ return;
3075
+ for (const listener of [...this.closeListeners]) {
3076
+ try {
3077
+ listener();
3078
+ } catch (listenerError) {
3079
+ this.emitError(listenerError);
3080
+ }
3081
+ }
3082
+ }
3083
+ emitError(error) {
3084
+ const normalized = toError(error);
3085
+ for (const listener of this.errorListeners)
3086
+ listener(normalized);
3087
+ }
3088
+ disposeTransportListeners() {
3089
+ for (const dispose of this.disposers.splice(0))
3090
+ dispose();
3091
+ }
3092
+ };
3093
+
3094
+ // node_modules/@earendil-works/pi-mcp/dist/transports/stdio.js
3095
+ var import_cross_spawn = __toESM(require_cross_spawn(), 1);
3096
+ import { spawn } from "node:child_process";
3097
+ import process2 from "node:process";
3098
+
3099
+ // node_modules/@earendil-works/pi-mcp/dist/transports/transport.js
3100
+ var DEFAULT_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
3101
+ var TransportEvents = class {
3102
+ static {
3103
+ __name(this, "TransportEvents");
3104
+ }
3105
+ messageListeners = /* @__PURE__ */ new Set();
3106
+ errorListeners = /* @__PURE__ */ new Set();
3107
+ closeListeners = /* @__PURE__ */ new Set();
3108
+ closeEmitted = false;
3109
+ onMessage(listener) {
3110
+ this.messageListeners.add(listener);
3111
+ return () => this.messageListeners.delete(listener);
3112
+ }
3113
+ onError(listener) {
3114
+ this.errorListeners.add(listener);
3115
+ return () => this.errorListeners.delete(listener);
3116
+ }
3117
+ onClose(listener) {
3118
+ this.closeListeners.add(listener);
3119
+ return () => this.closeListeners.delete(listener);
3120
+ }
3121
+ emitMessage(message) {
3122
+ for (const listener of this.messageListeners)
3123
+ listener(message);
3124
+ }
3125
+ emitError(error) {
3126
+ const normalized = toError(error);
3127
+ for (const listener of this.errorListeners)
3128
+ listener(normalized);
3129
+ }
3130
+ emitClose() {
3131
+ if (this.closeEmitted)
3132
+ return;
3133
+ this.closeEmitted = true;
3134
+ for (const listener of this.closeListeners)
3135
+ listener();
3136
+ }
3137
+ };
3138
+
3139
+ // node_modules/@earendil-works/pi-mcp/dist/transports/stdio.js
3140
+ var DEFAULT_MAX_STDERR_BYTES = 64 * 1024;
3141
+ var DEFAULT_CLOSE_TIMEOUT_MS = 2e3;
3142
+ var STDIN_CLOSE_GRACE_MS = 500;
3143
+ var USE_PROCESS_GROUPS = process2.platform !== "win32";
3144
+ var liveProcessGroups = /* @__PURE__ */ new Set();
3145
+ var exitHookInstalled = false;
3146
+ function killProcessTree(child, signal) {
3147
+ const pid = child.pid;
3148
+ if (process2.platform === "win32" && pid !== void 0) {
3149
+ if (child.exitCode !== null)
3150
+ return;
3151
+ spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => {
3152
+ });
3153
+ return;
3154
+ }
3155
+ if (USE_PROCESS_GROUPS && pid !== void 0) {
3156
+ try {
3157
+ process2.kill(-pid, signal);
3158
+ return;
3159
+ } catch {
3160
+ }
3161
+ }
3162
+ try {
3163
+ child.kill(signal);
3164
+ } catch {
3165
+ }
3166
+ }
3167
+ __name(killProcessTree, "killProcessTree");
3168
+ function installExitHook() {
3169
+ if (exitHookInstalled)
3170
+ return;
3171
+ exitHookInstalled = true;
3172
+ process2.once("exit", () => {
3173
+ for (const pid of liveProcessGroups) {
3174
+ try {
3175
+ process2.kill(-pid, "SIGTERM");
3176
+ } catch {
3177
+ }
3178
+ }
3179
+ });
3180
+ }
3181
+ __name(installExitHook, "installExitHook");
3182
+ var StdioTransport = class extends TransportEvents {
3183
+ static {
3184
+ __name(this, "StdioTransport");
3185
+ }
3186
+ options;
3187
+ child;
3188
+ stdoutBuffer = Buffer.alloc(0);
3189
+ stderrBuffer = Buffer.alloc(0);
3190
+ started = false;
3191
+ closed = false;
3192
+ constructor(options) {
3193
+ super();
3194
+ this.options = Object.freeze({ ...options, args: options.args ? [...options.args] : void 0 });
3195
+ }
3196
+ get pid() {
3197
+ return this.child?.pid;
3198
+ }
3199
+ get stderr() {
3200
+ return this.stderrBuffer.toString("utf8");
3201
+ }
3202
+ async start() {
3203
+ if (this.started)
3204
+ throw new Error("MCP stdio transport already started");
3205
+ if (this.closed)
3206
+ throw new McpConnectionClosedError();
3207
+ this.started = true;
3208
+ const env = this.options.inheritEnv === false ? { ...this.options.env } : { ...process2.env, ...this.options.env };
3209
+ const child = (0, import_cross_spawn.default)(this.options.command, this.options.args ?? [], {
3210
+ cwd: this.options.cwd,
3211
+ env,
3212
+ stdio: ["pipe", "pipe", this.options.stderr === "inherit" ? "inherit" : "pipe"],
3213
+ windowsHide: true,
3214
+ // Own process group, so closing the transport can terminate the server's children too.
3215
+ detached: USE_PROCESS_GROUPS
3216
+ });
3217
+ this.child = child;
3218
+ const pid = child.pid;
3219
+ if (USE_PROCESS_GROUPS && pid !== void 0) {
3220
+ installExitHook();
3221
+ liveProcessGroups.add(pid);
3222
+ child.once("exit", () => liveProcessGroups.delete(pid));
3223
+ }
3224
+ child.stdout?.on("data", (chunk) => this.handleStdout(chunk));
3225
+ child.stdout?.on("error", (error) => this.emitError(error));
3226
+ child.stdin?.on("error", (error) => {
3227
+ if (!this.closed)
3228
+ this.emitError(error);
3229
+ });
3230
+ child.stderr?.on("data", (chunk) => this.handleStderr(chunk));
3231
+ child.stderr?.on("error", (error) => this.emitError(error));
3232
+ child.on("close", () => {
3233
+ this.child = void 0;
3234
+ if (this.stdoutBuffer.toString("utf8").trim()) {
3235
+ this.emitError(new Error("MCP stdio server closed with an incomplete JSON-RPC message"));
3236
+ }
3237
+ this.stdoutBuffer = Buffer.alloc(0);
3238
+ this.emitClose();
3239
+ });
3240
+ await new Promise((resolve, reject) => {
3241
+ const onSpawn = /* @__PURE__ */ __name(() => {
3242
+ child.off("error", onError);
3243
+ resolve();
3244
+ }, "onSpawn");
3245
+ const onError = /* @__PURE__ */ __name((error) => {
3246
+ child.off("spawn", onSpawn);
3247
+ reject(error);
3248
+ }, "onError");
3249
+ child.once("spawn", onSpawn);
3250
+ child.once("error", onError);
3251
+ });
3252
+ child.on("error", (error) => {
3253
+ if (!this.closed)
3254
+ this.emitError(error);
3255
+ });
3256
+ }
3257
+ async send(message) {
3258
+ const stdin = this.child?.stdin;
3259
+ if (!this.started || this.closed || !stdin?.writable)
3260
+ throw new McpConnectionClosedError();
3261
+ const payload = `${JSON.stringify(message)}
3262
+ `;
3263
+ await new Promise((resolve, reject) => {
3264
+ stdin.write(payload, (error) => error ? reject(error) : resolve());
3265
+ });
3266
+ }
3267
+ async close() {
3268
+ if (this.closed)
3269
+ return;
3270
+ this.closed = true;
3271
+ const child = this.child;
3272
+ if (!child) {
3273
+ this.emitClose();
3274
+ return;
3275
+ }
3276
+ if (child.exitCode !== null || child.signalCode !== null) {
3277
+ child.stdin?.end();
3278
+ return;
3279
+ }
3280
+ const closeTimeoutMs = this.options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
3281
+ await new Promise((resolve) => {
3282
+ const timers = [];
3283
+ child.once("close", () => {
3284
+ for (const timer of timers)
3285
+ clearTimeout(timer);
3286
+ killProcessTree(child, "SIGTERM");
3287
+ resolve();
3288
+ });
3289
+ const grace = Math.min(STDIN_CLOSE_GRACE_MS, closeTimeoutMs);
3290
+ timers.push(setTimeout(() => killProcessTree(child, "SIGTERM"), grace));
3291
+ timers.push(setTimeout(() => killProcessTree(child, "SIGKILL"), grace + closeTimeoutMs));
3292
+ child.stdin?.end();
3293
+ });
3294
+ }
3295
+ handleStdout(chunk) {
3296
+ this.stdoutBuffer = Buffer.concat([this.stdoutBuffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
3297
+ const maxMessageBytes = this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;
3298
+ while (true) {
3299
+ const newline = this.stdoutBuffer.indexOf(10);
3300
+ if (newline < 0) {
3301
+ if (this.stdoutBuffer.length > maxMessageBytes) {
3302
+ this.stdoutBuffer = Buffer.alloc(0);
3303
+ this.emitError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`));
3304
+ }
3305
+ return;
3306
+ }
3307
+ const line = this.stdoutBuffer.subarray(0, newline);
3308
+ this.stdoutBuffer = this.stdoutBuffer.subarray(newline + 1);
3309
+ if (line.length > maxMessageBytes) {
3310
+ this.emitError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`));
3311
+ continue;
3312
+ }
3313
+ const text = line.toString("utf8").replace(/\r$/, "");
3314
+ if (!text.trim())
3315
+ continue;
3316
+ try {
3317
+ this.emitMessage(parseJsonRpcMessage(JSON.parse(text)));
3318
+ } catch (error) {
3319
+ this.emitError(error);
3320
+ }
3321
+ }
3322
+ }
3323
+ handleStderr(chunk) {
3324
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
3325
+ const maxStderrBytes = this.options.maxStderrBytes ?? DEFAULT_MAX_STDERR_BYTES;
3326
+ this.stderrBuffer = Buffer.concat([this.stderrBuffer, buffer]);
3327
+ if (this.stderrBuffer.length > maxStderrBytes)
3328
+ this.stderrBuffer = this.stderrBuffer.subarray(-maxStderrBytes);
3329
+ this.options.onStderr?.(buffer.toString("utf8"));
3330
+ }
3331
+ };
3332
+
3333
+ // node_modules/@earendil-works/pi-mcp/dist/transports/streamable-http.js
3334
+ var MAX_ERROR_BODY_BYTES = 8 * 1024;
3335
+ var ERROR_MESSAGE_BODY_CHARS = 500;
3336
+ var DEFAULT_RECONNECT_INITIAL_DELAY_MS = 1e3;
3337
+ var DEFAULT_RECONNECT_MAX_DELAY_MS = 3e4;
3338
+ var DEFAULT_RECONNECT_MAX_RETRIES = 5;
3339
+ async function consumeSseStream(stream, options) {
3340
+ const reader = stream.getReader();
3341
+ const decoder = new TextDecoder();
3342
+ let buffered = "";
3343
+ let eventName;
3344
+ let eventId;
3345
+ let dataLines = [];
3346
+ let dataBytes = 0;
3347
+ const maxEventBytes = options.maxEventBytes ?? DEFAULT_MAX_MESSAGE_BYTES;
3348
+ const dispatch = /* @__PURE__ */ __name(() => {
3349
+ if (dataLines.length === 0) {
3350
+ eventName = void 0;
3351
+ eventId = void 0;
3352
+ return;
3353
+ }
3354
+ const data = dataLines.join("\n");
3355
+ options.onEvent({ ...eventName ? { event: eventName } : {}, data, ...eventId ? { id: eventId } : {} });
3356
+ eventName = void 0;
3357
+ eventId = void 0;
3358
+ dataLines = [];
3359
+ dataBytes = 0;
3360
+ }, "dispatch");
3361
+ const processLine = /* @__PURE__ */ __name((rawLine) => {
3362
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
3363
+ if (line === "") {
3364
+ dispatch();
3365
+ return;
3366
+ }
3367
+ if (line.startsWith(":"))
3368
+ return;
3369
+ const colon = line.indexOf(":");
3370
+ const field = colon < 0 ? line : line.slice(0, colon);
3371
+ let value = colon < 0 ? "" : line.slice(colon + 1);
3372
+ if (value.startsWith(" "))
3373
+ value = value.slice(1);
3374
+ if (field === "data") {
3375
+ dataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);
3376
+ if (dataBytes > maxEventBytes)
3377
+ throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
3378
+ dataLines.push(value);
3379
+ } else if (field === "event")
3380
+ eventName = value;
3381
+ else if (field === "id" && !value.includes("\0")) {
3382
+ eventId = value;
3383
+ options.onId?.(value);
3384
+ } else if (field === "retry" && /^\d+$/.test(value))
3385
+ options.onRetry?.(Number(value));
3386
+ }, "processLine");
3387
+ try {
3388
+ while (true) {
3389
+ const { done, value } = await reader.read();
3390
+ if (done)
3391
+ break;
3392
+ buffered += decoder.decode(value, { stream: true });
3393
+ let newline = buffered.indexOf("\n");
3394
+ while (newline >= 0) {
3395
+ processLine(buffered.slice(0, newline));
3396
+ buffered = buffered.slice(newline + 1);
3397
+ newline = buffered.indexOf("\n");
3398
+ }
3399
+ if (Buffer.byteLength(buffered) > maxEventBytes)
3400
+ throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
3401
+ }
3402
+ buffered += decoder.decode();
3403
+ if (buffered)
3404
+ processLine(buffered);
3405
+ dispatch();
3406
+ } finally {
3407
+ reader.releaseLock();
3408
+ }
3409
+ }
3410
+ __name(consumeSseStream, "consumeSseStream");
3411
+ var McpHttpError = class extends Error {
3412
+ static {
3413
+ __name(this, "McpHttpError");
3414
+ }
3415
+ status;
3416
+ body;
3417
+ constructor(status, message, body = "") {
3418
+ super(message);
3419
+ this.name = "McpHttpError";
3420
+ this.status = status;
3421
+ this.body = body;
3422
+ }
3423
+ };
3424
+ var McpAuthRequiredError = class extends McpHttpError {
3425
+ static {
3426
+ __name(this, "McpAuthRequiredError");
3427
+ }
3428
+ wwwAuthenticate;
3429
+ constructor(response, body = "") {
3430
+ super(401, "MCP server requires authentication", body);
3431
+ this.name = "McpAuthRequiredError";
3432
+ this.wwwAuthenticate = response.headers.get("www-authenticate");
3433
+ }
3434
+ };
3435
+ var McpSessionExpiredError = class extends McpHttpError {
3436
+ static {
3437
+ __name(this, "McpSessionExpiredError");
3438
+ }
3439
+ constructor(body = "") {
3440
+ super(404, "MCP session expired", body);
3441
+ this.name = "McpSessionExpiredError";
3442
+ }
3443
+ };
3444
+ function contentType(response) {
3445
+ return response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
3446
+ }
3447
+ __name(contentType, "contentType");
3448
+ function needsAuthorization(response) {
3449
+ if (response.status === 401)
3450
+ return true;
3451
+ if (response.status !== 403)
3452
+ return false;
3453
+ return /(?:^|[\s,])error="?insufficient_scope"?/i.test(response.headers.get("www-authenticate") ?? "");
3454
+ }
3455
+ __name(needsAuthorization, "needsAuthorization");
3456
+ function isTransientStatus(status) {
3457
+ return status === 408 || status === 429 || status >= 500;
3458
+ }
3459
+ __name(isTransientStatus, "isTransientStatus");
3460
+ function discard(response) {
3461
+ return response.body?.cancel().catch(() => {
3462
+ }) ?? Promise.resolve();
3463
+ }
3464
+ __name(discard, "discard");
3465
+ function describeHttpFailure(status, body) {
3466
+ const text = body.trim();
3467
+ const snippet = text.length > ERROR_MESSAGE_BODY_CHARS ? `${text.slice(0, ERROR_MESSAGE_BODY_CHARS - 3)}...` : text;
3468
+ return `MCP HTTP request failed with status ${status}${snippet ? `: ${snippet}` : ""}`;
3469
+ }
3470
+ __name(describeHttpFailure, "describeHttpFailure");
3471
+ var StreamableHttpTransport = class extends TransportEvents {
3472
+ static {
3473
+ __name(this, "StreamableHttpTransport");
3474
+ }
3475
+ url;
3476
+ options;
3477
+ fetch;
3478
+ controller = new AbortController();
3479
+ started = false;
3480
+ closed = false;
3481
+ sessionIdValue;
3482
+ protocolVersion;
3483
+ getStreamStarted = false;
3484
+ /** Access token of the latest request, which `close()` reuses instead of asking the auth provider. */
3485
+ lastToken;
3486
+ constructor(options) {
3487
+ super();
3488
+ this.options = Object.freeze({ ...options, headers: options.headers ? { ...options.headers } : void 0 });
3489
+ this.url = new URL(options.url);
3490
+ const fetch = options.fetch ?? globalThis.fetch;
3491
+ this.fetch = (input, init) => fetch(input, init);
3492
+ }
3493
+ get sessionId() {
3494
+ return this.sessionIdValue;
3495
+ }
3496
+ async start() {
3497
+ if (this.started)
3498
+ throw new Error("MCP Streamable HTTP transport already started");
3499
+ if (this.closed)
3500
+ throw new McpConnectionClosedError();
3501
+ this.started = true;
3502
+ }
3503
+ setProtocolVersion(version) {
3504
+ this.protocolVersion = version;
3505
+ }
3506
+ async send(message, { signal } = {}) {
3507
+ if (!this.started || this.closed)
3508
+ throw new McpConnectionClosedError();
3509
+ const response = await this.authorizedFetch("POST", {
3510
+ headers: { accept: "application/json, text/event-stream", "content-type": "application/json" },
3511
+ body: JSON.stringify(message)
3512
+ }, signal);
3513
+ await this.checkResponse(response);
3514
+ this.captureSession(response);
3515
+ if (!isJsonRpcRequest(message)) {
3516
+ await discard(response);
3517
+ if ("method" in message && message.method === "notifications/initialized")
3518
+ this.startGetStream();
3519
+ return;
3520
+ }
3521
+ if (response.status === 202 || response.status === 204) {
3522
+ throw new McpHttpError(response.status, `MCP server accepted request ${message.method} without a response`);
3523
+ }
3524
+ const type = contentType(response);
3525
+ if (type === "application/json") {
3526
+ const body = await response.json();
3527
+ for (const item of Array.isArray(body) ? body : [body])
3528
+ this.emitMessage(parseJsonRpcMessage(item));
3529
+ return;
3530
+ }
3531
+ if (type === "text/event-stream" && response.body) {
3532
+ void this.consumeResponseStream(response.body, message.id);
3533
+ return;
3534
+ }
3535
+ await discard(response);
3536
+ throw new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? "missing"}`);
3537
+ }
3538
+ async close() {
3539
+ if (this.closed)
3540
+ return;
3541
+ this.closed = true;
3542
+ this.controller.abort();
3543
+ if (this.started && this.sessionIdValue) {
3544
+ try {
3545
+ const response = await this.fetch(this.url, {
3546
+ method: "DELETE",
3547
+ headers: this.buildHeaders({}, this.lastToken),
3548
+ signal: AbortSignal.timeout(1e3)
3549
+ });
3550
+ await discard(response);
3551
+ } catch {
3552
+ }
3553
+ }
3554
+ this.emitClose();
3555
+ }
3556
+ /**
3557
+ * Fetch with auth headers. A 401 (or a 403 asking for more scope) is handed to the auth provider
3558
+ * once, and the request is retried with whatever credentials it left behind.
3559
+ *
3560
+ * `signal` only stops dispatch: getting a token or the authorization recovery can take a while, and a
3561
+ * request its sender gave up on in the meantime must not reach the server. It does not abort the shared
3562
+ * recovery, which other requests may wait for.
3563
+ */
3564
+ async authorizedFetch(method, init, signal) {
3565
+ const onUnauthorized = this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);
3566
+ for (let attempt = 0; ; attempt++) {
3567
+ const { headers, token } = await this.headers(init.headers);
3568
+ if (signal?.aborted)
3569
+ throw new McpAbortError();
3570
+ const response = await this.fetch(this.url, {
3571
+ method,
3572
+ headers,
3573
+ body: init.body,
3574
+ signal: this.controller.signal
3575
+ });
3576
+ if (attempt > 0 || !onUnauthorized || !needsAuthorization(response))
3577
+ return response;
3578
+ try {
3579
+ await onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });
3580
+ } finally {
3581
+ await discard(response);
3582
+ }
3583
+ }
3584
+ }
3585
+ async headers(extra = {}) {
3586
+ const token = await this.options.authProvider?.token();
3587
+ this.lastToken = token;
3588
+ return { headers: this.buildHeaders(extra, token), ...token ? { token } : {} };
3589
+ }
3590
+ buildHeaders(extra, token) {
3591
+ const headers = new Headers(this.options.headers);
3592
+ for (const [name, value] of Object.entries(extra))
3593
+ headers.set(name, value);
3594
+ if (this.sessionIdValue)
3595
+ headers.set("Mcp-Session-Id", this.sessionIdValue);
3596
+ if (this.protocolVersion)
3597
+ headers.set("MCP-Protocol-Version", this.protocolVersion);
3598
+ if (token)
3599
+ headers.set("Authorization", `Bearer ${token}`);
3600
+ return headers;
3601
+ }
3602
+ captureSession(response) {
3603
+ const sessionId = response.headers.get("mcp-session-id");
3604
+ if (sessionId)
3605
+ this.sessionIdValue = sessionId;
3606
+ }
3607
+ async checkResponse(response) {
3608
+ if (response.ok)
3609
+ return;
3610
+ const body = (await response.text().catch(() => "")).slice(0, MAX_ERROR_BODY_BYTES);
3611
+ if (response.status === 401)
3612
+ throw new McpAuthRequiredError(response, body);
3613
+ if (response.status === 404 && this.sessionIdValue)
3614
+ throw new McpSessionExpiredError(body);
3615
+ throw new McpHttpError(response.status, describeHttpFailure(response.status, body), body);
3616
+ }
3617
+ async consumeSse(stream, cursor, onMessage) {
3618
+ await consumeSseStream(stream, {
3619
+ maxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,
3620
+ onId: /* @__PURE__ */ __name((id) => {
3621
+ cursor.lastEventId = id;
3622
+ }, "onId"),
3623
+ onRetry: /* @__PURE__ */ __name((delayMs) => {
3624
+ cursor.retryMs = delayMs;
3625
+ }, "onRetry"),
3626
+ onEvent: /* @__PURE__ */ __name((event) => {
3627
+ cursor.received = true;
3628
+ if (!event.data.trim() || event.event !== void 0 && event.event !== "message")
3629
+ return;
3630
+ let message;
3631
+ try {
3632
+ message = parseJsonRpcMessage(JSON.parse(event.data));
3633
+ } catch (error) {
3634
+ this.emitError(error);
3635
+ return;
3636
+ }
3637
+ onMessage?.(message);
3638
+ this.emitMessage(message);
3639
+ }, "onEvent")
3640
+ });
3641
+ }
3642
+ /**
3643
+ * Read the SSE stream answering one request. When the stream ends or breaks before the response
3644
+ * arrives and the server assigned event IDs, resume it with GET and `Last-Event-ID`, as the
3645
+ * server may close response streams at will. Otherwise only this request fails.
3646
+ */
3647
+ async consumeResponseStream(body, requestId) {
3648
+ const cursor = { lastEventId: void 0, retryMs: void 0, received: false };
3649
+ let answered = false;
3650
+ const onMessage = /* @__PURE__ */ __name((message) => {
3651
+ if (isJsonRpcResponse(message) && message.id === requestId)
3652
+ answered = true;
3653
+ }, "onMessage");
3654
+ let stream = body;
3655
+ let failure;
3656
+ for (let attempt = 0; ; ) {
3657
+ if (stream) {
3658
+ try {
3659
+ await this.consumeSse(stream, cursor, onMessage);
3660
+ failure = void 0;
3661
+ } catch (error) {
3662
+ failure = error;
3663
+ }
3664
+ }
3665
+ if (answered || this.closed)
3666
+ return;
3667
+ if (failure !== void 0 && !this.isRetryable(failure))
3668
+ break;
3669
+ if (cursor.lastEventId === void 0 || attempt >= this.maxRetries())
3670
+ break;
3671
+ if (cursor.received)
3672
+ attempt = 0;
3673
+ cursor.received = false;
3674
+ if (!await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))
3675
+ return;
3676
+ try {
3677
+ stream = await this.openSseStream(cursor.lastEventId);
3678
+ } catch (error) {
3679
+ failure = error;
3680
+ if (!this.isRetryable(error))
3681
+ break;
3682
+ stream = void 0;
3683
+ }
3684
+ }
3685
+ if (this.closed)
3686
+ return;
3687
+ const reason = failure === void 0 ? "stream ended without a response" : toError(failure).message;
3688
+ this.emitMessage({
3689
+ jsonrpc: "2.0",
3690
+ id: requestId,
3691
+ error: { code: JSON_RPC_ERROR_CODES.internalError, message: `MCP response stream failed: ${reason}` }
3692
+ });
3693
+ }
3694
+ startGetStream() {
3695
+ if (this.options.openGetStream === false || this.getStreamStarted || this.closed)
3696
+ return;
3697
+ this.getStreamStarted = true;
3698
+ void this.runGetStream();
3699
+ }
3700
+ /** Keep the server-to-client stream open, reconnecting with backoff when it drops. */
3701
+ async runGetStream() {
3702
+ const cursor = { lastEventId: void 0, retryMs: void 0, received: false };
3703
+ for (let attempt = 0; !this.closed; ) {
3704
+ try {
3705
+ const stream = await this.openSseStream(cursor.lastEventId);
3706
+ if (!stream)
3707
+ return;
3708
+ const openedAt = Date.now();
3709
+ await this.consumeSse(stream, cursor);
3710
+ if (cursor.received || Date.now() - openedAt > this.maxDelay())
3711
+ attempt = 0;
3712
+ } catch (error) {
3713
+ if (this.closed)
3714
+ return;
3715
+ if (!this.isRetryable(error)) {
3716
+ this.emitError(error);
3717
+ return;
3718
+ }
3719
+ }
3720
+ cursor.received = false;
3721
+ if (attempt >= this.maxRetries()) {
3722
+ this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));
3723
+ return;
3724
+ }
3725
+ if (!await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))
3726
+ return;
3727
+ }
3728
+ }
3729
+ /** Open a GET SSE stream. Resolves to undefined when the server answers 405 (no GET stream). */
3730
+ async openSseStream(lastEventId) {
3731
+ const response = await this.authorizedFetch("GET", {
3732
+ headers: {
3733
+ accept: "text/event-stream",
3734
+ ...lastEventId === void 0 ? {} : { "last-event-id": lastEventId }
3735
+ }
3736
+ });
3737
+ if (response.status === 405) {
3738
+ await discard(response);
3739
+ return void 0;
3740
+ }
3741
+ await this.checkResponse(response);
3742
+ this.captureSession(response);
3743
+ const type = contentType(response);
3744
+ if (type !== "text/event-stream" || !response.body) {
3745
+ await discard(response);
3746
+ throw new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? "missing"}`);
3747
+ }
3748
+ return response.body;
3749
+ }
3750
+ /**
3751
+ * Network failures and transient statuses are retried; auth, session, and protocol errors are not.
3752
+ * `fetch` reports network failures, including a connection dropped mid-body, as `TypeError`.
3753
+ */
3754
+ isRetryable(error) {
3755
+ if (error instanceof McpHttpError)
3756
+ return isTransientStatus(error.status);
3757
+ if (error instanceof TypeError)
3758
+ return true;
3759
+ const code = error?.code;
3760
+ return typeof code === "string" && (code.startsWith("E") || code.startsWith("UND_ERR"));
3761
+ }
3762
+ reconnectDelay(attempt, serverDelayMs) {
3763
+ if (serverDelayMs !== void 0)
3764
+ return serverDelayMs;
3765
+ const initial = this.options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS;
3766
+ return Math.min(initial * 2 ** attempt, this.maxDelay());
3767
+ }
3768
+ maxDelay() {
3769
+ return this.options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;
3770
+ }
3771
+ maxRetries() {
3772
+ return this.options.reconnect?.maxRetries ?? DEFAULT_RECONNECT_MAX_RETRIES;
3773
+ }
3774
+ /** Resolves false when the transport closed while waiting. */
3775
+ sleep(ms) {
3776
+ const signal = this.controller.signal;
3777
+ if (signal.aborted)
3778
+ return Promise.resolve(false);
3779
+ return new Promise((resolve) => {
3780
+ const onAbort = /* @__PURE__ */ __name(() => {
3781
+ clearTimeout(timer);
3782
+ resolve(false);
3783
+ }, "onAbort");
3784
+ const timer = setTimeout(() => {
3785
+ signal.removeEventListener("abort", onAbort);
3786
+ resolve(true);
3787
+ }, ms);
3788
+ timer.unref?.();
3789
+ signal.addEventListener("abort", onAbort, { once: true });
3790
+ });
3791
+ }
3792
+ };
3793
+
3794
+ // node_modules/@earendil-works/pi-mcp/dist/protocol/content.js
3795
+ function blockToLlmContent(block) {
3796
+ switch (block.type) {
3797
+ case "text":
3798
+ return { type: "text", text: block.text };
3799
+ case "image":
3800
+ return { type: "image", data: block.data, mimeType: block.mimeType };
3801
+ case "audio":
3802
+ return { type: "text", text: `[audio ${block.mimeType} omitted]` };
3803
+ case "resource_link":
3804
+ return { type: "text", text: `${block.name}: ${block.uri}` };
3805
+ case "resource": {
3806
+ const resource = block.resource;
3807
+ if ("text" in resource)
3808
+ return { type: "text", text: resource.text };
3809
+ if (resource.mimeType?.startsWith("image/")) {
3810
+ return { type: "image", data: resource.blob, mimeType: resource.mimeType };
3811
+ }
3812
+ return {
3813
+ type: "text",
3814
+ text: `[binary resource ${resource.uri} (${resource.mimeType ?? "unknown type"}) omitted]`
3815
+ };
3816
+ }
3817
+ default:
3818
+ return { type: "text", text: `[unsupported MCP content ${block.type}]` };
3819
+ }
3820
+ }
3821
+ __name(blockToLlmContent, "blockToLlmContent");
3822
+ function toLlmContent(result) {
3823
+ const content = (result.content ?? []).map(blockToLlmContent);
3824
+ if (content.length === 0 && result.structuredContent !== void 0) {
3825
+ content.push({ type: "text", text: JSON.stringify(result.structuredContent, null, 2) });
3826
+ }
3827
+ return content;
3828
+ }
3829
+ __name(toLlmContent, "toLlmContent");
3830
+
3831
+ export {
3832
+ require_proper_lockfile,
3833
+ operationSignal,
3834
+ raceWithAbortSignal,
3835
+ getConfigValueEnvVarNames,
3836
+ isCommandConfigValue,
3837
+ isConfigValueConfigured,
3838
+ resolveConfigValueOrThrow,
3839
+ resolveHeadersOrThrow,
3840
+ FileAuthStorageBackend,
3841
+ ReadOnlyAuthStorage,
3842
+ AuthStorage,
3843
+ readStoredCredential,
3844
+ createToolNameMatcher,
3845
+ LIST_MCP_RESOURCES_TOOL,
3846
+ LIST_MCP_RESOURCE_TEMPLATES_TOOL,
3847
+ READ_MCP_RESOURCE_TOOL,
3848
+ isMcpToolName,
3849
+ mcpNamespace,
3850
+ getMcpToolExposure,
3851
+ validateMcpServerConfig,
3852
+ McpServerRegistry,
3853
+ JSON_RPC_ERROR_CODES,
3854
+ McpError,
3855
+ isObject,
3856
+ LATEST_PROTOCOL_VERSION,
3857
+ McpClient,
3858
+ toLlmContent,
3859
+ StdioTransport,
3860
+ McpHttpError,
3861
+ McpAuthRequiredError,
3862
+ McpSessionExpiredError,
3863
+ StreamableHttpTransport
3864
+ };