privateer-agent 0.15.5 → 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 (214) 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/privateer-launch.mjs +14 -2
  5. package/bin/privateer-verify.mjs +12 -0
  6. package/dist-boot/boot.mjs +3 -0
  7. package/dist-boot/c-27JKSMWL.mjs +1460 -0
  8. package/dist-boot/c-2BMRFV24.mjs +269 -0
  9. package/dist-boot/c-2CTF6JA3.mjs +166 -0
  10. package/dist-boot/c-2G3BBHRJ.mjs +84 -0
  11. package/dist-boot/c-2IDLKXX6.mjs +250 -0
  12. package/dist-boot/c-2NJD5VYM.mjs +8 -0
  13. package/dist-boot/c-2S5EEQPW.mjs +1602 -0
  14. package/dist-boot/c-2WRDCUVI.mjs +25 -0
  15. package/dist-boot/c-2YN3M256.mjs +14 -0
  16. package/dist-boot/c-37GM3GMU.mjs +187 -0
  17. package/dist-boot/c-3STKRSVO.mjs +2480 -0
  18. package/dist-boot/c-3TPV6TQQ.mjs +2320 -0
  19. package/dist-boot/c-3UVHLQDJ.mjs +225 -0
  20. package/dist-boot/c-42PUUZYC.mjs +697 -0
  21. package/dist-boot/c-4D5UMWVW.mjs +683 -0
  22. package/dist-boot/c-4ETZRMTA.mjs +46 -0
  23. package/dist-boot/c-4QT25BD5.mjs +1482 -0
  24. package/dist-boot/c-4WVR32AP.mjs +2579 -0
  25. package/dist-boot/c-5EMM567G.mjs +152 -0
  26. package/dist-boot/c-5FA4CV63.mjs +145 -0
  27. package/dist-boot/c-5GV3X3RB.mjs +14 -0
  28. package/dist-boot/c-5JCEPRIY.mjs +52 -0
  29. package/dist-boot/c-5NDKIIWT.mjs +16 -0
  30. package/dist-boot/c-5QL3AR26.mjs +4665 -0
  31. package/dist-boot/c-5XY6MFKN.mjs +5142 -0
  32. package/dist-boot/c-65UZIZC7.mjs +2897 -0
  33. package/dist-boot/c-6FUXKHOK.mjs +1969 -0
  34. package/dist-boot/c-6JHWQE4V.mjs +18242 -0
  35. package/dist-boot/c-6LOBR4I6.mjs +5280 -0
  36. package/dist-boot/c-6QHOZXKQ.mjs +14394 -0
  37. package/dist-boot/c-6ZO2SADQ.mjs +178 -0
  38. package/dist-boot/c-6ZORVVZP.mjs +1449 -0
  39. package/dist-boot/c-76QH4UCP.mjs +2441 -0
  40. package/dist-boot/c-77GO5L5Y.mjs +20982 -0
  41. package/dist-boot/c-7M23XFTN.mjs +5052 -0
  42. package/dist-boot/c-7TC367E2.mjs +32 -0
  43. package/dist-boot/c-7UOG7POX.mjs +1524 -0
  44. package/dist-boot/c-7VHP3FLN.mjs +376 -0
  45. package/dist-boot/c-A73JHZP2.mjs +13207 -0
  46. package/dist-boot/c-ABXULAFL.mjs +71 -0
  47. package/dist-boot/c-ANDD2AQO.mjs +74 -0
  48. package/dist-boot/c-AOY77AZL.mjs +1430 -0
  49. package/dist-boot/c-AXEPZ22I.mjs +108 -0
  50. package/dist-boot/c-B2Y7VNHU.mjs +427 -0
  51. package/dist-boot/c-B7VJUH73.mjs +77 -0
  52. package/dist-boot/c-BFW6CDVL.mjs +24 -0
  53. package/dist-boot/c-BHNIF2AR.mjs +188 -0
  54. package/dist-boot/c-BKF2O6BL.mjs +23 -0
  55. package/dist-boot/c-BOZXFTZN.mjs +8 -0
  56. package/dist-boot/c-BRNYJWZL.mjs +28 -0
  57. package/dist-boot/c-C3N4Z2HO.mjs +93 -0
  58. package/dist-boot/c-C4IV7ZFG.mjs +717 -0
  59. package/dist-boot/c-C5NK6UYV.mjs +793 -0
  60. package/dist-boot/c-C67644MB.mjs +1659 -0
  61. package/dist-boot/c-C6S2YB53.mjs +620 -0
  62. package/dist-boot/c-CDBEJSBF.mjs +37 -0
  63. package/dist-boot/c-CG47HBKU.mjs +435 -0
  64. package/dist-boot/c-CKCTWCT5.mjs +51 -0
  65. package/dist-boot/c-CN77DCGF.mjs +60 -0
  66. package/dist-boot/c-CRBXNKFO.mjs +1795 -0
  67. package/dist-boot/c-CRIHASQ6.mjs +973 -0
  68. package/dist-boot/c-CU4NGAUO.mjs +3786 -0
  69. package/dist-boot/c-CWRFLGQU.mjs +1883 -0
  70. package/dist-boot/c-CYQB2USO.mjs +32 -0
  71. package/dist-boot/c-DEE67DJO.mjs +379 -0
  72. package/dist-boot/c-DIFDBYOP.mjs +1258 -0
  73. package/dist-boot/c-DOSGVXDZ.mjs +34879 -0
  74. package/dist-boot/c-DR7XQI32.mjs +381 -0
  75. package/dist-boot/c-DTGPSB46.mjs +14666 -0
  76. package/dist-boot/c-DTHDNA4P.mjs +320 -0
  77. package/dist-boot/c-E4Z3Y5B5.mjs +3864 -0
  78. package/dist-boot/c-E66Z2TI7.mjs +203 -0
  79. package/dist-boot/c-EBU6RLRV.mjs +1527 -0
  80. package/dist-boot/c-EBZZNGSF.mjs +432 -0
  81. package/dist-boot/c-EC3LJ2KF.mjs +1032 -0
  82. package/dist-boot/c-EQBKXWNX.mjs +15829 -0
  83. package/dist-boot/c-EUEPIW4S.mjs +574 -0
  84. package/dist-boot/c-EX4YVWAT.mjs +378 -0
  85. package/dist-boot/c-EYZGSAJU.mjs +98 -0
  86. package/dist-boot/c-F75VRKY4.mjs +172 -0
  87. package/dist-boot/c-FH4NXKHV.mjs +177 -0
  88. package/dist-boot/c-FHNUCTEM.mjs +140 -0
  89. package/dist-boot/c-FJ5T42DS.mjs +5349 -0
  90. package/dist-boot/c-FPCNRL7G.mjs +1728 -0
  91. package/dist-boot/c-G4DLN7Q4.mjs +8 -0
  92. package/dist-boot/c-G56GYQFZ.mjs +2507 -0
  93. package/dist-boot/c-GLIOERDQ.mjs +1200 -0
  94. package/dist-boot/c-GMJ5HUBM.mjs +14 -0
  95. package/dist-boot/c-H3HSGMAQ.mjs +461 -0
  96. package/dist-boot/c-HIKTO6P7.mjs +275 -0
  97. package/dist-boot/c-I2MCJ34O.mjs +464 -0
  98. package/dist-boot/c-I3C6LBW4.mjs +765 -0
  99. package/dist-boot/c-I54OKQHW.mjs +387 -0
  100. package/dist-boot/c-IFSP3R4D.mjs +80 -0
  101. package/dist-boot/c-IZK77VB7.mjs +171 -0
  102. package/dist-boot/c-J3Y25UGE.mjs +54 -0
  103. package/dist-boot/c-J5IESS7W.mjs +27750 -0
  104. package/dist-boot/c-JJWZBY7L.mjs +254 -0
  105. package/dist-boot/c-JKTFXTGF.mjs +463 -0
  106. package/dist-boot/c-JN57AXQ4.mjs +77 -0
  107. package/dist-boot/c-KFIO6LUW.mjs +1096 -0
  108. package/dist-boot/c-KIEMEFWW.mjs +478 -0
  109. package/dist-boot/c-KIVXWBYD.mjs +28 -0
  110. package/dist-boot/c-KP6CRIP4.mjs +580 -0
  111. package/dist-boot/c-L26VOJX4.mjs +11558 -0
  112. package/dist-boot/c-L5GHWG5G.mjs +5988 -0
  113. package/dist-boot/c-M7NSQAKK.mjs +353 -0
  114. package/dist-boot/c-MCEWOPBW.mjs +56 -0
  115. package/dist-boot/c-MGPIEG7I.mjs +20 -0
  116. package/dist-boot/c-NREXJV3M.mjs +393 -0
  117. package/dist-boot/c-O5PP6CTX.mjs +162 -0
  118. package/dist-boot/c-OBQDHSXM.mjs +1774 -0
  119. package/dist-boot/c-OLQHHDD4.mjs +21 -0
  120. package/dist-boot/c-OXW4JQQH.mjs +319 -0
  121. package/dist-boot/c-P3D7ZUWN.mjs +1288 -0
  122. package/dist-boot/c-P4PQZVV5.mjs +948 -0
  123. package/dist-boot/c-P63T3XL2.mjs +26373 -0
  124. package/dist-boot/c-P6N5DQGZ.mjs +194 -0
  125. package/dist-boot/c-P7MLKQFC.mjs +58 -0
  126. package/dist-boot/c-PB3PZJL5.mjs +1276 -0
  127. package/dist-boot/c-PTN4S6G2.mjs +1259 -0
  128. package/dist-boot/c-PYCE5J7U.mjs +1083 -0
  129. package/dist-boot/c-Q4HYCRLB.mjs +19410 -0
  130. package/dist-boot/c-QUXMETGG.mjs +68 -0
  131. package/dist-boot/c-RDMJZCOX.mjs +356 -0
  132. package/dist-boot/c-ROGJK76M.mjs +17 -0
  133. package/dist-boot/c-RQJJ26T4.mjs +708 -0
  134. package/dist-boot/c-RSKCUPJF.mjs +7559 -0
  135. package/dist-boot/c-RVJU4O6P.mjs +37 -0
  136. package/dist-boot/c-S2RVHR3M.mjs +165 -0
  137. package/dist-boot/c-SKMK3PEE.mjs +91120 -0
  138. package/dist-boot/c-TI7SM4EG.mjs +20 -0
  139. package/dist-boot/c-TILJ6GXD.mjs +1235 -0
  140. package/dist-boot/c-TT6BCUJD.mjs +114 -0
  141. package/dist-boot/c-U4ITOXAN.mjs +2107 -0
  142. package/dist-boot/c-UGERXVO2.mjs +7120 -0
  143. package/dist-boot/c-UPBH5AXY.mjs +1363 -0
  144. package/dist-boot/c-US2PUNZL.mjs +597 -0
  145. package/dist-boot/c-UU4WZPPE.mjs +20 -0
  146. package/dist-boot/c-UWVIYPQS.mjs +39 -0
  147. package/dist-boot/c-V4RHQBPQ.mjs +17683 -0
  148. package/dist-boot/c-V5MRVK47.mjs +351 -0
  149. package/dist-boot/c-V6CL266R.mjs +1755 -0
  150. package/dist-boot/c-VJTMFKYE.mjs +14975 -0
  151. package/dist-boot/c-VJTRUKIB.mjs +773 -0
  152. package/dist-boot/c-W4IFSHPW.mjs +43 -0
  153. package/dist-boot/c-WETGB2CF.mjs +113 -0
  154. package/dist-boot/c-WO3QSZUU.mjs +1337 -0
  155. package/dist-boot/c-WQLH73TY.mjs +242 -0
  156. package/dist-boot/c-XL735JW5.mjs +500 -0
  157. package/dist-boot/c-Y7HADL5B.mjs +1107 -0
  158. package/dist-boot/c-YGQHSVSK.mjs +41 -0
  159. package/dist-boot/c-YMP2AMEB.mjs +10350 -0
  160. package/dist-boot/c-YRDO2WEF.mjs +12012 -0
  161. package/dist-boot/c-YUSTRATJ.mjs +8 -0
  162. package/dist-boot/c-Z2262R22.mjs +2697 -0
  163. package/dist-boot/c-Z4ALQMJC.mjs +709 -0
  164. package/dist-boot/c-Z5ZUQVUY.mjs +62 -0
  165. package/dist-boot/c-ZDZUKXF7.mjs +874 -0
  166. package/dist-boot/c-ZJYLGIC3.mjs +32 -0
  167. package/dist-boot/c-ZNA5CDMI.mjs +77 -0
  168. package/dist-boot/c-ZSO6DI3M.mjs +204 -0
  169. package/dist-boot/c-ZWUVHKMK.mjs +100 -0
  170. package/dist-boot/c-ZY4MESEW.mjs +832 -0
  171. package/dist-boot/c-ZZ5REI4L.mjs +329 -0
  172. package/dist-boot/cli.mjs +51 -0
  173. package/dist-boot/ext-anthropic-attribution.mjs +207 -0
  174. package/dist-boot/ext-pi-background-tasks.mjs +7234 -0
  175. package/dist-boot/ext-pi-subagents.mjs +37 -0
  176. package/dist-boot/ext-privateer-account.mjs +4426 -0
  177. package/dist-boot/ext-privateer-brand.mjs +5274 -0
  178. package/dist-boot/ext-privateer-codemode.mjs +37 -0
  179. package/dist-boot/ext-privateer-computer.mjs +626 -0
  180. package/dist-boot/ext-privateer-connect.mjs +1862 -0
  181. package/dist-boot/ext-privateer-context.mjs +323 -0
  182. package/dist-boot/ext-privateer-desktop.mjs +92 -0
  183. package/dist-boot/ext-privateer-final-audit.mjs +48 -0
  184. package/dist-boot/ext-privateer-fresh.mjs +81 -0
  185. package/dist-boot/ext-privateer-gate.mjs +5959 -0
  186. package/dist-boot/ext-privateer-hints.mjs +236 -0
  187. package/dist-boot/ext-privateer-media.mjs +2626 -0
  188. package/dist-boot/ext-privateer-models.mjs +3397 -0
  189. package/dist-boot/ext-privateer-posture.mjs +3006 -0
  190. package/dist-boot/ext-privateer-privacy.mjs +4578 -0
  191. package/dist-boot/ext-privateer-recovery.mjs +287 -0
  192. package/dist-boot/ext-privateer-speak.mjs +4754 -0
  193. package/dist-boot/ext-privateer-terminals.mjs +725 -0
  194. package/dist-boot/ext-privateer-tools.mjs +528 -0
  195. package/dist-boot/ext-privateer-truncation.mjs +74 -0
  196. package/dist-boot/ext-privateer-update.mjs +210 -0
  197. package/dist-boot/ext-privateer-vision.mjs +148 -0
  198. package/dist-boot/ext-privateer-web.mjs +543 -0
  199. package/dist-boot/ext-rpiv-ask-user-question.mjs +710 -0
  200. package/dist-boot/manifest.json +9 -0
  201. package/extensions/privateer-brand.ts +3 -1
  202. package/extensions/privateer-context.ts +4 -2
  203. package/extensions/privateer-final-audit.ts +17 -0
  204. package/extensions/privateer-gate.ts +41 -8
  205. package/extensions/privateer-web.ts +4 -4
  206. package/package.json +3 -1
  207. package/patches/@earendil-works+pi-coding-agent+1.3.0.patch +110 -2
  208. package/patches/pi-background-tasks+2.6.10.patch +91 -7
  209. package/src/config/moatManifest.json +1 -0
  210. package/src/config/whatsNew.json +2 -2
  211. package/src/context.ts +33 -5
  212. package/src/engine/finalAudit.ts +38 -0
  213. package/src/engine/stallWatchdog.ts +8 -1
  214. package/src/providers/account.ts +34 -3
