@ait-co/devtools 0.1.117 → 0.1.118

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 (102) hide show
  1. package/dist/attach-orchestrator-BEMGBeWm.js +3 -0
  2. package/dist/attach-orchestrator-BZsqoFjB.js +2797 -0
  3. package/dist/attach-orchestrator-BZsqoFjB.js.map +1 -0
  4. package/dist/attach-orchestrator-CFotueL3.js +1749 -0
  5. package/dist/attach-orchestrator-CFotueL3.js.map +1 -0
  6. package/dist/attach-orchestrator-DEJfLm7V.js +1749 -0
  7. package/dist/attach-orchestrator-DEJfLm7V.js.map +1 -0
  8. package/dist/{cli-CvUNQKqw.js → attach-orchestrator-qFEMBUwb.js} +3 -805
  9. package/dist/attach-orchestrator-qFEMBUwb.js.map +1 -0
  10. package/dist/{bundle-KFs4t-wc.d.ts → bundle-CA1TCXED.d.ts} +1 -1
  11. package/dist/{bundle-KFs4t-wc.d.ts.map → bundle-CA1TCXED.d.ts.map} +1 -1
  12. package/dist/capture-BmK_cBqQ.d.ts +58 -0
  13. package/dist/capture-BmK_cBqQ.d.ts.map +1 -0
  14. package/dist/{cdp-connection-C0AP0tH2.d.ts → cdp-connection-DB2zgthr.d.ts} +1 -1
  15. package/dist/{cdp-connection-C0AP0tH2.d.ts.map → cdp-connection-DB2zgthr.d.ts.map} +1 -1
  16. package/dist/cell-BDFMsPXV.js +3 -0
  17. package/dist/cell-BPWZUm_X.js +85 -0
  18. package/dist/cell-BPWZUm_X.js.map +1 -0
  19. package/dist/cell-Cv3e_qwn.js +84 -0
  20. package/dist/cell-Cv3e_qwn.js.map +1 -0
  21. package/dist/cell-Dp_pDs_j.js +85 -0
  22. package/dist/cell-Dp_pDs_j.js.map +1 -0
  23. package/dist/cell-nrWFeqvG.js +84 -0
  24. package/dist/cell-nrWFeqvG.js.map +1 -0
  25. package/dist/cli-BA1ynNNx.js +1039 -0
  26. package/dist/cli-BA1ynNNx.js.map +1 -0
  27. package/dist/debug-server-BhHVy3XT.js +1191 -0
  28. package/dist/debug-server-BhHVy3XT.js.map +1 -0
  29. package/dist/{debug-server-BvrESnaV.js → debug-server-T8i9_iCc.js} +5 -3
  30. package/dist/debug-server-T8i9_iCc.js.map +1 -0
  31. package/dist/debug-server-krAOy6cl.js +1891 -0
  32. package/dist/debug-server-krAOy6cl.js.map +1 -0
  33. package/dist/{debug-server-jrI9U_f4.js → debug-server-wo18jR4T.js} +429 -2969
  34. package/dist/debug-server-wo18jR4T.js.map +1 -0
  35. package/dist/mcp/cli.js +3 -2
  36. package/dist/mcp/cli.js.map +1 -1
  37. package/dist/mcp/server.js +1 -1
  38. package/dist/panel/index.js +1 -1
  39. package/dist/{pool-htlVnEFl.d.ts → pool-U9FrxEuR.d.ts} +5 -5
  40. package/dist/{pool-htlVnEFl.d.ts.map → pool-U9FrxEuR.d.ts.map} +1 -1
  41. package/dist/relay-factory-DVI7TrX4.js +69 -0
  42. package/dist/relay-factory-DVI7TrX4.js.map +1 -0
  43. package/dist/relay-secret-store-BcVrWwTq.js +153 -0
  44. package/dist/relay-secret-store-BcVrWwTq.js.map +1 -0
  45. package/dist/{relay-secret-store-BHcOmaNK.js → relay-secret-store-BlFEhqwb.js} +1 -1
  46. package/dist/{relay-secret-store-CmqchhR5.js → relay-secret-store-CFc9n0OA.js} +1 -1
  47. package/dist/{relay-secret-store-CmqchhR5.js.map → relay-secret-store-CFc9n0OA.js.map} +1 -1
  48. package/dist/{relay-secret-store-CkA7KNUb.js → relay-secret-store-CmDDfZMh.js} +2 -2
  49. package/dist/{relay-secret-store-CkA7KNUb.js.map → relay-secret-store-CmDDfZMh.js.map} +1 -1
  50. package/dist/relay-secret-store-DNPJKHNs.js +153 -0
  51. package/dist/relay-secret-store-DNPJKHNs.js.map +1 -0
  52. package/dist/relay-url-store-CdA58fgw.js +122 -0
  53. package/dist/relay-url-store-CdA58fgw.js.map +1 -0
  54. package/dist/{relay-url-store-C0qukm3R.js → relay-url-store-CnL2zwbH.js} +2 -2
  55. package/dist/{relay-url-store-C0qukm3R.js.map → relay-url-store-CnL2zwbH.js.map} +1 -1
  56. package/dist/{relay-url-store-NDtEcOE-.js → relay-url-store-DGQ-HPQC.js} +2 -2
  57. package/dist/{relay-url-store-NDtEcOE-.js.map → relay-url-store-DGQ-HPQC.js.map} +1 -1
  58. package/dist/relay-url-store-Dv5HSzwb.js +122 -0
  59. package/dist/relay-url-store-Dv5HSzwb.js.map +1 -0
  60. package/dist/{relay-worker-DWW4vZxU.d.ts → relay-worker-D-3aAyDO.d.ts} +28 -4
  61. package/dist/relay-worker-D-3aAyDO.d.ts.map +1 -0
  62. package/dist/{runtime-BU-iMHz6.d.ts → runtime-D57Rtnsd.d.ts} +1 -1
  63. package/dist/{runtime-BU-iMHz6.d.ts.map → runtime-D57Rtnsd.d.ts.map} +1 -1
  64. package/dist/test-runner/bundle.d.ts +1 -1
  65. package/dist/test-runner/bundle.js +9 -9
  66. package/dist/test-runner/bundle.js.map +1 -1
  67. package/dist/test-runner/capture.d.ts +2 -0
  68. package/dist/test-runner/capture.js +44 -0
  69. package/dist/test-runner/capture.js.map +1 -0
  70. package/dist/test-runner/cli.d.ts +85 -12
  71. package/dist/test-runner/cli.d.ts.map +1 -1
  72. package/dist/test-runner/cli.js +2 -2
  73. package/dist/test-runner/config.d.ts +76 -2
  74. package/dist/test-runner/config.d.ts.map +1 -1
  75. package/dist/test-runner/config.js +4 -2
  76. package/dist/test-runner/config.js.map +1 -1
  77. package/dist/test-runner/pool.d.ts +1 -1
  78. package/dist/test-runner/relay-factory.d.ts +11136 -0
  79. package/dist/test-runner/relay-factory.d.ts.map +1 -0
  80. package/dist/test-runner/relay-factory.js +69 -0
  81. package/dist/test-runner/relay-factory.js.map +1 -0
  82. package/dist/test-runner/relay-worker.d.ts +1 -1
  83. package/dist/test-runner/relay-worker.js +66 -20
  84. package/dist/test-runner/relay-worker.js.map +1 -1
  85. package/dist/test-runner/report.d.ts +106 -0
  86. package/dist/test-runner/report.d.ts.map +1 -0
  87. package/dist/test-runner/report.js +139 -0
  88. package/dist/test-runner/report.js.map +1 -0
  89. package/dist/test-runner/rpc.d.ts +2 -2
  90. package/dist/test-runner/runtime.d.ts +1 -1
  91. package/dist/test-runner/task-graph.d.ts +1 -1
  92. package/dist/{totp-D70zD5tJ.js → totp-0bvlo9Yb.js} +1 -1
  93. package/dist/{totp-D70zD5tJ.js.map → totp-0bvlo9Yb.js.map} +1 -1
  94. package/dist/totp-DfekTBk3.js +211 -0
  95. package/dist/totp-DfekTBk3.js.map +1 -0
  96. package/dist/totp-zGIlDsZS.js +3 -0
  97. package/package.json +1 -1
  98. package/dist/cli-CvUNQKqw.js.map +0 -1
  99. package/dist/debug-server-BvrESnaV.js.map +0 -1
  100. package/dist/debug-server-jrI9U_f4.js.map +0 -1
  101. package/dist/relay-worker-DWW4vZxU.d.ts.map +0 -1
  102. package/dist/totp-D104cJQN.js +0 -3
