@ait-co/devtools 0.1.122 → 0.1.124

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 (78) hide show
  1. package/dist/{attach-orchestrator-EnZEr4Uu.js → attach-orchestrator-CpE0dMew.js} +2 -2
  2. package/dist/{attach-orchestrator-EnZEr4Uu.js.map → attach-orchestrator-CpE0dMew.js.map} +1 -1
  3. package/dist/{cell-3bIG9538.js → cell-Ba9lCI3B.js} +2 -2
  4. package/dist/{cell-3bIG9538.js.map → cell-Ba9lCI3B.js.map} +1 -1
  5. package/dist/{cell-Cad-vi7X.js → cell-CX92lDI0.js} +3 -3
  6. package/dist/{cell-CgKUkDxY.js.map → cell-CX92lDI0.js.map} +1 -1
  7. package/dist/{cell-CgKUkDxY.js → cell-D0dJSGHi.js} +2 -2
  8. package/dist/{cell-Cad-vi7X.js.map → cell-D0dJSGHi.js.map} +1 -1
  9. package/dist/{debug-server-D79E3hTa.js → debug-server-B3W_0Ejf.js} +6 -226
  10. package/dist/debug-server-B3W_0Ejf.js.map +1 -0
  11. package/dist/{debug-server-CF-1s3ks.js → debug-server-BDfeWytB.js} +6 -944
  12. package/dist/debug-server-BDfeWytB.js.map +1 -0
  13. package/dist/{debug-server-D_28CxC1.js → debug-server-BzzNkETg.js} +6 -6
  14. package/dist/{debug-server-D_28CxC1.js.map → debug-server-BzzNkETg.js.map} +1 -1
  15. package/dist/mcp/cli.js +8214 -4
  16. package/dist/mcp/cli.js.map +1 -1
  17. package/dist/mcp/server.js +1 -1
  18. package/dist/panel/index.js +1 -1
  19. package/dist/{qr-http-server-BsWlOA85.js → qr-http-server-BH0UFeUn.js} +11 -1
  20. package/dist/{qr-http-server-gHBd-z7T.js.map → qr-http-server-BH0UFeUn.js.map} +1 -1
  21. package/dist/{qr-http-server-UBV2qUEd.js → qr-http-server-Bo8LMOJQ.js} +11 -1
  22. package/dist/{qr-http-server-BJjw0hDr.js.map → qr-http-server-Bo8LMOJQ.js.map} +1 -1
  23. package/dist/{qr-http-server-CrVKno9V.cjs → qr-http-server-Bt_RAxFn.cjs} +11 -1
  24. package/dist/{qr-http-server-BpTvfeku.cjs.map → qr-http-server-Bt_RAxFn.cjs.map} +1 -1
  25. package/dist/{qr-http-server-CKbtqvKy.js → qr-http-server-CrGohOwC.js} +11 -1
  26. package/dist/{qr-http-server-CKbtqvKy.js.map → qr-http-server-CrGohOwC.js.map} +1 -1
  27. package/dist/{qr-http-server-BpTvfeku.cjs → qr-http-server-DM2R25jP.cjs} +11 -1
  28. package/dist/{qr-http-server-CrVKno9V.cjs.map → qr-http-server-DM2R25jP.cjs.map} +1 -1
  29. package/dist/{qr-http-server-BJjw0hDr.js → qr-http-server-s1iW_5VQ.js} +11 -1
  30. package/dist/{qr-http-server-BsWlOA85.js.map → qr-http-server-s1iW_5VQ.js.map} +1 -1
  31. package/dist/{relay-factory-BBnZM-an.js → relay-factory-CqY264j0.js} +22 -5
  32. package/dist/relay-factory-CqY264j0.js.map +1 -0
  33. package/dist/{relay-secret-store-BJjoxes1.js → relay-secret-store-CFc9n0OA.js} +1 -1
  34. package/dist/{relay-secret-store-BJjoxes1.js.map → relay-secret-store-CFc9n0OA.js.map} +1 -1
  35. package/dist/{relay-secret-store-CtK1eqoV.js → relay-secret-store-DhzAnnj-.js} +3 -3
  36. package/dist/{relay-secret-store-CtK1eqoV.js.map → relay-secret-store-DhzAnnj-.js.map} +1 -1
  37. package/dist/{relay-url-store-D3H067u0.js → relay-url-store-CwKT7i04.js} +2 -2
  38. package/dist/{relay-url-store-D3H067u0.js.map → relay-url-store-CwKT7i04.js.map} +1 -1
  39. package/dist/{relay-url-store-uyVNe-Az.js → relay-url-store-DGQ-HPQC.js} +2 -2
  40. package/dist/{relay-url-store-uyVNe-Az.js.map → relay-url-store-DGQ-HPQC.js.map} +1 -1
  41. package/dist/test-runner/bin.d.ts +2 -0
  42. package/dist/{cli-CaJ-vnBj.js → test-runner/bin.js} +49 -9
  43. package/dist/test-runner/bin.js.map +1 -0
  44. package/dist/test-runner/config.js +1 -1
  45. package/dist/test-runner/relay-factory.js +21 -4
  46. package/dist/test-runner/relay-factory.js.map +1 -1
  47. package/dist/totp-D1pulXLa.js +3 -0
  48. package/dist/{totp-0bvlo9Yb.js → totp-WY6l0ysP.js} +1 -1
  49. package/dist/{totp-0bvlo9Yb.js.map → totp-WY6l0ysP.js.map} +1 -1
  50. package/dist/{tunnel-B7U5k1xa.js → tunnel-BFwOSwT4.js} +2 -2
  51. package/dist/{tunnel-B7U5k1xa.js.map → tunnel-BFwOSwT4.js.map} +1 -1
  52. package/dist/{tunnel-C-cgMnyY.cjs → tunnel-DyEV6WwL.cjs} +2 -2
  53. package/dist/{tunnel-C-cgMnyY.cjs.map → tunnel-DyEV6WwL.cjs.map} +1 -1
  54. package/dist/unplugin/index.cjs +1 -1
  55. package/dist/unplugin/index.js +1 -1
  56. package/dist/unplugin/tunnel.cjs +1 -1
  57. package/dist/unplugin/tunnel.js +1 -1
  58. package/package.json +2 -2
  59. package/dist/attach-orchestrator-BYMCSPjf.js +0 -2797
  60. package/dist/attach-orchestrator-BYMCSPjf.js.map +0 -1
  61. package/dist/attach-orchestrator-LOjvsE9R.js +0 -3
  62. package/dist/cell-Bfbke0cT.js +0 -3
  63. package/dist/cell-SKNUQTr8.js +0 -85
  64. package/dist/cell-SKNUQTr8.js.map +0 -1
  65. package/dist/cli-CaJ-vnBj.js.map +0 -1
  66. package/dist/debug-server-CF-1s3ks.js.map +0 -1
  67. package/dist/debug-server-D79E3hTa.js.map +0 -1
  68. package/dist/debug-server-IVaJ9vHH.js +0 -4278
  69. package/dist/debug-server-IVaJ9vHH.js.map +0 -1
  70. package/dist/qr-http-server-BpcDt-cp.js +0 -3
  71. package/dist/qr-http-server-UBV2qUEd.js.map +0 -1
  72. package/dist/qr-http-server-gHBd-z7T.js +0 -1506
  73. package/dist/relay-factory-BBnZM-an.js.map +0 -1
  74. package/dist/relay-secret-store-BIM_0y18.js +0 -3
  75. package/dist/test-runner/cli.d.ts +0 -547
  76. package/dist/test-runner/cli.d.ts.map +0 -1
  77. package/dist/test-runner/cli.js +0 -3
  78. package/dist/totp-zGIlDsZS.js +0 -3
