@ait-co/devtools 0.1.113 → 0.1.116

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 (71) hide show
  1. package/dist/bundle-KFs4t-wc.d.ts.map +1 -1
  2. package/dist/cli-BLBo0lkP.js +2466 -0
  3. package/dist/cli-BLBo0lkP.js.map +1 -0
  4. package/dist/debug-server-DcAKrbnq.js +921 -0
  5. package/dist/debug-server-DcAKrbnq.js.map +1 -0
  6. package/dist/debug-server-DlXJARIC.js +8171 -0
  7. package/dist/debug-server-DlXJARIC.js.map +1 -0
  8. package/dist/mcp/cli.js +3 -7771
  9. package/dist/mcp/cli.js.map +1 -1
  10. package/dist/mcp/server.js +11 -2
  11. package/dist/mcp/server.js.map +1 -1
  12. package/dist/panel/index.js +7 -1
  13. package/dist/panel/index.js.map +1 -1
  14. package/dist/{pool-mZlgCmNQ.d.ts → pool-htlVnEFl.d.ts} +2 -2
  15. package/dist/{pool-mZlgCmNQ.d.ts.map → pool-htlVnEFl.d.ts.map} +1 -1
  16. package/dist/{qr-http-server-BVS-HZjU.cjs → qr-http-server-BpTvfeku.cjs} +92 -8
  17. package/dist/qr-http-server-BpTvfeku.cjs.map +1 -0
  18. package/dist/{qr-http-server-BJJt3ush.js → qr-http-server-BsWlOA85.js} +92 -8
  19. package/dist/qr-http-server-BsWlOA85.js.map +1 -0
  20. package/dist/{qr-http-server-C1T4RNbq.cjs → qr-http-server-CrVKno9V.cjs} +92 -8
  21. package/dist/qr-http-server-CrVKno9V.cjs.map +1 -0
  22. package/dist/{qr-http-server-Cs93vEPH.js → qr-http-server-UBV2qUEd.js} +92 -8
  23. package/dist/qr-http-server-UBV2qUEd.js.map +1 -0
  24. package/dist/relay-secret-store-BHcOmaNK.js +3 -0
  25. package/dist/relay-secret-store-CkA7KNUb.js +154 -0
  26. package/dist/{relay-secret-store-DhzAnnj-.js.map → relay-secret-store-CkA7KNUb.js.map} +1 -1
  27. package/dist/{relay-secret-store-DhzAnnj-.js → relay-secret-store-CmqchhR5.js} +3 -3
  28. package/dist/relay-secret-store-CmqchhR5.js.map +1 -0
  29. package/dist/{relay-url-store-CwKT7i04.js → relay-url-store-C0qukm3R.js} +2 -2
  30. package/dist/{relay-url-store-CwKT7i04.js.map → relay-url-store-C0qukm3R.js.map} +1 -1
  31. package/dist/relay-url-store-NDtEcOE-.js +123 -0
  32. package/dist/relay-url-store-NDtEcOE-.js.map +1 -0
  33. package/dist/{relay-worker-Dppp2yZj.d.ts → relay-worker-DWW4vZxU.d.ts} +2 -2
  34. package/dist/{relay-worker-Dppp2yZj.d.ts.map → relay-worker-DWW4vZxU.d.ts.map} +1 -1
  35. package/dist/runtime-BU-iMHz6.d.ts +192 -0
  36. package/dist/runtime-BU-iMHz6.d.ts.map +1 -0
  37. package/dist/test-runner/bundle.js +72 -2
  38. package/dist/test-runner/bundle.js.map +1 -1
  39. package/dist/test-runner/cli.d.ts +19 -7
  40. package/dist/test-runner/cli.d.ts.map +1 -1
  41. package/dist/test-runner/cli.js +1 -550
  42. package/dist/test-runner/config.d.ts +1 -1
  43. package/dist/test-runner/pool.d.ts +1 -1
  44. package/dist/test-runner/relay-worker.d.ts +1 -1
  45. package/dist/test-runner/rpc.d.ts +1 -1
  46. package/dist/test-runner/runtime.d.ts +2 -2
  47. package/dist/test-runner/runtime.js +407 -21
  48. package/dist/test-runner/runtime.js.map +1 -1
  49. package/dist/test-runner/task-graph.d.ts +1 -1
  50. package/dist/totp-D104cJQN.js +3 -0
  51. package/dist/{totp-WY6l0ysP.js → totp-D70zD5tJ.js} +1 -1
  52. package/dist/{totp-WY6l0ysP.js.map → totp-D70zD5tJ.js.map} +1 -1
  53. package/dist/totp-DvOYkYim.js +212 -0
  54. package/dist/totp-DvOYkYim.js.map +1 -0
  55. package/dist/{tunnel-Cpn3mA4u.js → tunnel-B7U5k1xa.js} +2 -2
  56. package/dist/{tunnel-Cpn3mA4u.js.map → tunnel-B7U5k1xa.js.map} +1 -1
  57. package/dist/{tunnel-Dj8Kf2QS.cjs → tunnel-C-cgMnyY.cjs} +2 -2
  58. package/dist/{tunnel-Dj8Kf2QS.cjs.map → tunnel-C-cgMnyY.cjs.map} +1 -1
  59. package/dist/unplugin/index.cjs +1 -1
  60. package/dist/unplugin/index.js +1 -1
  61. package/dist/unplugin/tunnel.cjs +1 -1
  62. package/dist/unplugin/tunnel.js +1 -1
  63. package/package.json +1 -1
  64. package/dist/qr-http-server-BJJt3ush.js.map +0 -1
  65. package/dist/qr-http-server-BVS-HZjU.cjs.map +0 -1
  66. package/dist/qr-http-server-C1T4RNbq.cjs.map +0 -1
  67. package/dist/qr-http-server-Cs93vEPH.js.map +0 -1
  68. package/dist/runtime-C7uxh3Mf.d.ts +0 -62
  69. package/dist/runtime-C7uxh3Mf.d.ts.map +0 -1
  70. package/dist/test-runner/cli.js.map +0 -1
  71. package/dist/totp-D1pulXLa.js +0 -3