@@ -0,0 +1,1774 @@
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
+ FileAuthStorageBackend,
4
+ JSON_RPC_ERROR_CODES,
5
+ LATEST_PROTOCOL_VERSION,
6
+ McpAuthRequiredError,
7
+ McpClient,
8
+ McpError,
9
+ McpHttpError,
10
+ McpSessionExpiredError,
11
+ StdioTransport,
12
+ StreamableHttpTransport,
13
+ isObject,
14
+ mcpNamespace,
15
+ require_proper_lockfile,
16
+ resolveConfigValueOrThrow,
17
+ resolveHeadersOrThrow
18
+ } from "./c-E4Z3Y5B5.mjs";
19
+ import {
20
+ APP_NAME,
21
+ VERSION,
22
+ getAgentDir
23
+ } from "./c-PTN4S6G2.mjs";
24
+ import {
25
+ __name,
26
+ __toESM
27
+ } from "./c-CN77DCGF.mjs";
28
+
29
+ // node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/runtime.js
30
+ import { homedir } from "node:os";
31
+ import { basename, join as join2, resolve } from "node:path";
32
+ import { setTimeout as sleep } from "node:timers/promises";
33
+ import { pathToFileURL } from "node:url";
34
+
35
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/callback.js
36
+ import { createServer } from "node:http";
37
+ function plainText(page) {
38
+ if (page.ok)
39
+ return "Authorization complete. You may close this window.";
40
+ return page.details ? `${page.message}
41
+
42
+ ${page.details}` : page.message;
43
+ }
44
+ __name(plainText, "plainText");
45
+ var OAuthCallbackServer = class _OAuthCallbackServer {
46
+ static {
47
+ __name(this, "OAuthCallbackServer");
48
+ }
49
+ redirectUrl;
50
+ server;
51
+ paths;
52
+ timeoutMs;
53
+ renderPage;
54
+ pending = /* @__PURE__ */ new Map();
55
+ constructor(server, redirectUrl, paths, timeoutMs, renderPage2) {
56
+ this.server = server;
57
+ this.redirectUrl = redirectUrl;
58
+ this.paths = paths;
59
+ this.timeoutMs = timeoutMs;
60
+ this.renderPage = renderPage2;
61
+ }
62
+ static async listen(options = {}) {
63
+ const host = options.host ?? "127.0.0.1";
64
+ const redirectHost = options.redirectHost ?? host;
65
+ const path = options.path ?? "/callback";
66
+ let instance;
67
+ const server = createServer((request, response) => instance?.handle(request.url ?? "/", response));
68
+ await new Promise((resolve2, reject) => {
69
+ server.once("error", reject);
70
+ server.listen(options.port ?? 0, host, () => {
71
+ server.off("error", reject);
72
+ resolve2();
73
+ });
74
+ });
75
+ const address = server.address();
76
+ if (!address || typeof address === "string")
77
+ throw new Error("OAuth callback server did not bind to TCP");
78
+ instance = new _OAuthCallbackServer(server, `http://${redirectHost.includes(":") ? `[${redirectHost}]` : redirectHost}:${address.port}${path}`, [path, ...options.extraPaths ?? []], options.timeoutMs ?? 5 * 6e4, options.renderPage);
79
+ return instance;
80
+ }
81
+ /**
82
+ * Wait for the authorization response with `state`. With `path`, a response on another path fails, so
83
+ * a server-specific redirect URI can tell authorization servers apart (RFC 9700 section 4.4.2.2).
84
+ */
85
+ waitForCallback(state, path) {
86
+ if (this.pending.has(state))
87
+ throw new Error("OAuth state is already pending");
88
+ return new Promise((resolve2, reject) => {
89
+ const timer = setTimeout(() => {
90
+ this.pending.delete(state);
91
+ reject(new Error("OAuth callback timed out"));
92
+ }, this.timeoutMs);
93
+ this.pending.set(state, { resolve: resolve2, reject, timer, path });
94
+ });
95
+ }
96
+ async close() {
97
+ for (const pending of this.pending.values()) {
98
+ clearTimeout(pending.timer);
99
+ pending.reject(new Error("OAuth callback server closed"));
100
+ }
101
+ this.pending.clear();
102
+ await new Promise((resolve2, reject) => {
103
+ this.server.close((error) => error ? reject(error) : resolve2());
104
+ });
105
+ }
106
+ reply(response, status, page) {
107
+ if (this.renderPage) {
108
+ response.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
109
+ response.end(this.renderPage(page));
110
+ } else {
111
+ response.writeHead(status, { "content-type": "text/plain; charset=utf-8" }).end(plainText(page));
112
+ }
113
+ }
114
+ handle(rawUrl, response) {
115
+ const url = new URL(rawUrl, this.redirectUrl);
116
+ if (!this.paths.includes(url.pathname)) {
117
+ this.reply(response, 404, { ok: false, message: "Not found" });
118
+ return;
119
+ }
120
+ const state = url.searchParams.get("state");
121
+ const pending = state ? this.pending.get(state) : void 0;
122
+ if (!state || !pending) {
123
+ this.reply(response, 400, { ok: false, message: "Invalid or expired OAuth state" });
124
+ return;
125
+ }
126
+ clearTimeout(pending.timer);
127
+ this.pending.delete(state);
128
+ if (pending.path !== void 0 && url.pathname !== pending.path) {
129
+ pending.reject(new Error("The authorization response arrived on another redirect URI"));
130
+ this.reply(response, 400, { ok: false, message: "Unexpected redirect URI" });
131
+ return;
132
+ }
133
+ const error = url.searchParams.get("error");
134
+ if (error) {
135
+ const description = url.searchParams.get("error_description") ?? error;
136
+ pending.reject(new Error(description));
137
+ this.reply(response, 200, {
138
+ ok: false,
139
+ message: "Authorization failed. You may close this window.",
140
+ details: description
141
+ });
142
+ return;
143
+ }
144
+ const code = url.searchParams.get("code");
145
+ if (!code) {
146
+ pending.reject(new Error("OAuth callback did not include an authorization code"));
147
+ this.reply(response, 400, { ok: false, message: "Missing authorization code" });
148
+ return;
149
+ }
150
+ const iss = url.searchParams.get("iss");
151
+ pending.resolve({ code, state, ...iss ? { iss } : {} });
152
+ this.reply(response, 200, { ok: true });
153
+ }
154
+ };
155
+
156
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/errors.js
157
+ var OAuthError = class extends Error {
158
+ static {
159
+ __name(this, "OAuthError");
160
+ }
161
+ code;
162
+ errorUri;
163
+ constructor(code, message, errorUri) {
164
+ super(message || code);
165
+ this.name = "OAuthError";
166
+ this.code = code;
167
+ this.errorUri = errorUri;
168
+ }
169
+ };
170
+ var OAuthIssuerMismatchError = class extends Error {
171
+ static {
172
+ __name(this, "OAuthIssuerMismatchError");
173
+ }
174
+ /** `undefined` when no authorization server metadata was discovered. */
175
+ expected;
176
+ /** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */
177
+ received;
178
+ constructor(expected, received) {
179
+ const format = /* @__PURE__ */ __name((issuer) => issuer === void 0 ? "none" : JSON.stringify(issuer), "format");
180
+ super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`);
181
+ this.name = "OAuthIssuerMismatchError";
182
+ this.expected = expected;
183
+ this.received = received;
184
+ }
185
+ };
186
+ var OAuthInsecureEndpointError = class extends Error {
187
+ static {
188
+ __name(this, "OAuthInsecureEndpointError");
189
+ }
190
+ endpoint;
191
+ constructor(endpoint) {
192
+ super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`);
193
+ this.name = "OAuthInsecureEndpointError";
194
+ this.endpoint = endpoint;
195
+ }
196
+ };
197
+ var OAuthRegistrationError = class extends Error {
198
+ static {
199
+ __name(this, "OAuthRegistrationError");
200
+ }
201
+ status;
202
+ body;
203
+ constructor(status, body) {
204
+ super(`OAuth dynamic client registration failed with status ${status}: ${body}`);
205
+ this.name = "OAuthRegistrationError";
206
+ this.status = status;
207
+ this.body = body;
208
+ }
209
+ };
210
+ var McpOAuthAuthorizationRequiredError = class extends Error {
211
+ static {
212
+ __name(this, "McpOAuthAuthorizationRequiredError");
213
+ }
214
+ constructor() {
215
+ super("MCP OAuth authorization requires user interaction");
216
+ this.name = "McpOAuthAuthorizationRequiredError";
217
+ }
218
+ };
219
+
220
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/types.js
221
+ function object(value, name) {
222
+ if (!isObject(value))
223
+ throw new Error(`Invalid ${name}`);
224
+ return value;
225
+ }
226
+ __name(object, "object");
227
+ function compact(value) {
228
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
229
+ }
230
+ __name(compact, "compact");
231
+ function requiredString(value, name) {
232
+ if (typeof value !== "string" || value.length === 0)
233
+ throw new Error(`Invalid ${name}`);
234
+ return value;
235
+ }
236
+ __name(requiredString, "requiredString");
237
+ function absent(value) {
238
+ return value === void 0 || value === null || value === "";
239
+ }
240
+ __name(absent, "absent");
241
+ function optionalString(value, name) {
242
+ if (absent(value))
243
+ return void 0;
244
+ return requiredString(value, name);
245
+ }
246
+ __name(optionalString, "optionalString");
247
+ function optionalStrings(value, name) {
248
+ if (value === void 0 || value === null)
249
+ return void 0;
250
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
251
+ throw new Error(`Invalid ${name}`);
252
+ return [...value];
253
+ }
254
+ __name(optionalStrings, "optionalStrings");
255
+ function safeUrl(value, name) {
256
+ const text = requiredString(value, name);
257
+ if (!URL.canParse(text))
258
+ throw new Error(`Invalid ${name}`);
259
+ const url = new URL(text);
260
+ if (["javascript:", "data:", "vbscript:"].includes(url.protocol))
261
+ throw new Error(`Invalid ${name}`);
262
+ return text;
263
+ }
264
+ __name(safeUrl, "safeUrl");
265
+ function optionalUrl(value, name) {
266
+ return absent(value) ? void 0 : safeUrl(value, name);
267
+ }
268
+ __name(optionalUrl, "optionalUrl");
269
+ function parseProtectedResourceMetadata(value) {
270
+ const input = object(value, "OAuth protected resource metadata");
271
+ return compact({
272
+ ...input,
273
+ resource: safeUrl(input.resource, "OAuth protected resource metadata resource"),
274
+ authorization_servers: optionalStrings(input.authorization_servers, "authorization_servers")?.map((url) => safeUrl(url, "authorization server URL")),
275
+ scopes_supported: optionalStrings(input.scopes_supported, "scopes_supported")
276
+ });
277
+ }
278
+ __name(parseProtectedResourceMetadata, "parseProtectedResourceMetadata");
279
+ function parseAuthorizationServerMetadata(value) {
280
+ const input = object(value, "authorization server metadata");
281
+ const responseTypes = optionalStrings(input.response_types_supported, "response_types_supported");
282
+ if (!responseTypes)
283
+ throw new Error("Invalid response_types_supported");
284
+ return compact({
285
+ ...input,
286
+ issuer: safeUrl(input.issuer, "authorization server issuer"),
287
+ authorization_endpoint: safeUrl(input.authorization_endpoint, "authorization endpoint"),
288
+ token_endpoint: safeUrl(input.token_endpoint, "token endpoint"),
289
+ registration_endpoint: optionalUrl(input.registration_endpoint, "registration endpoint"),
290
+ scopes_supported: optionalStrings(input.scopes_supported, "scopes_supported"),
291
+ response_types_supported: responseTypes,
292
+ grant_types_supported: optionalStrings(input.grant_types_supported, "grant_types_supported"),
293
+ token_endpoint_auth_methods_supported: optionalStrings(input.token_endpoint_auth_methods_supported, "token_endpoint_auth_methods_supported"),
294
+ code_challenge_methods_supported: optionalStrings(input.code_challenge_methods_supported, "code_challenge_methods_supported"),
295
+ client_id_metadata_document_supported: typeof input.client_id_metadata_document_supported === "boolean" ? input.client_id_metadata_document_supported : void 0,
296
+ authorization_response_iss_parameter_supported: typeof input.authorization_response_iss_parameter_supported === "boolean" ? input.authorization_response_iss_parameter_supported : void 0
297
+ });
298
+ }
299
+ __name(parseAuthorizationServerMetadata, "parseAuthorizationServerMetadata");
300
+ function parseOAuthTokens(value) {
301
+ const input = object(value, "OAuth token response");
302
+ const expires = absent(input.expires_in) ? void 0 : Number(input.expires_in);
303
+ if (expires !== void 0 && !Number.isFinite(expires))
304
+ throw new Error("Invalid expires_in");
305
+ return compact({
306
+ access_token: requiredString(input.access_token, "access_token"),
307
+ token_type: requiredString(input.token_type, "token_type"),
308
+ expires_in: expires,
309
+ scope: optionalString(input.scope, "scope"),
310
+ refresh_token: optionalString(input.refresh_token, "refresh_token"),
311
+ id_token: optionalString(input.id_token, "id_token")
312
+ });
313
+ }
314
+ __name(parseOAuthTokens, "parseOAuthTokens");
315
+ function parseClientInformation(value) {
316
+ const input = object(value, "OAuth client registration response");
317
+ return compact({
318
+ ...input,
319
+ client_id: requiredString(input.client_id, "client_id"),
320
+ client_secret: optionalString(input.client_secret, "client_secret"),
321
+ client_id_issued_at: typeof input.client_id_issued_at === "number" ? input.client_id_issued_at : void 0,
322
+ client_secret_expires_at: typeof input.client_secret_expires_at === "number" ? input.client_secret_expires_at : void 0,
323
+ redirect_uris: optionalStrings(input.redirect_uris, "redirect_uris") ?? []
324
+ });
325
+ }
326
+ __name(parseClientInformation, "parseClientInformation");
327
+
328
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/discovery.js
329
+ function discard(response) {
330
+ void response?.body?.cancel().catch(() => {
331
+ });
332
+ }
333
+ __name(discard, "discard");
334
+ function isDiscoveryMiss(status) {
335
+ return status >= 400 && status < 500 || status === 502;
336
+ }
337
+ __name(isDiscoveryMiss, "isDiscoveryMiss");
338
+ function pathSuffix(pathname) {
339
+ return pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
340
+ }
341
+ __name(pathSuffix, "pathSuffix");
342
+ function field(header, name) {
343
+ const match = header.match(new RegExp(String.raw`(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`, "i"));
344
+ return match?.[1] || match?.[2] || void 0;
345
+ }
346
+ __name(field, "field");
347
+ function parseWwwAuthenticate(header) {
348
+ if (!header)
349
+ return {};
350
+ const scheme = header.trimStart().split(/\s+/, 1)[0]?.toLowerCase();
351
+ if (scheme !== "bearer" && scheme !== "dpop")
352
+ return {};
353
+ const resourceMetadata = field(header, "resource_metadata");
354
+ let resourceMetadataUrl;
355
+ if (resourceMetadata) {
356
+ try {
357
+ resourceMetadataUrl = new URL(resourceMetadata);
358
+ } catch {
359
+ }
360
+ }
361
+ return {
362
+ resourceMetadataUrl,
363
+ scope: field(header, "scope"),
364
+ error: field(header, "error"),
365
+ errorDescription: field(header, "error_description")
366
+ };
367
+ }
368
+ __name(parseWwwAuthenticate, "parseWwwAuthenticate");
369
+ async function fetchMetadata(url, fetch, protocolVersion, signal) {
370
+ return fetch(url, {
371
+ headers: { Accept: "application/json", "MCP-Protocol-Version": protocolVersion },
372
+ signal
373
+ });
374
+ }
375
+ __name(fetchMetadata, "fetchMetadata");
376
+ async function discoverProtectedResourceMetadata(serverUrl, options = {}) {
377
+ const server = new URL(serverUrl);
378
+ const fetch = options.fetch ?? globalThis.fetch;
379
+ const version = options.protocolVersion ?? LATEST_PROTOCOL_VERSION;
380
+ let response = await fetchMetadata(options.resourceMetadataUrl ? new URL(options.resourceMetadataUrl) : new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`, server.origin), fetch, version, options.signal);
381
+ if (!options.resourceMetadataUrl && server.pathname !== "/" && isDiscoveryMiss(response.status)) {
382
+ discard(response);
383
+ response = await fetchMetadata(new URL("/.well-known/oauth-protected-resource", server.origin), fetch, version, options.signal);
384
+ }
385
+ if (!response.ok) {
386
+ discard(response);
387
+ throw new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);
388
+ }
389
+ return parseProtectedResourceMetadata(await response.json());
390
+ }
391
+ __name(discoverProtectedResourceMetadata, "discoverProtectedResourceMetadata");
392
+ function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl) {
393
+ const issuer = new URL(authorizationServerUrl);
394
+ const path = pathSuffix(issuer.pathname);
395
+ const urls = [
396
+ { url: new URL(`/.well-known/oauth-authorization-server${path}`, issuer.origin), type: "oauth" },
397
+ { url: new URL(`/.well-known/openid-configuration${path}`, issuer.origin), type: "oidc" }
398
+ ];
399
+ if (path)
400
+ urls.push({ url: new URL(`${path}/.well-known/openid-configuration`, issuer.origin), type: "oidc" });
401
+ return urls;
402
+ }
403
+ __name(buildAuthorizationServerDiscoveryUrls, "buildAuthorizationServerDiscoveryUrls");
404
+ async function discoverAuthorizationServerMetadata(authorizationServerUrl, options = {}) {
405
+ const fetch = options.fetch ?? globalThis.fetch;
406
+ for (const { url } of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)) {
407
+ const response = await fetchMetadata(url, fetch, options.protocolVersion ?? LATEST_PROTOCOL_VERSION, options.signal);
408
+ if (!response.ok) {
409
+ discard(response);
410
+ if (isDiscoveryMiss(response.status))
411
+ continue;
412
+ throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);
413
+ }
414
+ const metadata = parseAuthorizationServerMetadata(await response.json());
415
+ if (!options.skipIssuerValidation) {
416
+ const expected = String(authorizationServerUrl);
417
+ const trim = /* @__PURE__ */ __name((value) => value.endsWith("/") ? value.slice(0, -1) : value, "trim");
418
+ if (trim(metadata.issuer) !== trim(expected))
419
+ throw new OAuthIssuerMismatchError(expected, metadata.issuer);
420
+ }
421
+ return metadata;
422
+ }
423
+ return void 0;
424
+ }
425
+ __name(discoverAuthorizationServerMetadata, "discoverAuthorizationServerMetadata");
426
+ async function discoverOAuthServerInfo(serverUrl, options = {}) {
427
+ let resourceMetadata;
428
+ try {
429
+ resourceMetadata = await discoverProtectedResourceMetadata(serverUrl, {
430
+ resourceMetadataUrl: options.resourceMetadataUrl,
431
+ fetch: options.fetch,
432
+ signal: options.signal
433
+ });
434
+ } catch (error) {
435
+ if (error instanceof TypeError)
436
+ throw error;
437
+ }
438
+ if (options.authorizationServerMetadataUrl) {
439
+ const url = options.authorizationServerMetadataUrl;
440
+ const response = await fetchMetadata(url, options.fetch ?? globalThis.fetch, LATEST_PROTOCOL_VERSION, options.signal);
441
+ if (!response.ok) {
442
+ discard(response);
443
+ throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);
444
+ }
445
+ const metadata = parseAuthorizationServerMetadata(await response.json());
446
+ return { authorizationServerUrl: metadata.issuer, authorizationServerMetadata: metadata, resourceMetadata };
447
+ }
448
+ const authorizationServerUrl = resourceMetadata?.authorization_servers?.[0] ?? String(new URL("/", serverUrl));
449
+ return {
450
+ authorizationServerUrl,
451
+ authorizationServerMetadata: await discoverAuthorizationServerMetadata(authorizationServerUrl, {
452
+ fetch: options.fetch,
453
+ skipIssuerValidation: options.skipIssuerValidation,
454
+ signal: options.signal
455
+ }),
456
+ resourceMetadata
457
+ };
458
+ }
459
+ __name(discoverOAuthServerInfo, "discoverOAuthServerInfo");
460
+ function resourceUrlFromServerUrl(value) {
461
+ const url = new URL(value);
462
+ url.hash = "";
463
+ return url;
464
+ }
465
+ __name(resourceUrlFromServerUrl, "resourceUrlFromServerUrl");
466
+ function selectResource(serverUrl, metadata) {
467
+ if (!metadata)
468
+ return void 0;
469
+ const requested = resourceUrlFromServerUrl(serverUrl);
470
+ const configured = new URL(metadata.resource);
471
+ if (requested.origin !== configured.origin) {
472
+ throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);
473
+ }
474
+ const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : `${requested.pathname}/`;
475
+ const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : `${configured.pathname}/`;
476
+ if (!requestedPath.startsWith(configuredPath)) {
477
+ throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);
478
+ }
479
+ return metadata.resource;
480
+ }
481
+ __name(selectResource, "selectResource");
482
+
483
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/flow.js
484
+ function loopback(hostname) {
485
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
486
+ }
487
+ __name(loopback, "loopback");
488
+ function applicationType(redirectUris) {
489
+ const native = redirectUris.some((uri) => {
490
+ if (!URL.canParse(uri))
491
+ return false;
492
+ const url = new URL(uri);
493
+ return url.protocol !== "http:" && url.protocol !== "https:" || loopback(url.hostname);
494
+ });
495
+ return native ? "native" : "web";
496
+ }
497
+ __name(applicationType, "applicationType");
498
+ function secureEndpoint(value) {
499
+ const url = new URL(value);
500
+ if (url.protocol !== "https:" && !loopback(url.hostname))
501
+ throw new OAuthInsecureEndpointError(url.href);
502
+ return url;
503
+ }
504
+ __name(secureEndpoint, "secureEndpoint");
505
+ function selectClientAuthMethod(information, supported) {
506
+ const hinted = "token_endpoint_auth_method" in information ? information.token_endpoint_auth_method : void 0;
507
+ if (hinted && ["client_secret_basic", "client_secret_post", "none"].includes(hinted) && (supported.length === 0 || supported.includes(hinted))) {
508
+ return hinted;
509
+ }
510
+ if (supported.length === 0)
511
+ return information.client_secret ? "client_secret_basic" : "none";
512
+ if (information.client_secret && supported.includes("client_secret_basic"))
513
+ return "client_secret_basic";
514
+ if (information.client_secret && supported.includes("client_secret_post"))
515
+ return "client_secret_post";
516
+ if (supported.includes("none"))
517
+ return "none";
518
+ return information.client_secret ? "client_secret_post" : "none";
519
+ }
520
+ __name(selectClientAuthMethod, "selectClientAuthMethod");
521
+ function applyClientAuthentication(method, information, headers, params) {
522
+ if (method === "client_secret_basic") {
523
+ if (!information.client_secret)
524
+ throw new Error("client_secret_basic requires a client secret");
525
+ headers.set("Authorization", `Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`);
526
+ } else {
527
+ params.set("client_id", information.client_id);
528
+ if (method === "client_secret_post" && information.client_secret)
529
+ params.set("client_secret", information.client_secret);
530
+ }
531
+ }
532
+ __name(applyClientAuthentication, "applyClientAuthentication");
533
+ async function pkce() {
534
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
535
+ const verifier = Buffer.from(bytes).toString("base64url");
536
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
537
+ return { verifier, challenge: Buffer.from(digest).toString("base64url") };
538
+ }
539
+ __name(pkce, "pkce");
540
+ async function startAuthorization(authorizationServerUrl, options) {
541
+ const metadata = options.metadata;
542
+ if (metadata && !metadata.response_types_supported.includes("code")) {
543
+ throw new Error("Authorization server does not support authorization codes");
544
+ }
545
+ if (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes("S256")) {
546
+ throw new Error("Authorization server does not support PKCE S256");
547
+ }
548
+ const url = new URL(metadata?.authorization_endpoint ?? new URL("/authorize", authorizationServerUrl));
549
+ const { verifier, challenge } = await pkce();
550
+ url.searchParams.set("response_type", "code");
551
+ url.searchParams.set("client_id", options.clientInformation.client_id);
552
+ url.searchParams.set("code_challenge", challenge);
553
+ url.searchParams.set("code_challenge_method", "S256");
554
+ url.searchParams.set("redirect_uri", String(options.redirectUrl));
555
+ if (options.state)
556
+ url.searchParams.set("state", options.state);
557
+ if (options.scope)
558
+ url.searchParams.set("scope", options.scope);
559
+ if (options.scope?.split(/\s+/).includes("offline_access"))
560
+ url.searchParams.set("prompt", "consent");
561
+ if (options.resource)
562
+ url.searchParams.set("resource", options.resource);
563
+ return { authorizationUrl: url, codeVerifier: verifier };
564
+ }
565
+ __name(startAuthorization, "startAuthorization");
566
+ async function tokenRequest(authorizationServerUrl, options, params) {
567
+ const url = secureEndpoint(options.metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl));
568
+ const headers = new Headers({ Accept: "application/json", "content-type": "application/x-www-form-urlencoded" });
569
+ if (options.resource)
570
+ params.set("resource", options.resource);
571
+ if (options.addClientAuthentication) {
572
+ await options.addClientAuthentication(headers, params, url, options.metadata);
573
+ } else {
574
+ applyClientAuthentication(selectClientAuthMethod(options.clientInformation, options.metadata?.token_endpoint_auth_methods_supported ?? []), options.clientInformation, headers, params);
575
+ }
576
+ const response = await (options.fetch ?? globalThis.fetch)(url, {
577
+ method: "POST",
578
+ headers,
579
+ body: params,
580
+ signal: options.signal
581
+ });
582
+ const text = await response.text();
583
+ let value;
584
+ try {
585
+ value = JSON.parse(text);
586
+ } catch {
587
+ }
588
+ if (isObject(value) && typeof value.error === "string") {
589
+ throw new OAuthError(value.error, typeof value.error_description === "string" ? value.error_description : value.error, typeof value.error_uri === "string" ? value.error_uri : void 0);
590
+ }
591
+ if (!response.ok)
592
+ throw new OAuthError("server_error", `HTTP ${response.status}: ${text}`);
593
+ return parseOAuthTokens(value);
594
+ }
595
+ __name(tokenRequest, "tokenRequest");
596
+ async function registerClient(authorizationServerUrl, options) {
597
+ const endpoint = options.metadata?.registration_endpoint;
598
+ if (options.metadata && !endpoint)
599
+ throw new Error("Authorization server does not support dynamic client registration");
600
+ const response = await (options.fetch ?? globalThis.fetch)(new URL(endpoint ?? new URL("/register", authorizationServerUrl)), {
601
+ method: "POST",
602
+ headers: { Accept: "application/json", "content-type": "application/json" },
603
+ body: JSON.stringify({
604
+ ...options.clientMetadata,
605
+ application_type: options.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),
606
+ ...options.scope ? { scope: options.scope } : {}
607
+ }),
608
+ signal: options.signal
609
+ });
610
+ if (!response.ok)
611
+ throw new OAuthRegistrationError(response.status, await response.text());
612
+ return parseClientInformation(await response.json());
613
+ }
614
+ __name(registerClient, "registerClient");
615
+ async function exchangeAuthorizationCode(authorizationServerUrl, options) {
616
+ return tokenRequest(authorizationServerUrl, options, new URLSearchParams({
617
+ grant_type: "authorization_code",
618
+ code: options.code,
619
+ code_verifier: options.codeVerifier,
620
+ redirect_uri: String(options.redirectUrl)
621
+ }));
622
+ }
623
+ __name(exchangeAuthorizationCode, "exchangeAuthorizationCode");
624
+ async function refreshAuthorization(authorizationServerUrl, options) {
625
+ const tokens = await tokenRequest(authorizationServerUrl, options, new URLSearchParams({ grant_type: "refresh_token", refresh_token: options.refreshToken }));
626
+ return { refresh_token: options.refreshToken, ...tokens };
627
+ }
628
+ __name(refreshAuthorization, "refreshAuthorization");
629
+ function withScope(tokens, scope) {
630
+ return tokens.scope === void 0 && scope ? { ...tokens, scope } : tokens;
631
+ }
632
+ __name(withScope, "withScope");
633
+ function stepUpScope(granted, challenged) {
634
+ if (!challenged)
635
+ return void 0;
636
+ const scopes = [granted, challenged].flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []);
637
+ return [...new Set(scopes)].join(" ");
638
+ }
639
+ __name(stepUpScope, "stepUpScope");
640
+ async function runFlow(provider, options) {
641
+ const metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);
642
+ const cached = metadataUrl ? void 0 : await provider.discoveryState?.();
643
+ const discovered = cached?.authorizationServerUrl ? {
644
+ authorizationServerUrl: cached.authorizationServerUrl,
645
+ authorizationServerMetadata: cached.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {
646
+ fetch: options.fetch,
647
+ skipIssuerValidation: options.skipIssuerValidation,
648
+ signal: options.signal
649
+ }),
650
+ resourceMetadata: cached.resourceMetadata
651
+ } : await discoverOAuthServerInfo(options.serverUrl, {
652
+ resourceMetadataUrl: options.resourceMetadataUrl,
653
+ authorizationServerMetadataUrl: metadataUrl,
654
+ fetch: options.fetch,
655
+ skipIssuerValidation: options.skipIssuerValidation,
656
+ signal: options.signal
657
+ });
658
+ if (!metadataUrl) {
659
+ await provider.saveDiscoveryState?.({
660
+ ...discovered,
661
+ ...options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}
662
+ });
663
+ }
664
+ const metadata = discovered.authorizationServerMetadata;
665
+ const resource = selectResource(options.serverUrl, discovered.resourceMetadata);
666
+ const scope = options.scope || discovered.resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
667
+ const stored = await provider.clientInformation();
668
+ const clientDocument = stored ? void 0 : provider.clientMetadataDocument?.(metadata);
669
+ if (clientDocument) {
670
+ const url = new URL(clientDocument.url);
671
+ if (url.protocol !== "https:" || url.pathname === "/")
672
+ throw new Error("Invalid OAuth client metadata URL");
673
+ }
674
+ let client = stored ?? (clientDocument && { client_id: clientDocument.url });
675
+ if (!client) {
676
+ if (options.authorizationCode)
677
+ throw new Error("OAuth client information is missing during code exchange");
678
+ if (!provider.saveClientInformation)
679
+ throw new Error("OAuth client information cannot be persisted");
680
+ client = await registerClient(discovered.authorizationServerUrl, {
681
+ metadata,
682
+ clientMetadata: provider.clientMetadata,
683
+ scope,
684
+ fetch: options.fetch,
685
+ signal: options.signal
686
+ });
687
+ await provider.saveClientInformation(client);
688
+ }
689
+ const redirectUrl = clientDocument?.redirectUrl ?? provider.redirectUrl;
690
+ const tokenOptions = {
691
+ metadata,
692
+ clientInformation: client,
693
+ resource,
694
+ addClientAuthentication: provider.addClientAuthentication,
695
+ fetch: options.fetch,
696
+ signal: options.signal
697
+ };
698
+ if (options.authorizationCode) {
699
+ const iss = options.iss;
700
+ if (iss !== void 0 || metadata?.authorization_response_iss_parameter_supported) {
701
+ if (iss !== metadata?.issuer)
702
+ throw new OAuthIssuerMismatchError(metadata?.issuer, iss);
703
+ }
704
+ const tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {
705
+ ...tokenOptions,
706
+ code: options.authorizationCode,
707
+ codeVerifier: await provider.codeVerifier(),
708
+ redirectUrl
709
+ });
710
+ await provider.saveTokens(withScope(tokens, scope));
711
+ return "AUTHORIZED";
712
+ }
713
+ const existing = options.skipRefresh ? void 0 : await provider.tokens();
714
+ if (existing?.refresh_token) {
715
+ try {
716
+ const tokens = await refreshAuthorization(discovered.authorizationServerUrl, {
717
+ ...tokenOptions,
718
+ refreshToken: existing.refresh_token
719
+ });
720
+ await provider.saveTokens(withScope(tokens, existing.scope));
721
+ return "AUTHORIZED";
722
+ } catch (error) {
723
+ if (options.signal?.aborted || error instanceof OAuthInsecureEndpointError)
724
+ throw error;
725
+ if (error instanceof OAuthError && error.code !== "server_error")
726
+ throw error;
727
+ }
728
+ }
729
+ const state = await provider.state?.();
730
+ const authorization = await startAuthorization(discovered.authorizationServerUrl, {
731
+ metadata,
732
+ clientInformation: client,
733
+ redirectUrl,
734
+ scope,
735
+ state,
736
+ resource
737
+ });
738
+ await provider.saveCodeVerifier(authorization.codeVerifier);
739
+ await provider.redirectToAuthorization(authorization.authorizationUrl);
740
+ return "REDIRECT";
741
+ }
742
+ __name(runFlow, "runFlow");
743
+ async function authorizeMcp(provider, options) {
744
+ try {
745
+ return await runFlow(provider, options);
746
+ } catch (error) {
747
+ if (error instanceof OAuthError && ["invalid_client", "unauthorized_client"].includes(error.code)) {
748
+ await provider.invalidateCredentials?.("all");
749
+ return runFlow(provider, options);
750
+ }
751
+ if (error instanceof OAuthError && error.code === "invalid_grant") {
752
+ await provider.invalidateCredentials?.("tokens");
753
+ return runFlow(provider, options);
754
+ }
755
+ throw error;
756
+ }
757
+ }
758
+ __name(authorizeMcp, "authorizeMcp");
759
+
760
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/provider.js
761
+ var MemoryOAuthStateStore = class {
762
+ static {
763
+ __name(this, "MemoryOAuthStateStore");
764
+ }
765
+ value;
766
+ load() {
767
+ return this.value === void 0 ? void 0 : structuredClone(this.value);
768
+ }
769
+ save(state) {
770
+ this.value = structuredClone(state);
771
+ }
772
+ };
773
+ var McpOAuthProvider = class {
774
+ static {
775
+ __name(this, "McpOAuthProvider");
776
+ }
777
+ redirectUrl;
778
+ clientMetadata;
779
+ clientMetadataDocument;
780
+ serverUrl;
781
+ configuredClient;
782
+ store;
783
+ onRedirect;
784
+ writes = Promise.resolve();
785
+ constructor(options) {
786
+ this.serverUrl = String(new URL(options.serverUrl));
787
+ this.redirectUrl = String(options.redirectUrl);
788
+ this.clientMetadata = {
789
+ ...options.clientMetadata,
790
+ redirect_uris: options.clientMetadata.redirect_uris ?? [this.redirectUrl],
791
+ grant_types: options.clientMetadata.grant_types ?? ["authorization_code", "refresh_token"],
792
+ response_types: options.clientMetadata.response_types ?? ["code"],
793
+ token_endpoint_auth_method: options.clientMetadata.token_endpoint_auth_method ?? (options.clientSecret ? "client_secret_post" : "none")
794
+ };
795
+ this.clientMetadataDocument = options.clientMetadataDocument;
796
+ this.configuredClient = options.clientId ? { client_id: options.clientId, ...options.clientSecret ? { client_secret: options.clientSecret } : {} } : void 0;
797
+ this.store = options.store ?? new MemoryOAuthStateStore();
798
+ this.onRedirect = options.onRedirect;
799
+ }
800
+ async state() {
801
+ const existing = (await this.load()).oauthState;
802
+ if (existing)
803
+ return existing;
804
+ const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");
805
+ await this.update((value) => ({ ...value, oauthState: state }));
806
+ return state;
807
+ }
808
+ async clientInformation() {
809
+ return this.configuredClient ?? (await this.load()).clientInformation;
810
+ }
811
+ async saveClientInformation(information) {
812
+ if (this.configuredClient)
813
+ return;
814
+ await this.update((value) => ({ ...value, clientInformation: information }));
815
+ }
816
+ async tokens() {
817
+ return (await this.load()).tokens;
818
+ }
819
+ async saveTokens(tokens) {
820
+ const expiresAt = tokens.expires_in === void 0 ? void 0 : Date.now() + tokens.expires_in * 1e3;
821
+ await this.update((value) => {
822
+ const next = { ...value, tokens };
823
+ if (expiresAt === void 0)
824
+ delete next.tokensExpireAt;
825
+ else
826
+ next.tokensExpireAt = expiresAt;
827
+ return next;
828
+ });
829
+ }
830
+ async redirectToAuthorization(url) {
831
+ await this.onRedirect(url);
832
+ }
833
+ async saveCodeVerifier(verifier) {
834
+ await this.update((value) => ({ ...value, codeVerifier: verifier }));
835
+ }
836
+ async codeVerifier() {
837
+ const verifier = (await this.load()).codeVerifier;
838
+ if (!verifier)
839
+ throw new Error("No OAuth PKCE code verifier is stored");
840
+ return verifier;
841
+ }
842
+ async invalidateCredentials(kind) {
843
+ await this.update((value) => {
844
+ const next = { ...value };
845
+ if (kind === "all" || kind === "client")
846
+ delete next.clientInformation;
847
+ if (kind === "all" || kind === "tokens") {
848
+ delete next.tokens;
849
+ delete next.tokensExpireAt;
850
+ }
851
+ if (kind === "all" || kind === "verifier")
852
+ delete next.codeVerifier;
853
+ if (kind === "all" || kind === "discovery")
854
+ delete next.discovery;
855
+ if (kind === "all")
856
+ delete next.oauthState;
857
+ return next;
858
+ });
859
+ }
860
+ async saveDiscoveryState(discovery) {
861
+ await this.update((value) => ({ ...value, discovery }));
862
+ }
863
+ async discoveryState() {
864
+ return (await this.load()).discovery;
865
+ }
866
+ async load() {
867
+ await this.writes;
868
+ return this.own(await this.store.load());
869
+ }
870
+ async update(update) {
871
+ this.writes = this.writes.then(async () => {
872
+ await this.store.save(update(this.own(await this.store.load())));
873
+ });
874
+ await this.writes;
875
+ }
876
+ /** Stored state for another server URL is ignored so credentials never leak across servers. */
877
+ own(state) {
878
+ return state?.serverUrl === this.serverUrl ? state : { serverUrl: this.serverUrl };
879
+ }
880
+ };
881
+
882
+ // node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/oauth.js
883
+ import { createHash } from "node:crypto";
884
+ import { mkdirSync } from "node:fs";
885
+ import { join } from "node:path";
886
+
887
+ // node_modules/@earendil-works/pi-ai/dist/utils/oauth-page.js
888
+ var LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>`;
889
+ function escapeHtml(value) {
890
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
891
+ }
892
+ __name(escapeHtml, "escapeHtml");
893
+ function renderPage(options) {
894
+ const title = escapeHtml(options.title);
895
+ const heading = escapeHtml(options.heading);
896
+ const message = escapeHtml(options.message);
897
+ const details = options.details ? escapeHtml(options.details) : void 0;
898
+ return `<!doctype html>
899
+ <html lang="en">
900
+ <head>
901
+ <meta charset="utf-8" />
902
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
903
+ <title>${title}</title>
904
+ <style>
905
+ :root {
906
+ --text: #fafafa;
907
+ --text-dim: #a1a1aa;
908
+ --page-bg: #09090b;
909
+ --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
910
+ --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
911
+ }
912
+ * { box-sizing: border-box; }
913
+ html { color-scheme: dark; }
914
+ body {
915
+ margin: 0;
916
+ min-height: 100vh;
917
+ display: flex;
918
+ align-items: center;
919
+ justify-content: center;
920
+ padding: 24px;
921
+ background: var(--page-bg);
922
+ color: var(--text);
923
+ font-family: var(--font-sans);
924
+ text-align: center;
925
+ }
926
+ main {
927
+ width: 100%;
928
+ max-width: 560px;
929
+ display: flex;
930
+ flex-direction: column;
931
+ align-items: center;
932
+ justify-content: center;
933
+ }
934
+ .logo {
935
+ width: 72px;
936
+ height: 72px;
937
+ display: block;
938
+ margin-bottom: 24px;
939
+ }
940
+ h1 {
941
+ margin: 0 0 10px;
942
+ font-size: 28px;
943
+ line-height: 1.15;
944
+ font-weight: 650;
945
+ color: var(--text);
946
+ }
947
+ p {
948
+ margin: 0;
949
+ line-height: 1.7;
950
+ color: var(--text-dim);
951
+ font-size: 15px;
952
+ }
953
+ .details {
954
+ margin-top: 16px;
955
+ font-family: var(--font-mono);
956
+ font-size: 13px;
957
+ color: var(--text-dim);
958
+ white-space: pre-wrap;
959
+ word-break: break-word;
960
+ }
961
+ </style>
962
+ </head>
963
+ <body>
964
+ <main>
965
+ <div class="logo">${LOGO_SVG}</div>
966
+ <h1>${heading}</h1>
967
+ <p>${message}</p>
968
+ ${details ? `<div class="details">${details}</div>` : ""}
969
+ </main>
970
+ </body>
971
+ </html>`;
972
+ }
973
+ __name(renderPage, "renderPage");
974
+ function oauthSuccessHtml(message) {
975
+ return renderPage({
976
+ title: "Authentication successful",
977
+ heading: "Authentication successful",
978
+ message
979
+ });
980
+ }
981
+ __name(oauthSuccessHtml, "oauthSuccessHtml");
982
+ function oauthErrorHtml(message, details) {
983
+ return renderPage({
984
+ title: "Authentication failed",
985
+ heading: "Authentication failed",
986
+ message,
987
+ details
988
+ });
989
+ }
990
+ __name(oauthErrorHtml, "oauthErrorHtml");
991
+
992
+ // node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/oauth.js
993
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
994
+ var CALLBACK_HOST = "127.0.0.1";
995
+ var CALLBACK_PATH = "/callback";
996
+ var CLIENT_METADATA_BASE_URL = "https://pi.dev/oauth";
997
+ var FALLBACK_REDIRECT_URL = `http://${CALLBACK_HOST}${CALLBACK_PATH}`;
998
+ var REFRESH_SKEW_MS = 3e4;
999
+ var OAUTH_REQUEST_TIMEOUT_MS = 15e3;
1000
+ var REFRESH_LOCK_STALE_MS = 2e4;
1001
+ var REFRESH_LOCK_WAIT_MS = 25e3;
1002
+ var REFRESH_LOCK_RETRY_MS = 100;
1003
+ function callbackSettings(settings) {
1004
+ const url = new URL(settings.callbackUrl ?? `http://${CALLBACK_HOST}${CALLBACK_PATH}`);
1005
+ const address = url.hostname.replace(/^\[|\]$/g, "");
1006
+ const port = url.port ? Number(url.port) : settings.callbackPort;
1007
+ let fixedRedirectUrl;
1008
+ if (url.port)
1009
+ fixedRedirectUrl = settings.callbackUrl;
1010
+ else if (port !== void 0) {
1011
+ url.port = String(port);
1012
+ fixedRedirectUrl = url.href;
1013
+ }
1014
+ return {
1015
+ // `localhost` is served on 127.0.0.1; browsers fall back to it when ::1 refuses.
1016
+ host: address === "localhost" ? CALLBACK_HOST : address,
1017
+ redirectHost: address,
1018
+ port,
1019
+ path: url.pathname,
1020
+ fixedRedirectUrl
1021
+ };
1022
+ }
1023
+ __name(callbackSettings, "callbackSettings");
1024
+ function mergeScopes(...scopes) {
1025
+ const merged = [...new Set(scopes.flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []))];
1026
+ return merged.length > 0 ? merged.join(" ") : void 0;
1027
+ }
1028
+ __name(mergeScopes, "mergeScopes");
1029
+ function parseStates(content) {
1030
+ if (!content?.trim())
1031
+ return {};
1032
+ const parsed = JSON.parse(content);
1033
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
1034
+ }
1035
+ __name(parseStates, "parseStates");
1036
+ function serializeStates(states) {
1037
+ return `${JSON.stringify(states, null, 2)}
1038
+ `;
1039
+ }
1040
+ __name(serializeStates, "serializeStates");
1041
+ function storeKeys(name, serverUrl) {
1042
+ const legacyKey = String(new URL(serverUrl));
1043
+ return { key: `${mcpNamespace(name)}|${legacyKey}`, legacyKey };
1044
+ }
1045
+ __name(storeKeys, "storeKeys");
1046
+ var McpOAuthCredentialStore = class {
1047
+ static {
1048
+ __name(this, "McpOAuthCredentialStore");
1049
+ }
1050
+ backend;
1051
+ /** Directory for the refresh lock files. Without one, refreshes are only serialized in this process. */
1052
+ lockDir;
1053
+ constructor(backend, lockDir) {
1054
+ this.backend = backend ?? new FileAuthStorageBackend(join(getAgentDir(), "mcp-auth.json"));
1055
+ this.lockDir = backend ? lockDir : getAgentDir();
1056
+ }
1057
+ forServer(name, serverUrl) {
1058
+ const { key, legacyKey } = storeKeys(name, serverUrl);
1059
+ return {
1060
+ // The first server to load legacy state takes it over; others with the same URL sign in again.
1061
+ load: /* @__PURE__ */ __name(() => this.backend.withLock((current) => {
1062
+ const states = parseStates(current);
1063
+ if (states[key] || !states[legacyKey])
1064
+ return { result: states[key] };
1065
+ states[key] = states[legacyKey];
1066
+ delete states[legacyKey];
1067
+ return { result: states[key], next: serializeStates(states) };
1068
+ }), "load"),
1069
+ save: /* @__PURE__ */ __name((state) => this.write((states) => {
1070
+ states[key] = state;
1071
+ }), "save"),
1072
+ withRefreshLock: /* @__PURE__ */ __name((fn) => this.withRefreshLock(key, fn), "withRefreshLock")
1073
+ };
1074
+ }
1075
+ /**
1076
+ * A lock file per server. When the process exits, proper-lockfile removes the locks it holds; when
1077
+ * it is killed, the lock goes stale because it is no longer renewed, and the next process takes it over.
1078
+ */
1079
+ async withRefreshLock(key, fn) {
1080
+ if (!this.lockDir)
1081
+ return fn();
1082
+ mkdirSync(this.lockDir, { recursive: true, mode: 448 });
1083
+ const hash = createHash("sha256").update(key).digest("hex").slice(0, 16);
1084
+ const release = await import_proper_lockfile.default.lock(join(this.lockDir, `mcp-auth-refresh-${hash}`), {
1085
+ realpath: false,
1086
+ stale: REFRESH_LOCK_STALE_MS,
1087
+ retries: {
1088
+ retries: REFRESH_LOCK_WAIT_MS / REFRESH_LOCK_RETRY_MS,
1089
+ factor: 1,
1090
+ minTimeout: REFRESH_LOCK_RETRY_MS,
1091
+ maxTimeout: REFRESH_LOCK_RETRY_MS
1092
+ },
1093
+ // The default throws from a timer. A lost lock at worst lets two refreshes overlap.
1094
+ onCompromised: /* @__PURE__ */ __name(() => {
1095
+ }, "onCompromised")
1096
+ });
1097
+ try {
1098
+ return await fn();
1099
+ } finally {
1100
+ await release().catch(() => void 0);
1101
+ }
1102
+ }
1103
+ /** The stored tokens of a server, for noticing sign-ins done by another process. Does not take over legacy state. */
1104
+ tokens(name, serverUrl) {
1105
+ const { key, legacyKey } = storeKeys(name, serverUrl);
1106
+ const states = this.backend.withLock((current) => ({ result: parseStates(current) }));
1107
+ return (states[key] ?? states[legacyKey])?.tokens;
1108
+ }
1109
+ /** Returns whether credentials were stored for the server. Removes legacy state the server would take over. */
1110
+ remove(name, serverUrl) {
1111
+ const { key, legacyKey } = storeKeys(name, serverUrl);
1112
+ return this.backend.withLock((current) => {
1113
+ const states = parseStates(current);
1114
+ const stored = key in states ? key : legacyKey in states ? legacyKey : void 0;
1115
+ if (!stored)
1116
+ return { result: false };
1117
+ delete states[stored];
1118
+ return { result: true, next: serializeStates(states) };
1119
+ });
1120
+ }
1121
+ write(update) {
1122
+ this.backend.withLock((current) => {
1123
+ const states = parseStates(current);
1124
+ update(states);
1125
+ return { result: void 0, next: serializeStates(states) };
1126
+ });
1127
+ }
1128
+ };
1129
+ function timedFetch(fetch = globalThis.fetch) {
1130
+ return (input, init) => {
1131
+ const timeout = AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);
1132
+ return fetch(input, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout });
1133
+ };
1134
+ }
1135
+ __name(timedFetch, "timedFetch");
1136
+ function registeredRedirectUrls(client) {
1137
+ return client && "redirect_uris" in client ? client.redirect_uris : [];
1138
+ }
1139
+ __name(registeredRedirectUrls, "registeredRedirectUrls");
1140
+ function callbackId(serverUrl) {
1141
+ const url = new URL(serverUrl);
1142
+ url.hash = "";
1143
+ return createHash("sha256").update(url.href).digest().subarray(0, 9).toString("base64url");
1144
+ }
1145
+ __name(callbackId, "callbackId");
1146
+ function clientMetadataDocument(serverUrl, redirectUrl, metadata) {
1147
+ if (!metadata?.client_id_metadata_document_supported || !metadata.token_endpoint_auth_methods_supported?.includes("none")) {
1148
+ throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');
1149
+ }
1150
+ if (metadata.authorization_response_iss_parameter_supported) {
1151
+ return { url: `${CLIENT_METADATA_BASE_URL}/client.json`, redirectUrl };
1152
+ }
1153
+ const id = callbackId(serverUrl);
1154
+ const redirect = new URL(redirectUrl);
1155
+ redirect.pathname = `${CALLBACK_PATH}/${id}`;
1156
+ return { url: `${CLIENT_METADATA_BASE_URL}/${id}/client.json`, redirectUrl: redirect.href };
1157
+ }
1158
+ __name(clientMetadataDocument, "clientMetadataDocument");
1159
+ function createProvider(serverUrl, store, settings, redirectUrl, onRedirect) {
1160
+ return new McpOAuthProvider({
1161
+ serverUrl,
1162
+ redirectUrl,
1163
+ clientMetadata: { client_name: settings.clientName ?? APP_NAME },
1164
+ clientMetadataDocument: settings.clientRegistration === "cimd" ? (metadata) => clientMetadataDocument(serverUrl, redirectUrl, metadata) : void 0,
1165
+ clientId: settings.clientId,
1166
+ clientSecret: settings.clientSecret,
1167
+ store,
1168
+ onRedirect
1169
+ });
1170
+ }
1171
+ __name(createProvider, "createProvider");
1172
+ function createMcpAuthProvider(options) {
1173
+ const { serverUrl, store } = options;
1174
+ let refreshing;
1175
+ const refresh = /* @__PURE__ */ __name((staleToken, fetch = globalThis.fetch, challenge) => {
1176
+ refreshing ??= store.withRefreshLock(async () => {
1177
+ const state = await store.load();
1178
+ if (state?.tokens?.access_token !== staleToken)
1179
+ return;
1180
+ if (!state?.tokens?.refresh_token)
1181
+ throw new McpOAuthAuthorizationRequiredError();
1182
+ const settings = options.settings();
1183
+ const redirectUrl = callbackSettings(settings).fixedRedirectUrl ?? registeredRedirectUrls(state.clientInformation)[0] ?? FALLBACK_REDIRECT_URL;
1184
+ const provider = createProvider(serverUrl, store, settings, redirectUrl, () => {
1185
+ });
1186
+ const result = await authorizeMcp(provider, {
1187
+ serverUrl,
1188
+ resourceMetadataUrl: challenge?.resourceMetadataUrl,
1189
+ authorizationServerMetadataUrl: settings.authServerMetadataUrl,
1190
+ scope: challenge?.scope,
1191
+ fetch: timedFetch(fetch)
1192
+ });
1193
+ if (result === "REDIRECT")
1194
+ throw new McpOAuthAuthorizationRequiredError();
1195
+ }).finally(() => {
1196
+ refreshing = void 0;
1197
+ });
1198
+ return refreshing;
1199
+ }, "refresh");
1200
+ return {
1201
+ token: /* @__PURE__ */ __name(async () => {
1202
+ await refreshing?.catch(() => void 0);
1203
+ const state = await store.load();
1204
+ const token = state?.tokens?.access_token;
1205
+ const expired = state?.tokensExpireAt !== void 0 && state.tokensExpireAt - REFRESH_SKEW_MS <= Date.now();
1206
+ if (!expired || !state?.tokens?.refresh_token)
1207
+ return token;
1208
+ await refresh(token).catch(() => void 0);
1209
+ return (await store.load())?.tokens?.access_token;
1210
+ }, "token"),
1211
+ onUnauthorized: /* @__PURE__ */ __name(async (context) => {
1212
+ const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));
1213
+ options.onChallenge(challenge);
1214
+ if (challenge.error === "insufficient_scope")
1215
+ throw new McpOAuthAuthorizationRequiredError();
1216
+ await refresh(context.token, context.fetch, challenge);
1217
+ }, "onUnauthorized"),
1218
+ settled: /* @__PURE__ */ __name(async () => {
1219
+ await refreshing?.catch(() => void 0);
1220
+ }, "settled")
1221
+ };
1222
+ }
1223
+ __name(createMcpAuthProvider, "createMcpAuthProvider");
1224
+ var McpSignInCancelledError = class extends Error {
1225
+ static {
1226
+ __name(this, "McpSignInCancelledError");
1227
+ }
1228
+ constructor() {
1229
+ super("Sign-in cancelled");
1230
+ this.name = "McpSignInCancelledError";
1231
+ }
1232
+ };
1233
+ function responseFromRedirectUrl(input, state, redirectUrl) {
1234
+ let url;
1235
+ try {
1236
+ url = new URL(input.trim());
1237
+ } catch {
1238
+ throw new Error("Expected the full redirect URL from the browser address bar");
1239
+ }
1240
+ if (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {
1241
+ throw new Error("The redirect URL does not match this sign-in's redirect URI");
1242
+ }
1243
+ const error = url.searchParams.get("error");
1244
+ if (error)
1245
+ throw new Error(url.searchParams.get("error_description") ?? error);
1246
+ if (url.searchParams.get("state") !== state)
1247
+ throw new Error("The redirect URL belongs to a different sign-in");
1248
+ const code = url.searchParams.get("code");
1249
+ if (!code)
1250
+ throw new Error("The redirect URL does not contain an authorization code");
1251
+ return { code, iss: url.searchParams.get("iss") ?? void 0 };
1252
+ }
1253
+ __name(responseFromRedirectUrl, "responseFromRedirectUrl");
1254
+ async function waitForAuthorizationResponse(callback, state, redirectUrl, prompt, signal) {
1255
+ const controller = new AbortController();
1256
+ const promptSignal = signal ? AbortSignal.any([controller.signal, signal]) : controller.signal;
1257
+ const fromBrowser = callback.waitForCallback(state, redirectUrl.pathname);
1258
+ const fromUser = prompt.promptForRedirectUrl(promptSignal).then((input) => {
1259
+ if (!input?.trim())
1260
+ throw new McpSignInCancelledError();
1261
+ return responseFromRedirectUrl(input, state, redirectUrl);
1262
+ });
1263
+ try {
1264
+ return await Promise.race([fromBrowser, fromUser]);
1265
+ } finally {
1266
+ controller.abort();
1267
+ fromBrowser.catch(() => void 0);
1268
+ fromUser.catch(() => void 0);
1269
+ }
1270
+ }
1271
+ __name(waitForAuthorizationResponse, "waitForAuthorizationResponse");
1272
+ async function listenForCallback(settings, extraPaths, port, required) {
1273
+ const options = {
1274
+ host: settings.host,
1275
+ redirectHost: settings.redirectHost,
1276
+ path: settings.path,
1277
+ extraPaths,
1278
+ renderPage: /* @__PURE__ */ __name((page) => page.ok ? oauthSuccessHtml("Signed in to the MCP server. You may now close this page.") : oauthErrorHtml(page.message, page.details), "renderPage")
1279
+ };
1280
+ try {
1281
+ return await OAuthCallbackServer.listen({ ...options, port: port ?? 0 });
1282
+ } catch (error) {
1283
+ if (required || port === void 0)
1284
+ throw error;
1285
+ return OAuthCallbackServer.listen(options);
1286
+ }
1287
+ }
1288
+ __name(listenForCallback, "listenForCallback");
1289
+ async function signInMcpServer(options) {
1290
+ const { serverUrl, store, settings, signal } = options;
1291
+ if (signal?.aborted)
1292
+ throw new McpSignInCancelledError();
1293
+ const stored = await store.load();
1294
+ const stepUp = options.challenge?.error === "insufficient_scope";
1295
+ const callbackOptions = callbackSettings(settings);
1296
+ const registered = registeredRedirectUrls(stored?.clientInformation)[0];
1297
+ const preferredPort = callbackOptions.port ?? (registered ? Number(new URL(registered).port) || void 0 : void 0);
1298
+ const cimd = settings.clientRegistration === "cimd";
1299
+ const callback = await listenForCallback(
1300
+ callbackOptions,
1301
+ // The redirect URI of a server-specific Client ID Metadata Document.
1302
+ cimd ? [`${CALLBACK_PATH}/${callbackId(serverUrl)}`] : [],
1303
+ preferredPort,
1304
+ callbackOptions.port !== void 0
1305
+ );
1306
+ const redirectUrl = callbackOptions.fixedRedirectUrl ?? callback.redirectUrl;
1307
+ try {
1308
+ if (stored) {
1309
+ const next = { ...stored };
1310
+ delete next.oauthState;
1311
+ const keepClient = settings.clientId || (cimd ? !stored.clientInformation : registeredRedirectUrls(stored.clientInformation).includes(redirectUrl));
1312
+ if (!keepClient) {
1313
+ delete next.clientInformation;
1314
+ delete next.tokens;
1315
+ delete next.tokensExpireAt;
1316
+ }
1317
+ await store.save(next);
1318
+ }
1319
+ let authorizationUrl;
1320
+ const provider = createProvider(serverUrl, store, settings, redirectUrl, (url) => {
1321
+ authorizationUrl = url;
1322
+ });
1323
+ const flow = {
1324
+ serverUrl,
1325
+ fetch: timedFetch(),
1326
+ signal,
1327
+ resourceMetadataUrl: options.challenge?.resourceMetadataUrl,
1328
+ authorizationServerMetadataUrl: settings.authServerMetadataUrl,
1329
+ // A server asking for more scope gets it on top of the configured scope and, since the challenge
1330
+ // may list only the missing scopes, on top of the scope granted so far.
1331
+ scope: mergeScopes(settings.scope, stepUp ? stepUpScope(stored?.tokens?.scope, options.challenge?.scope) : options.challenge?.scope)
1332
+ };
1333
+ const skipRefresh = stepUp;
1334
+ if (await authorizeMcp(provider, { ...flow, skipRefresh }) === "AUTHORIZED")
1335
+ return;
1336
+ if (!authorizationUrl)
1337
+ throw new Error("OAuth flow did not produce an authorization URL");
1338
+ const state = await provider.state();
1339
+ const authorizationRedirectUrl = new URL(authorizationUrl.searchParams.get("redirect_uri") ?? redirectUrl);
1340
+ options.prompt.showAuthorizationUrl(authorizationUrl);
1341
+ const { code, iss } = await waitForAuthorizationResponse(callback, state, authorizationRedirectUrl, options.prompt, signal);
1342
+ await authorizeMcp(provider, { ...flow, authorizationCode: code, iss });
1343
+ } catch (error) {
1344
+ if (signal?.aborted)
1345
+ throw new McpSignInCancelledError();
1346
+ throw error;
1347
+ } finally {
1348
+ await callback.close();
1349
+ }
1350
+ }
1351
+ __name(signInMcpServer, "signInMcpServer");
1352
+
1353
+ // node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/log.js
1354
+ import { appendFileSync, mkdirSync as mkdirSync2, renameSync, statSync } from "node:fs";
1355
+ import { dirname } from "node:path";
1356
+ var MAX_LOG_BYTES = 5 * 1024 * 1024;
1357
+ function isRecord(value) {
1358
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1359
+ }
1360
+ __name(isRecord, "isRecord");
1361
+ function formatData(data) {
1362
+ if (typeof data === "string")
1363
+ return data;
1364
+ try {
1365
+ return JSON.stringify(data) ?? String(data);
1366
+ } catch {
1367
+ return String(data);
1368
+ }
1369
+ }
1370
+ __name(formatData, "formatData");
1371
+ function formatMcpLogMessage(server, params, now = /* @__PURE__ */ new Date()) {
1372
+ const message = isRecord(params) ? params : { data: params };
1373
+ const level = typeof message.level === "string" ? message.level : "info";
1374
+ const logger = typeof message.logger === "string" && message.logger ? ` ${message.logger}:` : "";
1375
+ const text = formatData(message.data).replace(/\r?\n/g, "\n ");
1376
+ return `${now.toISOString()} [${server}] ${level}${logger} ${text}
1377
+ `;
1378
+ }
1379
+ __name(formatMcpLogMessage, "formatMcpLogMessage");
1380
+ var McpServerLog = class {
1381
+ static {
1382
+ __name(this, "McpServerLog");
1383
+ }
1384
+ path;
1385
+ size;
1386
+ constructor(path) {
1387
+ this.path = path;
1388
+ }
1389
+ write(server, params) {
1390
+ const line = formatMcpLogMessage(server, params);
1391
+ try {
1392
+ if (this.size === void 0) {
1393
+ mkdirSync2(dirname(this.path), { recursive: true });
1394
+ this.size = this.currentSize();
1395
+ }
1396
+ if (this.size > MAX_LOG_BYTES) {
1397
+ if (this.currentSize() > MAX_LOG_BYTES)
1398
+ renameSync(this.path, `${this.path}.1`);
1399
+ this.size = this.currentSize();
1400
+ }
1401
+ appendFileSync(this.path, line);
1402
+ this.size += Buffer.byteLength(line);
1403
+ } catch {
1404
+ }
1405
+ }
1406
+ currentSize() {
1407
+ try {
1408
+ return statSync(this.path).size;
1409
+ } catch {
1410
+ return 0;
1411
+ }
1412
+ }
1413
+ };
1414
+
1415
+ // node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/runtime.js
1416
+ var DEFAULT_TIMEOUT_SECONDS = 60;
1417
+ var STDERR_TAIL_CHARS = 2e3;
1418
+ var CONNECT_RETRY_DELAYS_MS = [250, 1e3];
1419
+ function errorMessage(error) {
1420
+ return error instanceof Error ? error.message : String(error);
1421
+ }
1422
+ __name(errorMessage, "errorMessage");
1423
+ function isTransientError(error) {
1424
+ if (error instanceof McpHttpError) {
1425
+ return error.status === 408 || error.status === 429 || error.status >= 500 && error.status !== 501;
1426
+ }
1427
+ return error instanceof TypeError;
1428
+ }
1429
+ __name(isTransientError, "isTransientError");
1430
+ function signInRequiredMessage(entry) {
1431
+ const provider = "url" in entry.config ? entry.config.auth?.provider : void 0;
1432
+ return `MCP server "${entry.name}" requires sign-in. Run ${provider ? `/login ${provider}` : "/mcp"} to sign in.`;
1433
+ }
1434
+ __name(signInRequiredMessage, "signInRequiredMessage");
1435
+ function usesOAuth(entry) {
1436
+ const { config } = entry;
1437
+ if (!("url" in config) || config.auth)
1438
+ return false;
1439
+ return !Object.keys(config.headers ?? {}).some((header) => header.toLowerCase() === "authorization");
1440
+ }
1441
+ __name(usesOAuth, "usesOAuth");
1442
+ function expandHome(value) {
1443
+ if (value === "~")
1444
+ return homedir();
1445
+ if (value.startsWith("~/") || process.platform === "win32" && value.startsWith("~\\")) {
1446
+ return join2(homedir(), value.slice(2));
1447
+ }
1448
+ return value;
1449
+ }
1450
+ __name(expandHome, "expandHome");
1451
+ function createDefaultTransport(entry, cwd, authProvider) {
1452
+ const { config, name } = entry;
1453
+ if ("url" in config) {
1454
+ return new StreamableHttpTransport({
1455
+ url: config.url,
1456
+ headers: resolveHeadersOrThrow(config.headers, `MCP server "${name}"`),
1457
+ authProvider
1458
+ });
1459
+ }
1460
+ const env = {};
1461
+ for (const [key, value] of Object.entries(config.env ?? {})) {
1462
+ env[key] = resolveConfigValueOrThrow(value, `MCP server "${name}" env "${key}"`);
1463
+ }
1464
+ return new StdioTransport({
1465
+ command: expandHome(config.command),
1466
+ args: config.args?.map(expandHome),
1467
+ cwd: resolve(cwd, expandHome(config.cwd ?? ".")),
1468
+ env,
1469
+ stderr: "pipe"
1470
+ });
1471
+ }
1472
+ __name(createDefaultTransport, "createDefaultTransport");
1473
+ async function withoutTemplates(list, empty) {
1474
+ try {
1475
+ return await list();
1476
+ } catch (error) {
1477
+ if (error instanceof McpError && error.code === JSON_RPC_ERROR_CODES.methodNotFound)
1478
+ return empty;
1479
+ throw error;
1480
+ }
1481
+ }
1482
+ __name(withoutTemplates, "withoutTemplates");
1483
+ function listTemplates(client, options = {}) {
1484
+ return withoutTemplates(() => client.listResourceTemplates(options), []);
1485
+ }
1486
+ __name(listTemplates, "listTemplates");
1487
+ var McpServerConnection = class {
1488
+ static {
1489
+ __name(this, "McpServerConnection");
1490
+ }
1491
+ entry;
1492
+ state = "connecting";
1493
+ error;
1494
+ tools = [];
1495
+ /**
1496
+ * Whether the server offers resources, which the resource tools list and read on demand. They are
1497
+ * not listed at connect: listing every resource can take long (a large drive, say).
1498
+ */
1499
+ hasResources = false;
1500
+ /** Server instructions from `initialize`, describing its tools as a group. */
1501
+ instructions;
1502
+ /** Last OAuth challenge from the server; sign-in uses its resource metadata URL and scope. */
1503
+ challenge;
1504
+ client;
1505
+ opening;
1506
+ /** Aborted by `close()`; cancels a connect in progress, including the wait between retries. */
1507
+ shutdown = new AbortController();
1508
+ /** Stderr of the last stdio server that failed to connect. */
1509
+ stderrTail;
1510
+ cwd;
1511
+ createTransport;
1512
+ authProvider;
1513
+ onTools;
1514
+ onChange;
1515
+ log;
1516
+ constructor(options) {
1517
+ this.entry = options.entry;
1518
+ this.cwd = options.cwd;
1519
+ this.createTransport = options.createTransport;
1520
+ this.onTools = options.onTools;
1521
+ this.onChange = options.onChange;
1522
+ this.log = options.log;
1523
+ const url = this.oauthUrl;
1524
+ const provider = "url" in this.entry.config ? this.entry.config.auth?.provider : void 0;
1525
+ this.authProvider = url ? createMcpAuthProvider({
1526
+ serverUrl: url,
1527
+ store: options.credentials.forServer(this.entry.name, url),
1528
+ settings: /* @__PURE__ */ __name(() => this.oauthSettings(), "settings"),
1529
+ onChallenge: /* @__PURE__ */ __name((challenge) => {
1530
+ this.challenge = challenge;
1531
+ }, "onChallenge")
1532
+ }) : provider ? (
1533
+ // Read on every request, so the provider's refreshes apply; MCP stores no copy.
1534
+ { token: /* @__PURE__ */ __name(async () => options.providerToken?.(provider), "token"), settled: /* @__PURE__ */ __name(async () => {
1535
+ }, "settled") }
1536
+ ) : void 0;
1537
+ }
1538
+ get name() {
1539
+ return this.entry.name;
1540
+ }
1541
+ get closed() {
1542
+ return this.shutdown.signal.aborted;
1543
+ }
1544
+ get timeoutMs() {
1545
+ return (this.entry.config.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1e3;
1546
+ }
1547
+ /** Server URL when the server authenticates with OAuth. */
1548
+ get oauthUrl() {
1549
+ return usesOAuth(this.entry) && "url" in this.entry.config ? this.entry.config.url : void 0;
1550
+ }
1551
+ oauthSettings() {
1552
+ const oauth = "url" in this.entry.config ? this.entry.config.oauth : void 0;
1553
+ if (!oauth)
1554
+ return {};
1555
+ return {
1556
+ clientId: oauth.clientId,
1557
+ clientSecret: oauth.clientSecret === void 0 ? void 0 : resolveConfigValueOrThrow(oauth.clientSecret, `MCP server "${this.entry.name}" oauth.clientSecret`),
1558
+ callbackPort: oauth.callbackPort,
1559
+ callbackUrl: oauth.callbackUrl,
1560
+ scope: oauth.scope,
1561
+ clientName: oauth.clientName,
1562
+ clientRegistration: oauth.clientRegistration,
1563
+ authServerMetadataUrl: oauth.authServerMetadataUrl ? new URL(oauth.authServerMetadataUrl) : void 0
1564
+ };
1565
+ }
1566
+ getClient() {
1567
+ if (this.closed)
1568
+ return Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`));
1569
+ if (this.client?.connectionState === "connected")
1570
+ return Promise.resolve(this.client);
1571
+ this.opening ??= this.open().finally(() => {
1572
+ this.opening = void 0;
1573
+ });
1574
+ return this.opening;
1575
+ }
1576
+ callTool(name, args, options) {
1577
+ return this.withClient((client) => client.callTool(name, args, options));
1578
+ }
1579
+ readResource(uri, options) {
1580
+ return this.withClient((client) => client.readResource(uri, options), true);
1581
+ }
1582
+ resourcesPage(cursor, options) {
1583
+ return this.withClient((client) => client.listResourcesPage(cursor, options), true);
1584
+ }
1585
+ resourceTemplatesPage(cursor, options) {
1586
+ return this.withClient((client) => withoutTemplates(() => client.listResourceTemplatesPage(cursor, options), { resourceTemplates: [] }), true);
1587
+ }
1588
+ allResources(options) {
1589
+ return this.withClient((client) => client.listResources(options), true);
1590
+ }
1591
+ allResourceTemplates(options) {
1592
+ return this.withClient((client) => listTemplates(client, options), true);
1593
+ }
1594
+ /**
1595
+ * Run a request, reconnecting when needed. `readOnly` requests are retried once after a transient
1596
+ * HTTP error; tool calls are not, since they may have run.
1597
+ */
1598
+ async withClient(run, readOnly = false) {
1599
+ for (let attempt = 1; ; attempt++) {
1600
+ const client = await this.getClient();
1601
+ try {
1602
+ return await run(client);
1603
+ } catch (error) {
1604
+ if (readOnly && attempt === 1 && error instanceof McpHttpError && isTransientError(error)) {
1605
+ await new Promise((resolve2) => setTimeout(resolve2, CONNECT_RETRY_DELAYS_MS[0]));
1606
+ continue;
1607
+ }
1608
+ if (error instanceof McpSessionExpiredError && attempt === 1) {
1609
+ if (this.client === client)
1610
+ this.client = void 0;
1611
+ continue;
1612
+ }
1613
+ if (!this.needsSignIn(error))
1614
+ throw error;
1615
+ await this.dropClient(client);
1616
+ this.markNeedsAuth();
1617
+ throw new Error(signInRequiredMessage(this.entry));
1618
+ }
1619
+ }
1620
+ }
1621
+ /** Connect again with fresh credentials, for example after signing in. */
1622
+ async reconnect() {
1623
+ await this.opening?.catch(() => void 0);
1624
+ if (this.client)
1625
+ await this.dropClient(this.client);
1626
+ await this.getClient();
1627
+ }
1628
+ /** Disconnect after the stored credentials were removed. */
1629
+ async signOut() {
1630
+ await this.opening?.catch(() => void 0);
1631
+ if (this.client)
1632
+ await this.dropClient(this.client);
1633
+ if (!this.closed)
1634
+ this.markNeedsAuth();
1635
+ }
1636
+ /** OAuth servers that still reject the request after a refresh need the user to sign in again. */
1637
+ needsSignIn(error) {
1638
+ return error instanceof McpOAuthAuthorizationRequiredError || this.authProvider !== void 0 && error instanceof McpAuthRequiredError;
1639
+ }
1640
+ markNeedsAuth() {
1641
+ this.state = "needs-auth";
1642
+ this.error = void 0;
1643
+ this.changed();
1644
+ }
1645
+ changed() {
1646
+ this.onChange?.(this);
1647
+ }
1648
+ async dropClient(client) {
1649
+ if (this.client === client)
1650
+ this.client = void 0;
1651
+ await client.close().catch(() => void 0);
1652
+ }
1653
+ async open() {
1654
+ this.state = "connecting";
1655
+ this.changed();
1656
+ const retries = "url" in this.entry.config ? CONNECT_RETRY_DELAYS_MS : [];
1657
+ for (let attempt = 0; ; attempt++) {
1658
+ this.stderrTail = void 0;
1659
+ try {
1660
+ return await this.connectOnce();
1661
+ } catch (error) {
1662
+ const delay = retries[attempt];
1663
+ if (this.closed || delay === void 0 || !isTransientError(error)) {
1664
+ throw this.connectFailed(error);
1665
+ }
1666
+ await sleep(delay, void 0, { signal: this.shutdown.signal }).catch(() => void 0);
1667
+ if (this.closed)
1668
+ throw this.connectFailed(error);
1669
+ }
1670
+ }
1671
+ }
1672
+ async connectOnce() {
1673
+ const client = new McpClient({
1674
+ name: "pi",
1675
+ version: VERSION,
1676
+ requestTimeoutMs: this.timeoutMs,
1677
+ roots: [{ uri: pathToFileURL(this.cwd).href, name: basename(this.cwd) }]
1678
+ });
1679
+ const log = this.log;
1680
+ if (log)
1681
+ client.onNotification("notifications/message", (params) => log.write(this.entry.name, params));
1682
+ let closing;
1683
+ const closeClient = /* @__PURE__ */ __name(() => {
1684
+ closing ??= client.close().catch(() => void 0);
1685
+ return closing;
1686
+ }, "closeClient");
1687
+ this.shutdown.signal.addEventListener("abort", closeClient, { once: true });
1688
+ let transport;
1689
+ try {
1690
+ transport = this.createTransport(this.entry, this.cwd, this.authProvider);
1691
+ await client.connect(transport);
1692
+ client.onNotification("notifications/tools/list_changed", () => {
1693
+ void this.refreshTools(client);
1694
+ });
1695
+ const stdio = transport instanceof StdioTransport ? transport : void 0;
1696
+ client.onClose(() => this.handleClientClose(client, stdio));
1697
+ const tools = client.serverCapabilities?.tools ? await client.listTools() : [];
1698
+ if (this.closed)
1699
+ throw new Error("shut down while connecting");
1700
+ if (client.connectionState !== "connected")
1701
+ throw new Error("connection closed during setup");
1702
+ this.client = client;
1703
+ this.tools = tools;
1704
+ this.hasResources = client.serverCapabilities?.resources !== void 0;
1705
+ this.instructions = client.instructions?.trim() || void 0;
1706
+ this.state = "connected";
1707
+ this.error = void 0;
1708
+ this.onTools(this);
1709
+ this.changed();
1710
+ return client;
1711
+ } catch (error) {
1712
+ await closeClient();
1713
+ if (transport instanceof StdioTransport) {
1714
+ this.stderrTail = transport.stderr.trim().slice(-STDERR_TAIL_CHARS) || void 0;
1715
+ }
1716
+ throw error;
1717
+ } finally {
1718
+ this.shutdown.signal.removeEventListener("abort", closeClient);
1719
+ }
1720
+ }
1721
+ connectFailed(error) {
1722
+ if (this.needsSignIn(error) && !this.closed) {
1723
+ this.markNeedsAuth();
1724
+ return new Error(signInRequiredMessage(this.entry));
1725
+ }
1726
+ this.state = this.closed ? "closed" : "failed";
1727
+ this.error = this.stderrTail ? `${errorMessage(error)}
1728
+ ${this.stderrTail}` : errorMessage(error);
1729
+ this.changed();
1730
+ return new Error(`MCP server "${this.entry.name}" failed to connect: ${this.error}`);
1731
+ }
1732
+ /** The transport dropped. The next call reconnects; until then the status shows why. */
1733
+ handleClientClose(client, stdio) {
1734
+ if (this.client !== client || this.closed)
1735
+ return;
1736
+ this.client = void 0;
1737
+ this.state = "disconnected";
1738
+ const stderr = stdio?.stderr.trim().slice(-STDERR_TAIL_CHARS);
1739
+ this.error = stderr ? `Connection closed
1740
+ ${stderr}` : "Connection closed";
1741
+ this.changed();
1742
+ }
1743
+ async refreshTools(client) {
1744
+ try {
1745
+ const tools = await client.listTools();
1746
+ if (this.client !== client || this.closed)
1747
+ return;
1748
+ this.tools = tools;
1749
+ this.onTools(this);
1750
+ } catch (error) {
1751
+ this.error = `Failed to refresh tools: ${errorMessage(error)}`;
1752
+ }
1753
+ this.changed();
1754
+ }
1755
+ /** Resolves once no transport of this server is open, including one that was still connecting. */
1756
+ async close() {
1757
+ this.shutdown.abort();
1758
+ this.state = "closed";
1759
+ this.changed();
1760
+ const client = this.client;
1761
+ this.client = void 0;
1762
+ await Promise.all([client?.close().catch(() => void 0), this.opening?.catch(() => void 0)]);
1763
+ await this.authProvider?.settled();
1764
+ }
1765
+ };
1766
+
1767
+ export {
1768
+ McpOAuthCredentialStore,
1769
+ McpSignInCancelledError,
1770
+ signInMcpServer,
1771
+ McpServerLog,
1772
+ createDefaultTransport,
1773
+ McpServerConnection
1774
+ };