@@ -1,2797 +0,0 @@
1
- #!/usr/bin/env node
2
- import { i as generateTotp } from "./totp-0bvlo9Yb.js";
3
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
- import { homedir } from "node:os";
5
- import { join } from "node:path";
6
- import { randomBytes } from "node:crypto";
7
- import { Tunnel, bin, install } from "cloudflared";
8
- //#region src/shared/parent-watcher.ts
9
- /**
10
- * Shared parent-PID watcher — used by both the MCP debug daemon and the
11
- * unplugin tunnel path to self-terminate when the parent process (e.g. Claude
12
- * Code, vite) has died or been reparented without sending SIGTERM/SIGHUP.
13
- *
14
- * Intentionally react-free and Node-stdlib-only so this module is safe to
15
- * import from the MCP daemon bundle (`dist/mcp/cli.js`) without violating the
16
- * install-graph invariant.
17
- */
18
- /**
19
- * Returns `true` when the given PID refers to a running process.
20
- *
21
- * Uses `process.kill(pid, 0)` — a no-op signal that succeeds when the process
22
- * exists and we have permission to signal it; throws ESRCH when it doesn't exist.
23
- */
24
- function isPidAlive$1(pid) {
25
- try {
26
- process.kill(pid, 0);
27
- return true;
28
- } catch (err) {
29
- if (err.code === "EPERM") return true;
30
- return false;
31
- }
32
- }
33
- /**
34
- * Starts a periodic watcher that detects when the parent process (e.g. Claude
35
- * Code) has died without sending SIGTERM/SIGHUP, and calls `onOrphaned` so the
36
- * daemon can self-terminate rather than running as a zombie.
37
- *
38
- * Mirrors the `startAttachWatcher` pattern: `setInterval`-based, returns
39
- * `{ stop(): void }`, injectable deps for testability.
40
- *
41
- * @param onOrphaned - Called once when the parent is gone.
42
- * @param opts.intervalMs - Poll interval in milliseconds (default 5 000).
43
- * @param opts.initialPpid - Parent PID to watch (default `process.ppid`).
44
- * @param opts.isAlive - Predicate to test if a PID is running (default `isPidAlive`).
45
- * @param opts.getPpid - Supplier of current ppid (default `() => process.ppid`).
46
- * Detects ppid changes as well as death.
47
- * @param opts.log - Logger (default `process.stderr.write`).
48
- *
49
- * @returns `stop` — call during shutdown to clear the interval.
50
- */
51
- function startParentWatcher(onOrphaned, opts) {
52
- const { intervalMs = 5e3, initialPpid = process.ppid, isAlive = isPidAlive$1, getPpid = () => process.ppid, log = (msg) => process.stderr.write(msg) } = opts ?? {};
53
- if (initialPpid <= 1) {
54
- log("[ait-debug] parent-pid watcher: no parent to watch (ppid<=1), skipping\n");
55
- return { stop() {} };
56
- }
57
- let fired = false;
58
- const handle = setInterval(() => {
59
- if (fired) return;
60
- const currentPpid = getPpid();
61
- if (currentPpid !== initialPpid || !isAlive(initialPpid)) {
62
- fired = true;
63
- clearInterval(handle);
64
- log(`[ait-debug] parent-pid watcher: parent PID ${initialPpid} is gone (currentPpid=${currentPpid}) — shutting down\n`);
65
- onOrphaned();
66
- }
67
- }, intervalMs);
68
- return { stop() {
69
- clearInterval(handle);
70
- } };
71
- }
72
- /**
73
- * Starts a periodic watchdog that calls `onExpired` once after `maxAgeMs`
74
- * milliseconds have elapsed since the watchdog was created.
75
- *
76
- * Motivation (issue #571): cloudflared quick-tunnel lifetimes are finite (a
77
- * few hours). A daemon that has been running for days will have outlived its
78
- * tunnel regardless of whether the tunnel process exited cleanly. This watchdog
79
- * caps the daemon's maximum age and forces a fresh start so the tunnel is
80
- * replaced before it silently expires.
81
- *
82
- * @param onExpired - Called once when the maximum age is reached. The caller
83
- * should call `shutdown()` then `process.exit(0)`.
84
- * @param opts.maxAgeMs - Maximum daemon lifetime in ms. Default 6 h.
85
- * @param opts.intervalMs - Check interval in ms. Default 60 000 (1 min).
86
- * @param opts.now - Time source (injectable for tests). Default `Date.now`.
87
- *
88
- * @returns `stop` — call during shutdown to clear the interval.
89
- */
90
- function startMaxAgeWatchdog(onExpired, opts = {}) {
91
- const { maxAgeMs = 360 * 60 * 1e3, intervalMs = 6e4, now = () => Date.now() } = opts;
92
- const startedAt = now();
93
- let fired = false;
94
- const handle = setInterval(() => {
95
- if (fired) return;
96
- if (now() - startedAt >= maxAgeMs) {
97
- fired = true;
98
- clearInterval(handle);
99
- onExpired();
100
- }
101
- }, intervalMs);
102
- return { stop() {
103
- clearInterval(handle);
104
- } };
105
- }
106
- //#endregion
107
- //#region src/mcp/deeplink.ts
108
- /**
109
- * URL of the AITC Sandbox launcher PWA.
110
- *
111
- * Declared here (not imported from `src/unplugin/tunnel.ts`) to respect the
112
- * mcp → unplugin layering boundary. unplugin/tunnel.ts declares its own copy
113
- * for the same reason — keep the two in sync when the URL changes.
114
- */
115
- const LAUNCHER_URL = "https://devtools.aitc.dev/launcher/";
116
- /**
117
- * Builds a launcher PWA deep-link for env-2 MCP-attach (issue #378).
118
- *
119
- * The launcher at {@link LAUNCHER_URL} renders tunnelUrl in a full-viewport
120
- * iframe. `&debug=1&relay=<wssUrl>` is forwarded onto the iframe src so the
121
- * framed page's in-app debug gate (Layer C) is satisfied and a Chii target.js
122
- * is injected. `&at=<totpCode>` is added only when a code is provided (same
123
- * conditional as {@link buildDeepLinkAttachUrl}).
124
- *
125
- * When `opts.name` is given (non-blank), it is added as `&name=` so the
126
- * launcher partner bar shows the app name instead of the generic default (#498).
127
- * When `opts.icon` is an absolute https:// URL, it is added as `&icon=` so the
128
- * launcher can render an icon next to the title (#498).
129
- *
130
- * Unlike `buildDeepLinkAttachUrl` (which splices onto a non-special scheme URL
131
- * via raw string manipulation), this function uses WHATWG `encodeURIComponent`
132
- * because the target is a standard `https:` URL.
133
- *
134
- * SECRET-HANDLING: `totpCode` (when provided) is placed into the `at=` param
135
- * only — never logged or returned separately. Callers must NOT log the result
136
- * of this function to stdout/stderr.
137
- *
138
- * @param tunnelUrl - The `https://*.trycloudflare.com` app tunnel URL
139
- * (`AIT_TUNNEL_BASE_URL`). This is the URL the launcher frames.
140
- * @param wssUrl - The `wss://` relay URL the framed page will attach to.
141
- * @param totpCode - Optional current TOTP code (6 digits). When provided, it
142
- * is appended as `at=<totpCode>`. Must be computed at call time — it rotates
143
- * every 30 s. Omit when TOTP is disabled.
144
- * @param opts - Optional app identity hints: `name`, `icon`, and `selfdebug`
145
- * (#498, #543).
146
- * @returns The launcher deep-link URL with `?url=<enc>&debug=1&relay=<enc>
147
- * [&at=<code>][&name=<enc>][&icon=<enc>][&selfdebug=1]` params.
148
- */
149
- function buildLauncherAttachUrl(tunnelUrl, wssUrl, totpCode, opts) {
150
- let url = `${LAUNCHER_URL}?url=${encodeURIComponent(tunnelUrl)}&debug=1&relay=${encodeURIComponent(wssUrl)}`;
151
- if (totpCode !== void 0 && totpCode !== "") url += `&at=${encodeURIComponent(totpCode)}`;
152
- if (opts?.name !== void 0 && opts.name.trim() !== "") url += `&name=${encodeURIComponent(opts.name.trim())}`;
153
- if (opts?.icon !== void 0) {
154
- let iconParsed;
155
- try {
156
- iconParsed = new URL(opts.icon);
157
- } catch {
158
- iconParsed = null;
159
- }
160
- if (iconParsed?.protocol === "https:") url += `&icon=${encodeURIComponent(opts.icon)}`;
161
- }
162
- if (opts?.selfdebug === true) url += "&selfdebug=1";
163
- return url;
164
- }
165
- /**
166
- * Build a self-attaching dog-food deep-link.
167
- *
168
- * `ait deploy --scheme-only` prints an `intoss-private://…?_deploymentId=<uuid>`
169
- * URL that opens a dog-food bundle on a phone. The in-app debug gate
170
- * (`src/in-app/gate.ts`) auto-attaches when the entry URL also carries
171
- * `debug=1` and `relay=<wss-url>`. This helper splices those params (plus
172
- * `at=<code>` when TOTP is enabled) into the scheme URL; rendering the result
173
- * as a QR code and scanning it with the phone camera opens the mini-app and
174
- * attaches it to the live Chii relay. QR is the single entry path — it needs
175
- * no USB cable, platform CLI, or driver, and works the same on iOS/Android.
176
- *
177
- * The Toss app propagates extra query params from the entry deep link into the
178
- * mini-app WebView's `location.search` (confirmed behavior), so the gate reads
179
- * them at attach time.
180
- *
181
- * TOTP `at=` param:
182
- * When a TOTP secret is active, `buildDeepLinkAttachUrl` accepts an optional
183
- * `totpCode` argument and splices `at=<code>` alongside `debug` and `relay`.
184
- * The code must be computed by the caller at call time — do NOT pre-compute
185
- * and cache it, because the 30-second window expires quickly. The in-app gate
186
- * (`src/in-app/gate.ts` Layer C) validates this code against the baked secret.
187
- *
188
- * Why not `URL`/`URLSearchParams`: `intoss-private:` is a non-special scheme.
189
- * The WHATWG `URL` parser treats such schemes opaquely (no host/path/query
190
- * decomposition you can rely on across runtimes), so query manipulation via
191
- * `url.searchParams` is not portable here. We splice the query string directly
192
- * on the raw string instead, which keeps the scheme, authority, path, and any
193
- * pre-existing params (notably `_deploymentId`) byte-for-byte intact.
194
- */
195
- /**
196
- * Suspicious/generic authority values that indicate a malformed or placeholder
197
- * scheme URL. These are host strings that will almost certainly cause the Toss
198
- * app to fail with "bundle not found" silently.
199
- *
200
- * The expected form from `ait deploy --scheme-only` is:
201
- * intoss-private://<appName>?_deploymentId=<uuid>
202
- * where `<appName>` is a non-generic string like `aitc-sdk-example`.
203
- */
204
- const SUSPICIOUS_AUTHORITIES = new Set([
205
- "",
206
- "web",
207
- "localhost",
208
- "127.0.0.1",
209
- "app"
210
- ]);
211
- /**
212
- * Validates the authority (host) portion of a scheme URL.
213
- *
214
- * Returns a warning message if the authority is missing or looks like a
215
- * placeholder, or `null` if the authority looks valid.
216
- *
217
- * Expected form: `intoss-private://<appName>?_deploymentId=<uuid>`
218
- * The authority must be a non-empty, non-generic app name (e.g. `aitc-sdk-example`).
219
- */
220
- function validateSchemeAuthority(schemeUrl) {
221
- const afterScheme = schemeUrl.replace(/^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//, "");
222
- if (afterScheme === schemeUrl) return "scheme_url does not look like a scheme URL (expected `intoss-private://<appName>?_deploymentId=<uuid>`). Use the URL printed by `ait deploy --scheme-only`.";
223
- const authorityEnd = afterScheme.search(/[/?#]/);
224
- const authority = authorityEnd === -1 ? afterScheme : afterScheme.slice(0, authorityEnd);
225
- if (SUSPICIOUS_AUTHORITIES.has(authority.toLowerCase())) return `scheme_url authority ${authority === "" ? "(empty)" : `"${authority}"`} looks like a placeholder. Expected an app name like \`intoss-private://aitc-sdk-example?_deploymentId=<uuid>\`. Use the URL printed by \`ait deploy --scheme-only\` — it includes the correct app name as the host.`;
226
- return null;
227
- }
228
- function stripExisting(query, key) {
229
- if (query === "") return "";
230
- return query.split("&").filter((pair) => pair !== "" && pair.split("=")[0] !== key).join("&");
231
- }
232
- /**
233
- * Splices `debug=1`, `relay=<wssUrl>`, and (optionally) `at=<totpCode>` into a
234
- * scheme URL's query string, preserving everything else (scheme, authority,
235
- * path, hash, and the existing `_deploymentId` param). If any of the spliced
236
- * params is already present it is replaced so the helper is idempotent.
237
- *
238
- * @param schemeUrl - The `intoss-private://…?_deploymentId=<uuid>` URL printed
239
- * by `ait deploy --scheme-only`. Must already carry `_deploymentId` (Layer B
240
- * of the gate); this helper does not invent one.
241
- * @param wssUrl - The live relay URL (`wss://…trycloudflare.com`) from the
242
- * running debug MCP server's quick tunnel.
243
- * @param totpCode - Optional current TOTP code (6 digits). When provided, it
244
- * is spliced as `at=<totpCode>`. Must be computed at call time — it rotates
245
- * every 30 s. Pass `undefined` or omit when TOTP is disabled.
246
- * @returns The same URL with `debug=1&relay=<encoded wssUrl>[&at=<totpCode>]`
247
- * appended.
248
- * @throws If `wssUrl` is not a `wss:` URL (the gate rejects anything else, so
249
- * producing such a link would be a silent dead end).
250
- */
251
- function buildDeepLinkAttachUrl(schemeUrl, wssUrl, totpCode) {
252
- let relay;
253
- try {
254
- relay = new URL(wssUrl);
255
- } catch {
256
- throw new Error(`relay URL is not a valid URL: ${wssUrl}`);
257
- }
258
- if (relay.protocol !== "wss:") throw new Error(`relay URL must use the wss: scheme, got ${relay.protocol} (${wssUrl})`);
259
- const hashIndex = schemeUrl.indexOf("#");
260
- const hash = hashIndex === -1 ? "" : schemeUrl.slice(hashIndex);
261
- const beforeHash = hashIndex === -1 ? schemeUrl : schemeUrl.slice(0, hashIndex);
262
- const queryIndex = beforeHash.indexOf("?");
263
- const base = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
264
- let query = queryIndex === -1 ? "" : beforeHash.slice(queryIndex + 1);
265
- const appended = [["debug", "1"], ["relay", wssUrl]];
266
- if (totpCode !== void 0 && totpCode !== "") appended.push(["at", totpCode]);
267
- query = stripExisting(query, "at");
268
- for (const [key] of appended) query = stripExisting(query, key);
269
- for (const [key, value] of appended) {
270
- const pair = `${key}=${encodeURIComponent(value)}`;
271
- query = query === "" ? pair : `${query}&${pair}`;
272
- }
273
- return `${base}?${query}${hash}`;
274
- }
275
- //#endregion
276
- //#region src/mcp/errors.ts
277
- /**
278
- * 한국어 한 줄 "원인 + 다음 행동" 포맷으로 에러 결과를 빌드한다.
279
- *
280
- * @param message - 사용자에게 보여줄 에러 본문 (원인 + 다음 행동 포함).
281
- */
282
- function mcpError(message) {
283
- return {
284
- content: [{
285
- type: "text",
286
- text: message
287
- }],
288
- isError: true
289
- };
290
- }
291
- /**
292
- * Tier A/B 환경 불일치 거부 메시지.
293
- *
294
- * @param toolName - 거부된 tool 이름.
295
- * @param requiredEnv - 해당 tool이 요구하는 환경 ('mock' | 'relay').
296
- * @param currentEnv - 현재 세션 환경.
297
- * @param reason - 환경이 결정된 근거를 나타내는 파생 문자열
298
- * (예: `derived:kind=relay,liveIntent=true`).
299
- */
300
- function tierRejectionError(toolName, requiredEnv, currentEnv, reason) {
301
- return mcpError(`${`${toolName}은 ${requiredEnv === "relay" ? "relay (실기기 연결)" : "mock (로컬 브라우저)"} 환경에서만 사용할 수 있습니다. 현재 환경: ${currentEnv === "relay" ? "relay" : "mock"} (${reason}). ${requiredEnv === "relay" ? "relay로 전환하려면 MCP_ENV=relay 설정 후 서버를 재시작하고 start_attach → QR 스캔으로 실기기를 attach하세요." : "mock으로 전환하려면 MCP_ENV=mock 설정 후 서버를 재시작하세요."}`}\n\n${`tool ${toolName} is available only in ${requiredEnv}. Current environment is ${currentEnv} (${reason}).`}`);
302
- }
303
- /**
304
- * 상태 1: tunnel 미가동 — cloudflared 터널이 아직 뜨지 않았다.
305
- *
306
- * `start_attach` 호출 시 tunnel.up === false 인 경우.
307
- */
308
- function tunnelDownError() {
309
- return mcpError("cloudflared 터널이 안 떠 있습니다. MCP 서버를 재시작하거나 잠시 후 list_pages로 터널 상태를 다시 확인하세요.");
310
- }
311
- /**
312
- * 상태 2: page 미attach — 터널은 살아 있으나 아직 페이지가 연결되지 않았다.
313
- *
314
- * enableDomains()가 "No mini-app page attached" 에러를 던질 때.
315
- */
316
- function pageMissingError(toolName) {
317
- return mcpError(`${toolName ? `${toolName}: ` : ""}페이지가 attach 안 됨. dog-food 번들 배포 후 start_attach를 호출해 QR 생성 + attach까지 진행하세요: \`ait deploy --scheme-only\` → \`start_attach(scheme_url)\` → QR 스캔.`);
318
- }
319
- /**
320
- * 상태 3: page crash — 연결됐던 페이지가 crash/destroy됐다.
321
- *
322
- * chii-connection 이 'replaced-by-new-attach' / 'targetCrashed' / 'targetDestroyed' 를
323
- * 던질 때 이 메시지를 사용한다.
324
- */
325
- function pageCrashError(toolName) {
326
- return mcpError(`${toolName ? `${toolName}: ` : ""}페이지가 crash됐습니다. 토스 앱을 재실행한 뒤 start_attach → QR 스캔으로 재attach하세요.`);
327
- }
328
- /**
329
- * 상태 4: SDK 부재 — window.__sdkCall이 주입되지 않았다.
330
- *
331
- * call_sdk 호출 시 브리지가 없을 때. 같은 "브리지 부재"라도 다음 행동은
332
- * connection 종류에 따라 정반대다 (issue #360):
333
- * - relay(`--target` 없는 intoss / env-2): dog-food 빌드가 아니다 → dog-food
334
- * 채널로 재배포 후 QR 재스캔.
335
- * - local(`--target=local`, env 1 로컬 브라우저): 재배포가 아니라 dev 서버를
336
- * `pnpm dev`로 띄웠는지 + unplugin alias가 `@apps-in-toss/web-framework`를
337
- * devtools mock으로 resolve하는지 확인. dev 빌드면 `import.meta.env.DEV`
338
- * 경로로 `window.__sdkCall`이 자동 설치된다.
339
- *
340
- * `isLocal`이 생략되면 relay 안내(이전 동작)를 유지한다.
341
- */
342
- function sdkAbsentError(toolName, isLocal = false) {
343
- const prefix = toolName ? `${toolName}: ` : "";
344
- if (isLocal) return mcpError(`${prefix}window.__sdkCall이 주입되지 않았습니다 (로컬 dev 브리지 부재). sdk-example을 \`pnpm dev\`로 띄웠는지, 그리고 unplugin alias가 \`@apps-in-toss/web-framework\`를 devtools mock으로 resolve하는지 확인하세요. dev 빌드(\`import.meta.env.DEV\`)면 \`window.__sdkCall\`이 자동 설치됩니다.`);
345
- return mcpError(`${prefix}window.__sdkCall이 주입되지 않았습니다 (dog-food 빌드가 아닙니다). dog-food 채널(intoss-private)로 재배포 후 QR을 다시 스캔하세요: \`ait build && aitcc app deploy\`.`);
346
- }
347
- /**
348
- * relay WebSocket 연결이 끊겼을 때 — 크래시가 아닌 네트워크/프로세스 종료.
349
- */
350
- function relayDisconnectError(toolName) {
351
- return mcpError(`${toolName ? `${toolName}: ` : ""}relay 연결이 끊겼습니다. list_pages로 상태를 확인하고, 필요하면 앱을 재실행 후 재attach하세요.`);
352
- }
353
- /**
354
- * CDP/AIT 명령 중 발생한 예외를 4상태로 분류해 적절한 에러 결과를 반환한다.
355
- *
356
- * - SDK 부재 패턴 (`window.__sdkCall is not available`) → sdkAbsentError
357
- * - crash 패턴 (`replaced-by-new-attach`, `targetCrashed`, `targetDestroyed`) → pageCrashError
358
- * - 연결 끊김 패턴 (`relay에 연결되어 있지 않습니다`, `relay WebSocket`) → relayDisconnectError
359
- * - 그 외 (일반 에러) → 원본 메시지를 포함한 mcpError
360
- */
361
- function classifyToolError(err, toolName, isLocal = false) {
362
- const message = err instanceof Error ? err.message : String(err);
363
- if (message.startsWith("tunnel-down:") || message.includes("터널이 안 떠 있습니다")) return tunnelDownError();
364
- if (message.startsWith("sdk-absent:") || message.includes("__sdkCall이 주입되지 않았습니다") || message.includes("window.__sdkCall is not available") || message.includes("__sdkCall") && message.includes("not available")) return sdkAbsentError(toolName, isLocal);
365
- if (message.includes("replaced-by-new-attach") || message.includes("targetCrashed") || message.includes("targetDestroyed") || message.includes("detachedFromTarget")) return pageCrashError(toolName);
366
- if (message.includes("relay에 연결되어 있지 않습니다") || message.includes("relay WebSocket")) return relayDisconnectError(toolName);
367
- return mcpError(`${toolName} 실패: ${message}\nlist_pages로 미니앱이 relay에 attach됐는지 확인하세요.`);
368
- }
369
- //#endregion
370
- //#region src/mcp/log.ts
371
- /**
372
- * Allowed field keys that may pass through to a log line.
373
- * Unknown keys are dropped. Values are still redact-scanned.
374
- */
375
- const ALLOWED_KEYS = new Set([
376
- "ts",
377
- "level",
378
- "event",
379
- "msg",
380
- "port",
381
- "totpEnabled",
382
- "env",
383
- "tool",
384
- "deploymentId",
385
- "errorKind",
386
- "reason",
387
- "prevTargetId",
388
- "mode",
389
- "fileCount",
390
- "passed",
391
- "failed",
392
- "skipped"
393
- ]);
394
- /**
395
- * Patterns that match secret values.
396
- * Match order matters — more-specific patterns first.
397
- *
398
- * #268 redact script covers: relay=wss://…, at=<TOTP>, _deploymentId=<uuid>.
399
- * Here we extend to in-process value-level patterns used in server logs.
400
- */
401
- const SECRET_PATTERNS = [
402
- /^\d{6}$/,
403
- /^(aitcc_|AITCC_)/i,
404
- /^[A-Za-z0-9_-]+=.{4,}/,
405
- /^wss:\/\//,
406
- /(?:^|[?&])at=[A-Z0-9]{6}/i
407
- ];
408
- /**
409
- * Returns `true` when the string value matches any known-secret pattern.
410
- * Only string values are tested — numbers/booleans are always safe.
411
- */
412
- function isSecretValue(value) {
413
- return SECRET_PATTERNS.some((re) => re.test(value));
414
- }
415
- /**
416
- * Redacts a single scalar value.
417
- * - strings: return "***" if the value matches a secret pattern.
418
- * - other: return as-is.
419
- */
420
- function redactValue(value) {
421
- if (typeof value === "string" && isSecretValue(value)) return "***";
422
- return value;
423
- }
424
- /**
425
- * Builds a safe log payload from raw fields.
426
- *
427
- * - Only keys in `ALLOWED_KEYS` are included.
428
- * - String values are scanned for secret patterns and replaced with "***".
429
- * - `ts` and `level` and `event` are always included (they are injected by the
430
- * logger functions below, not by callers).
431
- */
432
- function buildPayload(level, event, fields) {
433
- const out = {
434
- ts: (/* @__PURE__ */ new Date()).toISOString(),
435
- level,
436
- event
437
- };
438
- for (const [key, value] of Object.entries(fields)) {
439
- if (!ALLOWED_KEYS.has(key)) continue;
440
- if (key === "ts" || key === "level" || key === "event") continue;
441
- out[key] = redactValue(value);
442
- }
443
- return out;
444
- }
445
- /**
446
- * Writes a single JSON log line to stderr.
447
- * MCP stdio transport uses stdout; all diagnostics go to stderr.
448
- */
449
- function writeLog(level, event, fields = {}) {
450
- const payload = buildPayload(level, event, fields);
451
- process.stderr.write(`${JSON.stringify(payload)}\n`);
452
- }
453
- /** Log an informational structured event. */
454
- function logInfo(event, fields = {}) {
455
- writeLog("info", event, fields);
456
- }
457
- /** Log a warning structured event. */
458
- function logWarn(event, fields = {}) {
459
- writeLog("warn", event, fields);
460
- }
461
- /** Log an error structured event. */
462
- function logError(event, fields = {}) {
463
- writeLog("error", event, fields);
464
- }
465
- //#endregion
466
- //#region src/mcp/environment.ts
467
- /**
468
- * Returns `true` when the environment is any relay variant (`relay-dev` or
469
- * `relay-mobile`). Use this instead of `env === 'relay'` for tier checks —
470
- * every relay env surfaces the Tier B / relay-only tool set.
471
- *
472
- * Written as an exhaustive switch so a future `McpEnvironment` member that is
473
- * missing an arm is a TS compile error rather than a silent `false`.
474
- */
475
- function isRelayEnv(env) {
476
- switch (env) {
477
- case "relay-dev":
478
- case "relay-mobile": return true;
479
- case "mock": return false;
480
- }
481
- }
482
- /**
483
- * Maps the `McpEnvironment` union to the legacy two-value union
484
- * (`'mock' | 'relay'`) for backward-compatible fields in diagnostics output.
485
- * Every relay variant (`relay-dev`, `relay-mobile`) collapses to `'relay'`.
486
- * Written as an exhaustive switch so a missing arm is a TS compile error.
487
- */
488
- function toLegacyEnv(env) {
489
- switch (env) {
490
- case "mock": return "mock";
491
- case "relay-dev":
492
- case "relay-mobile": return "relay";
493
- }
494
- }
495
- /**
496
- * Reconstructs the three-value `McpEnvironment` output string from the
497
- * orthogonal signals (issues #348, #378, #665):
498
- *
499
- * - `kind === 'local'` → `'mock'`
500
- * - `kind === 'relay'` && origin 'external-pwa' → `'relay-mobile'`
501
- * - `kind === 'relay'` && origin intoss/undefined → `'relay-dev'`
502
- *
503
- * `relayOrigin` is the booted-family discriminator (NOT sniffed from the URL)
504
- * that distinguishes the env-2 external-PWA relay (`relay-mobile`) from the
505
- * intoss-private dog-food relay (`relay-dev`); both are `kind: 'relay'`.
506
- *
507
- * `relay-live` (env 4) has been removed (#665). `liveIntent` parameter is gone.
508
- *
509
- * Pure — used at every output boundary (envelope `meta.env`, `get_debug_status`,
510
- * `measure_safe_area` provenance) so the surface never sniffs a URL again.
511
- *
512
- * Written switch-style so a missing arm is a TS compile error (never falls
513
- * through to a default).
514
- */
515
- function deriveEnvironment(kind, relayOrigin) {
516
- switch (kind) {
517
- case "local": return "mock";
518
- case "relay": return relayOrigin === "external-pwa" ? "relay-mobile" : "relay-dev";
519
- }
520
- }
521
- //#endregion
522
- //#region src/mcp/sdk-signatures.ts
523
- function isObject(v) {
524
- return typeof v === "object" && v !== null && !Array.isArray(v);
525
- }
526
- function describeArgs(args) {
527
- try {
528
- return JSON.stringify(args);
529
- } catch {
530
- return String(args);
531
- }
532
- }
533
- /**
534
- * 등록된 메서드 목록.
535
- *
536
- * 시그니처 출처 확인:
537
- * - 함수가 인자를 받지 않으면 args[0] 없음 → `args.length === 0`을 체크하지 않고
538
- * 그냥 통과시킨다(args 무시하는 stub가 많아서 noArgs 체크가 noise).
539
- * - 실 SDK 시그니처는 `src/__typecheck.ts`의 `Assert<Mock, Original>` 줄로 보장.
540
- */
541
- const SIGNATURES = [
542
- {
543
- name: "setDeviceOrientation",
544
- validateArgs(args) {
545
- const arg = args[0];
546
- if (!isObject(arg)) return {
547
- ok: false,
548
- expected: "{ type: 'portrait' | 'landscape' }",
549
- received: describeArgs(args)
550
- };
551
- const type = arg.type;
552
- if (type !== "portrait" && type !== "landscape") return {
553
- ok: false,
554
- expected: "{ type: 'portrait' | 'landscape' }",
555
- received: describeArgs(args)
556
- };
557
- return { ok: true };
558
- },
559
- example: "call_sdk('setDeviceOrientation', [{ type: 'landscape' }])"
560
- },
561
- {
562
- name: "setIosSwipeGestureEnabled",
563
- validateArgs(args) {
564
- const arg = args[0];
565
- if (!isObject(arg) || typeof arg.isEnabled !== "boolean") return {
566
- ok: false,
567
- expected: "{ isEnabled: boolean }",
568
- received: describeArgs(args)
569
- };
570
- return { ok: true };
571
- },
572
- example: "call_sdk('setIosSwipeGestureEnabled', [{ isEnabled: false }])"
573
- },
574
- {
575
- name: "setSecureScreen",
576
- validateArgs(args) {
577
- const arg = args[0];
578
- if (!isObject(arg) || typeof arg.enabled !== "boolean") return {
579
- ok: false,
580
- expected: "{ enabled: boolean }",
581
- received: describeArgs(args)
582
- };
583
- return { ok: true };
584
- },
585
- example: "call_sdk('setSecureScreen', [{ enabled: true }])"
586
- },
587
- {
588
- name: "setScreenAwakeMode",
589
- validateArgs(args) {
590
- const arg = args[0];
591
- if (!isObject(arg) || typeof arg.enabled !== "boolean") return {
592
- ok: false,
593
- expected: "{ enabled: boolean }",
594
- received: describeArgs(args)
595
- };
596
- return { ok: true };
597
- },
598
- example: "call_sdk('setScreenAwakeMode', [{ enabled: true }])"
599
- },
600
- {
601
- name: "getOperationalEnvironment",
602
- validateArgs(_args) {
603
- return { ok: true };
604
- },
605
- example: "call_sdk('getOperationalEnvironment', [])"
606
- },
607
- {
608
- name: "getPlatformOS",
609
- validateArgs(_args) {
610
- return { ok: true };
611
- },
612
- example: "call_sdk('getPlatformOS', [])"
613
- },
614
- {
615
- name: "getDeviceId",
616
- validateArgs(_args) {
617
- return { ok: true };
618
- },
619
- example: "call_sdk('getDeviceId', [])"
620
- },
621
- {
622
- name: "getLocale",
623
- validateArgs(_args) {
624
- return { ok: true };
625
- },
626
- example: "call_sdk('getLocale', [])"
627
- },
628
- {
629
- name: "getNetworkStatus",
630
- validateArgs(_args) {
631
- return { ok: true };
632
- },
633
- example: "call_sdk('getNetworkStatus', [])"
634
- },
635
- {
636
- name: "getSchemeUri",
637
- validateArgs(_args) {
638
- return { ok: true };
639
- },
640
- example: "call_sdk('getSchemeUri', [])"
641
- },
642
- {
643
- name: "requestReview",
644
- validateArgs(_args) {
645
- return { ok: true };
646
- },
647
- example: "call_sdk('requestReview', [])"
648
- },
649
- {
650
- name: "closeView",
651
- validateArgs(_args) {
652
- return { ok: true };
653
- },
654
- example: "call_sdk('closeView', [])"
655
- }
656
- ];
657
- const SIGNATURE_MAP = new Map(SIGNATURES.map((s) => [s.name, s]));
658
- /** 세션 내 passthrough 경고를 한 번만 emit하기 위한 Set */
659
- const _warnedPassthrough = /* @__PURE__ */ new Set();
660
- /**
661
- * 메서드 이름으로 시그니처를 조회한다.
662
- * 등록된 메서드이면 `SdkSignature`를 반환하고, 미등록이면 `undefined`.
663
- */
664
- function lookupSignature(name) {
665
- return SIGNATURE_MAP.get(name);
666
- }
667
- /**
668
- * 미등록 메서드에 대해 stderr에 passthrough 경고를 1회 출력한다.
669
- * 세션 내 동일 메서드 이름은 최초 1회만 출력.
670
- */
671
- function warnPassthrough(name) {
672
- if (_warnedPassthrough.has(name)) return;
673
- _warnedPassthrough.add(name);
674
- process.stderr.write(`[ait-debug] call_sdk: "${name}" 시그니처가 등록되지 않음 — passthrough\n`);
675
- }
676
- SIGNATURES.map((s) => s.name);
677
- //#endregion
678
- //#region src/mcp/server-lock.ts
679
- /**
680
- * Single debug session lock for the `devtools-mcp` debug server.
681
- *
682
- * At most one debug server process should run on a given machine at a time —
683
- * multiple concurrent instances create duplicate cloudflared tunnels, waste
684
- * resources, and confuse the user about which wssUrl to use.
685
- *
686
- * ## Lock file
687
- *
688
- * Location: `~/.ait-devtools/server.lock`
689
- *
690
- * Schema (JSON):
691
- * ```json
692
- * { "pid": 12345, "wssUrl": "wss://xxx.trycloudflare.com", "startedAt": "2026-01-01T00:00:00.000Z" }
693
- * ```
694
- *
695
- * ## Behaviour
696
- *
697
- * - **Acquire**: write PID + wssUrl + startedAt. Returns a `release()` handle.
698
- * - **Stale lock recovery**: if the stored PID is no longer alive
699
- * (`process.kill(pid, 0)` throws ESRCH), the lock is silently replaced.
700
- * - **Live conflict (option B)**: if the stored PID is alive, `acquireLock`
701
- * throws `ServerLockConflictError` with the existing PID and wssUrl so the
702
- * caller can surface a clear message to the agent.
703
- * - **Release**: remove the lock file. Called on graceful shutdown (SIGINT /
704
- * SIGTERM / SIGHUP). SIGKILL survivors leave a stale file — the next startup
705
- * recovers it automatically via the alive check.
706
- *
707
- * ## wssUrl update
708
- *
709
- * The lock is written before cloudflared starts, so `wssUrl` begins as `null`
710
- * and is updated in place once the tunnel URL is known via `updateWssUrl`.
711
- *
712
- * Node-only.
713
- */
714
- /** Thrown when a live server process already holds the lock. */
715
- var ServerLockConflictError = class extends Error {
716
- /** PID of the existing server process. */
717
- existingPid;
718
- /** wssUrl from the existing lock — may be `null` if the tunnel is still starting. */
719
- existingWssUrl;
720
- /** ISO timestamp from the existing lock — when that session started. */
721
- existingStartedAt;
722
- constructor(existingPid, existingWssUrl, existingStartedAt) {
723
- const urlNote = existingWssUrl != null ? ` relay URL: ${existingWssUrl}\n` : " relay URL: (tunnel still starting — retry in a moment)\n";
724
- super(`A debug server is already running (PID ${existingPid}).\n` + urlNote + `Stop the existing session before starting a new one.
725
- If it is already stopped but this error persists, remove the lock file:
726
- rm "${lockFilePath()}"`);
727
- this.name = "ServerLockConflictError";
728
- this.existingPid = existingPid;
729
- this.existingWssUrl = existingWssUrl;
730
- this.existingStartedAt = existingStartedAt;
731
- }
732
- };
733
- /** Returns `~/.ait-devtools/server.lock` (or `AIT_DEVTOOLS_LOCK_DIR` override for tests). */
734
- function lockFilePath() {
735
- return join(process.env.AIT_DEVTOOLS_LOCK_DIR ?? join(homedir(), ".ait-devtools"), "server.lock");
736
- }
737
- function ensureLockDir(lockPath) {
738
- mkdirSync(join(lockPath, ".."), { recursive: true });
739
- }
740
- /**
741
- * Returns `true` when the given PID refers to a running process.
742
- *
743
- * Re-exported from `../shared/parent-watcher` so external callers that
744
- * import from `./server-lock` keep working without an import-path change.
745
- */
746
- const isPidAlive = isPidAlive$1;
747
- function readLock(lockPath) {
748
- if (!existsSync(lockPath)) return null;
749
- try {
750
- const raw = readFileSync(lockPath, "utf8");
751
- const parsed = JSON.parse(raw);
752
- if (typeof parsed === "object" && parsed !== null && "pid" in parsed && typeof parsed.pid === "number" && "startedAt" in parsed && typeof parsed.startedAt === "string") {
753
- const p = parsed;
754
- const tunnelChildPid = typeof p.tunnelChildPid === "number" ? p.tunnelChildPid : null;
755
- return {
756
- pid: p.pid,
757
- wssUrl: typeof p.wssUrl === "string" ? p.wssUrl : null,
758
- startedAt: p.startedAt,
759
- tunnelChildPid
760
- };
761
- }
762
- return null;
763
- } catch {
764
- return null;
765
- }
766
- }
767
- function writeLock(lockPath, data) {
768
- ensureLockDir(lockPath);
769
- writeFileSync(lockPath, JSON.stringify(data, null, 2), { encoding: "utf8" });
770
- }
771
- function removeLock(lockPath) {
772
- try {
773
- rmSync(lockPath);
774
- } catch {}
775
- }
776
- /**
777
- * Sends SIGTERM to `pid` and waits up to `graceMs` (default 2 000 ms) for it
778
- * to exit; then falls back to SIGKILL. Synchronous — uses a busy-wait loop so
779
- * it is usable in the top-level startup path without async plumbing.
780
- *
781
- * Ignores errors from `process.kill` so that a race where the target exits
782
- * between the alive check and the kill call does not crash the caller.
783
- */
784
- function killAndWait(pid, graceMs = 2e3) {
785
- try {
786
- process.kill(pid, "SIGTERM");
787
- } catch {
788
- return;
789
- }
790
- const deadline = Date.now() + graceMs;
791
- while (isPidAlive(pid) && Date.now() < deadline) {
792
- const end = Date.now() + 100;
793
- while (Date.now() < end);
794
- }
795
- if (isPidAlive(pid)) try {
796
- process.kill(pid, "SIGKILL");
797
- } catch {}
798
- }
799
- /**
800
- * Reaps an orphaned cloudflared tunnel child left behind by a previous session
801
- * (issue #628). The normal shutdown path TERM-cascades to the child, but a
802
- * SIGKILL'd or crashed Node process can't run cleanup — its cloudflared child
803
- * keeps the (now stale) quick tunnel alive. When `acquireLock` reclaims such a
804
- * lock, this kills the still-alive `tunnelChildPid` so the new session starts
805
- * from a clean slate (companion to the #347/#571 zombie-daemon defenses).
806
- *
807
- * No-op when the lock carries no `tunnelChildPid` (older lock files) or the
808
- * child is already gone. SECRET-HANDLING: logs the PID only — never the tunnel
809
- * host/wss (those never enter the lock file or this path).
810
- */
811
- function reapOrphanTunnelChild(existing) {
812
- const childPid = existing.tunnelChildPid;
813
- if (typeof childPid !== "number" || !isPidAlive(childPid)) return;
814
- process.stderr.write(`[ait-debug] reaping orphaned tunnel child PID=${childPid} from previous session.\n`);
815
- killAndWait(childPid);
816
- }
817
- /**
818
- * Reads the current lock file without acquiring it. Returns the parsed
819
- * `LockData` when the file exists and is valid, otherwise `null`. Used by
820
- * `get_debug_status` to surface the `serverLockHolder` field without
821
- * interfering with the running lock owner.
822
- */
823
- function readServerLock() {
824
- return readLock(lockFilePath());
825
- }
826
- /**
827
- * Attempts to acquire the server lock.
828
- *
829
- * - If no lock exists (or the lock is stale): writes a new lock and returns a
830
- * `LockHandle` with `updateWssUrl` + `release`.
831
- * - If a live process holds the lock and `force` is `false` (default): writes
832
- * a clear recovery message to stderr and throws `ServerLockConflictError`.
833
- * - If a live process holds the lock and `force` is `true`: sends SIGTERM to
834
- * that process (waiting up to 2 s then SIGKILL) and takes over the lock.
835
- *
836
- * The initial `wssUrl` in the lock file is `null` — call
837
- * `handle.updateWssUrl(url)` once the cloudflared tunnel is ready.
838
- */
839
- function acquireLock(options = {}) {
840
- const { force = false } = options;
841
- const lockPath = lockFilePath();
842
- const existing = readLock(lockPath);
843
- if (existing !== null) if (isPidAlive(existing.pid)) {
844
- const tunnelChildPid = existing.tunnelChildPid;
845
- if (typeof tunnelChildPid === "number" && !isPidAlive(tunnelChildPid)) process.stderr.write(`[ait-debug] stale lock: holder PID=${existing.pid} alive but tunnel child PID=${tunnelChildPid} is dead — reclaiming lock.\n`);
846
- else if (force) {
847
- process.stderr.write(`[ait-debug] --force: terminating existing session PID=${existing.pid} …\n`);
848
- killAndWait(existing.pid);
849
- reapOrphanTunnelChild(existing);
850
- process.stderr.write(`[ait-debug] --force: PID=${existing.pid} stopped, taking over.\n`);
851
- } else {
852
- const urlPart = existing.wssUrl != null ? `wssUrl=${existing.wssUrl}` : "wssUrl=(tunnel starting)";
853
- process.stderr.write(`[ait-debug] 기존 debug-mode 세션이 이미 실행 중 — PID=${existing.pid}, started ${existing.startedAt}, ${urlPart}\n[ait-debug] 회복: \`kill ${existing.pid}\` 또는 \`npx @ait-co/devtools devtools-mcp --force\`\n`);
854
- throw new ServerLockConflictError(existing.pid, existing.wssUrl, existing.startedAt);
855
- }
856
- } else {
857
- process.stderr.write(`[ait-debug] stale lock from PID ${existing.pid} recovered — starting fresh.\n`);
858
- reapOrphanTunnelChild(existing);
859
- }
860
- const data = {
861
- pid: process.pid,
862
- wssUrl: null,
863
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
864
- };
865
- writeLock(lockPath, data);
866
- let released = false;
867
- return {
868
- updateWssUrl(wssUrl) {
869
- if (released) return;
870
- data.wssUrl = wssUrl;
871
- writeLock(lockPath, data);
872
- },
873
- updateTunnelChildPid(pid) {
874
- if (released) return;
875
- data.tunnelChildPid = pid;
876
- writeLock(lockPath, data);
877
- },
878
- release() {
879
- if (released) return;
880
- released = true;
881
- removeLock(lockPath);
882
- }
883
- };
884
- }
885
- //#endregion
886
- //#region src/mcp/tools.ts
887
- /** Static MCP tool descriptors (name + JSONSchema) for the full debug tool surface. */
888
- const DEBUG_TOOL_DEFINITIONS = [
889
- {
890
- name: "list_console_messages",
891
- description: "Lists recent console messages (console.log/warn/error/info) captured from the attached mini-app page over CDP (Runtime.consoleAPICalled). Read-only. Returns level, text, timestamp, and stringified args, oldest-first.",
892
- inputSchema: {
893
- type: "object",
894
- properties: {},
895
- required: []
896
- },
897
- availableIn: "both"
898
- },
899
- {
900
- name: "list_network_requests",
901
- description: "Lists recent network requests (XHR/fetch) captured from the attached mini-app page over CDP (Network.requestWillBeSent + Network.responseReceived). Read-only. Returns url, method, status, and timing, oldest-first.",
902
- inputSchema: {
903
- type: "object",
904
- properties: {},
905
- required: []
906
- },
907
- availableIn: "both"
908
- },
909
- {
910
- name: "list_pages",
911
- description: "Returns the single active page (at most one) the relay sees attached. When a second page attaches, the previous one is evicted (last-attach wins — single-attach model). The result includes `singleAttachModel: true` so the agent knows the array is always 0 or 1 entries. Also returns whether the cloudflared tunnel is up and the public wss relay URL. The `tunnel` field includes `droppedAt` (ISO timestamp or null/undefined): when non-null the tunnel has permanently dropped after 3 failed reissue attempts — restart the debug server with `npx @ait-co/devtools devtools-mcp`. Each page entry includes a `lastSeenAt` ISO timestamp (last inbound CDP message from that target — useful to detect stale entries when the phone app backgrounded). The result also includes `crashDetectedAt` (ISO timestamp or null): when non-null, a page crash was detected via Inspector.targetCrashed / Target.targetDestroyed since the last attach, the pages list will be empty, and `crashWarning` shows a Korean hint to re-attach. Call this first to confirm a page is attached before reading console/network. When a page attaches or detaches the server emits notifications/tools/list_changed — call tools/list again to get the full updated tool surface.",
912
- inputSchema: {
913
- type: "object",
914
- properties: {},
915
- required: []
916
- },
917
- availableIn: "both"
918
- },
919
- {
920
- name: "start_attach",
921
- description: "The tool result already shows the QR to the user directly (Claude Code renders MCP tool output to the user's screen; they press Ctrl+O to expand if it's collapsed). Do NOT re-print or re-render the QR in your reply — that just wastes output tokens. Simply tell the user to scan the QR shown in this tool's output with their phone camera. Single entry point to attach a real device: switches the debug mode (if `mode` is given), builds the self-attaching deep-link QR for the active relay environment, and waits for the phone to attach — all in one call (replaces the old attach-URL + start_debug two-step). Scan the QR with the phone camera to open the mini-app and attach it to this debug session (QR is the single entry path — no USB cable or platform CLI needed).\n\nmode (optional): pass \"relay-sandbox\" (env 2) or \"relay-staging\" (env 3) to switch the active environment first. When omitted, the current relay environment is used as-is (no switch). Passing \"local-browser\" returns an error — start_attach is relay-only (env 2/3). When the session is already in the requested mode, the switch is skipped.\n\nEnvironment-specific behaviour:\n • env 3 / relay-staging: requires scheme_url — the intoss-private://…?_deploymentId=<uuid> URL from `ait deploy --scheme-only`. Splices debug=1 + relay URL into the scheme URL.\n • env 2 / relay-sandbox: scheme_url is NOT used. Instead, reads AIT_TUNNEL_BASE_URL (the https://*.trycloudflare.com app tunnel from `tunnel:{cdp:true}`) and builds a launcher PWA deep-link (https://devtools.aitc.dev/launcher/?url=…&debug=1&relay=…). When projectRoot is given, the app name from <projectRoot>/package.json is added as name= so the launcher partner bar shows it.\n\nWaits for a page to attach by default (up to wait_timeout_seconds, default 60 s). The server automatically opens the QR dashboard in the OS default browser when running on a local GUI machine — headless/remote environments fall back to the text QR in the tool output.\n\nTOTP auto re-mint: when AIT_DEBUG_TOTP_SECRET is set on the MCP server, the attachUrl carries a one-time code (at=<code>) valid for ~3 minutes (the relay gate accepts ±6 TOTP steps). While waiting, start_attach AUTOMATICALLY re-mints a fresh code before the current one expires and refreshes the dashboard QR in place (no browser re-open). You do NOT need to re-call start_attach every time the code would expire — a single call covers the whole wait window. The response includes a `totp` field with `expiresAt` and a `reminted` count of how many fresh codes were issued during the wait. Without AIT_DEBUG_TOTP_SECRET, the attachUrl has no expiry.\n\nselfdebug (env 2 / relay-sandbox only): pass selfdebug=true to add &selfdebug=1 to the launcher deep-link. The launcher PWA then registers its own document as the CDP target instead of the framed mini-app. SINGLE-ATTACH MODEL: attaching the launcher self-target evicts any currently-attached mini-app target — use this mode exclusively for diagnosing the launcher document itself (DOM, safe-area, console). Not applicable in env 3 (relay-staging) — passing selfdebug=true there returns an error.",
922
- inputSchema: {
923
- type: "object",
924
- properties: {
925
- mode: {
926
- type: "string",
927
- enum: [
928
- "local-browser",
929
- "relay-sandbox",
930
- "relay-staging"
931
- ],
932
- description: "Optional debug mode to switch into before attaching. \"relay-sandbox\" = env 2 (launcher PWA), \"relay-staging\" = env 3 (intoss-private dog-food). \"local-browser\" returns an error (start_attach is relay-only). Omit to keep the current relay environment."
933
- },
934
- scheme_url: {
935
- type: "string",
936
- description: "The intoss-private:// scheme URL from `ait deploy --scheme-only` (must carry _deploymentId). Required for env 3/relay-staging mode. Not used in env 2/relay-sandbox mode (use AIT_TUNNEL_BASE_URL instead). The authority (host) must be the app name (e.g. intoss-private://aitc-sdk-example?_deploymentId=…). Generic values like \"web\" or an empty host indicate a malformed URL."
937
- },
938
- wait_timeout_seconds: {
939
- type: "number",
940
- description: "Maximum seconds to wait for a page to attach (default 60, range 1–600). Values outside the range or invalid inputs (0, negative, NaN) fall back to the default silently. During the wait the TOTP code is auto re-minted as needed, so a single call covers the whole window."
941
- },
942
- projectRoot: {
943
- type: "string",
944
- description: "Absolute path to the mini-app project root (the directory containing its package.json and .ait_urls). When AIT_TUNNEL_BASE_URL is unset (env 2 / relay-mobile only), the daemon reads the app tunnel URL from <projectRoot>/.ait_urls written by the dev server (tunnel:{cdp:true}). Pass this because the daemon's own cwd is fixed at launch. Omit when AIT_TUNNEL_BASE_URL is set explicitly."
945
- },
946
- selfdebug: {
947
- type: "boolean",
948
- description: "Env 2 / relay-sandbox only. When true, adds &selfdebug=1 to the launcher deep-link so the launcher PWA registers its own document as the CDP target (launcher diagnostics mode). SINGLE-ATTACH MODEL: self-target attach evicts any currently-attached mini-app target. Use only when you need to inspect the launcher itself (DOM, safe-area, console). Passing selfdebug=true in env 3 (relay-staging) returns an error. Default: false (omitted)."
949
- }
950
- },
951
- required: []
952
- },
953
- availableIn: "relay"
954
- },
955
- {
956
- name: "get_dom_document",
957
- description: "Returns the DOM tree of the attached mini-app page over CDP (DOM.getDocument). Read-only. Use for structural/layout regression diagnosis (e.g. confirming an element exists, inspecting attributes). Returns the document root node with children.",
958
- inputSchema: {
959
- type: "object",
960
- properties: {},
961
- required: []
962
- },
963
- availableIn: "both"
964
- },
965
- {
966
- name: "take_snapshot",
967
- description: "Captures a serialized snapshot of the attached page over CDP (DOMSnapshot.captureSnapshot). Read-only. Returns the documents + interned strings table for visual-regression diagnosis (e.g. checking computed CSS custom properties like --sat against the live layout).",
968
- inputSchema: {
969
- type: "object",
970
- properties: {},
971
- required: []
972
- },
973
- availableIn: "both"
974
- },
975
- {
976
- name: "take_screenshot",
977
- description: "Captures a PNG screenshot of the attached mini-app page over CDP (Page.captureScreenshot) so the agent can see the phone screen directly. Read-only. Returns an image content block — this is the only debug tool that returns an image; all other debug tools return text (JSON).",
978
- inputSchema: {
979
- type: "object",
980
- properties: {},
981
- required: []
982
- },
983
- availableIn: "both"
984
- },
985
- {
986
- name: "measure_safe_area",
987
- description: "Runs a safe-area probe on the attached mini-app page via Runtime.evaluate and returns normalized safe-area insets, viewport geometry, device pixel ratio, and User-Agent. Read-only — does not modify page state. Tier C per RFC #277: the same Runtime.evaluate probe runs in both `mock` (devtools panel page with window.__ait state) and `relay` (real-device WebView with window.__sdk). The result includes a `source: \"mock\" | \"relay-dev\" | \"relay-mobile\"` field so consumers can identify provenance without inspecting payload values. (`relay-mobile` = env 2 real-device PWA over an external relay; `relay-dev` = env 3 dog-food WebView; relay-live/env 4 removed #665.) Use in a relay session (phone attached) to get ground-truth values for upgrading a viewport preset from extrapolated/placeholder to measured. Requires a page to be attached — call list_pages first.",
988
- inputSchema: {
989
- type: "object",
990
- properties: {},
991
- required: []
992
- },
993
- availableIn: "both"
994
- },
995
- {
996
- name: "evaluate",
997
- description: "Evaluates an arbitrary JavaScript expression on the attached mini-app page via CDP Runtime.evaluate (returnByValue: true) and returns the result. NOT read-only — the expression can have side effects (DOM mutations, SDK calls, state changes). Requires the relay to be attached — call list_pages first. Throws if the evaluation throws an exception on the page.\n\nSECURITY: expression and result are not redacted — never include secrets or auth tokens in the expression.\n\nPositive-allowlist kill-switch (#665): this tool is blocked when the attached page is on a non-debug host (apps.tossmini.com / env 4). Only localhost, *.trycloudflare.com, and *.private-apps.tossmini.com are allowed. relay-live (env 4) and the LIVE confirm guard are removed.",
998
- inputSchema: {
999
- type: "object",
1000
- properties: { expression: {
1001
- type: "string",
1002
- description: "JavaScript expression to evaluate in the page context."
1003
- } },
1004
- required: ["expression"]
1005
- },
1006
- availableIn: "both"
1007
- },
1008
- {
1009
- name: "list_exceptions",
1010
- description: "Lists JS-level exceptions captured via `Runtime.exceptionThrown` from the relay attached page. Includes timestamp, exception text, source URL/line, and stack trace. Use to root-cause SDK throws that may precede a Toss app crash (#265 / #267). The buffer holds up to 50 most recent exceptions and survives target replaced/crashed/destroyed events so an exception just before a crash is preserved. Returns up to 50 most recent by default.",
1011
- inputSchema: {
1012
- type: "object",
1013
- properties: { limit: {
1014
- type: "number",
1015
- description: "Maximum number of exceptions to return (default 50, max 50)."
1016
- } },
1017
- required: []
1018
- },
1019
- availableIn: "both"
1020
- },
1021
- {
1022
- name: "call_sdk",
1023
- description: "Calls a dog-food SDK method via the window.__sdkCall bridge (exported by @apps-in-toss/web-framework only in __DEBUG_BUILD__ bundles). NOT read-only — SDK calls have side effects (navigation, payments, permissions, etc.). On env 3/4 (real device relay) this hits the real SDK; on env 1 (local mock) and env 2 (PWA relay — real WebKit, mock SDK) it hits the mock SDK. Requires the relay to be attached — call list_pages first. Returns {ok: true, value} on success or {ok: false, error} on failure. If a Runtime.exceptionThrown event was observed within [callStart-50ms, callEnd+200ms], the result also includes `recentException` for crash triage. Returns a clear error if window.__sdkCall is not available — on relay (env 3/4) that means a non-dog-food bundle (redeploy via `ait build && aitcc app deploy`); on local (--target=local, env 1) it means the dev bridge is not installed (start the dev server with `pnpm dev`).\n\nSECURITY: method name, args, and result value are not redacted — never include secrets.\n\nPositive-allowlist kill-switch (#665): blocked when the attached page is on a non-debug host (apps.tossmini.com / env 4). relay-live and the LIVE guard removed.\n\nIMPORTANT — 인자 시그니처 (잘못된 인자로 호출하면 토스 앱 crash 위험):\n setDeviceOrientation: call_sdk(\"setDeviceOrientation\", [{ type: \"landscape\" }]) // NOT \"landscape\"\n setIosSwipeGestureEnabled: call_sdk(\"setIosSwipeGestureEnabled\", [{ isEnabled: false }])\n setSecureScreen: call_sdk(\"setSecureScreen\", [{ enabled: true }])\n setScreenAwakeMode: call_sdk(\"setScreenAwakeMode\", [{ enabled: true }])\n getOperationalEnvironment: call_sdk(\"getOperationalEnvironment\", [])\n getPlatformOS: call_sdk(\"getPlatformOS\", [])\n getDeviceId: call_sdk(\"getDeviceId\", [])\n getLocale: call_sdk(\"getLocale\", [])\n getNetworkStatus: call_sdk(\"getNetworkStatus\", [])\n getSchemeUri: call_sdk(\"getSchemeUri\", [])\n requestReview: call_sdk(\"requestReview\", [])\n closeView: call_sdk(\"closeView\", [])",
1024
- inputSchema: {
1025
- type: "object",
1026
- properties: {
1027
- name: {
1028
- type: "string",
1029
- description: "SDK method name to call (e.g. \"getOperationalEnvironment\")."
1030
- },
1031
- args: {
1032
- type: "array",
1033
- description: "Arguments to pass to the SDK method (optional, default []).",
1034
- items: {}
1035
- }
1036
- },
1037
- required: ["name"]
1038
- },
1039
- availableIn: "both"
1040
- },
1041
- {
1042
- name: "AIT.getSdkCallHistory",
1043
- description: "Returns the recent Apps in Toss SDK call trace (method, args, result/error, timestamp) that raw CDP cannot observe. Read-only. Use to confirm an SDK call fired and how it resolved (e.g. a saveBase64Data permission regression).",
1044
- inputSchema: {
1045
- type: "object",
1046
- properties: {},
1047
- required: []
1048
- },
1049
- availableIn: "both"
1050
- },
1051
- {
1052
- name: "AIT.getMockState",
1053
- description: "Returns the devtools mock state snapshot (window.__ait) — environment, permissions, location, auth, network, IAP, and more. Read-only. In dev mode this is the live browser mock state; in debug mode the in-app side reports it over the AIT domain.",
1054
- inputSchema: {
1055
- type: "object",
1056
- properties: {},
1057
- required: []
1058
- },
1059
- availableIn: "both"
1060
- },
1061
- {
1062
- name: "AIT.getOperationalEnvironment",
1063
- description: "Returns getOperationalEnvironment() plus the resolved SDK version — metadata raw CDP cannot observe. Read-only.",
1064
- inputSchema: {
1065
- type: "object",
1066
- properties: {},
1067
- required: []
1068
- },
1069
- availableIn: "both"
1070
- },
1071
- {
1072
- name: "start_debug",
1073
- description: "Switches the active debug environment in-place (issue #348) — no Claude Code restart and no MCP re-handshake. One daemon holds both a local (env 1, mock SDK in a Chromium) and a relay (env 2/3, real-device over the Chii relay + cloudflared tunnel) connection at once; this tool flips which one every other tool reads from, lazily booting the requested family's infra on first use and keeping the inactive one warm so an existing attach survives the switch. After switching it emits notifications/tools/list_changed — call tools/list again to see the updated tool surface for the new environment.\n\nPositive-allowlist kill-switch (#665): relay sessions on apps.tossmini.com (env 4, released production) are silently blocked at both the in-app gate and this MCP layer — relay-live and the LIVE guard have been removed. Only localhost/loopback (env 1), *.trycloudflare.com (env 2), and *.private-apps.tossmini.com (env 3) are allowed.\n\nmodes:\n local-browser — env 1: desktop Chromium with the mock SDK and a local CDP attach. Side-effect tools (call_sdk/evaluate) run unguarded against the mock; nothing touches a real device or real users. No prerequisites — the default, always-available environment for state/contract and visual-layout work.\n relay-sandbox — env 2: a real-device PWA (real WebKit engine, mock SDK) over an external Chii relay. CDP covers real-device WebKit DOM, console, exceptions, and safe-area observation; call_sdk still hits the mock (SDK fidelity needs relay-staging). Side-effect tools run unguarded against the mock. Only the dual-connection daemon can enter relay-sandbox in-place; a single-connection session rejects it with \"동적 전환할 수 없습니다 … relay-sandbox 모드로 재시작하세요\" — follow that hint and restart the MCP server in relay-sandbox mode rather than retrying. Prerequisites: both AIT_RELAY_BASE_URL (the relay base the unplugin emits when started with tunnel:{cdp:true}, used for the CDP attach) and AIT_TUNNEL_BASE_URL (the dev-server tunnel host, required by start_attach to render the launcher QR) must be set before the MCP server starts — the unplugin does not auto-forward either; set them explicitly. Both carry relay/tunnel hosts (secret-class) — keep them out of logs.\n relay-staging — env 3: a real-device Toss WebView dog-food build with the REAL SDK over the intoss-private relay. The first environment where call_sdk exercises the genuine native bridge. Side-effect tools run unguarded (dog-food, not released to real users). Prerequisite: a dog-food candidate bundle built with `RELEASE_CHANNEL=dogfood ait build`, then uploaded with `ait deploy` (add `--scheme-only` to print the resulting intoss-private://…?_deploymentId=… deep-link); open that deep-link/QR on the device to cold-load the bundle with the relay injected. Unlike env 2, env 3 is NOT a dev-server tunnel — it is a deployed bundle reached via the intoss-private scheme, so `pnpm dev` plays no part here.\n\nFor a relay mode (relay-sandbox/relay-staging), also pass projectRoot — the absolute mini-app project root — so the daemon can read the relay auth secret from <projectRoot>/.ait_relay (read-only; the daemon never mints it). Omit it for local-browser.",
1074
- inputSchema: {
1075
- type: "object",
1076
- properties: {
1077
- mode: {
1078
- type: "string",
1079
- enum: [
1080
- "local-browser",
1081
- "relay-sandbox",
1082
- "relay-staging"
1083
- ],
1084
- description: "Target environment to switch to. relay-live (env 4) has been removed (#665) — use relay-staging (env 3) for dog-food debugging."
1085
- },
1086
- projectRoot: {
1087
- type: "string",
1088
- description: "Absolute path to the mini-app project root (the directory containing its package.json and .ait_relay). The daemon reads the relay auth secret from <projectRoot>/.ait_relay (read-only) when switching to a relay environment (relay-staging/relay-sandbox). Pass this because the daemon's own cwd is fixed at launch and may not be the project being debugged. Omit for mode=local-browser (no secret needed)."
1089
- }
1090
- },
1091
- required: ["mode"]
1092
- },
1093
- availableIn: "both"
1094
- },
1095
- {
1096
- name: "get_debug_status",
1097
- description: "Reports the current debug session state — which environment/mode is active, whether a page is attached, and a full diagnostic snapshot — in one call. Use this any time to answer \"what mode am I in right now?\" or \"why is this not working?\" without chaining tools. Fields: mcpVersion (MCP SDK version), devtoolsVersion (@ait-co/devtools package version), tunnel (up/wssUrl/pid/startedAt), pages (list_pages result + lastSeenAt stats), lastAttachAt, lastDetachAt, recentErrors (last N server-side errors, PII/secret redacted), authRejects ({count, lastAt} — relay TOTP 401 rejections, secret-free; count > 0 with empty pages means the phone reached the relay but its code was rejected), environment (kind: mock|relay-dev|relay-mobile, env: mock|relay backward-compat, reason, liveGuardActive: always false — relay-live and LIVE guard removed (#665); start_debug mode→kind mapping: relay-sandbox→relay-mobile, relay-staging→relay-dev, local-browser→mock), serverLockHolder (pid + startedAt from the lock file, or null), nextRecommendedAction ({tool, reason} or null — the single next tool to call; in local-target mode tunnel.up=false is normal so \"restart\" is never recommended). All fields are nullable — missing data is null, not an error. debug-mode only — dev-mode (--mode=dev) does not support relay diagnostics. Tier C (both mock and relay).",
1098
- inputSchema: {
1099
- type: "object",
1100
- properties: { recent_errors_limit: {
1101
- type: "number",
1102
- description: "Maximum number of recent server-side errors to include (default 10, max 50)."
1103
- } },
1104
- required: []
1105
- },
1106
- availableIn: "both"
1107
- },
1108
- {
1109
- name: "run_tests",
1110
- description: "Runs mini-app test files on the attached page over CDP (Runtime.evaluate). Each matched file is bundled with esbuild (SDK imports redirected to the live mock/SDK), injected into the attached WebView, and executed; returns per-file results plus flattened totals (passed/failed/skipped/total). When there is no attached page and the current environment is relay (env 3), this tool automatically shows the QR dashboard and waits for a phone to connect before running (scheme_url required for env 3 relay-dev). Files run SEQUENTIALLY (single-attach model: the relay/local target serves one page), and one run_tests call runs at a time (a concurrent call is rejected). Test verification (assert/snapshot) is delegated to the in-page Vitest runtime; this tool is the transport + report. The per-file results array is the progress record — on partial failure you see exactly which files passed/failed/timed-out. Positive-allowlist kill-switch (#665): blocked when the attached page is on a non-debug host. debug-mode only — dev-mode (--mode=dev) has no CDP. Tier C (both mock/local and relay).",
1111
- inputSchema: {
1112
- type: "object",
1113
- properties: {
1114
- files: {
1115
- type: "array",
1116
- items: { type: "string" },
1117
- description: "Glob patterns or file paths to run (e.g. [\"src/**/*.ait.test.ts\"]). Resolved relative to projectRoot when given, else the daemon cwd. Required, non-empty."
1118
- },
1119
- projectRoot: {
1120
- type: "string",
1121
- description: "Absolute path to the mini-app project root used as the glob base. Pass this because the daemon's cwd is fixed at launch. Optional."
1122
- },
1123
- timeout_ms: {
1124
- type: "number",
1125
- description: "Per-file evaluate timeout in ms (default 30000, range 1000–600000). Out-of-range/invalid values fall back to the default."
1126
- },
1127
- scheme_url: {
1128
- type: "string",
1129
- description: "intoss-private:// deep-link URL from `ait deploy --scheme-only` (env 3 relay-dev only). Required when there is no attached page and the environment is relay-dev — the tool uses it to build the QR attach URL and wait for the phone to connect. Ignored when a page is already attached."
1130
- },
1131
- cell: {
1132
- type: "object",
1133
- description: "Optional cell object to inject into globalThis BEFORE running tests (e.g. { \"__AIT_CELL__\": { \"sdkLine\": \"2.x\", \"platform\": \"ios\" } }). Applied only on the auto-attach path (no-page → attach → inject → run). When a page is already attached the caller is responsible for any prior injection. Ignored when empty or absent. Values must be JSON-serialisable.",
1134
- additionalProperties: true
1135
- }
1136
- },
1137
- required: ["files"]
1138
- },
1139
- availableIn: "both"
1140
- }
1141
- ];
1142
- const DEBUG_TOOL_NAMES = new Set(DEBUG_TOOL_DEFINITIONS.map((t) => t.name));
1143
- function isDebugToolName(name) {
1144
- return DEBUG_TOOL_NAMES.has(name);
1145
- }
1146
- /**
1147
- * Returns the `ToolAvailability` declared on a registered debug tool, or
1148
- * `undefined` when the name is not a known debug tool. Used by the tool
1149
- * registry to filter `tools/list` by current env and by the call handler to
1150
- * reject env-mismatch invocations.
1151
- */
1152
- function getToolAvailability(name) {
1153
- for (const t of DEBUG_TOOL_DEFINITIONS) if (t.name === name) return t.availableIn;
1154
- }
1155
- /**
1156
- * Returns true when the named tool is available in the given environment.
1157
- * Unknown tools return `false` — callers should reject them as unknown rather
1158
- * than as env-mismatched.
1159
- *
1160
- * Relay variants (`relay-dev`, `relay-mobile`) all satisfy the
1161
- * `'relay'` availability tier — `isRelayEnv()` is used for the check.
1162
- * (`relay-live` removed #665.)
1163
- */
1164
- function isToolAvailableIn(name, env) {
1165
- const availability = getToolAvailability(name);
1166
- if (availability === void 0) return false;
1167
- if (availability === "both") return true;
1168
- if (availability === "relay") return isRelayEnv(env);
1169
- return availability === env;
1170
- }
1171
- /**
1172
- * Filters a `DEBUG_TOOL_DEFINITIONS`-shaped list to those whose `availableIn`
1173
- * matches the given env. Pure — preserves order; both Tier C ("both") and the
1174
- * matching single-env tier pass through.
1175
- *
1176
- * Relay variants (`relay-dev`, `relay-mobile`) all satisfy the
1177
- * `'relay'` tier. (`relay-live` removed #665.)
1178
- */
1179
- function filterToolsByEnvironment(tools, env) {
1180
- return tools.filter((t) => t.availableIn === "both" || t.availableIn === "relay" && isRelayEnv(env) || t.availableIn === env);
1181
- }
1182
- /**
1183
- * Tool names that are available before any page attaches (bootstrap tier).
1184
- *
1185
- * `start_attach` — mode switch + QR synthesis + attach wait, no prior attach needed.
1186
- * `list_pages` — reports tunnel status + empty pages even pre-attach.
1187
- *
1188
- * All other tools require an attached page (`enableDomains` must succeed) and
1189
- * are only advertised in `tools/list` once a target appears.
1190
- */
1191
- const BOOTSTRAP_TOOL_NAMES = new Set([
1192
- "start_attach",
1193
- "get_debug_status",
1194
- "list_pages",
1195
- "start_debug"
1196
- ]);
1197
- /** Renders a CDP `RemoteObject` console arg to a stable display string. */
1198
- function renderRemoteObject(arg) {
1199
- if (arg.value !== void 0) {
1200
- if (typeof arg.value === "string") return arg.value;
1201
- try {
1202
- return JSON.stringify(arg.value);
1203
- } catch {
1204
- return String(arg.value);
1205
- }
1206
- }
1207
- if (arg.description !== void 0) return arg.description;
1208
- if (arg.className !== void 0) return arg.className;
1209
- return arg.subtype ?? arg.type;
1210
- }
1211
- function normalizeConsoleMessage(event) {
1212
- const args = event.args.map(renderRemoteObject);
1213
- return {
1214
- level: event.type,
1215
- text: args.join(" "),
1216
- timestamp: event.timestamp,
1217
- args
1218
- };
1219
- }
1220
- function listConsoleMessages(connection) {
1221
- return connection.getBufferedEvents("Runtime.consoleAPICalled").map((event) => normalizeConsoleMessage(event));
1222
- }
1223
- function listNetworkRequests(connection) {
1224
- const requests = connection.getBufferedEvents("Network.requestWillBeSent");
1225
- const responses = connection.getBufferedEvents("Network.responseReceived");
1226
- const responseByRequestId = /* @__PURE__ */ new Map();
1227
- for (const response of responses) responseByRequestId.set(response.requestId, response);
1228
- return requests.map((request) => {
1229
- const response = responseByRequestId.get(request.requestId);
1230
- return {
1231
- requestId: request.requestId,
1232
- url: request.request.url,
1233
- method: request.request.method,
1234
- status: response ? response.response.status : null,
1235
- statusText: response ? response.response.statusText : null,
1236
- startTime: request.timestamp,
1237
- endTime: response ? response.timestamp : null
1238
- };
1239
- });
1240
- }
1241
- /** Formats a single CDP call frame into `at fn (url:line:col)`. */
1242
- function formatCallFrame(frame) {
1243
- return `at ${frame.functionName || "(anonymous)"} (${frame.url}:${frame.lineNumber}:${frame.columnNumber})`;
1244
- }
1245
- /** Normalizes a raw `Runtime.exceptionThrown` event into a `BufferedException`. */
1246
- function normalizeException(event) {
1247
- const { timestamp, exceptionDetails } = event;
1248
- const frames = exceptionDetails.stackTrace?.callFrames;
1249
- const stack = frames && frames.length > 0 ? frames.map(formatCallFrame).join("\n") : void 0;
1250
- const exceptionText = exceptionDetails.exception?.description ?? void 0;
1251
- const result = {
1252
- timestamp,
1253
- text: exceptionDetails.text,
1254
- raw: event
1255
- };
1256
- if (exceptionDetails.url !== void 0) result.url = exceptionDetails.url;
1257
- if (exceptionDetails.lineNumber !== void 0) result.lineNumber = exceptionDetails.lineNumber;
1258
- if (exceptionDetails.columnNumber !== void 0) result.columnNumber = exceptionDetails.columnNumber;
1259
- if (exceptionText !== void 0) result.exceptionText = exceptionText;
1260
- if (stack !== void 0) result.stack = stack;
1261
- return result;
1262
- }
1263
- /**
1264
- * Returns the most recent buffered `Runtime.exceptionThrown` events, normalized.
1265
- * Oldest-first; limited to `limit` entries (default 50, max 50).
1266
- */
1267
- function listExceptions(connection, limit = 50) {
1268
- const cap = Math.min(Math.max(1, limit), 50);
1269
- const events = connection.getBufferedEvents("Runtime.exceptionThrown");
1270
- return (events.length > cap ? events.slice(events.length - cap) : events).map((e) => normalizeException(e));
1271
- }
1272
- function isCrashAware(conn) {
1273
- return typeof conn.getLastCrashDetectedAt === "function" && typeof conn.getTargetLastSeenAt === "function";
1274
- }
1275
- function listPages(connection, tunnel) {
1276
- const pages = connection.listTargets().map((t) => {
1277
- const lastSeenMs = isCrashAware(connection) ? connection.getTargetLastSeenAt(t.id) : null;
1278
- return {
1279
- id: t.id,
1280
- title: t.title,
1281
- url: redactAtParam(t.url),
1282
- lastSeenAt: lastSeenMs !== null ? new Date(lastSeenMs).toISOString() : null
1283
- };
1284
- });
1285
- const crashMs = isCrashAware(connection) ? connection.getLastCrashDetectedAt() : null;
1286
- const crashDetectedAt = crashMs !== null ? new Date(crashMs).toISOString() : null;
1287
- return {
1288
- pages,
1289
- tunnel,
1290
- crashDetectedAt,
1291
- crashWarning: crashDetectedAt ? `[ait-debug] page crash 감지됨 — 새 attach 필요 (관측 시각: ${crashDetectedAt})` : null,
1292
- singleAttachModel: true
1293
- };
1294
- }
1295
- /**
1296
- * Heuristic: can this process open a GUI browser?
1297
- *
1298
- * Returns `true` when we think a GUI is available:
1299
- * - On macOS (`darwin`) we assume yes (MCP normally runs on the user's Mac).
1300
- * - On Linux we check for `DISPLAY` or `WAYLAND_DISPLAY`.
1301
- * - On Windows we assume yes.
1302
- * - In a CI environment (`CI=true`) we assume no.
1303
- */
1304
- function canOpenBrowser() {
1305
- if (process.env.CI === "true" || process.env.CI === "1") return false;
1306
- const platform = process.platform;
1307
- if (platform === "darwin" || platform === "win32") return true;
1308
- if (platform === "linux") return Boolean(process.env.DISPLAY ?? process.env.WAYLAND_DISPLAY);
1309
- return false;
1310
- }
1311
- /** platform별 browser open 명령 후보 목록 — 앞에서부터 순차 시도. */
1312
- function getBrowserCandidates(httpUrl) {
1313
- const platform = process.platform;
1314
- if (platform === "darwin") return [
1315
- {
1316
- cmd: "open",
1317
- args: [httpUrl]
1318
- },
1319
- {
1320
- cmd: "open",
1321
- args: [
1322
- "-a",
1323
- "Safari",
1324
- httpUrl
1325
- ]
1326
- },
1327
- {
1328
- cmd: "open",
1329
- args: [
1330
- "-a",
1331
- "Google Chrome",
1332
- httpUrl
1333
- ]
1334
- },
1335
- {
1336
- cmd: "open",
1337
- args: [
1338
- "-a",
1339
- "Firefox",
1340
- httpUrl
1341
- ]
1342
- }
1343
- ];
1344
- if (platform === "win32") return [{
1345
- cmd: "cmd",
1346
- args: [
1347
- "/c",
1348
- "start",
1349
- "",
1350
- httpUrl
1351
- ]
1352
- }, {
1353
- cmd: "rundll32",
1354
- args: ["url.dll,FileProtocolHandler", httpUrl]
1355
- }];
1356
- return [
1357
- {
1358
- cmd: "xdg-open",
1359
- args: [httpUrl]
1360
- },
1361
- {
1362
- cmd: "sensible-browser",
1363
- args: [httpUrl]
1364
- },
1365
- {
1366
- cmd: "x-www-browser",
1367
- args: [httpUrl]
1368
- },
1369
- {
1370
- cmd: "firefox",
1371
- args: [httpUrl]
1372
- },
1373
- {
1374
- cmd: "google-chrome",
1375
- args: [httpUrl]
1376
- },
1377
- {
1378
- cmd: "chromium",
1379
- args: [httpUrl]
1380
- }
1381
- ];
1382
- }
1383
- /**
1384
- * Redacts ONLY the `at=<value>` (TOTP) query param to `at=<redacted>`, leaving
1385
- * every other query param (_deploymentId, debug, relay) intact. SECRET-HANDLING:
1386
- * the TOTP code is the single short-lived secret carried in a CDP page url.
1387
- */
1388
- function redactAtParam(text) {
1389
- return text.replace(/\bat=([^&\s"']+)/g, "at=<redacted>");
1390
- }
1391
- /** stderr에서 at= TOTP 코드 값을 redact한다. */
1392
- function redactSecrets(text) {
1393
- return redactAtParam(text);
1394
- }
1395
- /** spawnSync exit 0이어도 stderr에 launch 실패 시그널이 있으면 실패로 판단한다. */
1396
- const LAUNCH_FAILURE_PATTERNS = [
1397
- /LSOpenURLsWithRole\(\) failed/,
1398
- /kLSApplicationNotFoundErr/,
1399
- /No application/,
1400
- /Unable to find application/,
1401
- /xdg-open: not found/,
1402
- /command not found/
1403
- ];
1404
- function isLaunchFailureStderr(stderr) {
1405
- return LAUNCH_FAILURE_PATTERNS.some((p) => p.test(stderr));
1406
- }
1407
- /**
1408
- * 로컬 HTTP 서버 루트 URL(`http://127.0.0.1:<port>/`)을 OS 기본 브라우저로 연다 (#595).
1409
- *
1410
- * platform별 fallback chain으로 시도하며, 모두 실패하면 1회 retry를 수행한다
1411
- * (ephemeral process launch 타이밍 문제 대응). retry까지 실패해도 `opened: false` +
1412
- * `httpUrl`을 반환해 사용자가 직접 브라우저에 붙여넣을 수 있게 한다.
1413
- *
1414
- * SECRET-HANDLING:
1415
- * - tmp 파일을 만들지 않는다 (HTML/PNG는 HTTP 서버가 메모리에서 응답).
1416
- * - httpUrl은 `http://127.0.0.1:<port>/`(루트, 시크릿 없음). pngUrl은 127.0.0.1 로컬 전용.
1417
- * - stderr 캡처 결과에서 at= 코드 값을 redact한 후 stderrSummary에 포함.
1418
- * - attachUrl, deploymentId, TOTP 코드를 stdout/stderr/로그에 직접 출력 금지.
1419
- *
1420
- * @param httpUrl - `http://127.0.0.1:<port>/` 루트 URL (시크릿 없음, #595).
1421
- * @param pngUrl - `http://127.0.0.1:<port>/qr.png?u=<encoded>` PNG fallback URL.
1422
- */
1423
- async function openQrInBrowser(httpUrl, pngUrl) {
1424
- const { spawnSync } = await import("node:child_process");
1425
- /**
1426
- * 한 번의 fallback chain 시도. 성공하면 열린 후보 cmd를 반환, 실패하면 null.
1427
- * stderrLines에 각 후보의 stderr를 누적한다.
1428
- */
1429
- function tryOnce(stderrLines) {
1430
- const candidates = getBrowserCandidates(httpUrl);
1431
- for (const { cmd, args } of candidates) {
1432
- const result = spawnSync(cmd, args, {
1433
- encoding: "utf8",
1434
- timeout: 5e3
1435
- });
1436
- if (result.error) {
1437
- stderrLines.push(`${cmd}: ${result.error.message}`);
1438
- continue;
1439
- }
1440
- const stderr = typeof result.stderr === "string" ? result.stderr : "";
1441
- if (stderr) stderrLines.push(`${cmd}: ${redactSecrets(stderr.trim())}`);
1442
- if (result.status === 0 && !isLaunchFailureStderr(stderr)) return true;
1443
- }
1444
- return false;
1445
- }
1446
- const stderrLines = [];
1447
- if (tryOnce(stderrLines)) return {
1448
- opened: true,
1449
- httpUrl,
1450
- pngUrl
1451
- };
1452
- if (tryOnce(stderrLines)) return {
1453
- opened: true,
1454
- httpUrl,
1455
- pngUrl,
1456
- retried: true
1457
- };
1458
- return {
1459
- opened: false,
1460
- httpUrl,
1461
- pngUrl,
1462
- error: "모든 브라우저 실행 후보가 실패했습니다.",
1463
- stderrSummary: stderrLines.length > 0 ? stderrLines.join("\n") : void 0
1464
- };
1465
- }
1466
- /** Returns the DOM tree of the attached page (`DOM.getDocument`). */
1467
- function getDomDocument(connection) {
1468
- return connection.send("DOM.getDocument", {
1469
- depth: -1,
1470
- pierce: true
1471
- });
1472
- }
1473
- /** Returns a serialized page snapshot (`DOMSnapshot.captureSnapshot`). */
1474
- function takeSnapshot(connection) {
1475
- return connection.send("DOMSnapshot.captureSnapshot", {});
1476
- }
1477
- /** Captures a PNG screenshot of the attached page (`Page.captureScreenshot`). */
1478
- async function takeScreenshot(connection) {
1479
- const { data } = await connection.send("Page.captureScreenshot", { format: "png" });
1480
- return {
1481
- data,
1482
- dataUri: `data:image/png;base64,${data}`,
1483
- mimeType: "image/png"
1484
- };
1485
- }
1486
- /**
1487
- * The JS probe injected via `Runtime.evaluate`. It reads:
1488
- * 1. `env(safe-area-inset-*)` via a temporary element with padding set to
1489
- * those CSS env vars, then `getComputedStyle`.
1490
- * 2. SDK insets via a priority chain so the SAME probe works on both relay
1491
- * (real device) and mock (devtools panel page):
1492
- * a. `window.__sdk.SafeAreaInsets.get()` — dog-food bundle on real device.
1493
- * b. `window.__sdk.getSafeAreaInsets()` — dog-food bundle (deprecated).
1494
- * c. `window.__ait.state.safeAreaInsets` — devtools mock state (mock env).
1495
- * The probe records `sdkInsetsSource` = `'window.__sdk'` | `'window.__ait'`
1496
- * | `null`. If all paths fail the result carries `sdkInsetsError`.
1497
- * 3. nav bar geometry: the SDK does not expose navBar height as a standalone
1498
- * API — `.ait-navbar` DOM height is read as a cross-check, and
1499
- * `navBarHeightSource` records where it came from.
1500
- * 4. `innerWidth`, `innerHeight`, `devicePixelRatio`, `navigator.userAgent`.
1501
- *
1502
- * Returns a plain JSON-serialisable object so `returnByValue: true` works.
1503
- *
1504
- * NOTE: This expression is evaluated in the page context — on the real device
1505
- * (relay) or on the mock panel page. It does not mutate any page state — the
1506
- * temporary element is removed after reading. No secret or auth token is read
1507
- * or returned.
1508
- *
1509
- * RFC #277 Tier C parity: the SAME probe string runs in both envs. Mock fidelity
1510
- * comes from the panel's `applyViewport` / `computeSafeAreaInsets` correctly
1511
- * setting `window.__ait.state.safeAreaInsets` (#275). When that is correct,
1512
- * the cssEnv + sdkInsets pair returned here matches the relay's shape.
1513
- */
1514
- const SAFE_AREA_PROBE_EXPRESSION = `
1515
- (function() {
1516
- var el = document.createElement('div');
1517
- el.style.cssText = 'position:fixed;top:0;left:0;width:0;height:0;visibility:hidden;' +
1518
- 'padding-top:env(safe-area-inset-top,0px);' +
1519
- 'padding-right:env(safe-area-inset-right,0px);' +
1520
- 'padding-bottom:env(safe-area-inset-bottom,0px);' +
1521
- 'padding-left:env(safe-area-inset-left,0px)';
1522
- document.documentElement.appendChild(el);
1523
- var cs = window.getComputedStyle(el);
1524
- var cssEnv = {
1525
- top: parseFloat(cs.paddingTop) || 0,
1526
- right: parseFloat(cs.paddingRight) || 0,
1527
- bottom: parseFloat(cs.paddingBottom) || 0,
1528
- left: parseFloat(cs.paddingLeft) || 0
1529
- };
1530
- document.documentElement.removeChild(el);
1531
- var sdkInsets = null;
1532
- var sdkInsetsSource = null;
1533
- var sdkInsetsError = undefined;
1534
- try {
1535
- var sdk = window.__sdk;
1536
- var ait = window.__ait;
1537
- if (sdk && sdk.SafeAreaInsets && typeof sdk.SafeAreaInsets.get === 'function') {
1538
- sdkInsets = sdk.SafeAreaInsets.get();
1539
- sdkInsetsSource = 'window.__sdk';
1540
- } else if (sdk && typeof sdk.getSafeAreaInsets === 'function') {
1541
- sdkInsets = sdk.getSafeAreaInsets();
1542
- sdkInsetsSource = 'window.__sdk';
1543
- } else if (ait && ait.state && ait.state.safeAreaInsets &&
1544
- typeof ait.state.safeAreaInsets.top === 'number') {
1545
- var s = ait.state.safeAreaInsets;
1546
- sdkInsets = { top: s.top, bottom: s.bottom, left: s.left, right: s.right };
1547
- sdkInsetsSource = 'window.__ait';
1548
- } else if (!sdk && !ait) {
1549
- sdkInsetsError = 'neither window.__sdk (relay) nor window.__ait (mock) available';
1550
- } else if (sdk) {
1551
- sdkInsetsError = 'neither SafeAreaInsets.get nor getSafeAreaInsets found on window.__sdk';
1552
- } else {
1553
- sdkInsetsError = 'window.__ait.state.safeAreaInsets is missing or malformed';
1554
- }
1555
- } catch(e) {
1556
- sdkInsetsError = String(e && e.message || e);
1557
- }
1558
- var navBarHeight = null;
1559
- var navBarHeightSource = 'not-exposed-by-sdk';
1560
- try {
1561
- var nb = document.querySelector('.ait-navbar');
1562
- if (nb) {
1563
- navBarHeight = nb.getBoundingClientRect().height;
1564
- navBarHeightSource = 'dom-.ait-navbar';
1565
- }
1566
- } catch(_) {}
1567
- var result = {
1568
- cssEnv: cssEnv,
1569
- sdkInsets: sdkInsets,
1570
- sdkInsetsSource: sdkInsetsSource,
1571
- navBarHeight: navBarHeight,
1572
- navBarHeightSource: navBarHeightSource,
1573
- innerWidth: window.innerWidth,
1574
- innerHeight: window.innerHeight,
1575
- devicePixelRatio: window.devicePixelRatio,
1576
- userAgent: navigator.userAgent
1577
- };
1578
- if (sdkInsetsError !== undefined) result.sdkInsetsError = sdkInsetsError;
1579
- return JSON.stringify(result);
1580
- })()
1581
- `.trim();
1582
- /**
1583
- * Parses a raw `Runtime.evaluate` result value into a `SafeAreaMeasurement`.
1584
- * The probe returns a JSON string (because `returnByValue:true` with a plain
1585
- * object works unreliably across Chii relay versions — stringifying is safer).
1586
- *
1587
- * `source` is supplied by the caller (`measureSafeArea`) from the env SSoT.
1588
- *
1589
- * Throws if the result is missing, contains an exception, or cannot be parsed.
1590
- */
1591
- function normalizeSafeAreaResult(rawValue, source) {
1592
- if (typeof rawValue !== "string") throw new Error(`measure_safe_area: probe returned unexpected type "${typeof rawValue}" — expected JSON string`);
1593
- let parsed;
1594
- try {
1595
- parsed = JSON.parse(rawValue);
1596
- } catch {
1597
- throw new Error(`measure_safe_area: probe returned non-JSON string: ${rawValue}`);
1598
- }
1599
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("measure_safe_area: parsed result is not an object");
1600
- const obj = parsed;
1601
- function requireInsets(key) {
1602
- const v = obj[key];
1603
- if (v === null || v === void 0) return null;
1604
- if (typeof v !== "object") return null;
1605
- const r = v;
1606
- return {
1607
- top: typeof r.top === "number" ? r.top : 0,
1608
- right: typeof r.right === "number" ? r.right : 0,
1609
- bottom: typeof r.bottom === "number" ? r.bottom : 0,
1610
- left: typeof r.left === "number" ? r.left : 0
1611
- };
1612
- }
1613
- const cssEnv = requireInsets("cssEnv") ?? {
1614
- top: 0,
1615
- right: 0,
1616
- bottom: 0,
1617
- left: 0
1618
- };
1619
- const sdkInsets = requireInsets("sdkInsets");
1620
- const sdkInsetsSource = obj.sdkInsetsSource === "window.__sdk" || obj.sdkInsetsSource === "window.__ait" ? obj.sdkInsetsSource : null;
1621
- const sdkInsetsError = typeof obj.sdkInsetsError === "string" ? obj.sdkInsetsError : void 0;
1622
- const navBarHeight = typeof obj.navBarHeight === "number" ? obj.navBarHeight : null;
1623
- const navBarHeightSource = typeof obj.navBarHeightSource === "string" ? obj.navBarHeightSource : "not-exposed-by-sdk";
1624
- const innerWidth = typeof obj.innerWidth === "number" ? obj.innerWidth : 0;
1625
- const innerHeight = typeof obj.innerHeight === "number" ? obj.innerHeight : 0;
1626
- const devicePixelRatio = typeof obj.devicePixelRatio === "number" ? obj.devicePixelRatio : 1;
1627
- const userAgent = typeof obj.userAgent === "string" ? obj.userAgent : "";
1628
- return {
1629
- source,
1630
- cssEnv,
1631
- sdkInsets,
1632
- sdkInsetsSource,
1633
- ...sdkInsetsError !== void 0 ? { sdkInsetsError } : {},
1634
- navBarHeight,
1635
- navBarHeightSource,
1636
- innerWidth,
1637
- innerHeight,
1638
- devicePixelRatio,
1639
- userAgent
1640
- };
1641
- }
1642
- /**
1643
- * Runs the safe-area probe on the attached page and returns a normalized
1644
- * `SafeAreaMeasurement`. Read-only — does not mutate page state.
1645
- *
1646
- * `source` is supplied by the caller from the env detection SSoT (see
1647
- * `src/mcp/environment.ts`). The same `Runtime.evaluate` call runs in both
1648
- * envs — the probe expression tries `window.__sdk` first (relay) then
1649
- * `window.__ait` (mock), so mock fidelity is enforced by the panel's
1650
- * `applyViewport`/`computeSafeAreaInsets` keeping `__ait.state.safeAreaInsets`
1651
- * correct (RFC #277 Tier C parity, #275 model).
1652
- *
1653
- * Throws on CDP error, probe exception, or result parse failure.
1654
- */
1655
- async function measureSafeArea(connection, source) {
1656
- const result = await connection.send("Runtime.evaluate", {
1657
- expression: SAFE_AREA_PROBE_EXPRESSION,
1658
- returnByValue: true,
1659
- awaitPromise: false
1660
- });
1661
- if (result.exceptionDetails) {
1662
- const msg = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text ?? "Runtime.evaluate threw an exception";
1663
- throw new Error(`measure_safe_area: probe threw — ${msg}`);
1664
- }
1665
- return normalizeSafeAreaResult(result.result.value, source);
1666
- }
1667
- /**
1668
- * Evaluates an arbitrary JS expression on the attached page via
1669
- * `Runtime.evaluate`. NOT read-only — the expression may have side effects.
1670
- *
1671
- * Throws if the evaluation produced a CDP exception.
1672
- *
1673
- * SECRET-HANDLING: expression and result value are NOT written to any log.
1674
- */
1675
- async function evaluate(connection, expression) {
1676
- const result = await connection.send("Runtime.evaluate", {
1677
- expression,
1678
- returnByValue: true,
1679
- awaitPromise: false
1680
- });
1681
- if (result.exceptionDetails) {
1682
- const msg = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text ?? "Runtime.evaluate threw an exception";
1683
- throw new Error(`evaluate failed: ${msg}`);
1684
- }
1685
- return {
1686
- value: result.result.value,
1687
- type: result.result.type
1688
- };
1689
- }
1690
- /**
1691
- * Builds the Runtime.evaluate expression that calls `window.__sdkCall` with
1692
- * the given method name and args, awaits the promise, and returns a JSON
1693
- * envelope `{ok, value/error}` as a string.
1694
- *
1695
- * Name and args are embedded via `JSON.stringify` so they are safely escaped.
1696
- * The expression checks for `window.__sdkCall` and returns a clear error if
1697
- * it is absent (non-dog-food bundle).
1698
- *
1699
- * SECRET-HANDLING: the expression is built here and MUST NOT be written to
1700
- * any log or stderr by the caller.
1701
- */
1702
- function buildCallSdkExpression(name, args) {
1703
- return `(async () => { if (typeof window.__sdkCall !== 'function') { return JSON.stringify({ok:false,error:'sdk-absent: window.__sdkCall이 주입되지 않았습니다 (dog-food 빌드가 아닙니다). dog-food 채널로 재배포하세요.'}); } try { const r = await window.__sdkCall(${JSON.stringify(name)}, ...${JSON.stringify(args)}); return JSON.stringify({ok:true,value:r}); } catch(e) { return JSON.stringify({ok:false,error:String(e && e.message || e)}); }})()`;
1704
- }
1705
- /**
1706
- * Parses the JSON envelope string returned by the `call_sdk` expression.
1707
- * Returns a typed `CallSdkResult`.
1708
- *
1709
- * Throws only on parse failure (not on ok:false — that is a normal result).
1710
- */
1711
- function normalizeCallSdkResult(rawValue) {
1712
- if (typeof rawValue !== "string") throw new Error(`call_sdk: bridge returned unexpected type "${typeof rawValue}" — expected JSON string`);
1713
- let parsed;
1714
- try {
1715
- parsed = JSON.parse(rawValue);
1716
- } catch {
1717
- throw new Error("call_sdk: bridge returned non-JSON string");
1718
- }
1719
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("call_sdk: parsed result is not an object");
1720
- const obj = parsed;
1721
- if (obj.ok === true) return {
1722
- ok: true,
1723
- value: obj.value
1724
- };
1725
- if (obj.ok === false) return {
1726
- ok: false,
1727
- error: typeof obj.error === "string" ? obj.error : String(obj.error)
1728
- };
1729
- throw new Error("call_sdk: bridge result missing \"ok\" field");
1730
- }
1731
- /**
1732
- * Looks up the most recent exception from the buffer that falls within the
1733
- * triage window [windowStart, windowEnd]. Returns `undefined` if none found.
1734
- *
1735
- * The heuristic window is:
1736
- * - windowStart = callStart - 50ms (catch sync throws before bridge fires)
1737
- * - windowEnd = callEnd + 200ms (catch async throws resolved soon after)
1738
- *
1739
- * Only the most recent exception within the window is returned (the one most
1740
- * likely to be causally related to the SDK call).
1741
- */
1742
- function findRecentException(connection, windowStart, windowEnd) {
1743
- const events = connection.getBufferedEvents("Runtime.exceptionThrown");
1744
- for (let i = events.length - 1; i >= 0; i--) {
1745
- const e = events[i];
1746
- if (e.timestamp >= windowStart && e.timestamp <= windowEnd) return normalizeException(e);
1747
- }
1748
- }
1749
- /**
1750
- * Calls a dog-food SDK method via `window.__sdkCall` on the attached page.
1751
- * NOT read-only — SDK calls may have side effects.
1752
- *
1753
- * On env 3/4 (toss WebView relay) this hits the real SDK. On env 1 (local
1754
- * mock) and env 2 (PWA relay — real WebKit, mock SDK) it hits the mock SDK.
1755
- *
1756
- * 인자 시그니처 검증: 등록된 메서드는 bridge 호출 전에 인자를 검증하고, mismatch면
1757
- * `{ok:false, error}` MCP 오류 결과를 반환한다(bridge에 도달하지 않음).
1758
- * 미등록 메서드는 passthrough + stderr 경고 1회.
1759
- *
1760
- * Throws on CDP error or result parse failure. Returns `{ok:false, error}`
1761
- * for bridge-level errors (method not found, SDK threw, bridge absent) or
1762
- * argument schema violations.
1763
- *
1764
- * If a `Runtime.exceptionThrown` event was observed within the triage window
1765
- * [callStart-50ms, callEnd+200ms], the result includes `recentException` for
1766
- * crash triage. This window is a heuristic — it catches the common case of an
1767
- * SDK throw immediately before/after the bridge resolves.
1768
- *
1769
- * SECRET-HANDLING: name, args, and the result value are NOT written to any log.
1770
- */
1771
- async function callSdk(connection, name, args) {
1772
- const signature = lookupSignature(name);
1773
- if (signature !== void 0) {
1774
- const validation = signature.validateArgs(args);
1775
- if (!validation.ok) return {
1776
- ok: false,
1777
- error: `call_sdk("${name}") 인자 시그니처 오류.\n받음: ${validation.received}\n기대: ${validation.expected}\n올바른 예시: ${signature.example}`
1778
- };
1779
- } else warnPassthrough(name);
1780
- const callStart = Date.now();
1781
- const expression = buildCallSdkExpression(name, args);
1782
- const result = await connection.send("Runtime.evaluate", {
1783
- expression,
1784
- returnByValue: true,
1785
- awaitPromise: true
1786
- });
1787
- const callEnd = Date.now();
1788
- if (result.exceptionDetails) {
1789
- const msg = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text ?? "Runtime.evaluate threw an exception";
1790
- throw new Error(`call_sdk threw: ${msg}`);
1791
- }
1792
- const sdkResult = normalizeCallSdkResult(result.result.value);
1793
- const recentException = findRecentException(connection, callStart - 50, callEnd + 200);
1794
- if (recentException !== void 0) return {
1795
- ...sdkResult,
1796
- recentException
1797
- };
1798
- return sdkResult;
1799
- }
1800
- /** Set of tool names served by the AIT source rather than the CDP connection. */
1801
- const AIT_TOOL_NAMES = new Set([
1802
- "AIT.getSdkCallHistory",
1803
- "AIT.getMockState",
1804
- "AIT.getOperationalEnvironment"
1805
- ]);
1806
- /** True for the Phase 3 AIT.* tools (served by an `AitSource`, not CDP). */
1807
- function isAitToolName(name) {
1808
- return AIT_TOOL_NAMES.has(name);
1809
- }
1810
- /** Returns the recent SDK call trace (`AIT.getSdkCallHistory`). */
1811
- function getSdkCallHistory(source) {
1812
- return source.get("AIT.getSdkCallHistory");
1813
- }
1814
- /** Returns the devtools mock-state snapshot (`AIT.getMockState`). */
1815
- function getMockState(source) {
1816
- return source.get("AIT.getMockState");
1817
- }
1818
- /** Returns the operational environment + SDK version (`AIT.getOperationalEnvironment`). */
1819
- function getOperationalEnvironment(source) {
1820
- return source.get("AIT.getOperationalEnvironment");
1821
- }
1822
- /** Secret-redaction patterns applied before error messages enter the buffer. */
1823
- const SECRET_REDACT_PATTERNS = [
1824
- [/\bat=([^&\s"']+)/g, "at=<redacted>"],
1825
- [/((?:set-)?cookie)\s*:\s*.+/gi, "$1: <redacted>"],
1826
- [/AITCC_API_KEY\s*=\s*\S+/gi, "AITCC_API_KEY=<redacted>"],
1827
- [/Authorization\s*:\s*.+/gi, "Authorization: <redacted>"],
1828
- [/\bBearer\s+\S+/g, "Bearer <redacted>"]
1829
- ];
1830
- /**
1831
- * Applies all secret-redaction patterns to an error message string.
1832
- * Used before storing errors in the `DiagnosticsCollector` ring buffer.
1833
- *
1834
- * SECRET-HANDLING: this is the single bottleneck for redaction — all error
1835
- * strings must pass through here before reaching the buffer.
1836
- */
1837
- function redactErrorMessage(message) {
1838
- let result = message;
1839
- for (const [pattern, replacement] of SECRET_REDACT_PATTERNS) result = result.replace(pattern, replacement);
1840
- return result;
1841
- }
1842
- /** Default max buffer size for the error ring buffer. */
1843
- const DEFAULT_ERROR_BUFFER_SIZE = 50;
1844
- /**
1845
- * In-memory implementation of `DiagnosticsCollector`. Thread-safe in the
1846
- * single-threaded Node.js sense (synchronous mutations only).
1847
- */
1848
- var InMemoryDiagnosticsCollector = class {
1849
- buffer = [];
1850
- maxSize;
1851
- lastAttachAt = null;
1852
- lastDetachAt = null;
1853
- authRejectCount = 0;
1854
- lastAuthRejectAt = null;
1855
- constructor(maxSize = DEFAULT_ERROR_BUFFER_SIZE) {
1856
- this.maxSize = maxSize;
1857
- }
1858
- recordError(message, category) {
1859
- const entry = {
1860
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1861
- message: redactErrorMessage(message),
1862
- ...category !== void 0 ? { category } : {}
1863
- };
1864
- this.buffer.push(entry);
1865
- if (this.buffer.length > this.maxSize) this.buffer.shift();
1866
- }
1867
- getRecentErrors(limit) {
1868
- const cap = Math.min(Math.max(1, limit), DEFAULT_ERROR_BUFFER_SIZE);
1869
- return this.buffer.length > cap ? this.buffer.slice(this.buffer.length - cap) : [...this.buffer];
1870
- }
1871
- recordAttach() {
1872
- this.lastAttachAt = (/* @__PURE__ */ new Date()).toISOString();
1873
- }
1874
- recordDetach() {
1875
- this.lastDetachAt = (/* @__PURE__ */ new Date()).toISOString();
1876
- }
1877
- getLastAttachAt() {
1878
- return this.lastAttachAt;
1879
- }
1880
- getLastDetachAt() {
1881
- return this.lastDetachAt;
1882
- }
1883
- recordAuthReject() {
1884
- this.authRejectCount += 1;
1885
- this.lastAuthRejectAt = (/* @__PURE__ */ new Date()).toISOString();
1886
- }
1887
- getAuthRejects() {
1888
- return {
1889
- count: this.authRejectCount,
1890
- lastAt: this.lastAuthRejectAt
1891
- };
1892
- }
1893
- };
1894
- /**
1895
- * Returns the `@modelcontextprotocol/sdk` version baked in at build time via
1896
- * the `__MCP_SDK_VERSION__` define (see `tsdown.config.ts`). Returns `null`
1897
- * when the define is absent (unbundled test runs) and the runtime fallback
1898
- * below also fails — diagnostics must never throw.
1899
- *
1900
- * Earlier attempts resolved `@modelcontextprotocol/sdk/package.json` (not in
1901
- * the SDK `exports` map → `ERR_PACKAGE_PATH_NOT_EXPORTED`) or the bare
1902
- * `@modelcontextprotocol/sdk` main entry (also absent → `MODULE_NOT_FOUND`),
1903
- * so both this fallback AND the build-time define silently produced `null` —
1904
- * leaving `mcpVersion: null` in a real bundle (issue #361, observed live). The
1905
- * fix resolves a subpath that IS exported (`./server/mcp.js`) and walks back to
1906
- * the package root, in BOTH the build define and this fallback.
1907
- *
1908
- * Kept `async` for call-site compatibility (`Promise.all` at the caller); the
1909
- * body is synchronous apart from the best-effort fallback.
1910
- */
1911
- async function readMcpSdkVersion() {
1912
- return "1.29.0";
1913
- }
1914
- /**
1915
- * Returns the `@ait-co/devtools` package version injected at build time via
1916
- * the `__VERSION__` define. Returns `null` when the global is absent (e.g. in
1917
- * some test environments that skip the build step).
1918
- */
1919
- function readDevtoolsVersion() {
1920
- return "0.1.122";
1921
- }
1922
- /**
1923
- * Derives the next recommended action from a completed diagnostics snapshot.
1924
- *
1925
- * Branch rules (evaluated in priority order):
1926
- * 0. tunnel.droppedAt non-null → restart (permanent tunnel drop — highest priority)
1927
- * 1. tunnel.up === false AND env is relay → restart (relay needs a live tunnel)
1928
- * 1b. tunnel.up === false AND env is mock → wait_for_page (local target: tunnel-less is normal)
1929
- * 2a. authRejects.count > 0 AND pages empty → start_attach (relay TOTP 거부 관측 — QR 재스캔
1930
- * 또는 target-side `at` 전달 확인. 일반 rule 2보다 구체적이므로 먼저 평가 — issue #467)
1931
- * 2. tunnel.up, pages empty, env === relay → start_attach (start attach)
1932
- * 3. pages has entry + crashDetectedAt non-null → start_attach (re-attach after crash)
1933
- * 4. otherwise → null (session looks healthy)
1934
- *
1935
- * Pure — does not throw; receives the final assembled snapshot fields.
1936
- *
1937
- * SECRET-HANDLING: the auth-reject reason string carries only the count and
1938
- * timestamp from {@link AuthRejectsSnapshot} — never a URL, code, or secret.
1939
- */
1940
- function computeNextRecommendedAction(tunnel, pages, env, authRejects = null) {
1941
- if (tunnel.droppedAt != null) return {
1942
- tool: "restart",
1943
- reason: `tunnel permanently dropped at ${tunnel.droppedAt} after ${tunnel.reissueAttempts} reissue attempt(s) — restart the MCP server (npx @ait-co/devtools devtools-mcp)`
1944
- };
1945
- if (!tunnel.up) if (!isRelayEnv(env)) {
1946
- if (pages !== null && pages.pages.length === 0 && !pages.crashDetectedAt) return {
1947
- tool: "wait_for_page",
1948
- reason: "local Chromium spawn 직후 — 페이지 로드를 기다리거나 list_pages를 재호출하세요 (local 모드는 tunnel이 없는 게 정상입니다)"
1949
- };
1950
- } else return {
1951
- tool: "restart",
1952
- reason: "tunnel not up — run `npx @ait-co/devtools devtools-mcp` to restart"
1953
- };
1954
- if (authRejects !== null && authRejects.count > 0 && pages !== null && pages.pages.length === 0) return {
1955
- tool: "start_attach",
1956
- reason: `relay 인증(TOTP) 거부 ${authRejects.count}건 발생 (last ${authRejects.lastAt ?? "unknown"}) — QR을 다시 스캔해 새 코드로 attach하세요(코드는 ~3분마다 만료). 반복되면 폰 페이지 URL에 at 파라미터가 전달되는지(target-side TOTP 전달 경로)를 확인하세요`
1957
- };
1958
- if (isRelayEnv(env) && pages !== null && pages.pages.length === 0 && !pages.crashDetectedAt) return {
1959
- tool: "start_attach",
1960
- reason: "tunnel ready, no pages attached — call start_attach to generate the attach QR"
1961
- };
1962
- if (pages !== null && pages.crashDetectedAt !== null) return {
1963
- tool: "start_attach",
1964
- reason: `page crashed at ${pages.crashDetectedAt} — call start_attach to re-attach`
1965
- };
1966
- return null;
1967
- }
1968
- /**
1969
- * Builds the `get_debug_status` response. Pure — does not throw; missing data
1970
- * fields are `null`. Async because `readMcpSdkVersion` needs `import()`.
1971
- *
1972
- * SECRET-HANDLING:
1973
- * - `recentErrors` messages are already redacted by `recordError` (via
1974
- * `redactErrorMessage`). No additional redaction needed here.
1975
- * - `tunnel.wssUrl` is a public cloudflared hostname — not a secret.
1976
- * - Lock file data contains only pid + startedAt + wssUrl — no secrets.
1977
- */
1978
- async function getDiagnostics(input) {
1979
- const { tunnel, connection, env, envReason, collector, readLock: readLockFn, recentErrorsLimit = 10, getMcpVersion = readMcpSdkVersion, checkParentAlive = () => isPidAlive(process.ppid), tunnelChildPid } = input;
1980
- const [mcpVersion, devtoolsVersion] = await Promise.all([getMcpVersion(), Promise.resolve(readDevtoolsVersion())]);
1981
- const lockData = readLockFn();
1982
- const serverLockHolder = lockData ? {
1983
- pid: lockData.pid,
1984
- startedAt: lockData.startedAt,
1985
- wssUrl: lockData.wssUrl
1986
- } : null;
1987
- const effectiveTunnelChildPid = tunnelChildPid ?? lockData?.tunnelChildPid ?? null;
1988
- let effectiveUp = tunnel.up;
1989
- if (tunnel.up && typeof effectiveTunnelChildPid === "number" && effectiveTunnelChildPid !== null && !isPidAlive(effectiveTunnelChildPid)) effectiveUp = false;
1990
- const tunnelInfo = {
1991
- up: effectiveUp,
1992
- wssUrl: tunnel.wssUrl,
1993
- pid: lockData?.pid ?? null,
1994
- startedAt: lockData?.startedAt ?? null,
1995
- droppedAt: tunnel.droppedAt ?? null,
1996
- reissueAttempts: tunnel.reissueAttempts ?? 0
1997
- };
1998
- let pages = null;
1999
- if (connection !== void 0) {
2000
- try {
2001
- await connection.refreshTargets?.();
2002
- } catch {}
2003
- try {
2004
- pages = listPages(connection, tunnel);
2005
- } catch {}
2006
- }
2007
- const limit = Math.min(Math.max(1, recentErrorsLimit), 50);
2008
- const recentErrors = collector.getRecentErrors(limit);
2009
- const authRejects = collector.getAuthRejects();
2010
- if (authRejects.count > 0) recentErrors.push({
2011
- timestamp: authRejects.lastAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2012
- message: `WS upgrade auth-rejected (${authRejects.count} times, last ${authRejects.lastAt ?? "unknown"})`,
2013
- category: "auth"
2014
- });
2015
- const nextRecommendedAction = computeNextRecommendedAction(tunnelInfo, pages, env, authRejects);
2016
- return {
2017
- mcpVersion,
2018
- devtoolsVersion,
2019
- tunnel: tunnelInfo,
2020
- pages,
2021
- lastAttachAt: collector.getLastAttachAt(),
2022
- lastDetachAt: collector.getLastDetachAt(),
2023
- recentErrors,
2024
- authRejects,
2025
- environment: {
2026
- kind: env,
2027
- env: toLegacyEnv(env),
2028
- reason: envReason,
2029
- liveGuardActive: false
2030
- },
2031
- serverLockHolder,
2032
- process: {
2033
- pid: process.pid,
2034
- ppid: process.ppid,
2035
- parentAlive: checkParentAlive()
2036
- },
2037
- nextRecommendedAction
2038
- };
2039
- }
2040
- //#endregion
2041
- //#region src/mcp/tunnel.ts
2042
- /**
2043
- * cloudflared quick tunnel + attach banner for the debug-mode MCP server.
2044
- *
2045
- * On spawn, the debug server opens an accountless `*.trycloudflare.com` quick
2046
- * tunnel to the local Chii relay so the phone can attach over a public wss URL,
2047
- * then prints a unicode half-block QR + attach instructions. When TOTP auth is
2048
- * enabled (`AIT_DEBUG_TOTP_SECRET` is set), the QR encodes only the base relay
2049
- * URL — the TOTP code (`at=`) is NOT included because it rotates every 30 s
2050
- * and would be stale by the time a human scans. The in-app deep-link builder
2051
- * splices the live code at attach time.
2052
- *
2053
- * Tunnel health probe (`TunnelHealthProbe`):
2054
- * After the tunnel is up, a periodic HTTP HEAD probe hits the tunnel's
2055
- * `https://` URL every `probeIntervalMs` (default 60 s). Two consecutive
2056
- * failures trigger a reissue attempt (spawn a new cloudflared quick tunnel
2057
- * and redirect traffic). After `MAX_REISSUE_ATTEMPTS` (3) consecutive
2058
- * reissue failures, the probe gives up and marks the tunnel permanently
2059
- * dropped — `tunnelStatus.up` becomes false with `droppedAt` set. The caller
2060
- * should surface this to the agent so the user knows to restart the server.
2061
- *
2062
- * SECRET-HANDLING: The TOTP secret and computed code values MUST NOT appear
2063
- * in any output from this module.
2064
- *
2065
- * Node-only: spawns the cloudflared binary and writes to stdout/stderr.
2066
- */
2067
- /** Generates a 32-byte hex attach token shown as a pairing hint (relay-side validation is a later phase). */
2068
- function generateAttachToken() {
2069
- return randomBytes(32).toString("hex");
2070
- }
2071
- /** Ensures the cloudflared binary is installed (downloads + caches on first run). */
2072
- async function ensureCloudflaredBin() {
2073
- const { existsSync } = await import("node:fs");
2074
- if (!existsSync(bin)) await install(bin);
2075
- }
2076
- /**
2077
- * Opens a cloudflared quick tunnel to the local relay port and resolves once
2078
- * the public URL is assigned.
2079
- *
2080
- * FIX 1 (issue #571): after URL resolution the returned `QuickTunnel` object
2081
- * watches the cloudflared child process for unexpected exits and calls any
2082
- * registered `onUnexpectedExit` callback so the health probe can immediately
2083
- * trigger reissue instead of waiting for the next poll interval.
2084
- */
2085
- async function startQuickTunnel(localPort) {
2086
- await ensureCloudflaredBin();
2087
- const tunnel = Tunnel.quick(`http://127.0.0.1:${localPort}`);
2088
- const url = await new Promise((resolve, reject) => {
2089
- const onUrl = (assigned) => {
2090
- cleanup();
2091
- resolve(assigned);
2092
- };
2093
- const onError = (err) => {
2094
- cleanup();
2095
- reject(err);
2096
- };
2097
- const onExit = (code) => {
2098
- cleanup();
2099
- reject(/* @__PURE__ */ new Error(`cloudflared exited before assigning a URL (code ${code})`));
2100
- };
2101
- const cleanup = () => {
2102
- tunnel.off("url", onUrl);
2103
- tunnel.off("error", onError);
2104
- tunnel.off("exit", onExit);
2105
- };
2106
- tunnel.once("url", onUrl);
2107
- tunnel.once("error", onError);
2108
- tunnel.once("exit", onExit);
2109
- });
2110
- let intentionalStop = false;
2111
- let unexpectedExitCb = null;
2112
- tunnel.once("exit", (code) => {
2113
- if (!intentionalStop && unexpectedExitCb !== null) unexpectedExitCb(code);
2114
- });
2115
- return {
2116
- url,
2117
- wssUrl: url.replace(/^https/, "wss"),
2118
- childPid: tunnel.process?.pid,
2119
- onUnexpectedExit(cb) {
2120
- unexpectedExitCb = cb;
2121
- },
2122
- stop() {
2123
- intentionalStop = true;
2124
- tunnel.stop();
2125
- }
2126
- };
2127
- }
2128
- /**
2129
- * Renders a pure unicode half-block QR string for the given text.
2130
- *
2131
- * Uses `qrcode` (Node full lib) to get the raw bit matrix, then encodes every
2132
- * two vertical modules into a single half-block character:
2133
- * - both dark → `█`
2134
- * - top only → `▀`
2135
- * - bottom only → `▄`
2136
- * - both light → ` ` (space)
2137
- *
2138
- * The output contains **zero ANSI escape codes**, so it renders correctly in
2139
- * every surface (terminal, VS Code, JetBrains, web) and can be scanned by a
2140
- * phone camera when shown verbatim in an agent response.
2141
- *
2142
- * Shared by `renderAttachBanner` (relay wssUrl QR) and the `start_attach`
2143
- * MCP tool response (attach deep-link QR).
2144
- */
2145
- async function renderQr(text) {
2146
- const { default: QRCode } = await import("qrcode");
2147
- const qr = QRCode.create(text, { errorCorrectionLevel: "M" });
2148
- const size = qr.modules.size;
2149
- const data = qr.modules.data;
2150
- const isDark = (x, y) => {
2151
- if (x < 0 || y < 0 || x >= size || y >= size) return false;
2152
- return data[y * size + x] === 1;
2153
- };
2154
- const QUIET = 1;
2155
- const lines = [];
2156
- for (let y = -QUIET; y < size + QUIET; y += 2) {
2157
- let line = "";
2158
- for (let x = -QUIET; x < size + QUIET; x++) {
2159
- const top = isDark(x, y);
2160
- const bot = isDark(x, y + 1);
2161
- line += top && bot ? "█" : top ? "▀" : bot ? "▄" : " ";
2162
- }
2163
- lines.push(line);
2164
- }
2165
- return `${lines.join("\n")}\n`;
2166
- }
2167
- /**
2168
- * Renders the attach banner (relay URL + unicode half-block QR) as a string.
2169
- *
2170
- * The QR is produced by `renderQr` (a half-block matrix, not the
2171
- * `qrcode-terminal` ASCII art used by the unplugin banner) and encodes the
2172
- * base `wssUrl` only. When `totpEnabled` is true, a note
2173
- * is added that attach URLs generated by `start_attach` will include a
2174
- * live TOTP code (`at=`) appended at call time.
2175
- *
2176
- * SECRET-HANDLING: no secret value, TOTP code, or intermediate value is
2177
- * included in this output.
2178
- */
2179
- async function renderAttachBanner(input) {
2180
- const qr = await renderQr(input.wssUrl);
2181
- const authNote = input.totpEnabled ? " auth: TOTP enabled — attach URLs include a rotating code (at=)." : " auth: none (set AIT_DEBUG_TOTP_SECRET to enable TOTP).";
2182
- return [
2183
- "",
2184
- "AIT debug — attach a mini-app to this session",
2185
- "",
2186
- ` relay (wss): ${input.wssUrl}`,
2187
- authNote,
2188
- "",
2189
- " Use start_attach to generate a deep link with the current TOTP code.",
2190
- " Scan the QR to locate the relay (open the dog-food URL separately with",
2191
- " ?debug=1&relay=<wss>&at=<code> or use the start_attach tool):",
2192
- "",
2193
- qr
2194
- ].join("\n");
2195
- }
2196
- /** Prints the attach banner to stderr (stdout is the MCP stdio channel). */
2197
- async function printAttachBanner(input) {
2198
- const banner = await renderAttachBanner(input);
2199
- process.stderr.write(`${banner}\n`);
2200
- }
2201
- /**
2202
- * Probes `https://` URL with an HTTP HEAD request.
2203
- * Returns `true` when the server responds (any HTTP status), `false` on
2204
- * network error or timeout.
2205
- *
2206
- * We treat any HTTP response (including 4xx/5xx) as "tunnel alive" because
2207
- * cloudflared itself responds to the HEAD — if the tunnel process died, the
2208
- * request fails at the network level rather than returning a status code.
2209
- *
2210
- * @param httpsUrl - The `https://` tunnel URL to probe.
2211
- * @param timeoutMs - Abort timeout in ms. Default 10 000.
2212
- */
2213
- async function probeTunnel(httpsUrl, timeoutMs = 1e4) {
2214
- const { default: https } = await import("node:https");
2215
- return new Promise((resolve) => {
2216
- const url = new URL(httpsUrl);
2217
- const timer = setTimeout(() => {
2218
- req.destroy();
2219
- resolve(false);
2220
- }, timeoutMs);
2221
- const req = https.request({
2222
- hostname: url.hostname,
2223
- port: 443,
2224
- path: url.pathname || "/",
2225
- method: "HEAD"
2226
- }, (_res) => {
2227
- clearTimeout(timer);
2228
- _res.resume();
2229
- resolve(true);
2230
- });
2231
- req.on("error", () => {
2232
- clearTimeout(timer);
2233
- resolve(false);
2234
- });
2235
- req.end();
2236
- });
2237
- }
2238
- /**
2239
- * Starts a periodic health probe for a cloudflared quick tunnel.
2240
- *
2241
- * Every `probeIntervalMs` the probe sends an HTTP HEAD request to the tunnel's
2242
- * `https://` URL. When `failuresBeforeReissue` consecutive failures are
2243
- * detected, it attempts to spawn a new tunnel (up to `MAX_REISSUE_ATTEMPTS`
2244
- * times). On success the caller is notified via `onReissue`; on permanent
2245
- * failure via `onPermanentDrop`.
2246
- *
2247
- * FIX 1 (issue #571): the probe also subscribes to each tunnel's
2248
- * `onUnexpectedExit` callback to detect child death *immediately* instead of
2249
- * waiting for the next probe interval (which could be 60 s away).
2250
- *
2251
- * @returns `stop` — call during server shutdown to clear the probe interval.
2252
- */
2253
- function startTunnelHealthProbe(initialTunnel, localPort, options) {
2254
- const { probeIntervalMs = 6e4, failuresBeforeReissue = 2, onReissue, onPermanentDrop, log = (msg) => process.stderr.write(msg), probe = probeTunnel, spawnTunnel = startQuickTunnel } = options;
2255
- let currentTunnel = initialTunnel;
2256
- let consecutiveFailures = 0;
2257
- let reissueAttempts = 0;
2258
- let stopped = false;
2259
- const doReissueOrDrop = async () => {
2260
- if (stopped) return;
2261
- reissueAttempts += 1;
2262
- if (reissueAttempts > 3) return;
2263
- log(`[ait-debug] tunnel drop detected — reissuing (attempt ${reissueAttempts}/3)\n`);
2264
- try {
2265
- const newTunnel = await spawnTunnel(localPort);
2266
- try {
2267
- currentTunnel.stop();
2268
- } catch {}
2269
- currentTunnel = newTunnel;
2270
- consecutiveFailures = 0;
2271
- armChildExitWatch(newTunnel);
2272
- log(`[ait-debug] tunnel reissued — new relay: ${newTunnel.wssUrl}\n`);
2273
- onReissue(newTunnel);
2274
- } catch (err) {
2275
- const message = err instanceof Error ? err.message : String(err);
2276
- log(`[ait-debug] tunnel reissue attempt ${reissueAttempts} failed: ${message}\n`);
2277
- if (reissueAttempts >= 3) {
2278
- clearInterval(handle);
2279
- stopped = true;
2280
- const droppedAt = (/* @__PURE__ */ new Date()).toISOString();
2281
- log(`[ait-debug] tunnel permanently dropped after 3 reissue attempts — restart the debug server to continue (npx @ait-co/devtools devtools-mcp).
2282
- `);
2283
- onPermanentDrop(droppedAt);
2284
- }
2285
- }
2286
- };
2287
- const armChildExitWatch = (t) => {
2288
- t.onUnexpectedExit((code) => {
2289
- if (stopped) return;
2290
- log(`[ait-debug] cloudflared child exited unexpectedly (code=${code}) — triggering immediate reissue\n`);
2291
- consecutiveFailures = failuresBeforeReissue;
2292
- doReissueOrDrop();
2293
- });
2294
- };
2295
- armChildExitWatch(initialTunnel);
2296
- const handle = setInterval(() => {
2297
- (async () => {
2298
- if (stopped) return;
2299
- const httpsUrl = currentTunnel.url;
2300
- if (await probe(httpsUrl)) {
2301
- if (consecutiveFailures > 0) log("[ait-debug] tunnel health probe: tunnel recovered\n");
2302
- consecutiveFailures = 0;
2303
- reissueAttempts = 0;
2304
- return;
2305
- }
2306
- consecutiveFailures += 1;
2307
- log(`[ait-debug] tunnel health probe: failure ${consecutiveFailures}/${failuresBeforeReissue} (url=${httpsUrl})\n`);
2308
- if (consecutiveFailures < failuresBeforeReissue) return;
2309
- await doReissueOrDrop();
2310
- })();
2311
- }, probeIntervalMs);
2312
- return { stop() {
2313
- stopped = true;
2314
- clearInterval(handle);
2315
- } };
2316
- }
2317
- /**
2318
- * Builds a `TunnelStatus` snapshot that includes drop state.
2319
- *
2320
- * Convenience helper for callers (debug-server) that maintain a mutable
2321
- * `tunnelStatus` object — keeps the shape construction in one place.
2322
- */
2323
- function makeTunnelStatus(up, wssUrl, droppedAt = null, reissueAttempts = 0) {
2324
- return {
2325
- up,
2326
- wssUrl,
2327
- droppedAt,
2328
- reissueAttempts
2329
- };
2330
- }
2331
- //#endregion
2332
- //#region src/mcp/attach-orchestrator.ts
2333
- /**
2334
- * Maximum age (ms) of a page's `lastSeenAt` before it is treated as a ghost
2335
- * and excluded from the `wait_for_attach` short-circuit in `start_attach`
2336
- * (issue #610).
2337
- *
2338
- * Rationale: the env-2 relay is owned by the dev server (unplugin), so every
2339
- * `dev:phone:cdp` restart produces a new quick-tunnel. The old relay goes
2340
- * offline immediately, but the daemon's warm `ChiiCdpConnection` still lists
2341
- * the last-seen target — its `lastSeenAt` freezes at the moment the old relay
2342
- * died. A 5-minute threshold is large enough to be invisible in normal usage
2343
- * (active CDP sessions see a message every few seconds) while being small
2344
- * enough to catch a relay that went down before the daemon was re-entered.
2345
- *
2346
- * Injectable for tests via {@link AttachDeps.stalePageThresholdMs}.
2347
- */
2348
- const RELAY_SANDBOX_STALE_PAGE_MS = 300 * 1e3;
2349
- /**
2350
- * Segment length (ms) of the `start_attach` wait loop (issue #626 — TOTP in-call
2351
- * re-mint). The single-shot `wait_for_attach` of the old attach tool could
2352
- * not re-mint a TOTP code mid-wait; `start_attach` decomposes the wait into
2353
- * SEGMENT_MS slices so it can detect an aging code between slices and re-mint a
2354
- * fresh one without the agent re-calling the tool. 30 s = one TOTP step.
2355
- */
2356
- const START_ATTACH_SEGMENT_MS = 3e4;
2357
- /**
2358
- * Elapsed-since-mint threshold (ms) at which `start_attach` re-mints a fresh
2359
- * TOTP code during its wait loop (issue #626). The relay gate accepts a code for
2360
- * `RELAY_VERIFY_SKEW_STEPS` (6) × 30 s = 180 s backwards from issuance; we re-mint
2361
- * at 150 s to leave a 30 s margin so a phone scan never lands on an expired code.
2362
- */
2363
- const START_ATTACH_REMINT_THRESHOLD_MS = 15e4;
2364
- /**
2365
- * Predicate used by `start_attach`'s `wait_for_attach` loop to decide
2366
- * whether the relay-sandbox connection has a genuinely fresh page attached.
2367
- *
2368
- * Stale-ghost gating (issue #610): when the dev server restarts with a new
2369
- * quick-tunnel, the warm `ChiiCdpConnection` still lists the last-seen target
2370
- * but its `lastSeenAt` is frozen. A page whose `lastSeenAt` exceeds
2371
- * `stalePageThresholdMs` is a ghost from the dead relay — it must NOT
2372
- * short-circuit `wait_for_attach`.
2373
- *
2374
- * Rules:
2375
- * - `pages.length === 0` → false (nothing attached).
2376
- * - Connection has no `getLastSeenAt` (test fakes, local-browser) → falls back
2377
- * to `pages.length > 0` (regression-safe).
2378
- * - `seenMs === null` → treat as fresh (no CDP message received yet, first
2379
- * message pending — the connection is alive).
2380
- * - Otherwise: at least one page must satisfy `nowMs - seenMs <=
2381
- * stalePageThresholdMs`.
2382
- *
2383
- * Exported for unit testing.
2384
- */
2385
- function isSandboxPageFresh(pages, getLastSeenAt, nowMs, stalePageThresholdMs) {
2386
- if (pages.length === 0) return false;
2387
- if (getLastSeenAt === null) return true;
2388
- return pages.some((p) => {
2389
- const seenMs = getLastSeenAt(p.id);
2390
- if (seenMs === null) return true;
2391
- return nowMs - seenMs <= stalePageThresholdMs;
2392
- });
2393
- }
2394
- /**
2395
- * Parses `_deploymentId` from the query string of a scheme URL.
2396
- *
2397
- * Returns `null` when the param is absent or empty — callers treat that as
2398
- * "no deploymentId filter; match on presence only" and fall back to the
2399
- * original `attachedPages.length > 0` condition.
2400
- *
2401
- * SECRET-HANDLING: deploymentId is a public identifier and may appear in
2402
- * debug output. Never confuse it with TOTP secrets or relay tunnel URLs.
2403
- */
2404
- function extractDeploymentId(schemeUrl) {
2405
- try {
2406
- const qIndex = schemeUrl.indexOf("?");
2407
- if (qIndex === -1) return null;
2408
- const id = new URLSearchParams(schemeUrl.slice(qIndex + 1)).get("_deploymentId");
2409
- return id && id.length > 0 ? id : null;
2410
- } catch {
2411
- return null;
2412
- }
2413
- }
2414
- /** Resolves `deps.stalePageThresholdMs` to its default. */
2415
- function resolveStalePageThresholdMs(deps) {
2416
- return deps.stalePageThresholdMs ?? 3e5;
2417
- }
2418
- /** Resolves `deps.nowMs` to its default (`Date.now`). */
2419
- function resolveNowMs(deps) {
2420
- return deps.nowMs ?? (() => Date.now());
2421
- }
2422
- /** Resolves `deps.canOpenBrowser` to the module default. */
2423
- function resolveCanOpenBrowser(deps) {
2424
- return deps.canOpenBrowser ?? canOpenBrowser;
2425
- }
2426
- /**
2427
- * Waits for the first target matching `filterFn` to attach, using the
2428
- * event-driven `waitForFirstTarget()` when the connection supports it
2429
- * (interface-optional member, present on `ChiiCdpConnection`), or falling
2430
- * back to a polling loop for connections that don't implement it (test fakes,
2431
- * `LocalCdpConnection`).
2432
- *
2433
- * This eliminates the polling-only race that previously caused `wait_for_attach`
2434
- * to resolve before the relay had observed the first inbound CDP message from
2435
- * the phone.
2436
- *
2437
- * Timeout note: callers (e.g. the `start_attach` path) always pass an
2438
- * explicit `timeoutMs`, sourced from the factory's `waitForAttachTimeoutMs`
2439
- * (default 60 000). That value is forwarded to `waitForFirstTarget`, so it
2440
- * overrides that method's own 90 000 signature default — the effective
2441
- * wait on the tool path is 60 s, not 90 s.
2442
- *
2443
- * @param connection - The CDP connection (production or fake).
2444
- * @param filterFn - Resolves when this predicate is satisfied.
2445
- * @param timeoutMs - Maximum wait time in ms.
2446
- * @param pollIntervalMs - Fallback poll interval for connections without waitForFirstTarget.
2447
- */
2448
- function waitForAttachWithEvents(connection, filterFn, timeoutMs, pollIntervalMs = 1e3) {
2449
- if (connection.waitForFirstTarget) return connection.waitForFirstTarget(filterFn, timeoutMs, pollIntervalMs);
2450
- return new Promise((resolve, reject) => {
2451
- const deadline = Date.now() + timeoutMs;
2452
- let settled = false;
2453
- const poll = setInterval(() => {
2454
- const targets = connection.listTargets();
2455
- if (filterFn(targets)) {
2456
- settled = true;
2457
- clearInterval(poll);
2458
- resolve(targets);
2459
- } else if (Date.now() >= deadline) {
2460
- settled = true;
2461
- clearInterval(poll);
2462
- reject(/* @__PURE__ */ new Error(`waitForAttachWithEvents: 타임아웃 (${timeoutMs}ms)`));
2463
- }
2464
- }, pollIntervalMs);
2465
- const targets = connection.listTargets();
2466
- if (!settled && filterFn(targets)) {
2467
- settled = true;
2468
- clearInterval(poll);
2469
- resolve(targets);
2470
- }
2471
- });
2472
- }
2473
- /**
2474
- * Synthesizes an attach URL from stored components with a FRESHLY-minted TOTP
2475
- * code (issue #626 §3/§4 — the single mint point). Reads the late-bound secret
2476
- * via `deps.getTotpSecret()` so the project-local `.ait_relay` secret loaded by
2477
- * `switchMode` is visible. SECRET-HANDLING: the minted code rides inside the
2478
- * URL's `at=` param only — never logged or returned separately.
2479
- */
2480
- function mintAttachUrl(deps, parts) {
2481
- const secret = deps.getTotpSecret();
2482
- const code = secret ? generateTotp(secret) : void 0;
2483
- return parts.kind === "launcher" ? buildLauncherAttachUrl(parts.tunnelHttpUrl, parts.wssUrl, code, {
2484
- name: parts.appName,
2485
- ...parts.selfdebug ? { selfdebug: true } : {}
2486
- }) : buildDeepLinkAttachUrl(parts.schemeUrl, parts.wssUrl, code);
2487
- }
2488
- /** Builds the fresh TOTP metadata (expiresAt window) for a tool result. */
2489
- function buildTotpMeta(deps) {
2490
- const secret = deps.getTotpSecret();
2491
- if (secret === void 0 || secret === "") return void 0;
2492
- const STEP_SECONDS = 30;
2493
- const expiresAtMs = resolveNowMs(deps)() + 6 * STEP_SECONDS * 1e3;
2494
- return {
2495
- enabled: true,
2496
- ttlSeconds: 6 * STEP_SECONDS,
2497
- expiresAt: new Date(expiresAtMs).toISOString()
2498
- };
2499
- }
2500
- /**
2501
- * Env-specific validation + component bundle for `start_attach` (issue #626).
2502
- * Branches on `env`: `relay-mobile` reads AIT_TUNNEL_BASE_URL + builds launcher
2503
- * parts; `relay-dev` requires scheme_url + builds scheme parts. Returns
2504
- * `{ ok: false, error }` with a ready McpResult on any failure.
2505
- */
2506
- async function prepareAttach(deps, env, args, conn) {
2507
- const { getTunnelStatus, getTotpSecret } = deps;
2508
- const stalePageThresholdMs = resolveStalePageThresholdMs(deps);
2509
- const nowMs = resolveNowMs(deps);
2510
- const selfdebug = args?.selfdebug === true;
2511
- if (selfdebug && env !== "relay-mobile") return {
2512
- ok: false,
2513
- error: mcpError("start_attach: selfdebug=true는 env 2 / relay-sandbox 전용 기능입니다. 현재 환경(env 3)에서는 launcher가 없어 self-target 모드를 지원하지 않습니다. launcher self-target이 필요하다면 relay-sandbox 모드로 전환하세요.")
2514
- };
2515
- if (env === "relay-mobile") {
2516
- const rawProjectRoot = args?.projectRoot;
2517
- const buildProjectRoot = typeof rawProjectRoot === "string" ? rawProjectRoot : void 0;
2518
- let tunnelHttpUrl = process.env.AIT_TUNNEL_BASE_URL?.trim() ?? "";
2519
- if (tunnelHttpUrl === "" && buildProjectRoot !== void 0) {
2520
- const { readRelayUrls } = await import("./relay-url-store-D3H067u0.js");
2521
- tunnelHttpUrl = (await readRelayUrls({ projectRoot: buildProjectRoot }))?.tunnelBaseUrl ?? "";
2522
- }
2523
- if (tunnelHttpUrl === "") return {
2524
- ok: false,
2525
- error: mcpError("start_attach(mobile): AIT_TUNNEL_BASE_URL이 설정되지 않았습니다. dev 서버가 tunnel:{cdp:true}로 기동 중이면 .ait_urls 파일이 자동 생성돼 있어야 합니다. 자동 발견이 되지 않을 경우 앱 HTTP 터널 URL을 AIT_TUNNEL_BASE_URL 환경변수로 직접 전달하세요.")
2526
- };
2527
- const tunnelStatus = getTunnelStatus();
2528
- if (!tunnelStatus.up || tunnelStatus.wssUrl === null) return {
2529
- ok: false,
2530
- error: mcpError("start_attach(mobile): relay wssUrl이 아직 설정되지 않았습니다. unplugin tunnel:{cdp:true}가 relay를 완전히 기동할 때까지 잠시 후 다시 시도하세요.")
2531
- };
2532
- const secret = getTotpSecret();
2533
- if (secret === void 0 || secret === "") return {
2534
- ok: false,
2535
- error: mcpError("start_attach(relay): TOTP secret(AIT_DEBUG_TOTP_SECRET)이 설정되지 않았습니다. relay 환경은 TOTP 인증이 필수입니다 — relay를 secret과 함께 재기동하세요.")
2536
- };
2537
- let launcherAppName;
2538
- if (buildProjectRoot !== void 0) try {
2539
- const { readFileSync } = await import("node:fs");
2540
- const pkgRaw = readFileSync(`${buildProjectRoot}/package.json`, "utf8");
2541
- const pkg = JSON.parse(pkgRaw);
2542
- const rawName = typeof pkg.name === "string" ? pkg.name : "";
2543
- launcherAppName = (rawName.includes("/") ? rawName.slice(rawName.indexOf("/") + 1) : rawName).trim() || void 0;
2544
- } catch {}
2545
- const parts = {
2546
- kind: "launcher",
2547
- tunnelHttpUrl,
2548
- wssUrl: tunnelStatus.wssUrl,
2549
- appName: launcherAppName,
2550
- ...selfdebug ? { selfdebug: true } : {}
2551
- };
2552
- const connAsAny = conn;
2553
- const getLastSeenAt = typeof connAsAny.getTargetLastSeenAt === "function" ? (id) => connAsAny.getTargetLastSeenAt(id) : null;
2554
- const callNow = nowMs();
2555
- const isMatchingPage = (pages) => isSandboxPageFresh(pages, getLastSeenAt, callNow, stalePageThresholdMs);
2556
- const buildTimeoutError = (baseText, timeoutSec, observed) => {
2557
- const observedUrls = observed.slice(0, 3).map((p) => p.url.slice(0, 80)).join(", ");
2558
- return `${baseText}\n\nNo page attached within ${timeoutSec}s${observed.length > 0 ? ` — previously attached pages: [${observedUrls}]` : ""} — launcher QR을 폰 카메라로 스캔한 뒤 call list_pages를 다시 호출하세요.`;
2559
- };
2560
- return {
2561
- ok: true,
2562
- parts,
2563
- isMatchingPage,
2564
- buildTimeoutError,
2565
- authorityWarning: void 0,
2566
- totpMeta: buildTotpMeta(deps)
2567
- };
2568
- }
2569
- const schemeUrl = args?.scheme_url;
2570
- if (typeof schemeUrl !== "string" || schemeUrl === "") return {
2571
- ok: false,
2572
- error: mcpError("start_attach: scheme_url이 비어 있습니다. `ait deploy --scheme-only`가 출력하는 intoss-private:// URL을 인자로 전달하세요. 환경 2(mobile)라면 scheme_url 대신 AIT_TUNNEL_BASE_URL을 설정하세요.")
2573
- };
2574
- {
2575
- const relaySecret = getTotpSecret();
2576
- if (relaySecret === void 0 || relaySecret === "") return {
2577
- ok: false,
2578
- error: mcpError("start_attach(relay): TOTP secret(AIT_DEBUG_TOTP_SECRET)이 설정되지 않았습니다. relay 환경은 TOTP 인증이 필수입니다 — relay를 secret과 함께 재기동하세요.")
2579
- };
2580
- }
2581
- const tunnelForBuild = getTunnelStatus();
2582
- if (!tunnelForBuild.up || tunnelForBuild.wssUrl === null) return {
2583
- ok: false,
2584
- error: classifyToolError(/* @__PURE__ */ new Error("tunnel-down:"), "start_attach")
2585
- };
2586
- const authorityWarning = validateSchemeAuthority(schemeUrl) ?? void 0;
2587
- const parts = {
2588
- kind: "scheme",
2589
- schemeUrl,
2590
- wssUrl: tunnelForBuild.wssUrl
2591
- };
2592
- const deploymentId = extractDeploymentId(schemeUrl);
2593
- if (!deploymentId) logInfo("tool.call", {
2594
- tool: "start_attach",
2595
- msg: "no _deploymentId in scheme_url; matching on presence only"
2596
- });
2597
- const isMatchingPage = (pages) => {
2598
- if (pages.length === 0) return false;
2599
- if (deploymentId === null) return true;
2600
- return pages.some((p) => p.url.includes(deploymentId));
2601
- };
2602
- const buildTimeoutError = (baseText, timeoutSec, observed) => {
2603
- const observedUrls = observed.slice(0, 3).map((p) => p.url.slice(0, 80)).join(", ");
2604
- const observedNote = observed.length > 0 ? ` — previously attached pages: [${observedUrls}]` : "";
2605
- return `${baseText}\n\nNo page${deploymentId ? ` matching deploymentId=${deploymentId}` : ""} attached within ${timeoutSec}s${observedNote} — call list_pages to retry.`;
2606
- };
2607
- return {
2608
- ok: true,
2609
- parts,
2610
- isMatchingPage,
2611
- buildTimeoutError,
2612
- authorityWarning,
2613
- totpMeta: buildTotpMeta(deps)
2614
- };
2615
- }
2616
- /**
2617
- * QR render + browser open + segmented attach wait with in-call TOTP re-mint
2618
- * (issue #626 §3). Shared by env-2 and env-3 (4 render paths:
2619
- * headless / browser-opened / browser-open-failed / no-http-server).
2620
- *
2621
- * The wait is decomposed into `START_ATTACH_SEGMENT_MS` slices. Between slices,
2622
- * if the current TOTP code has aged past `START_ATTACH_REMINT_THRESHOLD_MS`,
2623
- * a fresh URL is minted via `mintAttachUrl` and pushed to the dashboard via
2624
- * `onAttachUrlBuilt` (SSE refresh — NO browser re-open). The `reminted` count
2625
- * rides in the success/timeout result.
2626
- *
2627
- * SECRET-HANDLING: attachUrl encodes tunnel/scheme host + the TOTP `at=` code
2628
- * in the QR payload only. The browser is opened on a 127.0.0.1 URL only. The
2629
- * tool result carries `totp.expiresAt` + `reminted` count — never the code.
2630
- */
2631
- async function renderAndMaybeWait(deps, prep, waitForAttach, callTimeoutMs, conn) {
2632
- const { getTunnelStatus, qrHttpServer, onAttachUrlBuilt } = deps;
2633
- const nowMs = resolveNowMs(deps);
2634
- const canOpenBrowserFn = resolveCanOpenBrowser(deps);
2635
- const { parts, isMatchingPage, buildTimeoutError, authorityWarning, totpMeta } = prep;
2636
- let attachUrl = mintAttachUrl(deps, parts);
2637
- onAttachUrlBuilt?.(parts);
2638
- let totpIssuedAt = nowMs();
2639
- let reminted = 0;
2640
- const relayUrl = parts.wssUrl;
2641
- const header = "This tool result is shown to the user directly — do NOT re-print the QR below in your reply (it wastes output tokens). Just tell the user to scan the QR in this output (Ctrl+O to expand if collapsed).";
2642
- const warningPrefix = authorityWarning ? `⚠️ scheme_url 경고: ${authorityWarning}\n\n` : "";
2643
- const guiAvailable = canOpenBrowserFn();
2644
- /** Builds the totp object surfaced in results (fresh expiresAt + reminted). */
2645
- const totpResult = () => {
2646
- if (!totpMeta) return void 0;
2647
- const expiresAtMs = totpIssuedAt + 180 * 1e3;
2648
- return {
2649
- enabled: true,
2650
- ttlSeconds: totpMeta.ttlSeconds,
2651
- expiresAt: new Date(expiresAtMs).toISOString(),
2652
- ...reminted > 0 ? { reminted } : {}
2653
- };
2654
- };
2655
- /**
2656
- * Segmented wait with TOTP re-mint (issue #626 §3). Resolves with the
2657
- * attached page list, or rejects on timeout. Between SEGMENT_MS slices it
2658
- * re-mints when the code has aged past the threshold (max ~4 re-mints over
2659
- * 600 s). Returns immediately once a matching page attaches (no re-mint).
2660
- */
2661
- async function waitWithRemint() {
2662
- const deadline = nowMs() + callTimeoutMs;
2663
- if (isMatchingPage(conn.listTargets())) return conn.listTargets();
2664
- for (;;) {
2665
- const remaining = deadline - nowMs();
2666
- if (remaining <= 0) throw new Error(`start_attach: 타임아웃 (${callTimeoutMs}ms)`);
2667
- const segmentMs = Math.min(START_ATTACH_SEGMENT_MS, remaining);
2668
- try {
2669
- return await waitForAttachWithEvents(conn, isMatchingPage, segmentMs);
2670
- } catch {
2671
- if (totpMeta && nowMs() - totpIssuedAt >= 15e4) {
2672
- attachUrl = mintAttachUrl(deps, parts);
2673
- onAttachUrlBuilt?.(parts);
2674
- totpIssuedAt = nowMs();
2675
- reminted += 1;
2676
- }
2677
- }
2678
- }
2679
- }
2680
- /**
2681
- * Assembles the success result after a page attaches. `baseText` carries the
2682
- * QR + pre-wait JSON block (the QR the user already scanned). The attach
2683
- * itself ends the wait, so the QR is moot — what matters now is the final
2684
- * TOTP state. If the segmented wait re-minted (issue #626 §3), surface the
2685
- * post-wait `totp` block (fresh `expiresAt` + `reminted` count) so the result
2686
- * reflects how many times the code rotated during the wait. SECRET-HANDLING:
2687
- * the totp block carries expiresAt + reminted only — never the code value.
2688
- */
2689
- const successResult = (baseText) => {
2690
- const pagesResult = listPages(conn, getTunnelStatus());
2691
- const finalTotp = totpResult();
2692
- const remintNote = finalTotp && reminted > 0 ? `\n\n${JSON.stringify({ totp: finalTotp }, null, 2)}` : "";
2693
- return { content: [{
2694
- type: "text",
2695
- text: `${baseText}\n\n${JSON.stringify(pagesResult, null, 2)}${remintNote}`
2696
- }] };
2697
- };
2698
- /** Runs the wait (when requested) and returns success/timeout result. */
2699
- const runWait = async (baseText) => {
2700
- if (!waitForAttach) return { content: [{
2701
- type: "text",
2702
- text: baseText
2703
- }] };
2704
- try {
2705
- await waitWithRemint();
2706
- } catch {
2707
- const observed = conn.listTargets();
2708
- return {
2709
- content: [{
2710
- type: "text",
2711
- text: buildTimeoutError(baseText, callTimeoutMs / 1e3, observed)
2712
- }],
2713
- isError: true
2714
- };
2715
- }
2716
- return successResult(baseText);
2717
- };
2718
- if (!guiAvailable) {
2719
- const headlessNote = "GUI 환경이 감지되지 않았습니다 (headless/remote 환경). 텍스트 QR을 폰 카메라로 스캔하거나, 로컬 GUI 환경에서 실행하세요.\n\n";
2720
- const qr = await renderQr(attachUrl);
2721
- return runWait(`${warningPrefix}${headlessNote}${header}\n${JSON.stringify({
2722
- attachUrl,
2723
- relayUrl,
2724
- ...totpResult() ? { totp: totpResult() } : {}
2725
- }, null, 2)}\n\n${qr}`);
2726
- }
2727
- if (guiAvailable && qrHttpServer) {
2728
- const browserResult = await openQrInBrowser(qrHttpServer.buildAttachPageUrl(attachUrl), `http://127.0.0.1:${qrHttpServer.port}/qr.png?u=${encodeURIComponent(attachUrl)}`);
2729
- if (browserResult.opened) {
2730
- const retriedNote = browserResult.retried ? " (1회 retry 후 성공)" : "";
2731
- const openResult = {
2732
- attempted: true,
2733
- succeeded: true,
2734
- ...browserResult.retried ? { retried: true } : {}
2735
- };
2736
- return runWait(`${warningPrefix}${header}\n${JSON.stringify({
2737
- relayUrl,
2738
- openResult,
2739
- ...totpResult() ? { totp: totpResult() } : {}
2740
- }, null, 2)}\n\n브라우저에서 QR을 열었습니다${retriedNote}. 폰 카메라로 스캔하세요.\nURL: ${browserResult.httpUrl}`);
2741
- }
2742
- const openResult = {
2743
- attempted: true,
2744
- succeeded: false,
2745
- failureReason: browserResult.error ?? "브라우저 실행 후보 모두 실패",
2746
- pngUrl: browserResult.pngUrl,
2747
- ...browserResult.stderrSummary ? { stderrSummary: browserResult.stderrSummary } : {}
2748
- };
2749
- const stderrNote = browserResult.stderrSummary ? `\nstderr: ${browserResult.stderrSummary}` : "";
2750
- const fallbackNote = `브라우저 자동 열기에 실패했습니다. 다음 URL을 직접 브라우저에서 여세요:\n${browserResult.httpUrl}\n또는 PNG로 받기: ${browserResult.pngUrl}` + stderrNote + "\n\n";
2751
- const qr = await renderQr(attachUrl);
2752
- return runWait(`${warningPrefix}${fallbackNote}${header}\n${JSON.stringify({
2753
- attachUrl,
2754
- relayUrl,
2755
- openResult,
2756
- ...totpResult() ? { totp: totpResult() } : {}
2757
- }, null, 2)}\n\n${qr}`);
2758
- }
2759
- const qr = await renderQr(attachUrl);
2760
- return runWait(`${warningPrefix}${header}\n${JSON.stringify({
2761
- attachUrl,
2762
- relayUrl,
2763
- ...totpResult() ? { totp: totpResult() } : {}
2764
- }, null, 2)}\n\n${qr}`);
2765
- }
2766
- /**
2767
- * Builds a self-contained IIFE DOM expression that renders a dismissible
2768
- * "Debugger Connected" badge on the bottom-left of the phone screen.
2769
- *
2770
- * **Pure function** — returns a JS expression string; does NOT inject it.
2771
- * Injection is performed by {@link injectDebugIndicator} in `cell.ts`.
2772
- *
2773
- * The expression, when evaluated on the page, does the following:
2774
- * 1. Early-returns if `#__ait_debug_indicator` already exists (idempotent —
2775
- * prevents duplicate badges on re-injection after page reload).
2776
- * 2. Appends a fixed-position `<div id="__ait_debug_indicator">` at the
2777
- * bottom-left, accounting for safe-area insets.
2778
- * 3. Attaches a `{ once: true }` `pointerdown` listener that removes the
2779
- * badge on first touch — one-tap dismiss.
2780
- *
2781
- * The expression intentionally contains NO relay URLs, wss addresses, TOTP
2782
- * codes, or any other secrets. It is pure DOM UI text only.
2783
- *
2784
- * SECRET-HANDLING: this expression contains no secrets, relay URLs, wss
2785
- * addresses, or TOTP codes whatsoever — DOM label text only.
2786
- *
2787
- * @param opts.label - Badge text (default: `'Debugger Connected'`).
2788
- * @returns A JS expression string suitable for `Runtime.evaluate`.
2789
- */
2790
- function buildIndicatorExpression(opts) {
2791
- const label = opts?.label ?? "Debugger Connected";
2792
- return `(() => {if (document.getElementById('__ait_debug_indicator')) return;const el = document.createElement('div');el.id = '__ait_debug_indicator';el.style.cssText = ['position:fixed','left:max(12px,calc(env(safe-area-inset-left,0px) + 8px))','bottom:max(12px,calc(env(safe-area-inset-bottom,0px) + 8px))','z-index:2147483647','background:#e5484d','color:#fff','font:bold 11px/1 system-ui,sans-serif','padding:5px 9px','border-radius:6px','pointer-events:auto','user-select:none',].join(';');el.textContent = ${JSON.stringify(label)};el.addEventListener('pointerdown', () => el.remove(), { once: true });document.body.appendChild(el);})()`;
2793
- }
2794
- //#endregion
2795
- export { buildDeepLinkAttachUrl as $, isDebugToolName as A, readServerLock as B, getDiagnostics as C, getSdkCallHistory as D, getOperationalEnvironment as E, listPages as F, logWarn as G, isRelayEnv as H, measureSafeArea as I, pageCrashError as J, classifyToolError as K, takeScreenshot as L, listConsoleMessages as M, listExceptions as N, getToolAvailability as O, listNetworkRequests as P, tierRejectionError as Q, takeSnapshot as R, filterToolsByEnvironment as S, getMockState as T, logError as U, deriveEnvironment as V, logInfo as W, relayDisconnectError as X, pageMissingError as Y, sdkAbsentError as Z, BOOTSTRAP_TOOL_NAMES as _, buildTotpMeta as a, callSdk as b, mintAttachUrl as c, waitForAttachWithEvents as d, buildLauncherAttachUrl as et, generateAttachToken as f, startTunnelHealthProbe as g, startQuickTunnel as h, buildIndicatorExpression as i, isToolAvailableIn as j, isAitToolName as k, prepareAttach as l, printAttachBanner as m, START_ATTACH_REMINT_THRESHOLD_MS as n, startParentWatcher as nt, extractDeploymentId as o, makeTunnelStatus as p, mcpError as q, START_ATTACH_SEGMENT_MS as r, isSandboxPageFresh as s, RELAY_SANDBOX_STALE_PAGE_MS as t, startMaxAgeWatchdog as tt, renderAndMaybeWait as u, DEBUG_TOOL_DEFINITIONS as v, getDomDocument as w, evaluate as x, InMemoryDiagnosticsCollector as y, acquireLock as z };
2796
-
2797
- //# sourceMappingURL=attach-orchestrator-BYMCSPjf.js.map