@@ -0,0 +1,1191 @@
1
+ import { n as buildRelayVerifyAuth, r as generateTotp, t as assertRelayAuthConfigured } from "./totp-DfekTBk3.js";
2
+ import { runTestFilesOverRelay } from "./test-runner/relay-worker.js";
3
+ import { t as createRelayConnectionFactory } from "./relay-factory-DVI7TrX4.js";
4
+ import { writeCaptureArtifacts, writeReportArtifact } from "./test-runner/report.js";
5
+ import { a as startTunnelHealthProbe, i as startQuickTunnel, n as makeTunnelStatus, o as logError, r as printAttachBanner, s as logInfo, t as generateAttachToken } from "./attach-orchestrator-CFotueL3.js";
6
+ import "./cell-nrWFeqvG.js";
7
+ import "./relay-secret-store-BcVrWwTq.js";
8
+ import { createRequire } from "node:module";
9
+ import { glob } from "node:fs/promises";
10
+ import { isAbsolute, resolve } from "node:path";
11
+ import "@modelcontextprotocol/sdk/server/index.js";
12
+ import "@modelcontextprotocol/sdk/server/stdio.js";
13
+ import "@modelcontextprotocol/sdk/types.js";
14
+ import { parseArgs } from "node:util";
15
+ import { EventEmitter } from "node:events";
16
+ import { WebSocket, WebSocketServer } from "ws";
17
+ import { createServer } from "node:http";
18
+ //#region src/test-runner/discover.ts
19
+ /**
20
+ * Test-file discovery shared by the `devtools-test` CLI and the `run_tests`
21
+ * MCP tool, so both expand glob patterns with identical semantics.
22
+ *
23
+ * Uses Node's built-in `fs/promises` `glob` (Node 22+) — no extra dependency,
24
+ * which keeps the MCP daemon install graph lean (a plain glob lib would land in
25
+ * the `npx … devtools-mcp` path for no benefit).
26
+ *
27
+ * Pure Node IO only (`node:fs/promises` + `node:path`) — react-free, so it is
28
+ * safe to import from the MCP daemon graph.
29
+ */
30
+ /**
31
+ * Expands `patterns` (globs or plain paths) into a sorted, de-duplicated list of
32
+ * ABSOLUTE test file paths, resolved relative to `cwd`.
33
+ *
34
+ * A plain (non-glob) path passes through when it matches a real file; a glob
35
+ * expands against `cwd`. Absolute matches are kept as-is; relative matches are
36
+ * resolved against `cwd`. `bundleTestFile` requires an absolute path, so the
37
+ * absolute output feeds it directly.
38
+ *
39
+ * @param patterns Glob patterns or file paths (e.g. `['src/**\/*.ait.test.ts']`).
40
+ * @param cwd Base directory for relative patterns/results.
41
+ * @returns Sorted, de-duplicated absolute file paths. Empty when nothing matches.
42
+ */
43
+ async function discoverTestFiles(patterns, cwd) {
44
+ const out = /* @__PURE__ */ new Set();
45
+ for await (const match of glob(patterns, { cwd })) out.add(isAbsolute(match) ? match : resolve(cwd, match));
46
+ return [...out].sort();
47
+ }
48
+ //#endregion
49
+ //#region src/test-runner/cli.ts
50
+ /**
51
+ * `devtools-test` CLI.
52
+ *
53
+ * Shares test-file discovery with the `run_tests` MCP tool (`discoverTestFiles`)
54
+ * and exposes `runWithConnection` — the pure run core that bundles, injects, and
55
+ * collects each file over a CDP connection. The CLI's `main()` performs a
56
+ * standalone relay attach (boot relay → QR → phone scan → cell inject → run).
57
+ *
58
+ * NOTE: no shebang in this source file — the tsdown entry's `banner` option
59
+ * injects `#!/usr/bin/env node` into the compiled output (same pattern as
60
+ * `src/mcp/cli.ts`).
61
+ */
62
+ const USAGE = `
63
+ devtools-test — run mini-app tests on a real device WebView over the CDP relay
64
+
65
+ USAGE
66
+ devtools-test <glob> [<glob> ...] [options]
67
+
68
+ OPTIONS
69
+ --scheme-url <url> intoss-private:// URL from \`ait deploy --scheme-only\`
70
+ (required for standalone relay attach / env3)
71
+ --timeout <ms> Per-file evaluate timeout in ms (default: 30000)
72
+ --cell-sdk-line <line> SDK line to inject as __AIT_CELL__.sdkLine (2.x|3.x)
73
+ --cell-platform <plat> Platform to inject as __AIT_CELL__.platform
74
+ (mock|ios|android, default: AIT_CELL_PLATFORM env)
75
+ --report-dir <dir> Persist a runner-agnostic report + captures to <dir>
76
+ (report: <sdkLine>.<platform>.json; captures:
77
+ <dir>/.ait-capture/<category>.<sdkLine>.<platform>.json).
78
+ Omitted = nothing saved. Enables console capture.
79
+ --no-qr-stdout Suppress the QR/attach block on stdout (auto-on for
80
+ non-interactive stdout / CI / AIT_NO_QR_STDOUT)
81
+ --headless Disable browser auto-open (text QR only)
82
+ --project-root <dir> Project root for .ait_relay secret lookup
83
+ (default: current working directory)
84
+ --help, -h Show this help message
85
+
86
+ DESCRIPTION
87
+ Boots a Chii relay + cloudflared tunnel, renders a QR code, waits for a real
88
+ device to scan and attach, injects the cell globals (__AIT_CELL__), bundles
89
+ each matched test file with esbuild (SDK imports redirected to window.__sdk),
90
+ injects the bundle into the attached WebView via Runtime.evaluate, and prints
91
+ a summary.
92
+
93
+ With --report-dir, also harvests __AIT_CAPTURE__ console lines and writes a
94
+ runner-agnostic report + per-category capture files so 2.x↔3.0 runs can be
95
+ compared offline.
96
+
97
+ The test files run against the live relay connection started by this process;
98
+ no separate MCP daemon is required.
99
+
100
+ EXAMPLE
101
+ devtools-test 'src/**/*.ait.test.ts' \\
102
+ --scheme-url "intoss-private://..." \\
103
+ --cell-sdk-line 3.x \\
104
+ --cell-platform ios \\
105
+ --report-dir .ait-report \\
106
+ --timeout 60000
107
+
108
+ `.trimStart();
109
+ /**
110
+ * Runs `files` over `connection` and returns the aggregate report.
111
+ * This pure function is the testable core of the CLI (and is what the
112
+ * `run_tests` MCP tool calls against the daemon's attached connection); it is
113
+ * separate from `main()` so tests can call it without spawning a subprocess.
114
+ */
115
+ async function runWithConnection(connection, files, opts) {
116
+ const report = await runTestFilesOverRelay(connection, files, opts);
117
+ if (opts?.printSummary) {
118
+ const { totals } = report;
119
+ process.stdout.write(`\ndevtools-test: ${totals.passed} passed, ${totals.failed} failed, ${totals.skipped} skipped (${report.duration}ms)\n`);
120
+ }
121
+ return report;
122
+ }
123
+ /**
124
+ * Decides whether to suppress the QR/attach block on stdout.
125
+ *
126
+ * Suppress when EITHER the user passed `--no-qr-stdout`, OR stdout is not a TTY
127
+ * / `CI` is set / `AIT_NO_QR_STDOUT` is set (non-interactive — a captured stdout
128
+ * must not leak the relay wss + TOTP `at=` code that the QR block encodes). The
129
+ * suppression is whole-chunk: `attachUrl` AND `relayUrl` ride in the same block.
130
+ *
131
+ * Exported for unit testing.
132
+ */
133
+ function shouldSuppressQr(noQrFlag) {
134
+ return noQrFlag || !process.stdout.isTTY || process.env.CI !== void 0 || process.env.AIT_NO_QR_STDOUT !== void 0;
135
+ }
136
+ /**
137
+ * CLI entry point.
138
+ *
139
+ * Performs a standalone relay attach → run lifecycle, sharing the attach
140
+ * assembly with the Vitest pool via `createRelayConnectionFactory` (single
141
+ * source — no drift):
142
+ *
143
+ * 1. Parse args: globs, --timeout, --cell-sdk-line, --cell-platform,
144
+ * --scheme-url (required for env3), --report-dir, --no-qr-stdout,
145
+ * --headless, --project-root.
146
+ * 2. Discover test files; exit 1 if none.
147
+ * 3. factory.open() — boot relay → render QR (suppressed on non-interactive
148
+ * stdout) → wait for phone → inject cell → enableDomains. Returns the conn.
149
+ * 4. runWithConnection(conn, files, { timeoutMs, collectCaptures, printSummary }).
150
+ * 5. With --report-dir: write the runner-agnostic report + capture files.
151
+ * 6. factory.close(); process.exitCode = failed > 0 ? 1 : 0.
152
+ *
153
+ * The CLI is not a daemon — no lock, router, SSE, or tools_list is needed.
154
+ * Attach timeout exits with code 1; test failures exit with code 1.
155
+ *
156
+ * SECRET-HANDLING: scheme_url / relay wssUrl / TOTP codes are never written to
157
+ * stdout/stderr directly. The QR block (which encodes the TOTP `at=` code) is
158
+ * printed only when stdout is interactive AND not suppressed.
159
+ */
160
+ async function main(argv = process.argv.slice(2)) {
161
+ let parsed;
162
+ try {
163
+ parsed = parseArgs({
164
+ args: argv,
165
+ options: {
166
+ help: {
167
+ type: "boolean",
168
+ short: "h"
169
+ },
170
+ timeout: { type: "string" },
171
+ "scheme-url": { type: "string" },
172
+ "cell-sdk-line": { type: "string" },
173
+ "cell-platform": { type: "string" },
174
+ "report-dir": { type: "string" },
175
+ "no-qr-stdout": { type: "boolean" },
176
+ headless: { type: "boolean" },
177
+ "project-root": { type: "string" }
178
+ },
179
+ allowPositionals: true
180
+ });
181
+ } catch (e) {
182
+ process.stderr.write(`devtools-test: ${e instanceof Error ? e.message : String(e)}\n`);
183
+ process.exitCode = 1;
184
+ return;
185
+ }
186
+ if (parsed.values.help || argv.length === 0) {
187
+ process.stdout.write(USAGE);
188
+ return;
189
+ }
190
+ const vals = parsed.values;
191
+ const rawTimeout = typeof vals.timeout === "string" ? vals.timeout : void 0;
192
+ const timeoutMs = rawTimeout !== void 0 ? parseInt(rawTimeout, 10) : 3e4;
193
+ if (Number.isNaN(timeoutMs) || timeoutMs <= 0) {
194
+ process.stderr.write(`devtools-test: --timeout must be a positive integer\n`);
195
+ process.exitCode = 1;
196
+ return;
197
+ }
198
+ const schemeUrl = typeof vals["scheme-url"] === "string" ? vals["scheme-url"] : "";
199
+ if (schemeUrl === "") {
200
+ process.stderr.write("devtools-test: --scheme-url is required for standalone relay attach.\n Pass the intoss-private:// URL from `ait deploy --scheme-only`.\n");
201
+ process.exitCode = 1;
202
+ return;
203
+ }
204
+ const headless = vals.headless === true;
205
+ const projectRoot = typeof vals["project-root"] === "string" ? vals["project-root"] : process.cwd();
206
+ const reportDir = typeof vals["report-dir"] === "string" ? vals["report-dir"] : void 0;
207
+ const suppressQr = shouldSuppressQr(vals["no-qr-stdout"] === true);
208
+ const cellSdkLine = typeof vals["cell-sdk-line"] === "string" ? vals["cell-sdk-line"] : void 0;
209
+ const cellPlatform = typeof vals["cell-platform"] === "string" ? vals["cell-platform"] : process.env.AIT_CELL_PLATFORM;
210
+ const hasCell = cellSdkLine !== void 0 || cellPlatform !== void 0;
211
+ const cell = {
212
+ sdkLine: cellSdkLine ?? "2.x",
213
+ platform: cellPlatform ?? "mock"
214
+ };
215
+ const globs = parsed.positionals;
216
+ if (globs.length === 0) {
217
+ process.stderr.write(`devtools-test: at least one glob pattern is required\n`);
218
+ process.stdout.write(USAGE);
219
+ process.exitCode = 1;
220
+ return;
221
+ }
222
+ const files = await discoverTestFiles(globs, process.cwd());
223
+ if (files.length === 0) {
224
+ process.stderr.write(`devtools-test: no test files matched ${globs.join(", ")}\n`);
225
+ process.exitCode = 1;
226
+ return;
227
+ }
228
+ process.stderr.write(`devtools-test: found ${files.length} test file(s)\n`);
229
+ if (hasCell) process.stderr.write(`devtools-test: injecting __AIT_CELL__ = ${JSON.stringify(cell)}\n`);
230
+ const factory = createRelayConnectionFactory({
231
+ schemeUrl,
232
+ projectRoot,
233
+ timeoutMs,
234
+ headless,
235
+ cell: hasCell ? cell : void 0,
236
+ onQrContent: (chunks) => {
237
+ if (suppressQr) {
238
+ process.stdout.write("QR suppressed (non-interactive)\n");
239
+ return;
240
+ }
241
+ for (const chunk of chunks) process.stdout.write(`${chunk}\n`);
242
+ }
243
+ });
244
+ let connection;
245
+ try {
246
+ connection = await factory.open();
247
+ } catch (e) {
248
+ process.stderr.write(`devtools-test: ${e instanceof Error ? e.message : String(e)}\n`);
249
+ process.exitCode = 1;
250
+ return;
251
+ }
252
+ let exitCode = 0;
253
+ try {
254
+ const report = await runWithConnection(connection, files, {
255
+ timeoutMs,
256
+ printSummary: true,
257
+ collectCaptures: reportDir !== void 0
258
+ });
259
+ if (reportDir !== void 0) try {
260
+ const reportPath = await writeReportArtifact(report, reportDir, {
261
+ sdkLine: cell.sdkLine,
262
+ platform: cell.platform,
263
+ projectRoot
264
+ });
265
+ process.stderr.write(`devtools-test: wrote report ${reportPath}\n`);
266
+ const capturePaths = await writeCaptureArtifacts(report.captures, `${reportDir}/.ait-capture`, cell);
267
+ if (capturePaths.length > 0) process.stderr.write(`devtools-test: wrote ${capturePaths.length} capture file(s)\n`);
268
+ } catch (e) {
269
+ process.stderr.write(`devtools-test: failed to write report artifacts: ${e instanceof Error ? e.message : String(e)}\n`);
270
+ }
271
+ exitCode = report.totals.failed > 0 ? 1 : 0;
272
+ } finally {
273
+ await factory.close(connection);
274
+ process.exitCode = exitCode;
275
+ }
276
+ }
277
+ if (import.meta.url === new URL(process.argv[1], "file://").href) main().catch((e) => {
278
+ process.stderr.write(`devtools-test: unexpected error: ${e instanceof Error ? e.message : String(e)}\n`);
279
+ process.exitCode = 1;
280
+ });
281
+ //#endregion
282
+ //#region src/shared/relay-auth-close.ts
283
+ /**
284
+ * Shared constants for the relay's named TOTP-auth rejection (issue #478).
285
+ *
286
+ * Before #478 the relay rejected an unauthenticated WebSocket upgrade with a
287
+ * raw `HTTP/1.1 401` + `socket.destroy()`. A handshake aborted that way is
288
+ * indistinguishable from a network failure on the browser side — the
289
+ * WebSocket only ever sees close code 1006, so the phone (env-2 launcher PWA)
290
+ * could not tell "stale TOTP code" apart from "tunnel down" and stayed
291
+ * silent. The fix is accept-then-close: complete the handshake, then close
292
+ * with an application close code that NAMES the rejection.
293
+ *
294
+ * Three parties share this contract:
295
+ * - `src/mcp/chii-relay.ts` (Node) sends the close frame / HTTP error body;
296
+ * - `src/in-app/attach.ts` (browser) observes relay-bound WebSockets and
297
+ * surfaces the code to the launcher shell;
298
+ * - `src/mcp/chii-connection.ts` (Node daemon client) recognises the code
299
+ * as an auth failure on its own `/client` dial (defensive — #439's fresh
300
+ * code mint means it should not normally hit this).
301
+ *
302
+ * This module is intentionally dependency-free (no Node, no DOM) so it is
303
+ * safe to import from both the browser in-app bundle and the MCP daemon
304
+ * bundle.
305
+ *
306
+ * SECRET-HANDLING: these are fixed enum values. The close reason / error body
307
+ * must never grow to carry a secret, a TOTP code, or a host.
308
+ */
309
+ /**
310
+ * WebSocket close code sent by the relay when TOTP auth is rejected.
311
+ *
312
+ * 4000–4999 is the application-reserved range (RFC 6455 §7.4.2); 4401 mirrors
313
+ * HTTP 401 so it reads as "unauthorized" at a glance.
314
+ */
315
+ const RELAY_AUTH_REJECT_CLOSE_CODE = 4401;
316
+ /**
317
+ * Close reason string accompanying {@link RELAY_AUTH_REJECT_CLOSE_CODE}, and
318
+ * the `error` value of the relay's HTTP 401 JSON body. Enum string only —
319
+ * never interpolated with request data.
320
+ */
321
+ const RELAY_AUTH_REJECT_REASON = "totp-rejected";
322
+ //#endregion
323
+ //#region src/mcp/chii-connection.ts
324
+ /**
325
+ * Production `CdpConnection` backed by the local Chii relay.
326
+ *
327
+ * Topology (debug mode):
328
+ * phone target.js --WS--> Chii relay :9100 <--WS-- this connection
329
+ *
330
+ * The phone connects to the relay as a `target`; this module connects as a
331
+ * `client` (the role a CDP frontend would take) so CDP events the page emits
332
+ * (`Runtime.consoleAPICalled`, `Network.*`) flow back here. We buffer recent
333
+ * events in ring buffers the tool layer reads via `getBufferedEvents`.
334
+ *
335
+ * Node-only: imports `ws`. Never bundled into the browser/in-app entries.
336
+ *
337
+ * Attach reliability (#281):
338
+ * `refreshTargets()` emits an internal 'target:attached' event whenever a
339
+ * new target is added to the relay. `waitForFirstTarget()` awaits that event
340
+ * (with a polling-interval fallback) so `start_attach`'s attach wait
341
+ * resolves deterministically rather than racing between polling rounds.
342
+ */
343
+ /** Max events retained per domain ring buffer. */
344
+ const DEFAULT_BUFFER_SIZE = 500;
345
+ function isObject(value) {
346
+ return typeof value === "object" && value !== null;
347
+ }
348
+ function parseInbound(raw) {
349
+ let parsed;
350
+ try {
351
+ parsed = JSON.parse(raw);
352
+ } catch {
353
+ return null;
354
+ }
355
+ if (!isObject(parsed)) return null;
356
+ const message = {};
357
+ if (typeof parsed.id === "number") message.id = parsed.id;
358
+ if (typeof parsed.method === "string") message.method = parsed.method;
359
+ if ("params" in parsed) message.params = parsed.params;
360
+ if ("result" in parsed) message.result = parsed.result;
361
+ if (isObject(parsed.error) && typeof parsed.error.message === "string") message.error = { message: parsed.error.message };
362
+ return message;
363
+ }
364
+ const PHASE_1_EVENTS = [
365
+ "Runtime.consoleAPICalled",
366
+ "Network.requestWillBeSent",
367
+ "Network.responseReceived"
368
+ ];
369
+ /**
370
+ * Ring buffer size for `Runtime.exceptionThrown`.
371
+ *
372
+ * Exceptions are rarer than console messages but each is heavier (stack
373
+ * trace). 50 is generous enough to cover a crash scenario while keeping
374
+ * memory bounded.
375
+ *
376
+ * **Lifecycle note**: the exception buffer intentionally survives `replaced` /
377
+ * `crashed` / `destroyed` lifecycle events — it is NOT cleared on target
378
+ * transitions. Rationale: an exception fired just before a crash is exactly
379
+ * the signal we want to preserve for root-cause analysis. The buffer
380
+ * represents "exceptions seen in this MCP session", not "exceptions in the
381
+ * current page".
382
+ */
383
+ const EXCEPTION_BUFFER_SIZE = 50;
384
+ /** Default per-command timeout if neither option nor env var is set. */
385
+ const DEFAULT_COMMAND_TIMEOUT_MS = 3e4;
386
+ /**
387
+ * Production CDP connection. Polls the relay for the first attached target,
388
+ * opens a client websocket to it, enables Phase 1 domains, and buffers events.
389
+ */
390
+ var ChiiCdpConnection = class {
391
+ /** Authoritative connection kind (issue #348) — relay-backed. */
392
+ kind = "relay";
393
+ relayBaseUrl;
394
+ bufferSize;
395
+ commandTimeoutMs;
396
+ totpSecret;
397
+ emitter = new EventEmitter();
398
+ buffers = /* @__PURE__ */ new Map();
399
+ targets = /* @__PURE__ */ new Map();
400
+ ws = null;
401
+ connectionState = "idle";
402
+ nextCommandId = 1;
403
+ /**
404
+ * The single active target id under the single-attach model.
405
+ * Updated by `refreshTargets()` whenever a non-null target is present.
406
+ * Used to detect a new (different) target attach and evict the previous one.
407
+ */
408
+ activeTargetId = null;
409
+ /** In-flight enableDomains() promise — concurrent callers share it. */
410
+ enablingPromise = null;
411
+ /** Pending request→response commands keyed by CDP message id. */
412
+ pending = /* @__PURE__ */ new Map();
413
+ /**
414
+ * Timestamp (ms since epoch) of the most recent crash/destroy/detach event,
415
+ * or `null` if no crash has been detected since the last `enableDomains()`.
416
+ */
417
+ lastCrashDetectedAt = null;
418
+ /**
419
+ * Per-target last-seen timestamp (ms since epoch). Updated on any inbound
420
+ * CDP message carrying data from a target. Keyed by target id.
421
+ */
422
+ targetLastSeenAt = /* @__PURE__ */ new Map();
423
+ /** Active heartbeat interval handle (only when `AIT_CDP_HEARTBEAT_MS` is set). */
424
+ heartbeatHandle = null;
425
+ /** Lifecycle event listeners (crash / destroyed / detached). */
426
+ lifecycleListeners = [];
427
+ constructor(options) {
428
+ this.relayBaseUrl = options.relayBaseUrl.replace(/\/$/, "");
429
+ this.bufferSize = options.bufferSize ?? DEFAULT_BUFFER_SIZE;
430
+ this.totpSecret = options.totpSecret;
431
+ const envMs = process.env.AIT_CDP_COMMAND_TIMEOUT_MS ? Number(process.env.AIT_CDP_COMMAND_TIMEOUT_MS) : void 0;
432
+ this.commandTimeoutMs = (envMs !== void 0 && Number.isFinite(envMs) && envMs > 0 ? envMs : void 0) ?? options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
433
+ for (const event of PHASE_1_EVENTS) this.buffers.set(event, []);
434
+ this.buffers.set("Runtime.exceptionThrown", []);
435
+ this.emitter.setMaxListeners(0);
436
+ }
437
+ /** Refresh the attached-target list from the relay's `GET /targets`. */
438
+ async refreshTargets() {
439
+ let targetsUrl = `${this.relayBaseUrl}/targets`;
440
+ if (this.totpSecret) {
441
+ const code = generateTotp(this.totpSecret);
442
+ targetsUrl += `?at=${encodeURIComponent(code)}`;
443
+ }
444
+ const res = await fetch(targetsUrl);
445
+ if (!res.ok) throw new Error(`Chii relay /targets returned HTTP ${res.status} ${res.statusText}`);
446
+ const body = await res.json();
447
+ const list = isObject(body) && Array.isArray(body.targets) ? body.targets : [];
448
+ let newestTargetId = null;
449
+ for (const item of list) {
450
+ if (!isObject(item) || typeof item.id !== "string") continue;
451
+ newestTargetId = item.id;
452
+ }
453
+ if (newestTargetId !== null && this.activeTargetId !== null && newestTargetId !== this.activeTargetId) {
454
+ const prevId = this.activeTargetId;
455
+ logInfo("page.detached", { prevTargetId: prevId });
456
+ this.evictTarget(prevId);
457
+ }
458
+ this.targets.clear();
459
+ for (const item of list) {
460
+ if (!isObject(item) || typeof item.id !== "string") continue;
461
+ if (item.id !== newestTargetId) continue;
462
+ this.targets.set(item.id, {
463
+ id: item.id,
464
+ title: typeof item.title === "string" ? item.title : "",
465
+ url: typeof item.url === "string" ? item.url : ""
466
+ });
467
+ }
468
+ if (newestTargetId !== null) this.activeTargetId = newestTargetId;
469
+ else this.activeTargetId = null;
470
+ const result = [...this.targets.values()];
471
+ if (newestTargetId !== null) this.emitter.emit("target:attached", result);
472
+ return result;
473
+ }
474
+ listTargets() {
475
+ return [...this.targets.values()];
476
+ }
477
+ /**
478
+ * Waits until at least one target matching `filterFn` is attached, then
479
+ * resolves with the full target list at that moment.
480
+ *
481
+ * Resolution happens on whichever comes first:
482
+ * (a) a `'target:attached'` event from `refreshTargets()` (triggered by
483
+ * the /targets poll finding a new target), OR
484
+ * (b) a `'target:attached'` event from `handleMessage()` (triggered by
485
+ * the first inbound CDP message from a target — confirms the relay
486
+ * websocket has data from the phone, not just a target entry in the map).
487
+ *
488
+ * This dual-signal approach eliminates the polling race that previously
489
+ * caused `wait_for_attach` to resolve before the first CDP message arrived.
490
+ *
491
+ * Falls back to checking `listTargets()` every `pollIntervalMs` in case the
492
+ * EventEmitter is missed (defensive belt-and-suspenders).
493
+ *
494
+ * @param filterFn - Predicate that the returned targets must satisfy.
495
+ * @param timeoutMs - Reject after this many ms (default 90 000).
496
+ * @param pollIntervalMs - Fallback poll interval (default 500ms).
497
+ */
498
+ waitForFirstTarget(filterFn, timeoutMs = 9e4, pollIntervalMs = 500) {
499
+ const current = this.listTargets();
500
+ if (filterFn(current)) return Promise.resolve(current);
501
+ return new Promise((resolve, reject) => {
502
+ let settled = false;
503
+ let pollHandle = null;
504
+ const settle = (targets) => {
505
+ if (settled) return;
506
+ settled = true;
507
+ clearTimeout(timeoutHandle);
508
+ if (pollHandle !== null) {
509
+ clearInterval(pollHandle);
510
+ pollHandle = null;
511
+ }
512
+ this.emitter.off("target:attached", onAttach);
513
+ resolve(targets);
514
+ };
515
+ const onAttach = (targets) => {
516
+ if (filterFn(targets)) settle(targets);
517
+ };
518
+ const timeoutHandle = setTimeout(() => {
519
+ if (settled) return;
520
+ settled = true;
521
+ if (pollHandle !== null) {
522
+ clearInterval(pollHandle);
523
+ pollHandle = null;
524
+ }
525
+ this.emitter.off("target:attached", onAttach);
526
+ reject(/* @__PURE__ */ new Error(`waitForFirstTarget: 타임아웃 (${timeoutMs}ms) — 폰이 relay에 attach되지 않았습니다.`));
527
+ }, timeoutMs);
528
+ this.emitter.on("target:attached", onAttach);
529
+ pollHandle = setInterval(() => {
530
+ this.refreshTargets().then((targets) => {
531
+ if (filterFn(targets)) settle(targets);
532
+ }, () => {});
533
+ }, pollIntervalMs);
534
+ });
535
+ }
536
+ /**
537
+ * Timestamp (ms since epoch) of the most recent crash/destroy/detach event
538
+ * detected since the last `enableDomains()` call, or `null` if none.
539
+ */
540
+ getLastCrashDetectedAt() {
541
+ return this.lastCrashDetectedAt;
542
+ }
543
+ /**
544
+ * Last-seen timestamp (ms since epoch) for a given target id, or `null` if
545
+ * the target is unknown / no message has been received from it yet.
546
+ */
547
+ getTargetLastSeenAt(targetId) {
548
+ return this.targetLastSeenAt.get(targetId) ?? null;
549
+ }
550
+ /** Subscribe to target lifecycle events (crash / destroyed / detached). */
551
+ onLifecycle(listener) {
552
+ this.lifecycleListeners.push(listener);
553
+ return () => {
554
+ const idx = this.lifecycleListeners.indexOf(listener);
555
+ if (idx !== -1) this.lifecycleListeners.splice(idx, 1);
556
+ };
557
+ }
558
+ /**
559
+ * Connect a client websocket to the first attached target and enable Phase 1
560
+ * domains. Resolves once the socket is open and enable commands are sent.
561
+ */
562
+ async enableDomains() {
563
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
564
+ if (this.enablingPromise) return this.enablingPromise;
565
+ this.enablingPromise = this._doEnableDomains().finally(() => {
566
+ this.enablingPromise = null;
567
+ });
568
+ return this.enablingPromise;
569
+ }
570
+ async _doEnableDomains() {
571
+ const target = (await this.refreshTargets())[0];
572
+ if (!target) throw new Error("No mini-app page attached to the Chii relay yet.");
573
+ let clientUrl = `${this.relayBaseUrl.replace(/^http/, "ws")}/client/${`devtools-mcp-${Date.now()}`}?target=${encodeURIComponent(target.id)}`;
574
+ if (this.totpSecret) {
575
+ const code = generateTotp(this.totpSecret);
576
+ clientUrl += `&at=${encodeURIComponent(code)}`;
577
+ }
578
+ const ws = new WebSocket(clientUrl);
579
+ this.ws = ws;
580
+ await new Promise((resolve, reject) => {
581
+ ws.once("open", () => resolve());
582
+ ws.once("error", (err) => reject(err));
583
+ ws.once("close", (code) => {
584
+ if (code === 4401) reject(/* @__PURE__ */ new Error("relay 인증(TOTP)이 거부됐습니다 (close 4401). 코드가 만료됐을 수 있습니다 — 재연결 시 새 코드가 발급됩니다."));
585
+ });
586
+ });
587
+ this.lastCrashDetectedAt = null;
588
+ this.targetLastSeenAt.clear();
589
+ this.connectionState = "connected";
590
+ ws.on("message", (data) => this.handleMessage(data.toString()));
591
+ ws.on("close", (code) => this.handleDisconnect(code === 4401 ? "relay 인증(TOTP)이 거부돼 연결이 종료됐습니다 (close 4401)" : "relay WebSocket 연결이 끊겼습니다"));
592
+ ws.on("error", (err) => this.handleDisconnect(`relay WebSocket 오류: ${err.message}`));
593
+ this.sendFireAndForget("Runtime.enable");
594
+ this.sendFireAndForget("Network.enable");
595
+ this.sendFireAndForget("DOM.enable");
596
+ this.sendFireAndForget("Page.enable");
597
+ this.sendFireAndForget("Inspector.enable");
598
+ this.sendFireAndForget("Target.setDiscoverTargets", { discover: true });
599
+ this.startHeartbeat(target.id);
600
+ }
601
+ /** Fire-and-forget CDP message (used for `*.enable`, no result awaited). */
602
+ sendFireAndForget(method, params = {}) {
603
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
604
+ const id = this.nextCommandId++;
605
+ this.ws.send(JSON.stringify({
606
+ id,
607
+ method,
608
+ params
609
+ }));
610
+ }
611
+ /**
612
+ * Issue a CDP command and resolve with its result (Phase 2). Rejects on a CDP
613
+ * error frame or when no websocket is open (no page attached yet).
614
+ */
615
+ send(method, params) {
616
+ return this.sendCommand(method, params ?? {});
617
+ }
618
+ /**
619
+ * Issue an arbitrary request→response command over the relay and resolve with
620
+ * its raw result. Both the typed CDP {@link send} and the AIT domain (Phase 3
621
+ * `AIT.*` methods, forwarded over the same Chii channel) build on this.
622
+ *
623
+ * Rejects immediately if the connection is disconnected (fail-fast — no
624
+ * auto-reconnect). Caller should re-run `list_pages` or `enableDomains` to
625
+ * reattach.
626
+ *
627
+ * Times out after `commandTimeoutMs` (default 30s, env
628
+ * `AIT_CDP_COMMAND_TIMEOUT_MS`). On timeout the pending entry is cleaned up
629
+ * and the promise rejects with a descriptive Korean error.
630
+ */
631
+ sendCommand(method, params = {}) {
632
+ if (this.connectionState === "disconnected") return Promise.reject(/* @__PURE__ */ new Error(`relay에 연결되어 있지 않습니다 (${method}). list_pages로 attach 상태를 확인하고 enableDomains()로 재연결하세요.`));
633
+ 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."));
634
+ const id = this.nextCommandId++;
635
+ const ws = this.ws;
636
+ const timeoutMs = this.commandTimeoutMs;
637
+ return new Promise((resolve, reject) => {
638
+ const handle = setTimeout(() => {
639
+ this.pending.delete(id);
640
+ reject(/* @__PURE__ */ new Error(`CDP 명령이 타임아웃됐습니다 (${method}, ${timeoutMs}ms). 폰 측 토스 앱이 백그라운드로 내려갔거나 미니앱이 unload됐을 수 있습니다. list_pages로 attach 상태를 확인하세요.`));
641
+ }, timeoutMs);
642
+ this.pending.set(id, {
643
+ resolve: (v) => {
644
+ clearTimeout(handle);
645
+ resolve(v);
646
+ },
647
+ reject: (e) => {
648
+ clearTimeout(handle);
649
+ reject(e);
650
+ }
651
+ });
652
+ ws.send(JSON.stringify({
653
+ id,
654
+ method,
655
+ params
656
+ }));
657
+ });
658
+ }
659
+ /**
660
+ * Called on WebSocket `close` or `error` after a successful connection.
661
+ * Rejects all pending commands and marks the connection as disconnected so
662
+ * subsequent `sendCommand` calls fail fast (no auto-reconnect).
663
+ */
664
+ handleDisconnect(reason) {
665
+ if (this.connectionState === "disconnected") return;
666
+ this.connectionState = "disconnected";
667
+ this.ws = null;
668
+ this.stopHeartbeat();
669
+ const err = /* @__PURE__ */ new Error(`${reason}. list_pages로 attach 상태를 확인하고 enableDomains()로 재연결하세요.`);
670
+ for (const waiter of this.pending.values()) waiter.reject(err);
671
+ this.pending.clear();
672
+ }
673
+ /**
674
+ * Evict a previously active target under the single-attach model.
675
+ * Rejects pending commands with a 'replaced-by-new-attach' reason and emits
676
+ * a 'replaced' lifecycle event. Does NOT clear all targets — only the specific
677
+ * targetId. The caller is responsible for rebuilding the targets map afterwards.
678
+ *
679
+ * The error message uses 'replaced-by-new-attach' so test assertions can match it.
680
+ */
681
+ evictTarget(targetId) {
682
+ const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
683
+ this.targets.delete(targetId);
684
+ this.targetLastSeenAt.delete(targetId);
685
+ const err = /* @__PURE__ */ new Error(`[ait-debug] replaced-by-new-attach — 이전 page 세션이 새 attach로 교체됐습니다 (targetId=${targetId}). list_pages로 현재 attach 상태를 확인하세요.`);
686
+ for (const waiter of this.pending.values()) waiter.reject(err);
687
+ this.pending.clear();
688
+ const event = {
689
+ kind: "replaced",
690
+ targetId,
691
+ detectedAt
692
+ };
693
+ for (const listener of this.lifecycleListeners) try {
694
+ listener(event);
695
+ } catch {}
696
+ }
697
+ /**
698
+ * Handle a page-level crash or target destruction event.
699
+ * Removes the target from the in-memory map, rejects all pending commands,
700
+ * and emits a lifecycle event.
701
+ *
702
+ * @param kind - Event kind: 'crashed' | 'destroyed' | 'detached'
703
+ * @param targetId - The target ID from the event params (may be null for
704
+ * Inspector.targetCrashed which has no targetId in the params).
705
+ */
706
+ handleTargetGone(kind, targetId) {
707
+ const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
708
+ this.lastCrashDetectedAt = Date.now();
709
+ if (targetId !== null) {
710
+ this.targets.delete(targetId);
711
+ this.targetLastSeenAt.delete(targetId);
712
+ if (this.activeTargetId === targetId) this.activeTargetId = null;
713
+ } else {
714
+ this.targets.clear();
715
+ this.targetLastSeenAt.clear();
716
+ this.activeTargetId = null;
717
+ }
718
+ 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()로 재연결).`);
719
+ for (const waiter of this.pending.values()) waiter.reject(err);
720
+ this.pending.clear();
721
+ const event = {
722
+ kind,
723
+ targetId,
724
+ detectedAt
725
+ };
726
+ for (const listener of this.lifecycleListeners) try {
727
+ listener(event);
728
+ } catch {}
729
+ }
730
+ /**
731
+ * Start the optional CDP heartbeat loop.
732
+ *
733
+ * When `AIT_CDP_HEARTBEAT_MS` is set to a positive integer, every interval
734
+ * we send `Runtime.evaluate({expression: '1'})` to each active target. If
735
+ * the command times out (2 s hard deadline) or errors, we treat the target
736
+ * as dead and call `handleTargetGone`.
737
+ *
738
+ * This is a zombie-detector fallback: cloudflared keeps-alive the tunnel ws
739
+ * even when the phone app has crashed, so the ws-level disconnect (#252) won't
740
+ * fire. The heartbeat catches this gap.
741
+ *
742
+ * Default: OFF. Only activates when `AIT_CDP_HEARTBEAT_MS` is set.
743
+ */
744
+ startHeartbeat(initialTargetId) {
745
+ this.stopHeartbeat();
746
+ const envMs = process.env.AIT_CDP_HEARTBEAT_MS ? Number(process.env.AIT_CDP_HEARTBEAT_MS) : void 0;
747
+ if (envMs === void 0 || !Number.isFinite(envMs) || envMs <= 0) return;
748
+ const PING_TIMEOUT_MS = 2e3;
749
+ this.heartbeatHandle = setInterval(() => {
750
+ const targetIds = this.targets.size > 0 ? [...this.targets.keys()] : [initialTargetId];
751
+ for (const targetId of targetIds) {
752
+ const pingPromise = this.sendCommand("Runtime.evaluate", {
753
+ expression: "1",
754
+ returnByValue: true,
755
+ timeout: PING_TIMEOUT_MS
756
+ });
757
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("heartbeat timeout")), PING_TIMEOUT_MS + 500));
758
+ Promise.race([pingPromise, timeoutPromise]).catch(() => {
759
+ if (this.targets.has(targetId)) this.handleTargetGone("destroyed", targetId);
760
+ });
761
+ }
762
+ }, envMs);
763
+ }
764
+ stopHeartbeat() {
765
+ if (this.heartbeatHandle !== null) {
766
+ clearInterval(this.heartbeatHandle);
767
+ this.heartbeatHandle = null;
768
+ }
769
+ }
770
+ handleMessage(raw) {
771
+ const message = parseInbound(raw);
772
+ if (!message) return;
773
+ if (typeof message.id === "number" && this.pending.has(message.id)) {
774
+ const waiter = this.pending.get(message.id);
775
+ this.pending.delete(message.id);
776
+ if (waiter) if (message.error) waiter.reject(new Error(message.error.message));
777
+ else waiter.resolve(message.result);
778
+ return;
779
+ }
780
+ const now = Date.now();
781
+ let firstMessageSeen = false;
782
+ for (const targetId of this.targets.keys()) {
783
+ if (!this.targetLastSeenAt.has(targetId)) firstMessageSeen = true;
784
+ this.targetLastSeenAt.set(targetId, now);
785
+ }
786
+ if (firstMessageSeen && this.targets.size > 0) this.emitter.emit("target:attached", [...this.targets.values()]);
787
+ if (typeof message.method !== "string") return;
788
+ if (message.method === "Inspector.targetCrashed") {
789
+ this.handleTargetGone("crashed", null);
790
+ return;
791
+ }
792
+ if (message.method === "Target.targetDestroyed") {
793
+ const targetId = isObject(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
794
+ this.handleTargetGone("destroyed", targetId);
795
+ return;
796
+ }
797
+ if (message.method === "Target.detachedFromTarget") {
798
+ const targetId = isObject(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
799
+ this.handleTargetGone("detached", targetId);
800
+ return;
801
+ }
802
+ if (!this.buffers.has(message.method)) return;
803
+ const event = message.method;
804
+ const buffer = this.buffers.get(event);
805
+ if (!buffer) return;
806
+ buffer.push(message.params);
807
+ const cap = event === "Runtime.exceptionThrown" ? EXCEPTION_BUFFER_SIZE : this.bufferSize;
808
+ if (buffer.length > cap) buffer.shift();
809
+ this.emitter.emit(event, message.params);
810
+ }
811
+ getBufferedEvents(event) {
812
+ return this.buffers.get(event) ?? [];
813
+ }
814
+ on(event, listener) {
815
+ this.emitter.on(event, listener);
816
+ return () => this.emitter.off(event, listener);
817
+ }
818
+ /** Close the relay client websocket and reject any in-flight commands. */
819
+ close() {
820
+ const ws = this.ws;
821
+ this.stopHeartbeat();
822
+ this.handleDisconnect("Chii relay connection closed");
823
+ ws?.close();
824
+ }
825
+ };
826
+ //#endregion
827
+ //#region src/mcp/chii-relay.ts
828
+ /**
829
+ * Boots the local Chii relay server.
830
+ *
831
+ * Chii (liriliri/chii) is a chobitsu-based CDP relay that lets non-Chrome
832
+ * WebViews (iOS WKWebView / Android WebView — i.e. the Toss app) expose CDP.
833
+ * The relay accepts a `target` websocket from the phone's injected `target.js`
834
+ * and `client` websockets from CDP frontends (our MCP connection).
835
+ *
836
+ * Node-only: `chii` pulls in Koa + ws. Never bundled into the browser/in-app
837
+ * entries.
838
+ *
839
+ * TOTP auth (relay-side, authoritative gate):
840
+ * When `verifyAuth` is provided, this module gates both inbound surfaces:
841
+ *
842
+ * - HTTP 'request': a listener registered BEFORE `chii.start({server})`.
843
+ * Node's `http.Server` calls listeners in registration order; the first
844
+ * to call `res.end()` wins. Invalid auth → 401 + CORS header + a tiny
845
+ * JSON body (`{"error":"totp-rejected"}`) so a cross-origin script
846
+ * `fetch()` probe can READ the status (issue #478). Valid auth → return
847
+ * without side-effect (chii's Koa handler serves it).
848
+ *
849
+ * - WS 'upgrade': after `chii.start()` has registered chii's own upgrade
850
+ * listener, we take over the upgrade chain (remove chii's listeners,
851
+ * re-dispatch manually). Invalid auth → accept-then-close: complete the
852
+ * handshake via a `noServer` WebSocketServer, then immediately close
853
+ * with code 4401 reason 'totp-rejected' (issue #478). A raw 401 +
854
+ * `socket.destroy()` only ever surfaced as close code 1006 in the
855
+ * browser — indistinguishable from a tunnel failure, which left the
856
+ * env-2 phone UI silent. The explicit dispatch (not listener ordering)
857
+ * is what keeps chii away from rejected sockets: accept-then-close
858
+ * leaves the socket alive, so an order-based early-return would let
859
+ * chii's later listener complete a SECOND handshake on the same socket
860
+ * — an auth bypass. Valid auth → forward to chii's captured listeners.
861
+ *
862
+ * TOTP code transports (issue #466) — two equivalent ways to carry the code:
863
+ * 1. Query param `at=<code>` — used by the daemon-side `/client` connection
864
+ * (`chii-connection.ts` appends it; it holds the secret).
865
+ * 2. Path prefix `/at/<code>/…` — used by the phone-side target. Chii's
866
+ * stock `target.js` derives its WS endpoint from the script `src`
867
+ * (`scriptEl.src.replace('target.js','')`), so the only way for the
868
+ * phone to carry a code is to embed it in the script URL path. The
869
+ * in-app attach injects `https://<host>/at/<code>/target.js`; both the
870
+ * script fetch and the derived `wss://<host>/at/<code>/target/<id>` WS
871
+ * dial then carry the prefix. The listeners below rewrite the prefix
872
+ * into the query form (`rewriteAtPathPrefix`) and MUTATE `req.url`
873
+ * before chii's own handlers (registered later) parse it — chii only
874
+ * ever sees the stripped URL.
875
+ *
876
+ * Threat model: "URL leak" — someone obtains the tunnel URL (Slack paste, QR
877
+ * screenshot, shoulder-surfing) but does not have the shared TOTP secret.
878
+ * Rotating 6-digit code makes the URL stale after 30 s.
879
+ * A determined attacker who extracts the secret from the dogfood bundle can
880
+ * still compute valid codes; that is out of scope (see umbrella CLAUDE.md §4).
881
+ *
882
+ * SECRET-HANDLING: The secret value and computed TOTP codes MUST NOT appear
883
+ * in any log, error message, or process output. `verifyAuth` is a black-box
884
+ * predicate from the caller's perspective; this module only forwards pass/fail.
885
+ */
886
+ const require = createRequire(import.meta.url);
887
+ /**
888
+ * WS keepalive ping interval (ms).
889
+ *
890
+ * Cloudflare proxied connections are dropped after ~100 s of no traffic.
891
+ * 45 s comfortably fits inside that window and lets both the phone-target leg
892
+ * and the daemon-client leg survive idle CDP sessions.
893
+ */
894
+ const DEFAULT_KEEPALIVE_INTERVAL_MS = 45e3;
895
+ /**
896
+ * Loads chii's internal WebSocketServer class and returns it together with a
897
+ * flag indicating whether the real class was found.
898
+ *
899
+ * Returns `null` if the internal path is not resolvable (future chii release
900
+ * changes the layout) — callers skip keepalive gracefully.
901
+ */
902
+ function tryLoadChiiWssClass() {
903
+ try {
904
+ const mod = require("chii/server/lib/WebSocketServer");
905
+ if (typeof mod === "function") return mod;
906
+ } catch {}
907
+ return null;
908
+ }
909
+ /**
910
+ * Calls `chii.start()` and returns the chii `WebSocketServer` instance that
911
+ * was constructed during the call.
912
+ *
913
+ * How: `chii/server/index.js`'s `start()` creates `new WebSocketServer()`
914
+ * where `WebSocketServer` is captured from `require('./lib/WebSocketServer')`
915
+ * at module load time. The class reference is stable, so we can temporarily
916
+ * patch `ChiiWssClass.prototype.start` — which runs *on the instance* —
917
+ * to record `this` before the original `start` runs.
918
+ *
919
+ * The patch is installed before `chii.start()` and removed (via `finally`)
920
+ * immediately after, so concurrent `startChiiRelay` calls nest correctly: each
921
+ * call's patch overrides the previous in the prototype chain for the duration
922
+ * of its own `chii.start()` call, restoring the prior descriptor on exit.
923
+ *
924
+ * If `ChiiWssClass` is null (internal path changed in a future chii release),
925
+ * `chii.start()` runs unpatched and the function returns null — callers skip
926
+ * keepalive gracefully without affecting relay correctness.
927
+ */
928
+ async function startChiiWithCapture(chii, startOptions, ChiiWssClass) {
929
+ if (ChiiWssClass === null) {
930
+ await chii.start(startOptions);
931
+ return null;
932
+ }
933
+ let captured = null;
934
+ const proto = ChiiWssClass.prototype;
935
+ const originalStart = proto.start;
936
+ proto.start = function(server) {
937
+ captured = this;
938
+ return originalStart.call(this, server);
939
+ };
940
+ try {
941
+ await chii.start(startOptions);
942
+ } finally {
943
+ proto.start = originalStart;
944
+ }
945
+ return captured;
946
+ }
947
+ function loadChiiServer() {
948
+ const mod = require("chii");
949
+ if (typeof mod === "object" && mod !== null && "start" in mod && typeof mod.start === "function") return mod;
950
+ throw new Error("chii server module did not expose start()");
951
+ }
952
+ /**
953
+ * Rewrites a `/at/<code>/…` path-prefixed request URL into the equivalent
954
+ * query-based form, e.g.:
955
+ *
956
+ * `/at/123456/target.js` → `/target.js?at=123456`
957
+ * `/at/123456/target/x?url=u` → `/target/x?url=u&at=123456`
958
+ * `/at/123456/` → `/?at=123456`
959
+ *
960
+ * Returns `null` when the URL does not carry the prefix (including an empty
961
+ * code segment) — callers fall back to the unmodified URL and the existing
962
+ * query-based auth path.
963
+ *
964
+ * Pure string surgery — this function knows nothing about secrets or code
965
+ * validity; verification stays inside the caller-provided `verifyAuth`
966
+ * predicate (which parses the query). The raw path segment is appended
967
+ * verbatim to the query: both path segments and query values are
968
+ * percent-decoded exactly once by their consumers, so no re-encoding is
969
+ * needed (TOTP codes are 6 digits and never percent-encoded in practice).
970
+ */
971
+ function rewriteAtPathPrefix(rawUrl) {
972
+ const match = /^\/at\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(rawUrl);
973
+ if (match === null) return null;
974
+ const code = match[1];
975
+ const path = match[2] === void 0 || match[2] === "" ? "/" : match[2];
976
+ const query = match[3] ?? "";
977
+ return `${path}${query}${query === "" ? "?" : "&"}at=${code}`;
978
+ }
979
+ /**
980
+ * Starts the Chii relay and resolves once listening.
981
+ *
982
+ * Default port is 0 (OS-assigned). With port 0 the OS picks a free ephemeral
983
+ * port on every start, so a stale cloudflared orphan holding any particular
984
+ * port cannot cause EADDRINUSE. The resolved `ChiiRelay.port` and `baseUrl`
985
+ * always reflect the actual bound port.
986
+ *
987
+ * chii.start() is called with `server` (our pre-created httpServer) BEFORE
988
+ * httpServer.listen(). This is intentional: chii attaches its Koa handler and
989
+ * WS upgrade listener to the server object, but the actual TCP bind is
990
+ * performed by our httpServer.listen() call below. The `port`/`domain` values
991
+ * passed to chii.start() are used for display/banner purposes inside chii and
992
+ * do not affect which port the server binds. The connection path (clients
993
+ * connecting to `relay.baseUrl`) always uses the post-listen confirmed port.
994
+ */
995
+ async function startChiiRelay(options = {}) {
996
+ const requestedPort = options.port ?? 0;
997
+ const host = options.host ?? "127.0.0.1";
998
+ const { verifyAuth, onAuthReject } = options;
999
+ const keepaliveIntervalMs = options.keepaliveIntervalMs !== void 0 ? options.keepaliveIntervalMs : DEFAULT_KEEPALIVE_INTERVAL_MS;
1000
+ const httpServer = createServer();
1001
+ const notifyAuthReject = (kind) => {
1002
+ if (onAuthReject === void 0) return;
1003
+ try {
1004
+ onAuthReject({ kind });
1005
+ } catch {}
1006
+ };
1007
+ if (verifyAuth) httpServer.on("request", (req, res) => {
1008
+ const rewritten = rewriteAtPathPrefix(req.url ?? "");
1009
+ if (rewritten !== null) {
1010
+ req.url = rewritten;
1011
+ if (!verifyAuth(req)) {
1012
+ res.statusCode = 401;
1013
+ res.setHeader("Access-Control-Allow-Origin", "*");
1014
+ res.setHeader("Content-Type", "application/json");
1015
+ res.end(JSON.stringify({ error: RELAY_AUTH_REJECT_REASON }));
1016
+ notifyAuthReject("http-request");
1017
+ }
1018
+ return;
1019
+ }
1020
+ const pathname = (req.url ?? "").split("?")[0];
1021
+ if (pathname === "/targets" || pathname === "/targets/") {
1022
+ if (!verifyAuth(req)) {
1023
+ res.statusCode = 401;
1024
+ res.setHeader("Access-Control-Allow-Origin", "*");
1025
+ res.setHeader("Content-Type", "application/json");
1026
+ res.end(JSON.stringify({ error: RELAY_AUTH_REJECT_REASON }));
1027
+ notifyAuthReject("http-request");
1028
+ return;
1029
+ }
1030
+ return;
1031
+ }
1032
+ });
1033
+ const chiiWssClass = keepaliveIntervalMs > 0 ? tryLoadChiiWssClass() : null;
1034
+ const capturedChiiWss = await startChiiWithCapture(loadChiiServer(), {
1035
+ server: httpServer,
1036
+ domain: `${host}:${requestedPort}`,
1037
+ port: requestedPort
1038
+ }, chiiWssClass);
1039
+ if (verifyAuth) {
1040
+ const chiiUpgradeListeners = httpServer.listeners("upgrade");
1041
+ httpServer.removeAllListeners("upgrade");
1042
+ const rejectWss = new WebSocketServer({ noServer: true });
1043
+ httpServer.on("upgrade", (req, socket, head) => {
1044
+ const rewritten = rewriteAtPathPrefix(req.url ?? "");
1045
+ if (rewritten !== null) req.url = rewritten;
1046
+ if (!verifyAuth(req)) {
1047
+ rejectWss.handleUpgrade(req, socket, head, (ws) => {
1048
+ ws.close(RELAY_AUTH_REJECT_CLOSE_CODE, RELAY_AUTH_REJECT_REASON);
1049
+ });
1050
+ notifyAuthReject("ws-upgrade");
1051
+ return;
1052
+ }
1053
+ for (const listener of chiiUpgradeListeners) listener(req, socket, head);
1054
+ });
1055
+ }
1056
+ const actualPort = await new Promise((resolve, reject) => {
1057
+ httpServer.once("error", reject);
1058
+ httpServer.listen(requestedPort, host, () => {
1059
+ httpServer.off("error", reject);
1060
+ resolve(httpServer.address().port);
1061
+ });
1062
+ });
1063
+ let keepaliveHandle = null;
1064
+ if (keepaliveIntervalMs > 0 && capturedChiiWss !== null) {
1065
+ const chiiWss = capturedChiiWss;
1066
+ keepaliveHandle = setInterval(() => {
1067
+ for (const client of chiiWss._wss.clients) if (client.readyState === 1) client.ping();
1068
+ }, keepaliveIntervalMs);
1069
+ }
1070
+ return {
1071
+ port: actualPort,
1072
+ baseUrl: `http://${host}:${actualPort}`,
1073
+ close: () => new Promise((resolve) => {
1074
+ if (keepaliveHandle !== null) {
1075
+ clearInterval(keepaliveHandle);
1076
+ keepaliveHandle = null;
1077
+ }
1078
+ httpServer.close(() => resolve());
1079
+ })
1080
+ };
1081
+ }
1082
+ //#endregion
1083
+ //#region src/mcp/debug-server.ts
1084
+ /**
1085
+ * Factory that constructs a `ChiiCdpConnection` for the given relay base URL.
1086
+ *
1087
+ * Introduced as a named seam so PR-2 (dual-connection, #348) can defer
1088
+ * construction to first-activation time by moving or replacing this call. Since
1089
+ * #396 every family (relay included) is constructed lazily on its first
1090
+ * `start_debug`, so this is always called from the lazy boot path.
1091
+ *
1092
+ * The relay base URL is only available after `startChiiRelay()` resolves, so
1093
+ * the factory is called right after that point (same as before this refactor).
1094
+ */
1095
+ function createRelayConnection(relayBaseUrl) {
1096
+ return new ChiiCdpConnection({
1097
+ relayBaseUrl,
1098
+ totpSecret: process.env.AIT_DEBUG_TOTP_SECRET
1099
+ });
1100
+ }
1101
+ /**
1102
+ * Boots the relay family (issues #348, #356): starts the Chii relay on an
1103
+ * OS-assigned port (with optional TOTP gate), opens a cloudflared quick tunnel
1104
+ * to the relay's confirmed port in the background, prints the attach banner,
1105
+ * and arms the tunnel health probe. Returns a {@link BootedFamily} whose
1106
+ * `getTunnelStatus()` reflects the live tunnel (it flips up once the background
1107
+ * tunnel resolves and follows reissues).
1108
+ *
1109
+ * Booted lazily via the dual router's `bootLazyFor('relay-intoss')` callback
1110
+ * (symmetry with {@link bootLocalFamily}), at most once on the first
1111
+ * `start_debug({ mode: 'relay-staging' })` (all-lazy, #396 — every relay boot now
1112
+ * flows through `switchMode` after the project-local secret load). `relay-live`
1113
+ * removed (#665).
1114
+ *
1115
+ * The relay base URL is only known after `startChiiRelay()` resolves, so the
1116
+ * `ChiiCdpConnection` (via {@link createRelayConnection}) is constructed inside
1117
+ * this function, after the relay port is confirmed.
1118
+ *
1119
+ * SECRET-HANDLING: the TOTP secret rides only inside `verifyAuth`; the wssUrl
1120
+ * (relay host) is never logged here directly.
1121
+ */
1122
+ async function bootRelayFamily(options = {}) {
1123
+ assertRelayAuthConfigured();
1124
+ const relayPort = options.relayPort ?? 0;
1125
+ const totpEnabled = options.verifyAuth !== void 0;
1126
+ const relay = await startChiiRelay({
1127
+ port: relayPort,
1128
+ verifyAuth: options.verifyAuth,
1129
+ onAuthReject: options.onAuthReject
1130
+ });
1131
+ logInfo("server.start", {
1132
+ port: relay.port,
1133
+ totpEnabled
1134
+ });
1135
+ let tunnel = null;
1136
+ let tunnelStatus = makeTunnelStatus(false, null);
1137
+ let tunnelProbe = null;
1138
+ generateAttachToken();
1139
+ startQuickTunnel(relay.port).then((t) => {
1140
+ tunnel = t;
1141
+ tunnelStatus = makeTunnelStatus(true, t.wssUrl);
1142
+ options.onWssUrl?.(t.wssUrl);
1143
+ if (t.childPid !== void 0) options.onTunnelChildPid?.(t.childPid);
1144
+ logInfo("tunnel.up", { totpEnabled });
1145
+ tunnelProbe = startTunnelHealthProbe(t, relay.port, {
1146
+ onReissue: (newTunnel) => {
1147
+ tunnel = newTunnel;
1148
+ tunnelStatus = makeTunnelStatus(true, newTunnel.wssUrl, null, 0);
1149
+ options.onWssUrl?.(newTunnel.wssUrl);
1150
+ if (newTunnel.childPid !== void 0) options.onTunnelChildPid?.(newTunnel.childPid);
1151
+ printAttachBanner({
1152
+ wssUrl: newTunnel.wssUrl,
1153
+ totpEnabled
1154
+ }).then(() => {
1155
+ logInfo("tunnel.up", {
1156
+ totpEnabled,
1157
+ reissued: true
1158
+ });
1159
+ });
1160
+ },
1161
+ onPermanentDrop: (droppedAt) => {
1162
+ tunnelStatus = makeTunnelStatus(false, null, droppedAt, 3);
1163
+ logError("tunnel.down", { msg: `tunnel permanently dropped (${droppedAt}). Restart: npx @ait-co/devtools devtools-mcp` });
1164
+ options.onTunnelDown?.();
1165
+ }
1166
+ });
1167
+ return printAttachBanner({
1168
+ wssUrl: t.wssUrl,
1169
+ totpEnabled
1170
+ });
1171
+ }, (err) => {
1172
+ 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.` });
1173
+ });
1174
+ const connection = createRelayConnection(relay.baseUrl);
1175
+ return {
1176
+ connection,
1177
+ relayOrigin: "intoss-webview",
1178
+ relayHttpUrl: relay.baseUrl,
1179
+ getTunnelStatus: () => tunnelStatus,
1180
+ stop() {
1181
+ tunnelProbe?.stop();
1182
+ tunnel?.stop();
1183
+ connection.close();
1184
+ relay.close();
1185
+ }
1186
+ };
1187
+ }
1188
+ //#endregion
1189
+ export { bootRelayFamily, buildRelayVerifyAuth };
1190
+
1191
+ //# sourceMappingURL=debug-server-BhHVy3XT.js.map