@@ -0,0 +1,921 @@
1
+ #!/usr/bin/env node
2
+ import { n as buildRelayVerifyAuth, r as generateTotp, t as assertRelayAuthConfigured } from "./totp-DvOYkYim.js";
3
+ import { c as generateAttachToken, d as startQuickTunnel, f as startTunnelHealthProbe, l as makeTunnelStatus, m as logInfo, p as logError, u as printAttachBanner } from "./cli-BLBo0lkP.js";
4
+ import "./relay-secret-store-CmqchhR5.js";
5
+ import { createRequire } from "node:module";
6
+ import "@modelcontextprotocol/sdk/server/index.js";
7
+ import "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import "@modelcontextprotocol/sdk/types.js";
9
+ import { EventEmitter } from "node:events";
10
+ import { WebSocket, WebSocketServer } from "ws";
11
+ import { createServer } from "node:http";
12
+ //#region src/shared/relay-auth-close.ts
13
+ /**
14
+ * Shared constants for the relay's named TOTP-auth rejection (issue #478).
15
+ *
16
+ * Before #478 the relay rejected an unauthenticated WebSocket upgrade with a
17
+ * raw `HTTP/1.1 401` + `socket.destroy()`. A handshake aborted that way is
18
+ * indistinguishable from a network failure on the browser side — the
19
+ * WebSocket only ever sees close code 1006, so the phone (env-2 launcher PWA)
20
+ * could not tell "stale TOTP code" apart from "tunnel down" and stayed
21
+ * silent. The fix is accept-then-close: complete the handshake, then close
22
+ * with an application close code that NAMES the rejection.
23
+ *
24
+ * Three parties share this contract:
25
+ * - `src/mcp/chii-relay.ts` (Node) sends the close frame / HTTP error body;
26
+ * - `src/in-app/attach.ts` (browser) observes relay-bound WebSockets and
27
+ * surfaces the code to the launcher shell;
28
+ * - `src/mcp/chii-connection.ts` (Node daemon client) recognises the code
29
+ * as an auth failure on its own `/client` dial (defensive — #439's fresh
30
+ * code mint means it should not normally hit this).
31
+ *
32
+ * This module is intentionally dependency-free (no Node, no DOM) so it is
33
+ * safe to import from both the browser in-app bundle and the MCP daemon
34
+ * bundle.
35
+ *
36
+ * SECRET-HANDLING: these are fixed enum values. The close reason / error body
37
+ * must never grow to carry a secret, a TOTP code, or a host.
38
+ */
39
+ /**
40
+ * WebSocket close code sent by the relay when TOTP auth is rejected.
41
+ *
42
+ * 4000–4999 is the application-reserved range (RFC 6455 §7.4.2); 4401 mirrors
43
+ * HTTP 401 so it reads as "unauthorized" at a glance.
44
+ */
45
+ const RELAY_AUTH_REJECT_CLOSE_CODE = 4401;
46
+ /**
47
+ * Close reason string accompanying {@link RELAY_AUTH_REJECT_CLOSE_CODE}, and
48
+ * the `error` value of the relay's HTTP 401 JSON body. Enum string only —
49
+ * never interpolated with request data.
50
+ */
51
+ const RELAY_AUTH_REJECT_REASON = "totp-rejected";
52
+ //#endregion
53
+ //#region src/mcp/chii-connection.ts
54
+ /**
55
+ * Production `CdpConnection` backed by the local Chii relay.
56
+ *
57
+ * Topology (debug mode):
58
+ * phone target.js --WS--> Chii relay :9100 <--WS-- this connection
59
+ *
60
+ * The phone connects to the relay as a `target`; this module connects as a
61
+ * `client` (the role a CDP frontend would take) so CDP events the page emits
62
+ * (`Runtime.consoleAPICalled`, `Network.*`) flow back here. We buffer recent
63
+ * events in ring buffers the tool layer reads via `getBufferedEvents`.
64
+ *
65
+ * Node-only: imports `ws`. Never bundled into the browser/in-app entries.
66
+ *
67
+ * Attach reliability (#281):
68
+ * `refreshTargets()` emits an internal 'target:attached' event whenever a
69
+ * new target is added to the relay. `waitForFirstTarget()` awaits that event
70
+ * (with a polling-interval fallback) so `start_attach`'s attach wait
71
+ * resolves deterministically rather than racing between polling rounds.
72
+ */
73
+ /** Max events retained per domain ring buffer. */
74
+ const DEFAULT_BUFFER_SIZE = 500;
75
+ function isObject(value) {
76
+ return typeof value === "object" && value !== null;
77
+ }
78
+ function parseInbound(raw) {
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(raw);
82
+ } catch {
83
+ return null;
84
+ }
85
+ if (!isObject(parsed)) return null;
86
+ const message = {};
87
+ if (typeof parsed.id === "number") message.id = parsed.id;
88
+ if (typeof parsed.method === "string") message.method = parsed.method;
89
+ if ("params" in parsed) message.params = parsed.params;
90
+ if ("result" in parsed) message.result = parsed.result;
91
+ if (isObject(parsed.error) && typeof parsed.error.message === "string") message.error = { message: parsed.error.message };
92
+ return message;
93
+ }
94
+ const PHASE_1_EVENTS = [
95
+ "Runtime.consoleAPICalled",
96
+ "Network.requestWillBeSent",
97
+ "Network.responseReceived"
98
+ ];
99
+ /**
100
+ * Ring buffer size for `Runtime.exceptionThrown`.
101
+ *
102
+ * Exceptions are rarer than console messages but each is heavier (stack
103
+ * trace). 50 is generous enough to cover a crash scenario while keeping
104
+ * memory bounded.
105
+ *
106
+ * **Lifecycle note**: the exception buffer intentionally survives `replaced` /
107
+ * `crashed` / `destroyed` lifecycle events — it is NOT cleared on target
108
+ * transitions. Rationale: an exception fired just before a crash is exactly
109
+ * the signal we want to preserve for root-cause analysis. The buffer
110
+ * represents "exceptions seen in this MCP session", not "exceptions in the
111
+ * current page".
112
+ */
113
+ const EXCEPTION_BUFFER_SIZE = 50;
114
+ /** Default per-command timeout if neither option nor env var is set. */
115
+ const DEFAULT_COMMAND_TIMEOUT_MS = 3e4;
116
+ /**
117
+ * Production CDP connection. Polls the relay for the first attached target,
118
+ * opens a client websocket to it, enables Phase 1 domains, and buffers events.
119
+ */
120
+ var ChiiCdpConnection = class {
121
+ /** Authoritative connection kind (issue #348) — relay-backed. */
122
+ kind = "relay";
123
+ relayBaseUrl;
124
+ bufferSize;
125
+ commandTimeoutMs;
126
+ totpSecret;
127
+ emitter = new EventEmitter();
128
+ buffers = /* @__PURE__ */ new Map();
129
+ targets = /* @__PURE__ */ new Map();
130
+ ws = null;
131
+ connectionState = "idle";
132
+ nextCommandId = 1;
133
+ /**
134
+ * The single active target id under the single-attach model.
135
+ * Updated by `refreshTargets()` whenever a non-null target is present.
136
+ * Used to detect a new (different) target attach and evict the previous one.
137
+ */
138
+ activeTargetId = null;
139
+ /** In-flight enableDomains() promise — concurrent callers share it. */
140
+ enablingPromise = null;
141
+ /** Pending request→response commands keyed by CDP message id. */
142
+ pending = /* @__PURE__ */ new Map();
143
+ /**
144
+ * Timestamp (ms since epoch) of the most recent crash/destroy/detach event,
145
+ * or `null` if no crash has been detected since the last `enableDomains()`.
146
+ */
147
+ lastCrashDetectedAt = null;
148
+ /**
149
+ * Per-target last-seen timestamp (ms since epoch). Updated on any inbound
150
+ * CDP message carrying data from a target. Keyed by target id.
151
+ */
152
+ targetLastSeenAt = /* @__PURE__ */ new Map();
153
+ /** Active heartbeat interval handle (only when `AIT_CDP_HEARTBEAT_MS` is set). */
154
+ heartbeatHandle = null;
155
+ /** Lifecycle event listeners (crash / destroyed / detached). */
156
+ lifecycleListeners = [];
157
+ constructor(options) {
158
+ this.relayBaseUrl = options.relayBaseUrl.replace(/\/$/, "");
159
+ this.bufferSize = options.bufferSize ?? DEFAULT_BUFFER_SIZE;
160
+ this.totpSecret = options.totpSecret;
161
+ const envMs = process.env.AIT_CDP_COMMAND_TIMEOUT_MS ? Number(process.env.AIT_CDP_COMMAND_TIMEOUT_MS) : void 0;
162
+ this.commandTimeoutMs = (envMs !== void 0 && Number.isFinite(envMs) && envMs > 0 ? envMs : void 0) ?? options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
163
+ for (const event of PHASE_1_EVENTS) this.buffers.set(event, []);
164
+ this.buffers.set("Runtime.exceptionThrown", []);
165
+ this.emitter.setMaxListeners(0);
166
+ }
167
+ /** Refresh the attached-target list from the relay's `GET /targets`. */
168
+ async refreshTargets() {
169
+ let targetsUrl = `${this.relayBaseUrl}/targets`;
170
+ if (this.totpSecret) {
171
+ const code = generateTotp(this.totpSecret);
172
+ targetsUrl += `?at=${encodeURIComponent(code)}`;
173
+ }
174
+ const res = await fetch(targetsUrl);
175
+ if (!res.ok) throw new Error(`Chii relay /targets returned HTTP ${res.status} ${res.statusText}`);
176
+ const body = await res.json();
177
+ const list = isObject(body) && Array.isArray(body.targets) ? body.targets : [];
178
+ let newestTargetId = null;
179
+ for (const item of list) {
180
+ if (!isObject(item) || typeof item.id !== "string") continue;
181
+ newestTargetId = item.id;
182
+ }
183
+ if (newestTargetId !== null && this.activeTargetId !== null && newestTargetId !== this.activeTargetId) {
184
+ const prevId = this.activeTargetId;
185
+ logInfo("page.detached", { prevTargetId: prevId });
186
+ this.evictTarget(prevId);
187
+ }
188
+ this.targets.clear();
189
+ for (const item of list) {
190
+ if (!isObject(item) || typeof item.id !== "string") continue;
191
+ if (item.id !== newestTargetId) continue;
192
+ this.targets.set(item.id, {
193
+ id: item.id,
194
+ title: typeof item.title === "string" ? item.title : "",
195
+ url: typeof item.url === "string" ? item.url : ""
196
+ });
197
+ }
198
+ if (newestTargetId !== null) this.activeTargetId = newestTargetId;
199
+ else this.activeTargetId = null;
200
+ const result = [...this.targets.values()];
201
+ if (newestTargetId !== null) this.emitter.emit("target:attached", result);
202
+ return result;
203
+ }
204
+ listTargets() {
205
+ return [...this.targets.values()];
206
+ }
207
+ /**
208
+ * Waits until at least one target matching `filterFn` is attached, then
209
+ * resolves with the full target list at that moment.
210
+ *
211
+ * Resolution happens on whichever comes first:
212
+ * (a) a `'target:attached'` event from `refreshTargets()` (triggered by
213
+ * the /targets poll finding a new target), OR
214
+ * (b) a `'target:attached'` event from `handleMessage()` (triggered by
215
+ * the first inbound CDP message from a target — confirms the relay
216
+ * websocket has data from the phone, not just a target entry in the map).
217
+ *
218
+ * This dual-signal approach eliminates the polling race that previously
219
+ * caused `wait_for_attach` to resolve before the first CDP message arrived.
220
+ *
221
+ * Falls back to checking `listTargets()` every `pollIntervalMs` in case the
222
+ * EventEmitter is missed (defensive belt-and-suspenders).
223
+ *
224
+ * @param filterFn - Predicate that the returned targets must satisfy.
225
+ * @param timeoutMs - Reject after this many ms (default 90 000).
226
+ * @param pollIntervalMs - Fallback poll interval (default 500ms).
227
+ */
228
+ waitForFirstTarget(filterFn, timeoutMs = 9e4, pollIntervalMs = 500) {
229
+ const current = this.listTargets();
230
+ if (filterFn(current)) return Promise.resolve(current);
231
+ return new Promise((resolve, reject) => {
232
+ let settled = false;
233
+ let pollHandle = null;
234
+ const settle = (targets) => {
235
+ if (settled) return;
236
+ settled = true;
237
+ clearTimeout(timeoutHandle);
238
+ if (pollHandle !== null) {
239
+ clearInterval(pollHandle);
240
+ pollHandle = null;
241
+ }
242
+ this.emitter.off("target:attached", onAttach);
243
+ resolve(targets);
244
+ };
245
+ const onAttach = (targets) => {
246
+ if (filterFn(targets)) settle(targets);
247
+ };
248
+ const timeoutHandle = setTimeout(() => {
249
+ if (settled) return;
250
+ settled = true;
251
+ if (pollHandle !== null) {
252
+ clearInterval(pollHandle);
253
+ pollHandle = null;
254
+ }
255
+ this.emitter.off("target:attached", onAttach);
256
+ reject(/* @__PURE__ */ new Error(`waitForFirstTarget: 타임아웃 (${timeoutMs}ms) — 폰이 relay에 attach되지 않았습니다.`));
257
+ }, timeoutMs);
258
+ this.emitter.on("target:attached", onAttach);
259
+ pollHandle = setInterval(() => {
260
+ this.refreshTargets().then((targets) => {
261
+ if (filterFn(targets)) settle(targets);
262
+ }, () => {});
263
+ }, pollIntervalMs);
264
+ });
265
+ }
266
+ /**
267
+ * Timestamp (ms since epoch) of the most recent crash/destroy/detach event
268
+ * detected since the last `enableDomains()` call, or `null` if none.
269
+ */
270
+ getLastCrashDetectedAt() {
271
+ return this.lastCrashDetectedAt;
272
+ }
273
+ /**
274
+ * Last-seen timestamp (ms since epoch) for a given target id, or `null` if
275
+ * the target is unknown / no message has been received from it yet.
276
+ */
277
+ getTargetLastSeenAt(targetId) {
278
+ return this.targetLastSeenAt.get(targetId) ?? null;
279
+ }
280
+ /** Subscribe to target lifecycle events (crash / destroyed / detached). */
281
+ onLifecycle(listener) {
282
+ this.lifecycleListeners.push(listener);
283
+ return () => {
284
+ const idx = this.lifecycleListeners.indexOf(listener);
285
+ if (idx !== -1) this.lifecycleListeners.splice(idx, 1);
286
+ };
287
+ }
288
+ /**
289
+ * Connect a client websocket to the first attached target and enable Phase 1
290
+ * domains. Resolves once the socket is open and enable commands are sent.
291
+ */
292
+ async enableDomains() {
293
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
294
+ if (this.enablingPromise) return this.enablingPromise;
295
+ this.enablingPromise = this._doEnableDomains().finally(() => {
296
+ this.enablingPromise = null;
297
+ });
298
+ return this.enablingPromise;
299
+ }
300
+ async _doEnableDomains() {
301
+ const target = (await this.refreshTargets())[0];
302
+ if (!target) throw new Error("No mini-app page attached to the Chii relay yet.");
303
+ let clientUrl = `${this.relayBaseUrl.replace(/^http/, "ws")}/client/${`devtools-mcp-${Date.now()}`}?target=${encodeURIComponent(target.id)}`;
304
+ if (this.totpSecret) {
305
+ const code = generateTotp(this.totpSecret);
306
+ clientUrl += `&at=${encodeURIComponent(code)}`;
307
+ }
308
+ const ws = new WebSocket(clientUrl);
309
+ this.ws = ws;
310
+ await new Promise((resolve, reject) => {
311
+ ws.once("open", () => resolve());
312
+ ws.once("error", (err) => reject(err));
313
+ ws.once("close", (code) => {
314
+ if (code === 4401) reject(/* @__PURE__ */ new Error("relay 인증(TOTP)이 거부됐습니다 (close 4401). 코드가 만료됐을 수 있습니다 — 재연결 시 새 코드가 발급됩니다."));
315
+ });
316
+ });
317
+ this.lastCrashDetectedAt = null;
318
+ this.targetLastSeenAt.clear();
319
+ this.connectionState = "connected";
320
+ ws.on("message", (data) => this.handleMessage(data.toString()));
321
+ ws.on("close", (code) => this.handleDisconnect(code === 4401 ? "relay 인증(TOTP)이 거부돼 연결이 종료됐습니다 (close 4401)" : "relay WebSocket 연결이 끊겼습니다"));
322
+ ws.on("error", (err) => this.handleDisconnect(`relay WebSocket 오류: ${err.message}`));
323
+ this.sendFireAndForget("Runtime.enable");
324
+ this.sendFireAndForget("Network.enable");
325
+ this.sendFireAndForget("DOM.enable");
326
+ this.sendFireAndForget("Page.enable");
327
+ this.sendFireAndForget("Inspector.enable");
328
+ this.sendFireAndForget("Target.setDiscoverTargets", { discover: true });
329
+ this.startHeartbeat(target.id);
330
+ }
331
+ /** Fire-and-forget CDP message (used for `*.enable`, no result awaited). */
332
+ sendFireAndForget(method, params = {}) {
333
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
334
+ const id = this.nextCommandId++;
335
+ this.ws.send(JSON.stringify({
336
+ id,
337
+ method,
338
+ params
339
+ }));
340
+ }
341
+ /**
342
+ * Issue a CDP command and resolve with its result (Phase 2). Rejects on a CDP
343
+ * error frame or when no websocket is open (no page attached yet).
344
+ */
345
+ send(method, params) {
346
+ return this.sendCommand(method, params ?? {});
347
+ }
348
+ /**
349
+ * Issue an arbitrary request→response command over the relay and resolve with
350
+ * its raw result. Both the typed CDP {@link send} and the AIT domain (Phase 3
351
+ * `AIT.*` methods, forwarded over the same Chii channel) build on this.
352
+ *
353
+ * Rejects immediately if the connection is disconnected (fail-fast — no
354
+ * auto-reconnect). Caller should re-run `list_pages` or `enableDomains` to
355
+ * reattach.
356
+ *
357
+ * Times out after `commandTimeoutMs` (default 30s, env
358
+ * `AIT_CDP_COMMAND_TIMEOUT_MS`). On timeout the pending entry is cleaned up
359
+ * and the promise rejects with a descriptive Korean error.
360
+ */
361
+ sendCommand(method, params = {}) {
362
+ if (this.connectionState === "disconnected") return Promise.reject(/* @__PURE__ */ new Error(`relay에 연결되어 있지 않습니다 (${method}). list_pages로 attach 상태를 확인하고 enableDomains()로 재연결하세요.`));
363
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return Promise.reject(/* @__PURE__ */ new Error("No mini-app page attached to the Chii relay yet. Call enableDomains() first."));
364
+ const id = this.nextCommandId++;
365
+ const ws = this.ws;
366
+ const timeoutMs = this.commandTimeoutMs;
367
+ return new Promise((resolve, reject) => {
368
+ const handle = setTimeout(() => {
369
+ this.pending.delete(id);
370
+ reject(/* @__PURE__ */ new Error(`CDP 명령이 타임아웃됐습니다 (${method}, ${timeoutMs}ms). 폰 측 토스 앱이 백그라운드로 내려갔거나 미니앱이 unload됐을 수 있습니다. list_pages로 attach 상태를 확인하세요.`));
371
+ }, timeoutMs);
372
+ this.pending.set(id, {
373
+ resolve: (v) => {
374
+ clearTimeout(handle);
375
+ resolve(v);
376
+ },
377
+ reject: (e) => {
378
+ clearTimeout(handle);
379
+ reject(e);
380
+ }
381
+ });
382
+ ws.send(JSON.stringify({
383
+ id,
384
+ method,
385
+ params
386
+ }));
387
+ });
388
+ }
389
+ /**
390
+ * Called on WebSocket `close` or `error` after a successful connection.
391
+ * Rejects all pending commands and marks the connection as disconnected so
392
+ * subsequent `sendCommand` calls fail fast (no auto-reconnect).
393
+ */
394
+ handleDisconnect(reason) {
395
+ if (this.connectionState === "disconnected") return;
396
+ this.connectionState = "disconnected";
397
+ this.ws = null;
398
+ this.stopHeartbeat();
399
+ const err = /* @__PURE__ */ new Error(`${reason}. list_pages로 attach 상태를 확인하고 enableDomains()로 재연결하세요.`);
400
+ for (const waiter of this.pending.values()) waiter.reject(err);
401
+ this.pending.clear();
402
+ }
403
+ /**
404
+ * Evict a previously active target under the single-attach model.
405
+ * Rejects pending commands with a 'replaced-by-new-attach' reason and emits
406
+ * a 'replaced' lifecycle event. Does NOT clear all targets — only the specific
407
+ * targetId. The caller is responsible for rebuilding the targets map afterwards.
408
+ *
409
+ * The error message uses 'replaced-by-new-attach' so test assertions can match it.
410
+ */
411
+ evictTarget(targetId) {
412
+ const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
413
+ this.targets.delete(targetId);
414
+ this.targetLastSeenAt.delete(targetId);
415
+ const err = /* @__PURE__ */ new Error(`[ait-debug] replaced-by-new-attach — 이전 page 세션이 새 attach로 교체됐습니다 (targetId=${targetId}). list_pages로 현재 attach 상태를 확인하세요.`);
416
+ for (const waiter of this.pending.values()) waiter.reject(err);
417
+ this.pending.clear();
418
+ const event = {
419
+ kind: "replaced",
420
+ targetId,
421
+ detectedAt
422
+ };
423
+ for (const listener of this.lifecycleListeners) try {
424
+ listener(event);
425
+ } catch {}
426
+ }
427
+ /**
428
+ * Handle a page-level crash or target destruction event.
429
+ * Removes the target from the in-memory map, rejects all pending commands,
430
+ * and emits a lifecycle event.
431
+ *
432
+ * @param kind - Event kind: 'crashed' | 'destroyed' | 'detached'
433
+ * @param targetId - The target ID from the event params (may be null for
434
+ * Inspector.targetCrashed which has no targetId in the params).
435
+ */
436
+ handleTargetGone(kind, targetId) {
437
+ const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
438
+ this.lastCrashDetectedAt = Date.now();
439
+ if (targetId !== null) {
440
+ this.targets.delete(targetId);
441
+ this.targetLastSeenAt.delete(targetId);
442
+ if (this.activeTargetId === targetId) this.activeTargetId = null;
443
+ } else {
444
+ this.targets.clear();
445
+ this.targetLastSeenAt.clear();
446
+ this.activeTargetId = null;
447
+ }
448
+ const err = /* @__PURE__ */ new Error(`[ait-debug] ${kind === "crashed" ? "page crash (Inspector.targetCrashed)" : kind === "destroyed" ? "target 종료 (Target.targetDestroyed)" : "target detach (Target.detachedFromTarget)"} 감지됨 — relay에서 제거됐습니다. 새 attach가 필요합니다 (list_pages로 확인 → enableDomains()로 재연결).`);
449
+ for (const waiter of this.pending.values()) waiter.reject(err);
450
+ this.pending.clear();
451
+ const event = {
452
+ kind,
453
+ targetId,
454
+ detectedAt
455
+ };
456
+ for (const listener of this.lifecycleListeners) try {
457
+ listener(event);
458
+ } catch {}
459
+ }
460
+ /**
461
+ * Start the optional CDP heartbeat loop.
462
+ *
463
+ * When `AIT_CDP_HEARTBEAT_MS` is set to a positive integer, every interval
464
+ * we send `Runtime.evaluate({expression: '1'})` to each active target. If
465
+ * the command times out (2 s hard deadline) or errors, we treat the target
466
+ * as dead and call `handleTargetGone`.
467
+ *
468
+ * This is a zombie-detector fallback: cloudflared keeps-alive the tunnel ws
469
+ * even when the phone app has crashed, so the ws-level disconnect (#252) won't
470
+ * fire. The heartbeat catches this gap.
471
+ *
472
+ * Default: OFF. Only activates when `AIT_CDP_HEARTBEAT_MS` is set.
473
+ */
474
+ startHeartbeat(initialTargetId) {
475
+ this.stopHeartbeat();
476
+ const envMs = process.env.AIT_CDP_HEARTBEAT_MS ? Number(process.env.AIT_CDP_HEARTBEAT_MS) : void 0;
477
+ if (envMs === void 0 || !Number.isFinite(envMs) || envMs <= 0) return;
478
+ const PING_TIMEOUT_MS = 2e3;
479
+ this.heartbeatHandle = setInterval(() => {
480
+ const targetIds = this.targets.size > 0 ? [...this.targets.keys()] : [initialTargetId];
481
+ for (const targetId of targetIds) {
482
+ const pingPromise = this.sendCommand("Runtime.evaluate", {
483
+ expression: "1",
484
+ returnByValue: true,
485
+ timeout: PING_TIMEOUT_MS
486
+ });
487
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("heartbeat timeout")), PING_TIMEOUT_MS + 500));
488
+ Promise.race([pingPromise, timeoutPromise]).catch(() => {
489
+ if (this.targets.has(targetId)) this.handleTargetGone("destroyed", targetId);
490
+ });
491
+ }
492
+ }, envMs);
493
+ }
494
+ stopHeartbeat() {
495
+ if (this.heartbeatHandle !== null) {
496
+ clearInterval(this.heartbeatHandle);
497
+ this.heartbeatHandle = null;
498
+ }
499
+ }
500
+ handleMessage(raw) {
501
+ const message = parseInbound(raw);
502
+ if (!message) return;
503
+ if (typeof message.id === "number" && this.pending.has(message.id)) {
504
+ const waiter = this.pending.get(message.id);
505
+ this.pending.delete(message.id);
506
+ if (waiter) if (message.error) waiter.reject(new Error(message.error.message));
507
+ else waiter.resolve(message.result);
508
+ return;
509
+ }
510
+ const now = Date.now();
511
+ let firstMessageSeen = false;
512
+ for (const targetId of this.targets.keys()) {
513
+ if (!this.targetLastSeenAt.has(targetId)) firstMessageSeen = true;
514
+ this.targetLastSeenAt.set(targetId, now);
515
+ }
516
+ if (firstMessageSeen && this.targets.size > 0) this.emitter.emit("target:attached", [...this.targets.values()]);
517
+ if (typeof message.method !== "string") return;
518
+ if (message.method === "Inspector.targetCrashed") {
519
+ this.handleTargetGone("crashed", null);
520
+ return;
521
+ }
522
+ if (message.method === "Target.targetDestroyed") {
523
+ const targetId = isObject(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
524
+ this.handleTargetGone("destroyed", targetId);
525
+ return;
526
+ }
527
+ if (message.method === "Target.detachedFromTarget") {
528
+ const targetId = isObject(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
529
+ this.handleTargetGone("detached", targetId);
530
+ return;
531
+ }
532
+ if (!this.buffers.has(message.method)) return;
533
+ const event = message.method;
534
+ const buffer = this.buffers.get(event);
535
+ if (!buffer) return;
536
+ buffer.push(message.params);
537
+ const cap = event === "Runtime.exceptionThrown" ? EXCEPTION_BUFFER_SIZE : this.bufferSize;
538
+ if (buffer.length > cap) buffer.shift();
539
+ this.emitter.emit(event, message.params);
540
+ }
541
+ getBufferedEvents(event) {
542
+ return this.buffers.get(event) ?? [];
543
+ }
544
+ on(event, listener) {
545
+ this.emitter.on(event, listener);
546
+ return () => this.emitter.off(event, listener);
547
+ }
548
+ /** Close the relay client websocket and reject any in-flight commands. */
549
+ close() {
550
+ const ws = this.ws;
551
+ this.stopHeartbeat();
552
+ this.handleDisconnect("Chii relay connection closed");
553
+ ws?.close();
554
+ }
555
+ };
556
+ //#endregion
557
+ //#region src/mcp/chii-relay.ts
558
+ /**
559
+ * Boots the local Chii relay server.
560
+ *
561
+ * Chii (liriliri/chii) is a chobitsu-based CDP relay that lets non-Chrome
562
+ * WebViews (iOS WKWebView / Android WebView — i.e. the Toss app) expose CDP.
563
+ * The relay accepts a `target` websocket from the phone's injected `target.js`
564
+ * and `client` websockets from CDP frontends (our MCP connection).
565
+ *
566
+ * Node-only: `chii` pulls in Koa + ws. Never bundled into the browser/in-app
567
+ * entries.
568
+ *
569
+ * TOTP auth (relay-side, authoritative gate):
570
+ * When `verifyAuth` is provided, this module gates both inbound surfaces:
571
+ *
572
+ * - HTTP 'request': a listener registered BEFORE `chii.start({server})`.
573
+ * Node's `http.Server` calls listeners in registration order; the first
574
+ * to call `res.end()` wins. Invalid auth → 401 + CORS header + a tiny
575
+ * JSON body (`{"error":"totp-rejected"}`) so a cross-origin script
576
+ * `fetch()` probe can READ the status (issue #478). Valid auth → return
577
+ * without side-effect (chii's Koa handler serves it).
578
+ *
579
+ * - WS 'upgrade': after `chii.start()` has registered chii's own upgrade
580
+ * listener, we take over the upgrade chain (remove chii's listeners,
581
+ * re-dispatch manually). Invalid auth → accept-then-close: complete the
582
+ * handshake via a `noServer` WebSocketServer, then immediately close
583
+ * with code 4401 reason 'totp-rejected' (issue #478). A raw 401 +
584
+ * `socket.destroy()` only ever surfaced as close code 1006 in the
585
+ * browser — indistinguishable from a tunnel failure, which left the
586
+ * env-2 phone UI silent. The explicit dispatch (not listener ordering)
587
+ * is what keeps chii away from rejected sockets: accept-then-close
588
+ * leaves the socket alive, so an order-based early-return would let
589
+ * chii's later listener complete a SECOND handshake on the same socket
590
+ * — an auth bypass. Valid auth → forward to chii's captured listeners.
591
+ *
592
+ * TOTP code transports (issue #466) — two equivalent ways to carry the code:
593
+ * 1. Query param `at=<code>` — used by the daemon-side `/client` connection
594
+ * (`chii-connection.ts` appends it; it holds the secret).
595
+ * 2. Path prefix `/at/<code>/…` — used by the phone-side target. Chii's
596
+ * stock `target.js` derives its WS endpoint from the script `src`
597
+ * (`scriptEl.src.replace('target.js','')`), so the only way for the
598
+ * phone to carry a code is to embed it in the script URL path. The
599
+ * in-app attach injects `https://<host>/at/<code>/target.js`; both the
600
+ * script fetch and the derived `wss://<host>/at/<code>/target/<id>` WS
601
+ * dial then carry the prefix. The listeners below rewrite the prefix
602
+ * into the query form (`rewriteAtPathPrefix`) and MUTATE `req.url`
603
+ * before chii's own handlers (registered later) parse it — chii only
604
+ * ever sees the stripped URL.
605
+ *
606
+ * Threat model: "URL leak" — someone obtains the tunnel URL (Slack paste, QR
607
+ * screenshot, shoulder-surfing) but does not have the shared TOTP secret.
608
+ * Rotating 6-digit code makes the URL stale after 30 s.
609
+ * A determined attacker who extracts the secret from the dogfood bundle can
610
+ * still compute valid codes; that is out of scope (see umbrella CLAUDE.md §4).
611
+ *
612
+ * SECRET-HANDLING: The secret value and computed TOTP codes MUST NOT appear
613
+ * in any log, error message, or process output. `verifyAuth` is a black-box
614
+ * predicate from the caller's perspective; this module only forwards pass/fail.
615
+ */
616
+ const require = createRequire(import.meta.url);
617
+ /**
618
+ * WS keepalive ping interval (ms).
619
+ *
620
+ * Cloudflare proxied connections are dropped after ~100 s of no traffic.
621
+ * 45 s comfortably fits inside that window and lets both the phone-target leg
622
+ * and the daemon-client leg survive idle CDP sessions.
623
+ */
624
+ const DEFAULT_KEEPALIVE_INTERVAL_MS = 45e3;
625
+ /**
626
+ * Loads chii's internal WebSocketServer class and returns it together with a
627
+ * flag indicating whether the real class was found.
628
+ *
629
+ * Returns `null` if the internal path is not resolvable (future chii release
630
+ * changes the layout) — callers skip keepalive gracefully.
631
+ */
632
+ function tryLoadChiiWssClass() {
633
+ try {
634
+ const mod = require("chii/server/lib/WebSocketServer");
635
+ if (typeof mod === "function") return mod;
636
+ } catch {}
637
+ return null;
638
+ }
639
+ /**
640
+ * Calls `chii.start()` and returns the chii `WebSocketServer` instance that
641
+ * was constructed during the call.
642
+ *
643
+ * How: `chii/server/index.js`'s `start()` creates `new WebSocketServer()`
644
+ * where `WebSocketServer` is captured from `require('./lib/WebSocketServer')`
645
+ * at module load time. The class reference is stable, so we can temporarily
646
+ * patch `ChiiWssClass.prototype.start` — which runs *on the instance* —
647
+ * to record `this` before the original `start` runs.
648
+ *
649
+ * The patch is installed before `chii.start()` and removed (via `finally`)
650
+ * immediately after, so concurrent `startChiiRelay` calls nest correctly: each
651
+ * call's patch overrides the previous in the prototype chain for the duration
652
+ * of its own `chii.start()` call, restoring the prior descriptor on exit.
653
+ *
654
+ * If `ChiiWssClass` is null (internal path changed in a future chii release),
655
+ * `chii.start()` runs unpatched and the function returns null — callers skip
656
+ * keepalive gracefully without affecting relay correctness.
657
+ */
658
+ async function startChiiWithCapture(chii, startOptions, ChiiWssClass) {
659
+ if (ChiiWssClass === null) {
660
+ await chii.start(startOptions);
661
+ return null;
662
+ }
663
+ let captured = null;
664
+ const proto = ChiiWssClass.prototype;
665
+ const originalStart = proto.start;
666
+ proto.start = function(server) {
667
+ captured = this;
668
+ return originalStart.call(this, server);
669
+ };
670
+ try {
671
+ await chii.start(startOptions);
672
+ } finally {
673
+ proto.start = originalStart;
674
+ }
675
+ return captured;
676
+ }
677
+ function loadChiiServer() {
678
+ const mod = require("chii");
679
+ if (typeof mod === "object" && mod !== null && "start" in mod && typeof mod.start === "function") return mod;
680
+ throw new Error("chii server module did not expose start()");
681
+ }
682
+ /**
683
+ * Rewrites a `/at/<code>/…` path-prefixed request URL into the equivalent
684
+ * query-based form, e.g.:
685
+ *
686
+ * `/at/123456/target.js` → `/target.js?at=123456`
687
+ * `/at/123456/target/x?url=u` → `/target/x?url=u&at=123456`
688
+ * `/at/123456/` → `/?at=123456`
689
+ *
690
+ * Returns `null` when the URL does not carry the prefix (including an empty
691
+ * code segment) — callers fall back to the unmodified URL and the existing
692
+ * query-based auth path.
693
+ *
694
+ * Pure string surgery — this function knows nothing about secrets or code
695
+ * validity; verification stays inside the caller-provided `verifyAuth`
696
+ * predicate (which parses the query). The raw path segment is appended
697
+ * verbatim to the query: both path segments and query values are
698
+ * percent-decoded exactly once by their consumers, so no re-encoding is
699
+ * needed (TOTP codes are 6 digits and never percent-encoded in practice).
700
+ */
701
+ function rewriteAtPathPrefix(rawUrl) {
702
+ const match = /^\/at\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(rawUrl);
703
+ if (match === null) return null;
704
+ const code = match[1];
705
+ const path = match[2] === void 0 || match[2] === "" ? "/" : match[2];
706
+ const query = match[3] ?? "";
707
+ return `${path}${query}${query === "" ? "?" : "&"}at=${code}`;
708
+ }
709
+ /**
710
+ * Starts the Chii relay and resolves once listening.
711
+ *
712
+ * Default port is 0 (OS-assigned). With port 0 the OS picks a free ephemeral
713
+ * port on every start, so a stale cloudflared orphan holding any particular
714
+ * port cannot cause EADDRINUSE. The resolved `ChiiRelay.port` and `baseUrl`
715
+ * always reflect the actual bound port.
716
+ *
717
+ * chii.start() is called with `server` (our pre-created httpServer) BEFORE
718
+ * httpServer.listen(). This is intentional: chii attaches its Koa handler and
719
+ * WS upgrade listener to the server object, but the actual TCP bind is
720
+ * performed by our httpServer.listen() call below. The `port`/`domain` values
721
+ * passed to chii.start() are used for display/banner purposes inside chii and
722
+ * do not affect which port the server binds. The connection path (clients
723
+ * connecting to `relay.baseUrl`) always uses the post-listen confirmed port.
724
+ */
725
+ async function startChiiRelay(options = {}) {
726
+ const requestedPort = options.port ?? 0;
727
+ const host = options.host ?? "127.0.0.1";
728
+ const { verifyAuth, onAuthReject } = options;
729
+ const keepaliveIntervalMs = options.keepaliveIntervalMs !== void 0 ? options.keepaliveIntervalMs : DEFAULT_KEEPALIVE_INTERVAL_MS;
730
+ const httpServer = createServer();
731
+ const notifyAuthReject = (kind) => {
732
+ if (onAuthReject === void 0) return;
733
+ try {
734
+ onAuthReject({ kind });
735
+ } catch {}
736
+ };
737
+ if (verifyAuth) httpServer.on("request", (req, res) => {
738
+ const rewritten = rewriteAtPathPrefix(req.url ?? "");
739
+ if (rewritten !== null) {
740
+ req.url = rewritten;
741
+ if (!verifyAuth(req)) {
742
+ res.statusCode = 401;
743
+ res.setHeader("Access-Control-Allow-Origin", "*");
744
+ res.setHeader("Content-Type", "application/json");
745
+ res.end(JSON.stringify({ error: RELAY_AUTH_REJECT_REASON }));
746
+ notifyAuthReject("http-request");
747
+ }
748
+ return;
749
+ }
750
+ const pathname = (req.url ?? "").split("?")[0];
751
+ if (pathname === "/targets" || pathname === "/targets/") {
752
+ if (!verifyAuth(req)) {
753
+ res.statusCode = 401;
754
+ res.setHeader("Access-Control-Allow-Origin", "*");
755
+ res.setHeader("Content-Type", "application/json");
756
+ res.end(JSON.stringify({ error: RELAY_AUTH_REJECT_REASON }));
757
+ notifyAuthReject("http-request");
758
+ return;
759
+ }
760
+ return;
761
+ }
762
+ });
763
+ const chiiWssClass = keepaliveIntervalMs > 0 ? tryLoadChiiWssClass() : null;
764
+ const capturedChiiWss = await startChiiWithCapture(loadChiiServer(), {
765
+ server: httpServer,
766
+ domain: `${host}:${requestedPort}`,
767
+ port: requestedPort
768
+ }, chiiWssClass);
769
+ if (verifyAuth) {
770
+ const chiiUpgradeListeners = httpServer.listeners("upgrade");
771
+ httpServer.removeAllListeners("upgrade");
772
+ const rejectWss = new WebSocketServer({ noServer: true });
773
+ httpServer.on("upgrade", (req, socket, head) => {
774
+ const rewritten = rewriteAtPathPrefix(req.url ?? "");
775
+ if (rewritten !== null) req.url = rewritten;
776
+ if (!verifyAuth(req)) {
777
+ rejectWss.handleUpgrade(req, socket, head, (ws) => {
778
+ ws.close(RELAY_AUTH_REJECT_CLOSE_CODE, RELAY_AUTH_REJECT_REASON);
779
+ });
780
+ notifyAuthReject("ws-upgrade");
781
+ return;
782
+ }
783
+ for (const listener of chiiUpgradeListeners) listener(req, socket, head);
784
+ });
785
+ }
786
+ const actualPort = await new Promise((resolve, reject) => {
787
+ httpServer.once("error", reject);
788
+ httpServer.listen(requestedPort, host, () => {
789
+ httpServer.off("error", reject);
790
+ resolve(httpServer.address().port);
791
+ });
792
+ });
793
+ let keepaliveHandle = null;
794
+ if (keepaliveIntervalMs > 0 && capturedChiiWss !== null) {
795
+ const chiiWss = capturedChiiWss;
796
+ keepaliveHandle = setInterval(() => {
797
+ for (const client of chiiWss._wss.clients) if (client.readyState === 1) client.ping();
798
+ }, keepaliveIntervalMs);
799
+ }
800
+ return {
801
+ port: actualPort,
802
+ baseUrl: `http://${host}:${actualPort}`,
803
+ close: () => new Promise((resolve) => {
804
+ if (keepaliveHandle !== null) {
805
+ clearInterval(keepaliveHandle);
806
+ keepaliveHandle = null;
807
+ }
808
+ httpServer.close(() => resolve());
809
+ })
810
+ };
811
+ }
812
+ //#endregion
813
+ //#region src/mcp/debug-server.ts
814
+ /**
815
+ * Factory that constructs a `ChiiCdpConnection` for the given relay base URL.
816
+ *
817
+ * Introduced as a named seam so PR-2 (dual-connection, #348) can defer
818
+ * construction to first-activation time by moving or replacing this call. Since
819
+ * #396 every family (relay included) is constructed lazily on its first
820
+ * `start_debug`, so this is always called from the lazy boot path.
821
+ *
822
+ * The relay base URL is only available after `startChiiRelay()` resolves, so
823
+ * the factory is called right after that point (same as before this refactor).
824
+ */
825
+ function createRelayConnection(relayBaseUrl) {
826
+ return new ChiiCdpConnection({
827
+ relayBaseUrl,
828
+ totpSecret: process.env.AIT_DEBUG_TOTP_SECRET
829
+ });
830
+ }
831
+ /**
832
+ * Boots the relay family (issues #348, #356): starts the Chii relay on an
833
+ * OS-assigned port (with optional TOTP gate), opens a cloudflared quick tunnel
834
+ * to the relay's confirmed port in the background, prints the attach banner,
835
+ * and arms the tunnel health probe. Returns a {@link BootedFamily} whose
836
+ * `getTunnelStatus()` reflects the live tunnel (it flips up once the background
837
+ * tunnel resolves and follows reissues).
838
+ *
839
+ * Booted lazily via the dual router's `bootLazyFor('relay-intoss')` callback
840
+ * (symmetry with {@link bootLocalFamily}), at most once on the first
841
+ * `start_debug({ mode: 'relay-staging' })` (all-lazy, #396 — every relay boot now
842
+ * flows through `switchMode` after the project-local secret load). `relay-live`
843
+ * removed (#665).
844
+ *
845
+ * The relay base URL is only known after `startChiiRelay()` resolves, so the
846
+ * `ChiiCdpConnection` (via {@link createRelayConnection}) is constructed inside
847
+ * this function, after the relay port is confirmed.
848
+ *
849
+ * SECRET-HANDLING: the TOTP secret rides only inside `verifyAuth`; the wssUrl
850
+ * (relay host) is never logged here directly.
851
+ */
852
+ async function bootRelayFamily(options = {}) {
853
+ assertRelayAuthConfigured();
854
+ const relayPort = options.relayPort ?? 0;
855
+ const totpEnabled = options.verifyAuth !== void 0;
856
+ const relay = await startChiiRelay({
857
+ port: relayPort,
858
+ verifyAuth: options.verifyAuth,
859
+ onAuthReject: options.onAuthReject
860
+ });
861
+ logInfo("server.start", {
862
+ port: relay.port,
863
+ totpEnabled
864
+ });
865
+ let tunnel = null;
866
+ let tunnelStatus = makeTunnelStatus(false, null);
867
+ let tunnelProbe = null;
868
+ generateAttachToken();
869
+ startQuickTunnel(relay.port).then((t) => {
870
+ tunnel = t;
871
+ tunnelStatus = makeTunnelStatus(true, t.wssUrl);
872
+ options.onWssUrl?.(t.wssUrl);
873
+ if (t.childPid !== void 0) options.onTunnelChildPid?.(t.childPid);
874
+ logInfo("tunnel.up", { totpEnabled });
875
+ tunnelProbe = startTunnelHealthProbe(t, relay.port, {
876
+ onReissue: (newTunnel) => {
877
+ tunnel = newTunnel;
878
+ tunnelStatus = makeTunnelStatus(true, newTunnel.wssUrl, null, 0);
879
+ options.onWssUrl?.(newTunnel.wssUrl);
880
+ if (newTunnel.childPid !== void 0) options.onTunnelChildPid?.(newTunnel.childPid);
881
+ printAttachBanner({
882
+ wssUrl: newTunnel.wssUrl,
883
+ totpEnabled
884
+ }).then(() => {
885
+ logInfo("tunnel.up", {
886
+ totpEnabled,
887
+ reissued: true
888
+ });
889
+ });
890
+ },
891
+ onPermanentDrop: (droppedAt) => {
892
+ tunnelStatus = makeTunnelStatus(false, null, droppedAt, 3);
893
+ logError("tunnel.down", { msg: `tunnel permanently dropped (${droppedAt}). Restart: npx @ait-co/devtools devtools-mcp` });
894
+ options.onTunnelDown?.();
895
+ }
896
+ });
897
+ return printAttachBanner({
898
+ wssUrl: t.wssUrl,
899
+ totpEnabled
900
+ });
901
+ }, (err) => {
902
+ logError("tunnel.down", { msg: `Failed to open cloudflared quick tunnel: ${err instanceof Error ? err.message : String(err)}. The relay is up locally; attach over the public URL is unavailable until the tunnel starts.` });
903
+ });
904
+ const connection = createRelayConnection(relay.baseUrl);
905
+ return {
906
+ connection,
907
+ relayOrigin: "intoss-webview",
908
+ relayHttpUrl: relay.baseUrl,
909
+ getTunnelStatus: () => tunnelStatus,
910
+ stop() {
911
+ tunnelProbe?.stop();
912
+ tunnel?.stop();
913
+ connection.close();
914
+ relay.close();
915
+ }
916
+ };
917
+ }
918
+ //#endregion
919
+ export { bootRelayFamily, buildRelayVerifyAuth };
920
+
921
+ //# sourceMappingURL=debug-server-DcAKrbnq.js.map