@ait-co/devtools 0.1.115 → 0.1.117

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 (46) hide show
  1. package/dist/cli-CvUNQKqw.js +2552 -0
  2. package/dist/cli-CvUNQKqw.js.map +1 -0
  3. package/dist/debug-server-BvrESnaV.js +921 -0
  4. package/dist/debug-server-BvrESnaV.js.map +1 -0
  5. package/dist/debug-server-jrI9U_f4.js +8259 -0
  6. package/dist/debug-server-jrI9U_f4.js.map +1 -0
  7. package/dist/mcp/cli.js +3 -7925
  8. package/dist/mcp/cli.js.map +1 -1
  9. package/dist/mcp/server.js +11 -2
  10. package/dist/mcp/server.js.map +1 -1
  11. package/dist/panel/index.js +1 -1
  12. package/dist/{pool-D23t4ibd.d.ts → pool-htlVnEFl.d.ts} +2 -2
  13. package/dist/{pool-D23t4ibd.d.ts.map → pool-htlVnEFl.d.ts.map} +1 -1
  14. package/dist/relay-secret-store-BHcOmaNK.js +3 -0
  15. package/dist/relay-secret-store-CkA7KNUb.js +154 -0
  16. package/dist/{relay-secret-store-DhzAnnj-.js.map → relay-secret-store-CkA7KNUb.js.map} +1 -1
  17. package/dist/{relay-secret-store-DhzAnnj-.js → relay-secret-store-CmqchhR5.js} +3 -3
  18. package/dist/relay-secret-store-CmqchhR5.js.map +1 -0
  19. package/dist/{relay-url-store-CwKT7i04.js → relay-url-store-C0qukm3R.js} +2 -2
  20. package/dist/{relay-url-store-CwKT7i04.js.map → relay-url-store-C0qukm3R.js.map} +1 -1
  21. package/dist/relay-url-store-NDtEcOE-.js +123 -0
  22. package/dist/relay-url-store-NDtEcOE-.js.map +1 -0
  23. package/dist/{relay-worker-DERQUao2.d.ts → relay-worker-DWW4vZxU.d.ts} +2 -2
  24. package/dist/{relay-worker-DERQUao2.d.ts.map → relay-worker-DWW4vZxU.d.ts.map} +1 -1
  25. package/dist/{runtime-BKMMoeMj.d.ts → runtime-BU-iMHz6.d.ts} +43 -4
  26. package/dist/runtime-BU-iMHz6.d.ts.map +1 -0
  27. package/dist/test-runner/cli.d.ts +19 -7
  28. package/dist/test-runner/cli.d.ts.map +1 -1
  29. package/dist/test-runner/cli.js +1 -620
  30. package/dist/test-runner/config.d.ts +1 -1
  31. package/dist/test-runner/pool.d.ts +1 -1
  32. package/dist/test-runner/relay-worker.d.ts +1 -1
  33. package/dist/test-runner/rpc.d.ts +1 -1
  34. package/dist/test-runner/runtime.d.ts +1 -1
  35. package/dist/test-runner/runtime.js +111 -3
  36. package/dist/test-runner/runtime.js.map +1 -1
  37. package/dist/test-runner/task-graph.d.ts +1 -1
  38. package/dist/totp-D104cJQN.js +3 -0
  39. package/dist/{totp-WY6l0ysP.js → totp-D70zD5tJ.js} +1 -1
  40. package/dist/{totp-WY6l0ysP.js.map → totp-D70zD5tJ.js.map} +1 -1
  41. package/dist/totp-DvOYkYim.js +212 -0
  42. package/dist/totp-DvOYkYim.js.map +1 -0
  43. package/package.json +1 -1
  44. package/dist/runtime-BKMMoeMj.d.ts.map +0 -1
  45. package/dist/test-runner/cli.js.map +0 -1
  46. package/dist/totp-D1pulXLa.js +0 -3
@@ -0,0 +1,2552 @@
1
+ #!/usr/bin/env node
2
+ import { r as generateTotp } from "./totp-DvOYkYim.js";
3
+ import { parseArgs } from "node:util";
4
+ import { accessSync } from "node:fs";
5
+ import * as path from "node:path";
6
+ import { isAbsolute, resolve } from "node:path";
7
+ import { randomBytes } from "node:crypto";
8
+ import { Tunnel, bin, install } from "cloudflared";
9
+ import * as fs from "node:fs/promises";
10
+ import { glob } from "node:fs/promises";
11
+ import { fileURLToPath } from "node:url";
12
+ //#region src/mcp/deeplink.ts
13
+ /**
14
+ * URL of the AITC Sandbox launcher PWA.
15
+ *
16
+ * Declared here (not imported from `src/unplugin/tunnel.ts`) to respect the
17
+ * mcp → unplugin layering boundary. unplugin/tunnel.ts declares its own copy
18
+ * for the same reason — keep the two in sync when the URL changes.
19
+ */
20
+ const LAUNCHER_URL = "https://devtools.aitc.dev/launcher/";
21
+ /**
22
+ * Builds a launcher PWA deep-link for env-2 MCP-attach (issue #378).
23
+ *
24
+ * The launcher at {@link LAUNCHER_URL} renders tunnelUrl in a full-viewport
25
+ * iframe. `&debug=1&relay=<wssUrl>` is forwarded onto the iframe src so the
26
+ * framed page's in-app debug gate (Layer C) is satisfied and a Chii target.js
27
+ * is injected. `&at=<totpCode>` is added only when a code is provided (same
28
+ * conditional as {@link buildDeepLinkAttachUrl}).
29
+ *
30
+ * When `opts.name` is given (non-blank), it is added as `&name=` so the
31
+ * launcher partner bar shows the app name instead of the generic default (#498).
32
+ * When `opts.icon` is an absolute https:// URL, it is added as `&icon=` so the
33
+ * launcher can render an icon next to the title (#498).
34
+ *
35
+ * Unlike `buildDeepLinkAttachUrl` (which splices onto a non-special scheme URL
36
+ * via raw string manipulation), this function uses WHATWG `encodeURIComponent`
37
+ * because the target is a standard `https:` URL.
38
+ *
39
+ * SECRET-HANDLING: `totpCode` (when provided) is placed into the `at=` param
40
+ * only — never logged or returned separately. Callers must NOT log the result
41
+ * of this function to stdout/stderr.
42
+ *
43
+ * @param tunnelUrl - The `https://*.trycloudflare.com` app tunnel URL
44
+ * (`AIT_TUNNEL_BASE_URL`). This is the URL the launcher frames.
45
+ * @param wssUrl - The `wss://` relay URL the framed page will attach to.
46
+ * @param totpCode - Optional current TOTP code (6 digits). When provided, it
47
+ * is appended as `at=<totpCode>`. Must be computed at call time — it rotates
48
+ * every 30 s. Omit when TOTP is disabled.
49
+ * @param opts - Optional app identity hints: `name`, `icon`, and `selfdebug`
50
+ * (#498, #543).
51
+ * @returns The launcher deep-link URL with `?url=<enc>&debug=1&relay=<enc>
52
+ * [&at=<code>][&name=<enc>][&icon=<enc>][&selfdebug=1]` params.
53
+ */
54
+ function buildLauncherAttachUrl(tunnelUrl, wssUrl, totpCode, opts) {
55
+ let url = `${LAUNCHER_URL}?url=${encodeURIComponent(tunnelUrl)}&debug=1&relay=${encodeURIComponent(wssUrl)}`;
56
+ if (totpCode !== void 0 && totpCode !== "") url += `&at=${encodeURIComponent(totpCode)}`;
57
+ if (opts?.name !== void 0 && opts.name.trim() !== "") url += `&name=${encodeURIComponent(opts.name.trim())}`;
58
+ if (opts?.icon !== void 0) {
59
+ let iconParsed;
60
+ try {
61
+ iconParsed = new URL(opts.icon);
62
+ } catch {
63
+ iconParsed = null;
64
+ }
65
+ if (iconParsed?.protocol === "https:") url += `&icon=${encodeURIComponent(opts.icon)}`;
66
+ }
67
+ if (opts?.selfdebug === true) url += "&selfdebug=1";
68
+ return url;
69
+ }
70
+ /**
71
+ * Build a self-attaching dog-food deep-link.
72
+ *
73
+ * `ait deploy --scheme-only` prints an `intoss-private://…?_deploymentId=<uuid>`
74
+ * URL that opens a dog-food bundle on a phone. The in-app debug gate
75
+ * (`src/in-app/gate.ts`) auto-attaches when the entry URL also carries
76
+ * `debug=1` and `relay=<wss-url>`. This helper splices those params (plus
77
+ * `at=<code>` when TOTP is enabled) into the scheme URL; rendering the result
78
+ * as a QR code and scanning it with the phone camera opens the mini-app and
79
+ * attaches it to the live Chii relay. QR is the single entry path — it needs
80
+ * no USB cable, platform CLI, or driver, and works the same on iOS/Android.
81
+ *
82
+ * The Toss app propagates extra query params from the entry deep link into the
83
+ * mini-app WebView's `location.search` (confirmed behavior), so the gate reads
84
+ * them at attach time.
85
+ *
86
+ * TOTP `at=` param:
87
+ * When a TOTP secret is active, `buildDeepLinkAttachUrl` accepts an optional
88
+ * `totpCode` argument and splices `at=<code>` alongside `debug` and `relay`.
89
+ * The code must be computed by the caller at call time — do NOT pre-compute
90
+ * and cache it, because the 30-second window expires quickly. The in-app gate
91
+ * (`src/in-app/gate.ts` Layer C) validates this code against the baked secret.
92
+ *
93
+ * Why not `URL`/`URLSearchParams`: `intoss-private:` is a non-special scheme.
94
+ * The WHATWG `URL` parser treats such schemes opaquely (no host/path/query
95
+ * decomposition you can rely on across runtimes), so query manipulation via
96
+ * `url.searchParams` is not portable here. We splice the query string directly
97
+ * on the raw string instead, which keeps the scheme, authority, path, and any
98
+ * pre-existing params (notably `_deploymentId`) byte-for-byte intact.
99
+ */
100
+ /**
101
+ * Suspicious/generic authority values that indicate a malformed or placeholder
102
+ * scheme URL. These are host strings that will almost certainly cause the Toss
103
+ * app to fail with "bundle not found" silently.
104
+ *
105
+ * The expected form from `ait deploy --scheme-only` is:
106
+ * intoss-private://<appName>?_deploymentId=<uuid>
107
+ * where `<appName>` is a non-generic string like `aitc-sdk-example`.
108
+ */
109
+ const SUSPICIOUS_AUTHORITIES = new Set([
110
+ "",
111
+ "web",
112
+ "localhost",
113
+ "127.0.0.1",
114
+ "app"
115
+ ]);
116
+ /**
117
+ * Validates the authority (host) portion of a scheme URL.
118
+ *
119
+ * Returns a warning message if the authority is missing or looks like a
120
+ * placeholder, or `null` if the authority looks valid.
121
+ *
122
+ * Expected form: `intoss-private://<appName>?_deploymentId=<uuid>`
123
+ * The authority must be a non-empty, non-generic app name (e.g. `aitc-sdk-example`).
124
+ */
125
+ function validateSchemeAuthority(schemeUrl) {
126
+ const afterScheme = schemeUrl.replace(/^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//, "");
127
+ 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`.";
128
+ const authorityEnd = afterScheme.search(/[/?#]/);
129
+ const authority = authorityEnd === -1 ? afterScheme : afterScheme.slice(0, authorityEnd);
130
+ 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.`;
131
+ return null;
132
+ }
133
+ function stripExisting(query, key) {
134
+ if (query === "") return "";
135
+ return query.split("&").filter((pair) => pair !== "" && pair.split("=")[0] !== key).join("&");
136
+ }
137
+ /**
138
+ * Splices `debug=1`, `relay=<wssUrl>`, and (optionally) `at=<totpCode>` into a
139
+ * scheme URL's query string, preserving everything else (scheme, authority,
140
+ * path, hash, and the existing `_deploymentId` param). If any of the spliced
141
+ * params is already present it is replaced so the helper is idempotent.
142
+ *
143
+ * @param schemeUrl - The `intoss-private://…?_deploymentId=<uuid>` URL printed
144
+ * by `ait deploy --scheme-only`. Must already carry `_deploymentId` (Layer B
145
+ * of the gate); this helper does not invent one.
146
+ * @param wssUrl - The live relay URL (`wss://…trycloudflare.com`) from the
147
+ * running debug MCP server's quick tunnel.
148
+ * @param totpCode - Optional current TOTP code (6 digits). When provided, it
149
+ * is spliced as `at=<totpCode>`. Must be computed at call time — it rotates
150
+ * every 30 s. Pass `undefined` or omit when TOTP is disabled.
151
+ * @returns The same URL with `debug=1&relay=<encoded wssUrl>[&at=<totpCode>]`
152
+ * appended.
153
+ * @throws If `wssUrl` is not a `wss:` URL (the gate rejects anything else, so
154
+ * producing such a link would be a silent dead end).
155
+ */
156
+ function buildDeepLinkAttachUrl(schemeUrl, wssUrl, totpCode) {
157
+ let relay;
158
+ try {
159
+ relay = new URL(wssUrl);
160
+ } catch {
161
+ throw new Error(`relay URL is not a valid URL: ${wssUrl}`);
162
+ }
163
+ if (relay.protocol !== "wss:") throw new Error(`relay URL must use the wss: scheme, got ${relay.protocol} (${wssUrl})`);
164
+ const hashIndex = schemeUrl.indexOf("#");
165
+ const hash = hashIndex === -1 ? "" : schemeUrl.slice(hashIndex);
166
+ const beforeHash = hashIndex === -1 ? schemeUrl : schemeUrl.slice(0, hashIndex);
167
+ const queryIndex = beforeHash.indexOf("?");
168
+ const base = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
169
+ let query = queryIndex === -1 ? "" : beforeHash.slice(queryIndex + 1);
170
+ const appended = [["debug", "1"], ["relay", wssUrl]];
171
+ if (totpCode !== void 0 && totpCode !== "") appended.push(["at", totpCode]);
172
+ query = stripExisting(query, "at");
173
+ for (const [key] of appended) query = stripExisting(query, key);
174
+ for (const [key, value] of appended) {
175
+ const pair = `${key}=${encodeURIComponent(value)}`;
176
+ query = query === "" ? pair : `${query}&${pair}`;
177
+ }
178
+ return `${base}?${query}${hash}`;
179
+ }
180
+ //#endregion
181
+ //#region src/mcp/errors.ts
182
+ /**
183
+ * 한국어 한 줄 "원인 + 다음 행동" 포맷으로 에러 결과를 빌드한다.
184
+ *
185
+ * @param message - 사용자에게 보여줄 에러 본문 (원인 + 다음 행동 포함).
186
+ */
187
+ function mcpError(message) {
188
+ return {
189
+ content: [{
190
+ type: "text",
191
+ text: message
192
+ }],
193
+ isError: true
194
+ };
195
+ }
196
+ /**
197
+ * 상태 1: tunnel 미가동 — cloudflared 터널이 아직 뜨지 않았다.
198
+ *
199
+ * `start_attach` 호출 시 tunnel.up === false 인 경우.
200
+ */
201
+ function tunnelDownError() {
202
+ return mcpError("cloudflared 터널이 안 떠 있습니다. MCP 서버를 재시작하거나 잠시 후 list_pages로 터널 상태를 다시 확인하세요.");
203
+ }
204
+ /**
205
+ * 상태 3: page crash — 연결됐던 페이지가 crash/destroy됐다.
206
+ *
207
+ * chii-connection 이 'replaced-by-new-attach' / 'targetCrashed' / 'targetDestroyed' 를
208
+ * 던질 때 이 메시지를 사용한다.
209
+ */
210
+ function pageCrashError(toolName) {
211
+ return mcpError(`${toolName ? `${toolName}: ` : ""}페이지가 crash됐습니다. 토스 앱을 재실행한 뒤 start_attach → QR 스캔으로 재attach하세요.`);
212
+ }
213
+ /**
214
+ * 상태 4: SDK 부재 — window.__sdkCall이 주입되지 않았다.
215
+ *
216
+ * call_sdk 호출 시 브리지가 없을 때. 같은 "브리지 부재"라도 다음 행동은
217
+ * connection 종류에 따라 정반대다 (issue #360):
218
+ * - relay(`--target` 없는 intoss / env-2): dog-food 빌드가 아니다 → dog-food
219
+ * 채널로 재배포 후 QR 재스캔.
220
+ * - local(`--target=local`, env 1 로컬 브라우저): 재배포가 아니라 dev 서버를
221
+ * `pnpm dev`로 띄웠는지 + unplugin alias가 `@apps-in-toss/web-framework`를
222
+ * devtools mock으로 resolve하는지 확인. dev 빌드면 `import.meta.env.DEV`
223
+ * 경로로 `window.__sdkCall`이 자동 설치된다.
224
+ *
225
+ * `isLocal`이 생략되면 relay 안내(이전 동작)를 유지한다.
226
+ */
227
+ function sdkAbsentError(toolName, isLocal = false) {
228
+ const prefix = toolName ? `${toolName}: ` : "";
229
+ 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\`이 자동 설치됩니다.`);
230
+ return mcpError(`${prefix}window.__sdkCall이 주입되지 않았습니다 (dog-food 빌드가 아닙니다). dog-food 채널(intoss-private)로 재배포 후 QR을 다시 스캔하세요: \`ait build && aitcc app deploy\`.`);
231
+ }
232
+ /**
233
+ * relay WebSocket 연결이 끊겼을 때 — 크래시가 아닌 네트워크/프로세스 종료.
234
+ */
235
+ function relayDisconnectError(toolName) {
236
+ return mcpError(`${toolName ? `${toolName}: ` : ""}relay 연결이 끊겼습니다. list_pages로 상태를 확인하고, 필요하면 앱을 재실행 후 재attach하세요.`);
237
+ }
238
+ /**
239
+ * CDP/AIT 명령 중 발생한 예외를 4상태로 분류해 적절한 에러 결과를 반환한다.
240
+ *
241
+ * - SDK 부재 패턴 (`window.__sdkCall is not available`) → sdkAbsentError
242
+ * - crash 패턴 (`replaced-by-new-attach`, `targetCrashed`, `targetDestroyed`) → pageCrashError
243
+ * - 연결 끊김 패턴 (`relay에 연결되어 있지 않습니다`, `relay WebSocket`) → relayDisconnectError
244
+ * - 그 외 (일반 에러) → 원본 메시지를 포함한 mcpError
245
+ */
246
+ function classifyToolError(err, toolName, isLocal = false) {
247
+ const message = err instanceof Error ? err.message : String(err);
248
+ if (message.startsWith("tunnel-down:") || message.includes("터널이 안 떠 있습니다")) return tunnelDownError();
249
+ 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);
250
+ if (message.includes("replaced-by-new-attach") || message.includes("targetCrashed") || message.includes("targetDestroyed") || message.includes("detachedFromTarget")) return pageCrashError(toolName);
251
+ if (message.includes("relay에 연결되어 있지 않습니다") || message.includes("relay WebSocket")) return relayDisconnectError(toolName);
252
+ return mcpError(`${toolName} 실패: ${message}\nlist_pages로 미니앱이 relay에 attach됐는지 확인하세요.`);
253
+ }
254
+ //#endregion
255
+ //#region src/mcp/log.ts
256
+ /**
257
+ * Allowed field keys that may pass through to a log line.
258
+ * Unknown keys are dropped. Values are still redact-scanned.
259
+ */
260
+ const ALLOWED_KEYS = new Set([
261
+ "ts",
262
+ "level",
263
+ "event",
264
+ "msg",
265
+ "port",
266
+ "totpEnabled",
267
+ "env",
268
+ "tool",
269
+ "deploymentId",
270
+ "errorKind",
271
+ "reason",
272
+ "prevTargetId",
273
+ "mode",
274
+ "fileCount",
275
+ "passed",
276
+ "failed",
277
+ "skipped"
278
+ ]);
279
+ /**
280
+ * Patterns that match secret values.
281
+ * Match order matters — more-specific patterns first.
282
+ *
283
+ * #268 redact script covers: relay=wss://…, at=<TOTP>, _deploymentId=<uuid>.
284
+ * Here we extend to in-process value-level patterns used in server logs.
285
+ */
286
+ const SECRET_PATTERNS = [
287
+ /^\d{6}$/,
288
+ /^(aitcc_|AITCC_)/i,
289
+ /^[A-Za-z0-9_-]+=.{4,}/,
290
+ /^wss:\/\//,
291
+ /(?:^|[?&])at=[A-Z0-9]{6}/i
292
+ ];
293
+ /**
294
+ * Returns `true` when the string value matches any known-secret pattern.
295
+ * Only string values are tested — numbers/booleans are always safe.
296
+ */
297
+ function isSecretValue(value) {
298
+ return SECRET_PATTERNS.some((re) => re.test(value));
299
+ }
300
+ /**
301
+ * Redacts a single scalar value.
302
+ * - strings: return "***" if the value matches a secret pattern.
303
+ * - other: return as-is.
304
+ */
305
+ function redactValue(value) {
306
+ if (typeof value === "string" && isSecretValue(value)) return "***";
307
+ return value;
308
+ }
309
+ /**
310
+ * Builds a safe log payload from raw fields.
311
+ *
312
+ * - Only keys in `ALLOWED_KEYS` are included.
313
+ * - String values are scanned for secret patterns and replaced with "***".
314
+ * - `ts` and `level` and `event` are always included (they are injected by the
315
+ * logger functions below, not by callers).
316
+ */
317
+ function buildPayload(level, event, fields) {
318
+ const out = {
319
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
320
+ level,
321
+ event
322
+ };
323
+ for (const [key, value] of Object.entries(fields)) {
324
+ if (!ALLOWED_KEYS.has(key)) continue;
325
+ if (key === "ts" || key === "level" || key === "event") continue;
326
+ out[key] = redactValue(value);
327
+ }
328
+ return out;
329
+ }
330
+ /**
331
+ * Writes a single JSON log line to stderr.
332
+ * MCP stdio transport uses stdout; all diagnostics go to stderr.
333
+ */
334
+ function writeLog(level, event, fields = {}) {
335
+ const payload = buildPayload(level, event, fields);
336
+ process.stderr.write(`${JSON.stringify(payload)}\n`);
337
+ }
338
+ /** Log an informational structured event. */
339
+ function logInfo(event, fields = {}) {
340
+ writeLog("info", event, fields);
341
+ }
342
+ /** Log an error structured event. */
343
+ function logError(event, fields = {}) {
344
+ writeLog("error", event, fields);
345
+ }
346
+ //#endregion
347
+ //#region src/mcp/sdk-signatures.ts
348
+ function isObject(v) {
349
+ return typeof v === "object" && v !== null && !Array.isArray(v);
350
+ }
351
+ function describeArgs(args) {
352
+ try {
353
+ return JSON.stringify(args);
354
+ } catch {
355
+ return String(args);
356
+ }
357
+ }
358
+ /**
359
+ * 등록된 메서드 목록.
360
+ *
361
+ * 시그니처 출처 확인:
362
+ * - 함수가 인자를 받지 않으면 args[0] 없음 → `args.length === 0`을 체크하지 않고
363
+ * 그냥 통과시킨다(args 무시하는 stub가 많아서 noArgs 체크가 noise).
364
+ * - 실 SDK 시그니처는 `src/__typecheck.ts`의 `Assert<Mock, Original>` 줄로 보장.
365
+ */
366
+ const SIGNATURES = [
367
+ {
368
+ name: "setDeviceOrientation",
369
+ validateArgs(args) {
370
+ const arg = args[0];
371
+ if (!isObject(arg)) return {
372
+ ok: false,
373
+ expected: "{ type: 'portrait' | 'landscape' }",
374
+ received: describeArgs(args)
375
+ };
376
+ const type = arg.type;
377
+ if (type !== "portrait" && type !== "landscape") return {
378
+ ok: false,
379
+ expected: "{ type: 'portrait' | 'landscape' }",
380
+ received: describeArgs(args)
381
+ };
382
+ return { ok: true };
383
+ },
384
+ example: "call_sdk('setDeviceOrientation', [{ type: 'landscape' }])"
385
+ },
386
+ {
387
+ name: "setIosSwipeGestureEnabled",
388
+ validateArgs(args) {
389
+ const arg = args[0];
390
+ if (!isObject(arg) || typeof arg.isEnabled !== "boolean") return {
391
+ ok: false,
392
+ expected: "{ isEnabled: boolean }",
393
+ received: describeArgs(args)
394
+ };
395
+ return { ok: true };
396
+ },
397
+ example: "call_sdk('setIosSwipeGestureEnabled', [{ isEnabled: false }])"
398
+ },
399
+ {
400
+ name: "setSecureScreen",
401
+ validateArgs(args) {
402
+ const arg = args[0];
403
+ if (!isObject(arg) || typeof arg.enabled !== "boolean") return {
404
+ ok: false,
405
+ expected: "{ enabled: boolean }",
406
+ received: describeArgs(args)
407
+ };
408
+ return { ok: true };
409
+ },
410
+ example: "call_sdk('setSecureScreen', [{ enabled: true }])"
411
+ },
412
+ {
413
+ name: "setScreenAwakeMode",
414
+ validateArgs(args) {
415
+ const arg = args[0];
416
+ if (!isObject(arg) || typeof arg.enabled !== "boolean") return {
417
+ ok: false,
418
+ expected: "{ enabled: boolean }",
419
+ received: describeArgs(args)
420
+ };
421
+ return { ok: true };
422
+ },
423
+ example: "call_sdk('setScreenAwakeMode', [{ enabled: true }])"
424
+ },
425
+ {
426
+ name: "getOperationalEnvironment",
427
+ validateArgs(_args) {
428
+ return { ok: true };
429
+ },
430
+ example: "call_sdk('getOperationalEnvironment', [])"
431
+ },
432
+ {
433
+ name: "getPlatformOS",
434
+ validateArgs(_args) {
435
+ return { ok: true };
436
+ },
437
+ example: "call_sdk('getPlatformOS', [])"
438
+ },
439
+ {
440
+ name: "getDeviceId",
441
+ validateArgs(_args) {
442
+ return { ok: true };
443
+ },
444
+ example: "call_sdk('getDeviceId', [])"
445
+ },
446
+ {
447
+ name: "getLocale",
448
+ validateArgs(_args) {
449
+ return { ok: true };
450
+ },
451
+ example: "call_sdk('getLocale', [])"
452
+ },
453
+ {
454
+ name: "getNetworkStatus",
455
+ validateArgs(_args) {
456
+ return { ok: true };
457
+ },
458
+ example: "call_sdk('getNetworkStatus', [])"
459
+ },
460
+ {
461
+ name: "getSchemeUri",
462
+ validateArgs(_args) {
463
+ return { ok: true };
464
+ },
465
+ example: "call_sdk('getSchemeUri', [])"
466
+ },
467
+ {
468
+ name: "requestReview",
469
+ validateArgs(_args) {
470
+ return { ok: true };
471
+ },
472
+ example: "call_sdk('requestReview', [])"
473
+ },
474
+ {
475
+ name: "closeView",
476
+ validateArgs(_args) {
477
+ return { ok: true };
478
+ },
479
+ example: "call_sdk('closeView', [])"
480
+ }
481
+ ];
482
+ new Map(SIGNATURES.map((s) => [s.name, s]));
483
+ SIGNATURES.map((s) => s.name);
484
+ new Set([
485
+ {
486
+ name: "list_console_messages",
487
+ 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.",
488
+ inputSchema: {
489
+ type: "object",
490
+ properties: {},
491
+ required: []
492
+ },
493
+ availableIn: "both"
494
+ },
495
+ {
496
+ name: "list_network_requests",
497
+ 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.",
498
+ inputSchema: {
499
+ type: "object",
500
+ properties: {},
501
+ required: []
502
+ },
503
+ availableIn: "both"
504
+ },
505
+ {
506
+ name: "list_pages",
507
+ 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.",
508
+ inputSchema: {
509
+ type: "object",
510
+ properties: {},
511
+ required: []
512
+ },
513
+ availableIn: "both"
514
+ },
515
+ {
516
+ name: "start_attach",
517
+ 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.",
518
+ inputSchema: {
519
+ type: "object",
520
+ properties: {
521
+ mode: {
522
+ type: "string",
523
+ enum: [
524
+ "local-browser",
525
+ "relay-sandbox",
526
+ "relay-staging"
527
+ ],
528
+ 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."
529
+ },
530
+ scheme_url: {
531
+ type: "string",
532
+ 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."
533
+ },
534
+ wait_timeout_seconds: {
535
+ type: "number",
536
+ 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."
537
+ },
538
+ projectRoot: {
539
+ type: "string",
540
+ 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."
541
+ },
542
+ selfdebug: {
543
+ type: "boolean",
544
+ 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)."
545
+ }
546
+ },
547
+ required: []
548
+ },
549
+ availableIn: "relay"
550
+ },
551
+ {
552
+ name: "get_dom_document",
553
+ 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.",
554
+ inputSchema: {
555
+ type: "object",
556
+ properties: {},
557
+ required: []
558
+ },
559
+ availableIn: "both"
560
+ },
561
+ {
562
+ name: "take_snapshot",
563
+ 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).",
564
+ inputSchema: {
565
+ type: "object",
566
+ properties: {},
567
+ required: []
568
+ },
569
+ availableIn: "both"
570
+ },
571
+ {
572
+ name: "take_screenshot",
573
+ 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).",
574
+ inputSchema: {
575
+ type: "object",
576
+ properties: {},
577
+ required: []
578
+ },
579
+ availableIn: "both"
580
+ },
581
+ {
582
+ name: "measure_safe_area",
583
+ 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.",
584
+ inputSchema: {
585
+ type: "object",
586
+ properties: {},
587
+ required: []
588
+ },
589
+ availableIn: "both"
590
+ },
591
+ {
592
+ name: "evaluate",
593
+ 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.",
594
+ inputSchema: {
595
+ type: "object",
596
+ properties: { expression: {
597
+ type: "string",
598
+ description: "JavaScript expression to evaluate in the page context."
599
+ } },
600
+ required: ["expression"]
601
+ },
602
+ availableIn: "both"
603
+ },
604
+ {
605
+ name: "list_exceptions",
606
+ 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.",
607
+ inputSchema: {
608
+ type: "object",
609
+ properties: { limit: {
610
+ type: "number",
611
+ description: "Maximum number of exceptions to return (default 50, max 50)."
612
+ } },
613
+ required: []
614
+ },
615
+ availableIn: "both"
616
+ },
617
+ {
618
+ name: "call_sdk",
619
+ 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\", [])",
620
+ inputSchema: {
621
+ type: "object",
622
+ properties: {
623
+ name: {
624
+ type: "string",
625
+ description: "SDK method name to call (e.g. \"getOperationalEnvironment\")."
626
+ },
627
+ args: {
628
+ type: "array",
629
+ description: "Arguments to pass to the SDK method (optional, default []).",
630
+ items: {}
631
+ }
632
+ },
633
+ required: ["name"]
634
+ },
635
+ availableIn: "both"
636
+ },
637
+ {
638
+ name: "AIT.getSdkCallHistory",
639
+ 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).",
640
+ inputSchema: {
641
+ type: "object",
642
+ properties: {},
643
+ required: []
644
+ },
645
+ availableIn: "both"
646
+ },
647
+ {
648
+ name: "AIT.getMockState",
649
+ 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.",
650
+ inputSchema: {
651
+ type: "object",
652
+ properties: {},
653
+ required: []
654
+ },
655
+ availableIn: "both"
656
+ },
657
+ {
658
+ name: "AIT.getOperationalEnvironment",
659
+ description: "Returns getOperationalEnvironment() plus the resolved SDK version — metadata raw CDP cannot observe. Read-only.",
660
+ inputSchema: {
661
+ type: "object",
662
+ properties: {},
663
+ required: []
664
+ },
665
+ availableIn: "both"
666
+ },
667
+ {
668
+ name: "start_debug",
669
+ 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.",
670
+ inputSchema: {
671
+ type: "object",
672
+ properties: {
673
+ mode: {
674
+ type: "string",
675
+ enum: [
676
+ "local-browser",
677
+ "relay-sandbox",
678
+ "relay-staging"
679
+ ],
680
+ description: "Target environment to switch to. relay-live (env 4) has been removed (#665) — use relay-staging (env 3) for dog-food debugging."
681
+ },
682
+ projectRoot: {
683
+ type: "string",
684
+ 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)."
685
+ }
686
+ },
687
+ required: ["mode"]
688
+ },
689
+ availableIn: "both"
690
+ },
691
+ {
692
+ name: "get_debug_status",
693
+ 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).",
694
+ inputSchema: {
695
+ type: "object",
696
+ properties: { recent_errors_limit: {
697
+ type: "number",
698
+ description: "Maximum number of recent server-side errors to include (default 10, max 50)."
699
+ } },
700
+ required: []
701
+ },
702
+ availableIn: "both"
703
+ },
704
+ {
705
+ name: "run_tests",
706
+ 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).",
707
+ inputSchema: {
708
+ type: "object",
709
+ properties: {
710
+ files: {
711
+ type: "array",
712
+ items: { type: "string" },
713
+ 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."
714
+ },
715
+ projectRoot: {
716
+ type: "string",
717
+ 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."
718
+ },
719
+ timeout_ms: {
720
+ type: "number",
721
+ description: "Per-file evaluate timeout in ms (default 30000, range 1000–600000). Out-of-range/invalid values fall back to the default."
722
+ },
723
+ scheme_url: {
724
+ type: "string",
725
+ 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."
726
+ },
727
+ cell: {
728
+ type: "object",
729
+ 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.",
730
+ additionalProperties: true
731
+ }
732
+ },
733
+ required: ["files"]
734
+ },
735
+ availableIn: "both"
736
+ }
737
+ ].map((t) => t.name));
738
+ function isCrashAware(conn) {
739
+ return typeof conn.getLastCrashDetectedAt === "function" && typeof conn.getTargetLastSeenAt === "function";
740
+ }
741
+ function listPages(connection, tunnel) {
742
+ const pages = connection.listTargets().map((t) => {
743
+ const lastSeenMs = isCrashAware(connection) ? connection.getTargetLastSeenAt(t.id) : null;
744
+ return {
745
+ id: t.id,
746
+ title: t.title,
747
+ url: redactAtParam(t.url),
748
+ lastSeenAt: lastSeenMs !== null ? new Date(lastSeenMs).toISOString() : null
749
+ };
750
+ });
751
+ const crashMs = isCrashAware(connection) ? connection.getLastCrashDetectedAt() : null;
752
+ const crashDetectedAt = crashMs !== null ? new Date(crashMs).toISOString() : null;
753
+ return {
754
+ pages,
755
+ tunnel,
756
+ crashDetectedAt,
757
+ crashWarning: crashDetectedAt ? `[ait-debug] page crash 감지됨 — 새 attach 필요 (관측 시각: ${crashDetectedAt})` : null,
758
+ singleAttachModel: true
759
+ };
760
+ }
761
+ /**
762
+ * Heuristic: can this process open a GUI browser?
763
+ *
764
+ * Returns `true` when we think a GUI is available:
765
+ * - On macOS (`darwin`) we assume yes (MCP normally runs on the user's Mac).
766
+ * - On Linux we check for `DISPLAY` or `WAYLAND_DISPLAY`.
767
+ * - On Windows we assume yes.
768
+ * - In a CI environment (`CI=true`) we assume no.
769
+ */
770
+ function canOpenBrowser() {
771
+ if (process.env.CI === "true" || process.env.CI === "1") return false;
772
+ const platform = process.platform;
773
+ if (platform === "darwin" || platform === "win32") return true;
774
+ if (platform === "linux") return Boolean(process.env.DISPLAY ?? process.env.WAYLAND_DISPLAY);
775
+ return false;
776
+ }
777
+ /** platform별 browser open 명령 후보 목록 — 앞에서부터 순차 시도. */
778
+ function getBrowserCandidates(httpUrl) {
779
+ const platform = process.platform;
780
+ if (platform === "darwin") return [
781
+ {
782
+ cmd: "open",
783
+ args: [httpUrl]
784
+ },
785
+ {
786
+ cmd: "open",
787
+ args: [
788
+ "-a",
789
+ "Safari",
790
+ httpUrl
791
+ ]
792
+ },
793
+ {
794
+ cmd: "open",
795
+ args: [
796
+ "-a",
797
+ "Google Chrome",
798
+ httpUrl
799
+ ]
800
+ },
801
+ {
802
+ cmd: "open",
803
+ args: [
804
+ "-a",
805
+ "Firefox",
806
+ httpUrl
807
+ ]
808
+ }
809
+ ];
810
+ if (platform === "win32") return [{
811
+ cmd: "cmd",
812
+ args: [
813
+ "/c",
814
+ "start",
815
+ "",
816
+ httpUrl
817
+ ]
818
+ }, {
819
+ cmd: "rundll32",
820
+ args: ["url.dll,FileProtocolHandler", httpUrl]
821
+ }];
822
+ return [
823
+ {
824
+ cmd: "xdg-open",
825
+ args: [httpUrl]
826
+ },
827
+ {
828
+ cmd: "sensible-browser",
829
+ args: [httpUrl]
830
+ },
831
+ {
832
+ cmd: "x-www-browser",
833
+ args: [httpUrl]
834
+ },
835
+ {
836
+ cmd: "firefox",
837
+ args: [httpUrl]
838
+ },
839
+ {
840
+ cmd: "google-chrome",
841
+ args: [httpUrl]
842
+ },
843
+ {
844
+ cmd: "chromium",
845
+ args: [httpUrl]
846
+ }
847
+ ];
848
+ }
849
+ /**
850
+ * Redacts ONLY the `at=<value>` (TOTP) query param to `at=<redacted>`, leaving
851
+ * every other query param (_deploymentId, debug, relay) intact. SECRET-HANDLING:
852
+ * the TOTP code is the single short-lived secret carried in a CDP page url.
853
+ */
854
+ function redactAtParam(text) {
855
+ return text.replace(/\bat=([^&\s"']+)/g, "at=<redacted>");
856
+ }
857
+ /** stderr에서 at= TOTP 코드 값을 redact한다. */
858
+ function redactSecrets(text) {
859
+ return redactAtParam(text);
860
+ }
861
+ /** spawnSync exit 0이어도 stderr에 launch 실패 시그널이 있으면 실패로 판단한다. */
862
+ const LAUNCH_FAILURE_PATTERNS = [
863
+ /LSOpenURLsWithRole\(\) failed/,
864
+ /kLSApplicationNotFoundErr/,
865
+ /No application/,
866
+ /Unable to find application/,
867
+ /xdg-open: not found/,
868
+ /command not found/
869
+ ];
870
+ function isLaunchFailureStderr(stderr) {
871
+ return LAUNCH_FAILURE_PATTERNS.some((p) => p.test(stderr));
872
+ }
873
+ /**
874
+ * 로컬 HTTP 서버 루트 URL(`http://127.0.0.1:<port>/`)을 OS 기본 브라우저로 연다 (#595).
875
+ *
876
+ * platform별 fallback chain으로 시도하며, 모두 실패하면 1회 retry를 수행한다
877
+ * (ephemeral process launch 타이밍 문제 대응). retry까지 실패해도 `opened: false` +
878
+ * `httpUrl`을 반환해 사용자가 직접 브라우저에 붙여넣을 수 있게 한다.
879
+ *
880
+ * SECRET-HANDLING:
881
+ * - tmp 파일을 만들지 않는다 (HTML/PNG는 HTTP 서버가 메모리에서 응답).
882
+ * - httpUrl은 `http://127.0.0.1:<port>/`(루트, 시크릿 없음). pngUrl은 127.0.0.1 로컬 전용.
883
+ * - stderr 캡처 결과에서 at= 코드 값을 redact한 후 stderrSummary에 포함.
884
+ * - attachUrl, deploymentId, TOTP 코드를 stdout/stderr/로그에 직접 출력 금지.
885
+ *
886
+ * @param httpUrl - `http://127.0.0.1:<port>/` 루트 URL (시크릿 없음, #595).
887
+ * @param pngUrl - `http://127.0.0.1:<port>/qr.png?u=<encoded>` PNG fallback URL.
888
+ */
889
+ async function openQrInBrowser(httpUrl, pngUrl) {
890
+ const { spawnSync } = await import("node:child_process");
891
+ /**
892
+ * 한 번의 fallback chain 시도. 성공하면 열린 후보 cmd를 반환, 실패하면 null.
893
+ * stderrLines에 각 후보의 stderr를 누적한다.
894
+ */
895
+ function tryOnce(stderrLines) {
896
+ const candidates = getBrowserCandidates(httpUrl);
897
+ for (const { cmd, args } of candidates) {
898
+ const result = spawnSync(cmd, args, {
899
+ encoding: "utf8",
900
+ timeout: 5e3
901
+ });
902
+ if (result.error) {
903
+ stderrLines.push(`${cmd}: ${result.error.message}`);
904
+ continue;
905
+ }
906
+ const stderr = typeof result.stderr === "string" ? result.stderr : "";
907
+ if (stderr) stderrLines.push(`${cmd}: ${redactSecrets(stderr.trim())}`);
908
+ if (result.status === 0 && !isLaunchFailureStderr(stderr)) return true;
909
+ }
910
+ return false;
911
+ }
912
+ const stderrLines = [];
913
+ if (tryOnce(stderrLines)) return {
914
+ opened: true,
915
+ httpUrl,
916
+ pngUrl
917
+ };
918
+ if (tryOnce(stderrLines)) return {
919
+ opened: true,
920
+ httpUrl,
921
+ pngUrl,
922
+ retried: true
923
+ };
924
+ return {
925
+ opened: false,
926
+ httpUrl,
927
+ pngUrl,
928
+ error: "모든 브라우저 실행 후보가 실패했습니다.",
929
+ stderrSummary: stderrLines.length > 0 ? stderrLines.join("\n") : void 0
930
+ };
931
+ }
932
+ `
933
+ (function() {
934
+ var el = document.createElement('div');
935
+ el.style.cssText = 'position:fixed;top:0;left:0;width:0;height:0;visibility:hidden;' +
936
+ 'padding-top:env(safe-area-inset-top,0px);' +
937
+ 'padding-right:env(safe-area-inset-right,0px);' +
938
+ 'padding-bottom:env(safe-area-inset-bottom,0px);' +
939
+ 'padding-left:env(safe-area-inset-left,0px)';
940
+ document.documentElement.appendChild(el);
941
+ var cs = window.getComputedStyle(el);
942
+ var cssEnv = {
943
+ top: parseFloat(cs.paddingTop) || 0,
944
+ right: parseFloat(cs.paddingRight) || 0,
945
+ bottom: parseFloat(cs.paddingBottom) || 0,
946
+ left: parseFloat(cs.paddingLeft) || 0
947
+ };
948
+ document.documentElement.removeChild(el);
949
+ var sdkInsets = null;
950
+ var sdkInsetsSource = null;
951
+ var sdkInsetsError = undefined;
952
+ try {
953
+ var sdk = window.__sdk;
954
+ var ait = window.__ait;
955
+ if (sdk && sdk.SafeAreaInsets && typeof sdk.SafeAreaInsets.get === 'function') {
956
+ sdkInsets = sdk.SafeAreaInsets.get();
957
+ sdkInsetsSource = 'window.__sdk';
958
+ } else if (sdk && typeof sdk.getSafeAreaInsets === 'function') {
959
+ sdkInsets = sdk.getSafeAreaInsets();
960
+ sdkInsetsSource = 'window.__sdk';
961
+ } else if (ait && ait.state && ait.state.safeAreaInsets &&
962
+ typeof ait.state.safeAreaInsets.top === 'number') {
963
+ var s = ait.state.safeAreaInsets;
964
+ sdkInsets = { top: s.top, bottom: s.bottom, left: s.left, right: s.right };
965
+ sdkInsetsSource = 'window.__ait';
966
+ } else if (!sdk && !ait) {
967
+ sdkInsetsError = 'neither window.__sdk (relay) nor window.__ait (mock) available';
968
+ } else if (sdk) {
969
+ sdkInsetsError = 'neither SafeAreaInsets.get nor getSafeAreaInsets found on window.__sdk';
970
+ } else {
971
+ sdkInsetsError = 'window.__ait.state.safeAreaInsets is missing or malformed';
972
+ }
973
+ } catch(e) {
974
+ sdkInsetsError = String(e && e.message || e);
975
+ }
976
+ var navBarHeight = null;
977
+ var navBarHeightSource = 'not-exposed-by-sdk';
978
+ try {
979
+ var nb = document.querySelector('.ait-navbar');
980
+ if (nb) {
981
+ navBarHeight = nb.getBoundingClientRect().height;
982
+ navBarHeightSource = 'dom-.ait-navbar';
983
+ }
984
+ } catch(_) {}
985
+ var result = {
986
+ cssEnv: cssEnv,
987
+ sdkInsets: sdkInsets,
988
+ sdkInsetsSource: sdkInsetsSource,
989
+ navBarHeight: navBarHeight,
990
+ navBarHeightSource: navBarHeightSource,
991
+ innerWidth: window.innerWidth,
992
+ innerHeight: window.innerHeight,
993
+ devicePixelRatio: window.devicePixelRatio,
994
+ userAgent: navigator.userAgent
995
+ };
996
+ if (sdkInsetsError !== undefined) result.sdkInsetsError = sdkInsetsError;
997
+ return JSON.stringify(result);
998
+ })()
999
+ `.trim();
1000
+ //#endregion
1001
+ //#region src/mcp/tunnel.ts
1002
+ /**
1003
+ * cloudflared quick tunnel + attach banner for the debug-mode MCP server.
1004
+ *
1005
+ * On spawn, the debug server opens an accountless `*.trycloudflare.com` quick
1006
+ * tunnel to the local Chii relay so the phone can attach over a public wss URL,
1007
+ * then prints a unicode half-block QR + attach instructions. When TOTP auth is
1008
+ * enabled (`AIT_DEBUG_TOTP_SECRET` is set), the QR encodes only the base relay
1009
+ * URL — the TOTP code (`at=`) is NOT included because it rotates every 30 s
1010
+ * and would be stale by the time a human scans. The in-app deep-link builder
1011
+ * splices the live code at attach time.
1012
+ *
1013
+ * Tunnel health probe (`TunnelHealthProbe`):
1014
+ * After the tunnel is up, a periodic HTTP HEAD probe hits the tunnel's
1015
+ * `https://` URL every `probeIntervalMs` (default 60 s). Two consecutive
1016
+ * failures trigger a reissue attempt (spawn a new cloudflared quick tunnel
1017
+ * and redirect traffic). After `MAX_REISSUE_ATTEMPTS` (3) consecutive
1018
+ * reissue failures, the probe gives up and marks the tunnel permanently
1019
+ * dropped — `tunnelStatus.up` becomes false with `droppedAt` set. The caller
1020
+ * should surface this to the agent so the user knows to restart the server.
1021
+ *
1022
+ * SECRET-HANDLING: The TOTP secret and computed code values MUST NOT appear
1023
+ * in any output from this module.
1024
+ *
1025
+ * Node-only: spawns the cloudflared binary and writes to stdout/stderr.
1026
+ */
1027
+ /** Generates a 32-byte hex attach token shown as a pairing hint (relay-side validation is a later phase). */
1028
+ function generateAttachToken() {
1029
+ return randomBytes(32).toString("hex");
1030
+ }
1031
+ /** Ensures the cloudflared binary is installed (downloads + caches on first run). */
1032
+ async function ensureCloudflaredBin() {
1033
+ const { existsSync } = await import("node:fs");
1034
+ if (!existsSync(bin)) await install(bin);
1035
+ }
1036
+ /**
1037
+ * Opens a cloudflared quick tunnel to the local relay port and resolves once
1038
+ * the public URL is assigned.
1039
+ *
1040
+ * FIX 1 (issue #571): after URL resolution the returned `QuickTunnel` object
1041
+ * watches the cloudflared child process for unexpected exits and calls any
1042
+ * registered `onUnexpectedExit` callback so the health probe can immediately
1043
+ * trigger reissue instead of waiting for the next poll interval.
1044
+ */
1045
+ async function startQuickTunnel(localPort) {
1046
+ await ensureCloudflaredBin();
1047
+ const tunnel = Tunnel.quick(`http://127.0.0.1:${localPort}`);
1048
+ const url = await new Promise((resolve, reject) => {
1049
+ const onUrl = (assigned) => {
1050
+ cleanup();
1051
+ resolve(assigned);
1052
+ };
1053
+ const onError = (err) => {
1054
+ cleanup();
1055
+ reject(err);
1056
+ };
1057
+ const onExit = (code) => {
1058
+ cleanup();
1059
+ reject(/* @__PURE__ */ new Error(`cloudflared exited before assigning a URL (code ${code})`));
1060
+ };
1061
+ const cleanup = () => {
1062
+ tunnel.off("url", onUrl);
1063
+ tunnel.off("error", onError);
1064
+ tunnel.off("exit", onExit);
1065
+ };
1066
+ tunnel.once("url", onUrl);
1067
+ tunnel.once("error", onError);
1068
+ tunnel.once("exit", onExit);
1069
+ });
1070
+ let intentionalStop = false;
1071
+ let unexpectedExitCb = null;
1072
+ tunnel.once("exit", (code) => {
1073
+ if (!intentionalStop && unexpectedExitCb !== null) unexpectedExitCb(code);
1074
+ });
1075
+ return {
1076
+ url,
1077
+ wssUrl: url.replace(/^https/, "wss"),
1078
+ childPid: tunnel.process?.pid,
1079
+ onUnexpectedExit(cb) {
1080
+ unexpectedExitCb = cb;
1081
+ },
1082
+ stop() {
1083
+ intentionalStop = true;
1084
+ tunnel.stop();
1085
+ }
1086
+ };
1087
+ }
1088
+ /**
1089
+ * Renders a pure unicode half-block QR string for the given text.
1090
+ *
1091
+ * Uses `qrcode` (Node full lib) to get the raw bit matrix, then encodes every
1092
+ * two vertical modules into a single half-block character:
1093
+ * - both dark → `█`
1094
+ * - top only → `▀`
1095
+ * - bottom only → `▄`
1096
+ * - both light → ` ` (space)
1097
+ *
1098
+ * The output contains **zero ANSI escape codes**, so it renders correctly in
1099
+ * every surface (terminal, VS Code, JetBrains, web) and can be scanned by a
1100
+ * phone camera when shown verbatim in an agent response.
1101
+ *
1102
+ * Shared by `renderAttachBanner` (relay wssUrl QR) and the `start_attach`
1103
+ * MCP tool response (attach deep-link QR).
1104
+ */
1105
+ async function renderQr(text) {
1106
+ const { default: QRCode } = await import("qrcode");
1107
+ const qr = QRCode.create(text, { errorCorrectionLevel: "M" });
1108
+ const size = qr.modules.size;
1109
+ const data = qr.modules.data;
1110
+ const isDark = (x, y) => {
1111
+ if (x < 0 || y < 0 || x >= size || y >= size) return false;
1112
+ return data[y * size + x] === 1;
1113
+ };
1114
+ const QUIET = 1;
1115
+ const lines = [];
1116
+ for (let y = -QUIET; y < size + QUIET; y += 2) {
1117
+ let line = "";
1118
+ for (let x = -QUIET; x < size + QUIET; x++) {
1119
+ const top = isDark(x, y);
1120
+ const bot = isDark(x, y + 1);
1121
+ line += top && bot ? "█" : top ? "▀" : bot ? "▄" : " ";
1122
+ }
1123
+ lines.push(line);
1124
+ }
1125
+ return `${lines.join("\n")}\n`;
1126
+ }
1127
+ /**
1128
+ * Renders the attach banner (relay URL + unicode half-block QR) as a string.
1129
+ *
1130
+ * The QR is produced by `renderQr` (a half-block matrix, not the
1131
+ * `qrcode-terminal` ASCII art used by the unplugin banner) and encodes the
1132
+ * base `wssUrl` only. When `totpEnabled` is true, a note
1133
+ * is added that attach URLs generated by `start_attach` will include a
1134
+ * live TOTP code (`at=`) appended at call time.
1135
+ *
1136
+ * SECRET-HANDLING: no secret value, TOTP code, or intermediate value is
1137
+ * included in this output.
1138
+ */
1139
+ async function renderAttachBanner(input) {
1140
+ const qr = await renderQr(input.wssUrl);
1141
+ const authNote = input.totpEnabled ? " auth: TOTP enabled — attach URLs include a rotating code (at=)." : " auth: none (set AIT_DEBUG_TOTP_SECRET to enable TOTP).";
1142
+ return [
1143
+ "",
1144
+ "AIT debug — attach a mini-app to this session",
1145
+ "",
1146
+ ` relay (wss): ${input.wssUrl}`,
1147
+ authNote,
1148
+ "",
1149
+ " Use start_attach to generate a deep link with the current TOTP code.",
1150
+ " Scan the QR to locate the relay (open the dog-food URL separately with",
1151
+ " ?debug=1&relay=<wss>&at=<code> or use the start_attach tool):",
1152
+ "",
1153
+ qr
1154
+ ].join("\n");
1155
+ }
1156
+ /** Prints the attach banner to stderr (stdout is the MCP stdio channel). */
1157
+ async function printAttachBanner(input) {
1158
+ const banner = await renderAttachBanner(input);
1159
+ process.stderr.write(`${banner}\n`);
1160
+ }
1161
+ /**
1162
+ * Probes `https://` URL with an HTTP HEAD request.
1163
+ * Returns `true` when the server responds (any HTTP status), `false` on
1164
+ * network error or timeout.
1165
+ *
1166
+ * We treat any HTTP response (including 4xx/5xx) as "tunnel alive" because
1167
+ * cloudflared itself responds to the HEAD — if the tunnel process died, the
1168
+ * request fails at the network level rather than returning a status code.
1169
+ *
1170
+ * @param httpsUrl - The `https://` tunnel URL to probe.
1171
+ * @param timeoutMs - Abort timeout in ms. Default 10 000.
1172
+ */
1173
+ async function probeTunnel(httpsUrl, timeoutMs = 1e4) {
1174
+ const { default: https } = await import("node:https");
1175
+ return new Promise((resolve) => {
1176
+ const url = new URL(httpsUrl);
1177
+ const timer = setTimeout(() => {
1178
+ req.destroy();
1179
+ resolve(false);
1180
+ }, timeoutMs);
1181
+ const req = https.request({
1182
+ hostname: url.hostname,
1183
+ port: 443,
1184
+ path: url.pathname || "/",
1185
+ method: "HEAD"
1186
+ }, (_res) => {
1187
+ clearTimeout(timer);
1188
+ _res.resume();
1189
+ resolve(true);
1190
+ });
1191
+ req.on("error", () => {
1192
+ clearTimeout(timer);
1193
+ resolve(false);
1194
+ });
1195
+ req.end();
1196
+ });
1197
+ }
1198
+ /**
1199
+ * Starts a periodic health probe for a cloudflared quick tunnel.
1200
+ *
1201
+ * Every `probeIntervalMs` the probe sends an HTTP HEAD request to the tunnel's
1202
+ * `https://` URL. When `failuresBeforeReissue` consecutive failures are
1203
+ * detected, it attempts to spawn a new tunnel (up to `MAX_REISSUE_ATTEMPTS`
1204
+ * times). On success the caller is notified via `onReissue`; on permanent
1205
+ * failure via `onPermanentDrop`.
1206
+ *
1207
+ * FIX 1 (issue #571): the probe also subscribes to each tunnel's
1208
+ * `onUnexpectedExit` callback to detect child death *immediately* instead of
1209
+ * waiting for the next probe interval (which could be 60 s away).
1210
+ *
1211
+ * @returns `stop` — call during server shutdown to clear the probe interval.
1212
+ */
1213
+ function startTunnelHealthProbe(initialTunnel, localPort, options) {
1214
+ const { probeIntervalMs = 6e4, failuresBeforeReissue = 2, onReissue, onPermanentDrop, log = (msg) => process.stderr.write(msg), probe = probeTunnel, spawnTunnel = startQuickTunnel } = options;
1215
+ let currentTunnel = initialTunnel;
1216
+ let consecutiveFailures = 0;
1217
+ let reissueAttempts = 0;
1218
+ let stopped = false;
1219
+ const doReissueOrDrop = async () => {
1220
+ if (stopped) return;
1221
+ reissueAttempts += 1;
1222
+ if (reissueAttempts > 3) return;
1223
+ log(`[ait-debug] tunnel drop detected — reissuing (attempt ${reissueAttempts}/3)\n`);
1224
+ try {
1225
+ const newTunnel = await spawnTunnel(localPort);
1226
+ try {
1227
+ currentTunnel.stop();
1228
+ } catch {}
1229
+ currentTunnel = newTunnel;
1230
+ consecutiveFailures = 0;
1231
+ armChildExitWatch(newTunnel);
1232
+ log(`[ait-debug] tunnel reissued — new relay: ${newTunnel.wssUrl}\n`);
1233
+ onReissue(newTunnel);
1234
+ } catch (err) {
1235
+ const message = err instanceof Error ? err.message : String(err);
1236
+ log(`[ait-debug] tunnel reissue attempt ${reissueAttempts} failed: ${message}\n`);
1237
+ if (reissueAttempts >= 3) {
1238
+ clearInterval(handle);
1239
+ stopped = true;
1240
+ const droppedAt = (/* @__PURE__ */ new Date()).toISOString();
1241
+ log(`[ait-debug] tunnel permanently dropped after 3 reissue attempts — restart the debug server to continue (npx @ait-co/devtools devtools-mcp).
1242
+ `);
1243
+ onPermanentDrop(droppedAt);
1244
+ }
1245
+ }
1246
+ };
1247
+ const armChildExitWatch = (t) => {
1248
+ t.onUnexpectedExit((code) => {
1249
+ if (stopped) return;
1250
+ log(`[ait-debug] cloudflared child exited unexpectedly (code=${code}) — triggering immediate reissue\n`);
1251
+ consecutiveFailures = failuresBeforeReissue;
1252
+ doReissueOrDrop();
1253
+ });
1254
+ };
1255
+ armChildExitWatch(initialTunnel);
1256
+ const handle = setInterval(() => {
1257
+ (async () => {
1258
+ if (stopped) return;
1259
+ const httpsUrl = currentTunnel.url;
1260
+ if (await probe(httpsUrl)) {
1261
+ if (consecutiveFailures > 0) log("[ait-debug] tunnel health probe: tunnel recovered\n");
1262
+ consecutiveFailures = 0;
1263
+ reissueAttempts = 0;
1264
+ return;
1265
+ }
1266
+ consecutiveFailures += 1;
1267
+ log(`[ait-debug] tunnel health probe: failure ${consecutiveFailures}/${failuresBeforeReissue} (url=${httpsUrl})\n`);
1268
+ if (consecutiveFailures < failuresBeforeReissue) return;
1269
+ await doReissueOrDrop();
1270
+ })();
1271
+ }, probeIntervalMs);
1272
+ return { stop() {
1273
+ stopped = true;
1274
+ clearInterval(handle);
1275
+ } };
1276
+ }
1277
+ /**
1278
+ * Builds a `TunnelStatus` snapshot that includes drop state.
1279
+ *
1280
+ * Convenience helper for callers (debug-server) that maintain a mutable
1281
+ * `tunnelStatus` object — keeps the shape construction in one place.
1282
+ */
1283
+ function makeTunnelStatus(up, wssUrl, droppedAt = null, reissueAttempts = 0) {
1284
+ return {
1285
+ up,
1286
+ wssUrl,
1287
+ droppedAt,
1288
+ reissueAttempts
1289
+ };
1290
+ }
1291
+ //#endregion
1292
+ //#region src/mcp/attach-orchestrator.ts
1293
+ /**
1294
+ * Maximum age (ms) of a page's `lastSeenAt` before it is treated as a ghost
1295
+ * and excluded from the `wait_for_attach` short-circuit in `start_attach`
1296
+ * (issue #610).
1297
+ *
1298
+ * Rationale: the env-2 relay is owned by the dev server (unplugin), so every
1299
+ * `dev:phone:cdp` restart produces a new quick-tunnel. The old relay goes
1300
+ * offline immediately, but the daemon's warm `ChiiCdpConnection` still lists
1301
+ * the last-seen target — its `lastSeenAt` freezes at the moment the old relay
1302
+ * died. A 5-minute threshold is large enough to be invisible in normal usage
1303
+ * (active CDP sessions see a message every few seconds) while being small
1304
+ * enough to catch a relay that went down before the daemon was re-entered.
1305
+ *
1306
+ * Injectable for tests via {@link AttachDeps.stalePageThresholdMs}.
1307
+ */
1308
+ const RELAY_SANDBOX_STALE_PAGE_MS = 300 * 1e3;
1309
+ /**
1310
+ * Segment length (ms) of the `start_attach` wait loop (issue #626 — TOTP in-call
1311
+ * re-mint). The single-shot `wait_for_attach` of the old attach tool could
1312
+ * not re-mint a TOTP code mid-wait; `start_attach` decomposes the wait into
1313
+ * SEGMENT_MS slices so it can detect an aging code between slices and re-mint a
1314
+ * fresh one without the agent re-calling the tool. 30 s = one TOTP step.
1315
+ */
1316
+ const START_ATTACH_SEGMENT_MS = 3e4;
1317
+ /**
1318
+ * Elapsed-since-mint threshold (ms) at which `start_attach` re-mints a fresh
1319
+ * TOTP code during its wait loop (issue #626). The relay gate accepts a code for
1320
+ * `RELAY_VERIFY_SKEW_STEPS` (6) × 30 s = 180 s backwards from issuance; we re-mint
1321
+ * at 150 s to leave a 30 s margin so a phone scan never lands on an expired code.
1322
+ */
1323
+ const START_ATTACH_REMINT_THRESHOLD_MS = 15e4;
1324
+ /**
1325
+ * Predicate used by `start_attach`'s `wait_for_attach` loop to decide
1326
+ * whether the relay-sandbox connection has a genuinely fresh page attached.
1327
+ *
1328
+ * Stale-ghost gating (issue #610): when the dev server restarts with a new
1329
+ * quick-tunnel, the warm `ChiiCdpConnection` still lists the last-seen target
1330
+ * but its `lastSeenAt` is frozen. A page whose `lastSeenAt` exceeds
1331
+ * `stalePageThresholdMs` is a ghost from the dead relay — it must NOT
1332
+ * short-circuit `wait_for_attach`.
1333
+ *
1334
+ * Rules:
1335
+ * - `pages.length === 0` → false (nothing attached).
1336
+ * - Connection has no `getLastSeenAt` (test fakes, local-browser) → falls back
1337
+ * to `pages.length > 0` (regression-safe).
1338
+ * - `seenMs === null` → treat as fresh (no CDP message received yet, first
1339
+ * message pending — the connection is alive).
1340
+ * - Otherwise: at least one page must satisfy `nowMs - seenMs <=
1341
+ * stalePageThresholdMs`.
1342
+ *
1343
+ * Exported for unit testing.
1344
+ */
1345
+ function isSandboxPageFresh(pages, getLastSeenAt, nowMs, stalePageThresholdMs) {
1346
+ if (pages.length === 0) return false;
1347
+ if (getLastSeenAt === null) return true;
1348
+ return pages.some((p) => {
1349
+ const seenMs = getLastSeenAt(p.id);
1350
+ if (seenMs === null) return true;
1351
+ return nowMs - seenMs <= stalePageThresholdMs;
1352
+ });
1353
+ }
1354
+ /**
1355
+ * Parses `_deploymentId` from the query string of a scheme URL.
1356
+ *
1357
+ * Returns `null` when the param is absent or empty — callers treat that as
1358
+ * "no deploymentId filter; match on presence only" and fall back to the
1359
+ * original `attachedPages.length > 0` condition.
1360
+ *
1361
+ * SECRET-HANDLING: deploymentId is a public identifier and may appear in
1362
+ * debug output. Never confuse it with TOTP secrets or relay tunnel URLs.
1363
+ */
1364
+ function extractDeploymentId(schemeUrl) {
1365
+ try {
1366
+ const qIndex = schemeUrl.indexOf("?");
1367
+ if (qIndex === -1) return null;
1368
+ const id = new URLSearchParams(schemeUrl.slice(qIndex + 1)).get("_deploymentId");
1369
+ return id && id.length > 0 ? id : null;
1370
+ } catch {
1371
+ return null;
1372
+ }
1373
+ }
1374
+ /** Resolves `deps.stalePageThresholdMs` to its default. */
1375
+ function resolveStalePageThresholdMs(deps) {
1376
+ return deps.stalePageThresholdMs ?? 3e5;
1377
+ }
1378
+ /** Resolves `deps.nowMs` to its default (`Date.now`). */
1379
+ function resolveNowMs(deps) {
1380
+ return deps.nowMs ?? (() => Date.now());
1381
+ }
1382
+ /** Resolves `deps.canOpenBrowser` to the module default. */
1383
+ function resolveCanOpenBrowser(deps) {
1384
+ return deps.canOpenBrowser ?? canOpenBrowser;
1385
+ }
1386
+ /**
1387
+ * Waits for the first target matching `filterFn` to attach, using the
1388
+ * event-driven `waitForFirstTarget()` when the connection supports it
1389
+ * (interface-optional member, present on `ChiiCdpConnection`), or falling
1390
+ * back to a polling loop for connections that don't implement it (test fakes,
1391
+ * `LocalCdpConnection`).
1392
+ *
1393
+ * This eliminates the polling-only race that previously caused `wait_for_attach`
1394
+ * to resolve before the relay had observed the first inbound CDP message from
1395
+ * the phone.
1396
+ *
1397
+ * Timeout note: callers (e.g. the `start_attach` path) always pass an
1398
+ * explicit `timeoutMs`, sourced from the factory's `waitForAttachTimeoutMs`
1399
+ * (default 60 000). That value is forwarded to `waitForFirstTarget`, so it
1400
+ * overrides that method's own 90 000 signature default — the effective
1401
+ * wait on the tool path is 60 s, not 90 s.
1402
+ *
1403
+ * @param connection - The CDP connection (production or fake).
1404
+ * @param filterFn - Resolves when this predicate is satisfied.
1405
+ * @param timeoutMs - Maximum wait time in ms.
1406
+ * @param pollIntervalMs - Fallback poll interval for connections without waitForFirstTarget.
1407
+ */
1408
+ function waitForAttachWithEvents(connection, filterFn, timeoutMs, pollIntervalMs = 1e3) {
1409
+ if (connection.waitForFirstTarget) return connection.waitForFirstTarget(filterFn, timeoutMs, pollIntervalMs);
1410
+ return new Promise((resolve, reject) => {
1411
+ const deadline = Date.now() + timeoutMs;
1412
+ let settled = false;
1413
+ const poll = setInterval(() => {
1414
+ const targets = connection.listTargets();
1415
+ if (filterFn(targets)) {
1416
+ settled = true;
1417
+ clearInterval(poll);
1418
+ resolve(targets);
1419
+ } else if (Date.now() >= deadline) {
1420
+ settled = true;
1421
+ clearInterval(poll);
1422
+ reject(/* @__PURE__ */ new Error(`waitForAttachWithEvents: 타임아웃 (${timeoutMs}ms)`));
1423
+ }
1424
+ }, pollIntervalMs);
1425
+ const targets = connection.listTargets();
1426
+ if (!settled && filterFn(targets)) {
1427
+ settled = true;
1428
+ clearInterval(poll);
1429
+ resolve(targets);
1430
+ }
1431
+ });
1432
+ }
1433
+ /**
1434
+ * Synthesizes an attach URL from stored components with a FRESHLY-minted TOTP
1435
+ * code (issue #626 §3/§4 — the single mint point). Reads the late-bound secret
1436
+ * via `deps.getTotpSecret()` so the project-local `.ait_relay` secret loaded by
1437
+ * `switchMode` is visible. SECRET-HANDLING: the minted code rides inside the
1438
+ * URL's `at=` param only — never logged or returned separately.
1439
+ */
1440
+ function mintAttachUrl(deps, parts) {
1441
+ const secret = deps.getTotpSecret();
1442
+ const code = secret ? generateTotp(secret) : void 0;
1443
+ return parts.kind === "launcher" ? buildLauncherAttachUrl(parts.tunnelHttpUrl, parts.wssUrl, code, {
1444
+ name: parts.appName,
1445
+ ...parts.selfdebug ? { selfdebug: true } : {}
1446
+ }) : buildDeepLinkAttachUrl(parts.schemeUrl, parts.wssUrl, code);
1447
+ }
1448
+ /** Builds the fresh TOTP metadata (expiresAt window) for a tool result. */
1449
+ function buildTotpMeta(deps) {
1450
+ const secret = deps.getTotpSecret();
1451
+ if (secret === void 0 || secret === "") return void 0;
1452
+ const STEP_SECONDS = 30;
1453
+ const expiresAtMs = resolveNowMs(deps)() + 6 * STEP_SECONDS * 1e3;
1454
+ return {
1455
+ enabled: true,
1456
+ ttlSeconds: 6 * STEP_SECONDS,
1457
+ expiresAt: new Date(expiresAtMs).toISOString()
1458
+ };
1459
+ }
1460
+ /**
1461
+ * Env-specific validation + component bundle for `start_attach` (issue #626).
1462
+ * Branches on `env`: `relay-mobile` reads AIT_TUNNEL_BASE_URL + builds launcher
1463
+ * parts; `relay-dev` requires scheme_url + builds scheme parts. Returns
1464
+ * `{ ok: false, error }` with a ready McpResult on any failure.
1465
+ */
1466
+ async function prepareAttach(deps, env, args, conn) {
1467
+ const { getTunnelStatus, getTotpSecret } = deps;
1468
+ const stalePageThresholdMs = resolveStalePageThresholdMs(deps);
1469
+ const nowMs = resolveNowMs(deps);
1470
+ const selfdebug = args?.selfdebug === true;
1471
+ if (selfdebug && env !== "relay-mobile") return {
1472
+ ok: false,
1473
+ error: mcpError("start_attach: selfdebug=true는 env 2 / relay-sandbox 전용 기능입니다. 현재 환경(env 3)에서는 launcher가 없어 self-target 모드를 지원하지 않습니다. launcher self-target이 필요하다면 relay-sandbox 모드로 전환하세요.")
1474
+ };
1475
+ if (env === "relay-mobile") {
1476
+ const rawProjectRoot = args?.projectRoot;
1477
+ const buildProjectRoot = typeof rawProjectRoot === "string" ? rawProjectRoot : void 0;
1478
+ let tunnelHttpUrl = process.env.AIT_TUNNEL_BASE_URL?.trim() ?? "";
1479
+ if (tunnelHttpUrl === "" && buildProjectRoot !== void 0) {
1480
+ const { readRelayUrls } = await import("./relay-url-store-NDtEcOE-.js");
1481
+ tunnelHttpUrl = (await readRelayUrls({ projectRoot: buildProjectRoot }))?.tunnelBaseUrl ?? "";
1482
+ }
1483
+ if (tunnelHttpUrl === "") return {
1484
+ ok: false,
1485
+ error: mcpError("start_attach(mobile): AIT_TUNNEL_BASE_URL이 설정되지 않았습니다. dev 서버가 tunnel:{cdp:true}로 기동 중이면 .ait_urls 파일이 자동 생성돼 있어야 합니다. 자동 발견이 되지 않을 경우 앱 HTTP 터널 URL을 AIT_TUNNEL_BASE_URL 환경변수로 직접 전달하세요.")
1486
+ };
1487
+ const tunnelStatus = getTunnelStatus();
1488
+ if (!tunnelStatus.up || tunnelStatus.wssUrl === null) return {
1489
+ ok: false,
1490
+ error: mcpError("start_attach(mobile): relay wssUrl이 아직 설정되지 않았습니다. unplugin tunnel:{cdp:true}가 relay를 완전히 기동할 때까지 잠시 후 다시 시도하세요.")
1491
+ };
1492
+ const secret = getTotpSecret();
1493
+ if (secret === void 0 || secret === "") return {
1494
+ ok: false,
1495
+ error: mcpError("start_attach(relay): TOTP secret(AIT_DEBUG_TOTP_SECRET)이 설정되지 않았습니다. relay 환경은 TOTP 인증이 필수입니다 — relay를 secret과 함께 재기동하세요.")
1496
+ };
1497
+ let launcherAppName;
1498
+ if (buildProjectRoot !== void 0) try {
1499
+ const { readFileSync } = await import("node:fs");
1500
+ const pkgRaw = readFileSync(`${buildProjectRoot}/package.json`, "utf8");
1501
+ const pkg = JSON.parse(pkgRaw);
1502
+ const rawName = typeof pkg.name === "string" ? pkg.name : "";
1503
+ launcherAppName = (rawName.includes("/") ? rawName.slice(rawName.indexOf("/") + 1) : rawName).trim() || void 0;
1504
+ } catch {}
1505
+ const parts = {
1506
+ kind: "launcher",
1507
+ tunnelHttpUrl,
1508
+ wssUrl: tunnelStatus.wssUrl,
1509
+ appName: launcherAppName,
1510
+ ...selfdebug ? { selfdebug: true } : {}
1511
+ };
1512
+ const connAsAny = conn;
1513
+ const getLastSeenAt = typeof connAsAny.getTargetLastSeenAt === "function" ? (id) => connAsAny.getTargetLastSeenAt(id) : null;
1514
+ const callNow = nowMs();
1515
+ const isMatchingPage = (pages) => isSandboxPageFresh(pages, getLastSeenAt, callNow, stalePageThresholdMs);
1516
+ const buildTimeoutError = (baseText, timeoutSec, observed) => {
1517
+ const observedUrls = observed.slice(0, 3).map((p) => p.url.slice(0, 80)).join(", ");
1518
+ return `${baseText}\n\nNo page attached within ${timeoutSec}s${observed.length > 0 ? ` — previously attached pages: [${observedUrls}]` : ""} — launcher QR을 폰 카메라로 스캔한 뒤 call list_pages를 다시 호출하세요.`;
1519
+ };
1520
+ return {
1521
+ ok: true,
1522
+ parts,
1523
+ isMatchingPage,
1524
+ buildTimeoutError,
1525
+ authorityWarning: void 0,
1526
+ totpMeta: buildTotpMeta(deps)
1527
+ };
1528
+ }
1529
+ const schemeUrl = args?.scheme_url;
1530
+ if (typeof schemeUrl !== "string" || schemeUrl === "") return {
1531
+ ok: false,
1532
+ error: mcpError("start_attach: scheme_url이 비어 있습니다. `ait deploy --scheme-only`가 출력하는 intoss-private:// URL을 인자로 전달하세요. 환경 2(mobile)라면 scheme_url 대신 AIT_TUNNEL_BASE_URL을 설정하세요.")
1533
+ };
1534
+ {
1535
+ const relaySecret = getTotpSecret();
1536
+ if (relaySecret === void 0 || relaySecret === "") return {
1537
+ ok: false,
1538
+ error: mcpError("start_attach(relay): TOTP secret(AIT_DEBUG_TOTP_SECRET)이 설정되지 않았습니다. relay 환경은 TOTP 인증이 필수입니다 — relay를 secret과 함께 재기동하세요.")
1539
+ };
1540
+ }
1541
+ const tunnelForBuild = getTunnelStatus();
1542
+ if (!tunnelForBuild.up || tunnelForBuild.wssUrl === null) return {
1543
+ ok: false,
1544
+ error: classifyToolError(/* @__PURE__ */ new Error("tunnel-down:"), "start_attach")
1545
+ };
1546
+ const authorityWarning = validateSchemeAuthority(schemeUrl) ?? void 0;
1547
+ const parts = {
1548
+ kind: "scheme",
1549
+ schemeUrl,
1550
+ wssUrl: tunnelForBuild.wssUrl
1551
+ };
1552
+ const deploymentId = extractDeploymentId(schemeUrl);
1553
+ if (!deploymentId) logInfo("tool.call", {
1554
+ tool: "start_attach",
1555
+ msg: "no _deploymentId in scheme_url; matching on presence only"
1556
+ });
1557
+ const isMatchingPage = (pages) => {
1558
+ if (pages.length === 0) return false;
1559
+ if (deploymentId === null) return true;
1560
+ return pages.some((p) => p.url.includes(deploymentId));
1561
+ };
1562
+ const buildTimeoutError = (baseText, timeoutSec, observed) => {
1563
+ const observedUrls = observed.slice(0, 3).map((p) => p.url.slice(0, 80)).join(", ");
1564
+ const observedNote = observed.length > 0 ? ` — previously attached pages: [${observedUrls}]` : "";
1565
+ return `${baseText}\n\nNo page${deploymentId ? ` matching deploymentId=${deploymentId}` : ""} attached within ${timeoutSec}s${observedNote} — call list_pages to retry.`;
1566
+ };
1567
+ return {
1568
+ ok: true,
1569
+ parts,
1570
+ isMatchingPage,
1571
+ buildTimeoutError,
1572
+ authorityWarning,
1573
+ totpMeta: buildTotpMeta(deps)
1574
+ };
1575
+ }
1576
+ /**
1577
+ * QR render + browser open + segmented attach wait with in-call TOTP re-mint
1578
+ * (issue #626 §3). Shared by env-2 and env-3 (4 render paths:
1579
+ * headless / browser-opened / browser-open-failed / no-http-server).
1580
+ *
1581
+ * The wait is decomposed into `START_ATTACH_SEGMENT_MS` slices. Between slices,
1582
+ * if the current TOTP code has aged past `START_ATTACH_REMINT_THRESHOLD_MS`,
1583
+ * a fresh URL is minted via `mintAttachUrl` and pushed to the dashboard via
1584
+ * `onAttachUrlBuilt` (SSE refresh — NO browser re-open). The `reminted` count
1585
+ * rides in the success/timeout result.
1586
+ *
1587
+ * SECRET-HANDLING: attachUrl encodes tunnel/scheme host + the TOTP `at=` code
1588
+ * in the QR payload only. The browser is opened on a 127.0.0.1 URL only. The
1589
+ * tool result carries `totp.expiresAt` + `reminted` count — never the code.
1590
+ */
1591
+ async function renderAndMaybeWait(deps, prep, waitForAttach, callTimeoutMs, conn) {
1592
+ const { getTunnelStatus, qrHttpServer, onAttachUrlBuilt } = deps;
1593
+ const nowMs = resolveNowMs(deps);
1594
+ const canOpenBrowserFn = resolveCanOpenBrowser(deps);
1595
+ const { parts, isMatchingPage, buildTimeoutError, authorityWarning, totpMeta } = prep;
1596
+ let attachUrl = mintAttachUrl(deps, parts);
1597
+ onAttachUrlBuilt?.(parts);
1598
+ let totpIssuedAt = nowMs();
1599
+ let reminted = 0;
1600
+ const relayUrl = parts.wssUrl;
1601
+ 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).";
1602
+ const warningPrefix = authorityWarning ? `⚠️ scheme_url 경고: ${authorityWarning}\n\n` : "";
1603
+ const guiAvailable = canOpenBrowserFn();
1604
+ /** Builds the totp object surfaced in results (fresh expiresAt + reminted). */
1605
+ const totpResult = () => {
1606
+ if (!totpMeta) return void 0;
1607
+ const expiresAtMs = totpIssuedAt + 180 * 1e3;
1608
+ return {
1609
+ enabled: true,
1610
+ ttlSeconds: totpMeta.ttlSeconds,
1611
+ expiresAt: new Date(expiresAtMs).toISOString(),
1612
+ ...reminted > 0 ? { reminted } : {}
1613
+ };
1614
+ };
1615
+ /**
1616
+ * Segmented wait with TOTP re-mint (issue #626 §3). Resolves with the
1617
+ * attached page list, or rejects on timeout. Between SEGMENT_MS slices it
1618
+ * re-mints when the code has aged past the threshold (max ~4 re-mints over
1619
+ * 600 s). Returns immediately once a matching page attaches (no re-mint).
1620
+ */
1621
+ async function waitWithRemint() {
1622
+ const deadline = nowMs() + callTimeoutMs;
1623
+ if (isMatchingPage(conn.listTargets())) return conn.listTargets();
1624
+ for (;;) {
1625
+ const remaining = deadline - nowMs();
1626
+ if (remaining <= 0) throw new Error(`start_attach: 타임아웃 (${callTimeoutMs}ms)`);
1627
+ const segmentMs = Math.min(START_ATTACH_SEGMENT_MS, remaining);
1628
+ try {
1629
+ return await waitForAttachWithEvents(conn, isMatchingPage, segmentMs);
1630
+ } catch {
1631
+ if (totpMeta && nowMs() - totpIssuedAt >= 15e4) {
1632
+ attachUrl = mintAttachUrl(deps, parts);
1633
+ onAttachUrlBuilt?.(parts);
1634
+ totpIssuedAt = nowMs();
1635
+ reminted += 1;
1636
+ }
1637
+ }
1638
+ }
1639
+ }
1640
+ /**
1641
+ * Assembles the success result after a page attaches. `baseText` carries the
1642
+ * QR + pre-wait JSON block (the QR the user already scanned). The attach
1643
+ * itself ends the wait, so the QR is moot — what matters now is the final
1644
+ * TOTP state. If the segmented wait re-minted (issue #626 §3), surface the
1645
+ * post-wait `totp` block (fresh `expiresAt` + `reminted` count) so the result
1646
+ * reflects how many times the code rotated during the wait. SECRET-HANDLING:
1647
+ * the totp block carries expiresAt + reminted only — never the code value.
1648
+ */
1649
+ const successResult = (baseText) => {
1650
+ const pagesResult = listPages(conn, getTunnelStatus());
1651
+ const finalTotp = totpResult();
1652
+ const remintNote = finalTotp && reminted > 0 ? `\n\n${JSON.stringify({ totp: finalTotp }, null, 2)}` : "";
1653
+ return { content: [{
1654
+ type: "text",
1655
+ text: `${baseText}\n\n${JSON.stringify(pagesResult, null, 2)}${remintNote}`
1656
+ }] };
1657
+ };
1658
+ /** Runs the wait (when requested) and returns success/timeout result. */
1659
+ const runWait = async (baseText) => {
1660
+ if (!waitForAttach) return { content: [{
1661
+ type: "text",
1662
+ text: baseText
1663
+ }] };
1664
+ try {
1665
+ await waitWithRemint();
1666
+ } catch {
1667
+ const observed = conn.listTargets();
1668
+ return {
1669
+ content: [{
1670
+ type: "text",
1671
+ text: buildTimeoutError(baseText, callTimeoutMs / 1e3, observed)
1672
+ }],
1673
+ isError: true
1674
+ };
1675
+ }
1676
+ return successResult(baseText);
1677
+ };
1678
+ if (!guiAvailable) {
1679
+ const headlessNote = "GUI 환경이 감지되지 않았습니다 (headless/remote 환경). 텍스트 QR을 폰 카메라로 스캔하거나, 로컬 GUI 환경에서 실행하세요.\n\n";
1680
+ const qr = await renderQr(attachUrl);
1681
+ return runWait(`${warningPrefix}${headlessNote}${header}\n${JSON.stringify({
1682
+ attachUrl,
1683
+ relayUrl,
1684
+ ...totpResult() ? { totp: totpResult() } : {}
1685
+ }, null, 2)}\n\n${qr}`);
1686
+ }
1687
+ if (guiAvailable && qrHttpServer) {
1688
+ const browserResult = await openQrInBrowser(qrHttpServer.buildAttachPageUrl(attachUrl), `http://127.0.0.1:${qrHttpServer.port}/qr.png?u=${encodeURIComponent(attachUrl)}`);
1689
+ if (browserResult.opened) {
1690
+ const retriedNote = browserResult.retried ? " (1회 retry 후 성공)" : "";
1691
+ const openResult = {
1692
+ attempted: true,
1693
+ succeeded: true,
1694
+ ...browserResult.retried ? { retried: true } : {}
1695
+ };
1696
+ return runWait(`${warningPrefix}${header}\n${JSON.stringify({
1697
+ relayUrl,
1698
+ openResult,
1699
+ ...totpResult() ? { totp: totpResult() } : {}
1700
+ }, null, 2)}\n\n브라우저에서 QR을 열었습니다${retriedNote}. 폰 카메라로 스캔하세요.\nURL: ${browserResult.httpUrl}`);
1701
+ }
1702
+ const openResult = {
1703
+ attempted: true,
1704
+ succeeded: false,
1705
+ failureReason: browserResult.error ?? "브라우저 실행 후보 모두 실패",
1706
+ pngUrl: browserResult.pngUrl,
1707
+ ...browserResult.stderrSummary ? { stderrSummary: browserResult.stderrSummary } : {}
1708
+ };
1709
+ const stderrNote = browserResult.stderrSummary ? `\nstderr: ${browserResult.stderrSummary}` : "";
1710
+ const fallbackNote = `브라우저 자동 열기에 실패했습니다. 다음 URL을 직접 브라우저에서 여세요:\n${browserResult.httpUrl}\n또는 PNG로 받기: ${browserResult.pngUrl}` + stderrNote + "\n\n";
1711
+ const qr = await renderQr(attachUrl);
1712
+ return runWait(`${warningPrefix}${fallbackNote}${header}\n${JSON.stringify({
1713
+ attachUrl,
1714
+ relayUrl,
1715
+ openResult,
1716
+ ...totpResult() ? { totp: totpResult() } : {}
1717
+ }, null, 2)}\n\n${qr}`);
1718
+ }
1719
+ const qr = await renderQr(attachUrl);
1720
+ return runWait(`${warningPrefix}${header}\n${JSON.stringify({
1721
+ attachUrl,
1722
+ relayUrl,
1723
+ ...totpResult() ? { totp: totpResult() } : {}
1724
+ }, null, 2)}\n\n${qr}`);
1725
+ }
1726
+ /**
1727
+ * Builds a self-contained IIFE DOM expression that renders a dismissible
1728
+ * "Debugger Connected" badge on the bottom-left of the phone screen.
1729
+ *
1730
+ * **Pure function** — returns a JS expression string; does NOT inject it.
1731
+ * Injection is performed by {@link injectDebugIndicator} in `cell.ts`.
1732
+ *
1733
+ * The expression, when evaluated on the page, does the following:
1734
+ * 1. Early-returns if `#__ait_debug_indicator` already exists (idempotent —
1735
+ * prevents duplicate badges on re-injection after page reload).
1736
+ * 2. Appends a fixed-position `<div id="__ait_debug_indicator">` at the
1737
+ * bottom-left, accounting for safe-area insets.
1738
+ * 3. Attaches a `{ once: true }` `pointerdown` listener that removes the
1739
+ * badge on first touch — one-tap dismiss.
1740
+ *
1741
+ * The expression intentionally contains NO relay URLs, wss addresses, TOTP
1742
+ * codes, or any other secrets. It is pure DOM UI text only.
1743
+ *
1744
+ * SECRET-HANDLING: this expression contains no secrets, relay URLs, wss
1745
+ * addresses, or TOTP codes whatsoever — DOM label text only.
1746
+ *
1747
+ * @param opts.label - Badge text (default: `'Debugger Connected'`).
1748
+ * @returns A JS expression string suitable for `Runtime.evaluate`.
1749
+ */
1750
+ function buildIndicatorExpression(opts) {
1751
+ const label = opts?.label ?? "Debugger Connected";
1752
+ 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);})()`;
1753
+ }
1754
+ //#endregion
1755
+ //#region src/test-runner/cell.ts
1756
+ /**
1757
+ * Cell injection utility for the `devtools-test` CLI (issue #684 §4.1).
1758
+ *
1759
+ * Injects arbitrary globals into the page via `Runtime.evaluate` BEFORE the
1760
+ * first test bundle is injected. The injected values are session-global — one
1761
+ * call covers all files in the run.
1762
+ *
1763
+ * The primary use-case is injecting `__AIT_CELL__` (sdkLine/platform) so
1764
+ * sdk-example's `aitCapture.ts` picks up the correct test-axis values instead
1765
+ * of falling back to `'2.x'`/`'mock'`.
1766
+ *
1767
+ * devtools does NOT know the shape of `__AIT_CELL__` — it only provides the
1768
+ * general injection mechanism. The caller (CLI or MCP auto-attach path) is
1769
+ * responsible for constructing the cell object.
1770
+ *
1771
+ * SECRET-HANDLING: cell values (sdkLine/platform) are not secrets and may be
1772
+ * logged at the caller's discretion. This module does NOT log them itself.
1773
+ *
1774
+ * Node-only. react-free. CdpConnection only.
1775
+ */
1776
+ /**
1777
+ * Injects each key of `globals` into `globalThis` in the page via a single
1778
+ * `Runtime.evaluate` call. Must be called BEFORE the first `bundleTestFile`
1779
+ * inject — the cell is session-global and applies to all subsequent files.
1780
+ *
1781
+ * Throws if the CDP evaluate returns an exception.
1782
+ *
1783
+ * @param conn - The live CDP connection (relay-attached page).
1784
+ * @param globals - Plain-JSON-serialisable key→value map to assign onto `globalThis`.
1785
+ */
1786
+ async function injectGlobals(conn, globals) {
1787
+ const expr = `(() => { Object.assign(globalThis, ${JSON.stringify(globals)}); return true; })()`;
1788
+ const result = await conn.send("Runtime.evaluate", {
1789
+ expression: expr,
1790
+ returnByValue: true
1791
+ });
1792
+ if (result.exceptionDetails) {
1793
+ const msg = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text ?? "unknown error";
1794
+ throw new Error(`injectGlobals: Runtime.evaluate threw: ${msg}`);
1795
+ }
1796
+ }
1797
+ /**
1798
+ * Injects the "Debugger Connected" on-phone indicator via `Runtime.evaluate`.
1799
+ *
1800
+ * Uses the same CDP mechanism as {@link injectGlobals} — a single
1801
+ * `Runtime.evaluate` round-trip with the expression built by
1802
+ * {@link buildIndicatorExpression}. The indicator is a dismissible red badge
1803
+ * rendered at the bottom-left of the page (position:fixed, safe-area-aware).
1804
+ *
1805
+ * **Isolation**: unlike {@link injectGlobals}, this function NEVER throws to
1806
+ * its caller. Injection failure (e.g. page detached during inject, CSS not
1807
+ * supported) is swallowed and logged as `console.debug` — the badge is
1808
+ * informational UI and must never block attach success or test execution.
1809
+ * This is the same fire-and-forget spirit as the eruda mount in
1810
+ * `src/in-app/attach.ts`.
1811
+ *
1812
+ * Call this ONLY on the manual debug paths (start_attach MCP, devtools-test
1813
+ * CLI). Do NOT call on the `run_tests` auto-attach path — the red badge
1814
+ * would contaminate screenshots, measure_safe_area probes, and DOM snapshots
1815
+ * taken during automated measurement runs.
1816
+ *
1817
+ * SECRET-HANDLING: the injected expression contains no secrets, relay URLs,
1818
+ * wss addresses, or TOTP codes — it is pure DOM UI text built by
1819
+ * {@link buildIndicatorExpression}.
1820
+ *
1821
+ * @param conn - The live CDP connection (relay-attached page).
1822
+ * @param opts - Optional overrides forwarded to {@link buildIndicatorExpression}.
1823
+ */
1824
+ async function injectDebugIndicator(conn, opts) {
1825
+ try {
1826
+ await conn.send("Runtime.evaluate", {
1827
+ expression: buildIndicatorExpression(opts),
1828
+ returnByValue: true
1829
+ });
1830
+ } catch (err) {
1831
+ console.debug("[@ait-co/devtools] debug indicator inject skipped:", err);
1832
+ }
1833
+ }
1834
+ //#endregion
1835
+ //#region src/test-runner/discover.ts
1836
+ /**
1837
+ * Test-file discovery shared by the `devtools-test` CLI and the `run_tests`
1838
+ * MCP tool, so both expand glob patterns with identical semantics.
1839
+ *
1840
+ * Uses Node's built-in `fs/promises` `glob` (Node 22+) — no extra dependency,
1841
+ * which keeps the MCP daemon install graph lean (a plain glob lib would land in
1842
+ * the `npx … devtools-mcp` path for no benefit).
1843
+ *
1844
+ * Pure Node IO only (`node:fs/promises` + `node:path`) — react-free, so it is
1845
+ * safe to import from the MCP daemon graph.
1846
+ */
1847
+ /**
1848
+ * Expands `patterns` (globs or plain paths) into a sorted, de-duplicated list of
1849
+ * ABSOLUTE test file paths, resolved relative to `cwd`.
1850
+ *
1851
+ * A plain (non-glob) path passes through when it matches a real file; a glob
1852
+ * expands against `cwd`. Absolute matches are kept as-is; relative matches are
1853
+ * resolved against `cwd`. `bundleTestFile` requires an absolute path, so the
1854
+ * absolute output feeds it directly.
1855
+ *
1856
+ * @param patterns Glob patterns or file paths (e.g. `['src/**\/*.ait.test.ts']`).
1857
+ * @param cwd Base directory for relative patterns/results.
1858
+ * @returns Sorted, de-duplicated absolute file paths. Empty when nothing matches.
1859
+ */
1860
+ async function discoverTestFiles(patterns, cwd) {
1861
+ const out = /* @__PURE__ */ new Set();
1862
+ for await (const match of glob(patterns, { cwd })) out.add(isAbsolute(match) ? match : resolve(cwd, match));
1863
+ return [...out].sort();
1864
+ }
1865
+ //#endregion
1866
+ //#region src/test-runner/bundle.ts
1867
+ /**
1868
+ * esbuild-based bundler for user test files.
1869
+ *
1870
+ * Bundles a single test file into a self-contained IIFE string that can be
1871
+ * injected into a WebView via `Runtime.evaluate`. The bundle includes the
1872
+ * test runtime (`runtime.ts`), which provides `describe/it/test/expect` and
1873
+ * the `runTestModule(factory)` entry point.
1874
+ *
1875
+ * ## How the wiring works
1876
+ *
1877
+ * The bundle exposes two exports on `globalThis.__testBundle`:
1878
+ * - `runTestModule` — the runtime's entry function.
1879
+ * - `__userFactory` — an async function whose body is the user's top-level
1880
+ * test registration code (describe/it/test calls).
1881
+ *
1882
+ * The Node-side RPC (`rpc.ts`) calls:
1883
+ * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
1884
+ *
1885
+ * `runTestModule` then installs `describe/it/test/expect` as globals, invokes
1886
+ * the factory (which registers all tests), runs them, and returns a `RunReport`.
1887
+ *
1888
+ * ## Why a factory wrapper is needed
1889
+ *
1890
+ * Naively adding the runtime to `entryPoints` and bundling the user file would
1891
+ * fail for two reasons:
1892
+ * 1. `describe/it/test/expect` from the runtime are module-local in the IIFE
1893
+ * scope. The user's top-level `describe(...)` calls expect them as globals —
1894
+ * they are not globals until `runTestModule` installs them.
1895
+ * 2. Even with globals pre-installed, the user file runs at IIFE-evaluation
1896
+ * time, before the RPC layer calls `runTestModule` to reset state and start
1897
+ * the test clock.
1898
+ *
1899
+ * The factory approach solves both: the user's registration code is deferred
1900
+ * into a function that `runTestModule` calls AFTER installing the globals.
1901
+ *
1902
+ * ## Factory extraction algorithm
1903
+ *
1904
+ * The `userFactoryPlugin` reads the user file and splits lines into:
1905
+ * - **top-level**: `import …` and re-export lines — kept at module scope
1906
+ * (the only valid position for static `import` in ESM).
1907
+ * - **body**: all other statements — moved into the body of the exported
1908
+ * `__userFactory` async function.
1909
+ *
1910
+ * esbuild processes the re-generated module, following each static import
1911
+ * through the normal dependency graph (including the SDK-redirect plugin).
1912
+ *
1913
+ * ## SDK redirect
1914
+ *
1915
+ * Imports of `@apps-in-toss/web-framework` (and sub-paths) are intercepted via
1916
+ * the `sdkRedirectPlugin` and replaced with a virtual `window.__sdk` proxy that
1917
+ * `src/in-app/auto.ts` installs at runtime. This works for both 2.x and 3.x SDK.
1918
+ *
1919
+ * SECRET-HANDLING: the returned bundle code is caller-managed; never log it.
1920
+ */
1921
+ /** The SDK package name that mini-app test code imports from. */
1922
+ const SDK_PACKAGE = "@apps-in-toss/web-framework";
1923
+ /**
1924
+ * Names the runtime installs as globals before invoking the user factory.
1925
+ * The `vitest` virtual module re-exports each as a lazy getter that reads from
1926
+ * `globalThis` at access time. Keep in sync with the globals installed in
1927
+ * `runtime.ts#runTestModule`.
1928
+ */
1929
+ const VITEST_GLOBAL_NAMES = [
1930
+ "describe",
1931
+ "it",
1932
+ "test",
1933
+ "expect",
1934
+ "beforeAll",
1935
+ "afterAll",
1936
+ "beforeEach",
1937
+ "afterEach",
1938
+ "vi"
1939
+ ];
1940
+ /**
1941
+ * Matches the bare SDK package and any sub-path import
1942
+ * (`@apps-in-toss/web-framework`, `@apps-in-toss/web-framework/foo`).
1943
+ * Built from {@link SDK_PACKAGE} so the package name has a single source.
1944
+ */
1945
+ const SDK_IMPORT_FILTER = new RegExp(`^${SDK_PACKAGE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
1946
+ /**
1947
+ * esbuild plugin that intercepts SDK imports and redirects them to the
1948
+ * `window.__sdk` proxy that `src/in-app/auto.ts` installs at runtime.
1949
+ *
1950
+ * Strategy: for every import of `@apps-in-toss/web-framework` (or sub-paths),
1951
+ * esbuild resolves it to a virtual module that re-exports all named exports
1952
+ * via `window.__sdk[name]`. This avoids bundling the real SDK (which may not
1953
+ * be available in the test environment) while still making named imports work.
1954
+ *
1955
+ * If `window.__sdk` is absent (non-dog-food build), every access throws a
1956
+ * descriptive error rather than returning `undefined` silently.
1957
+ */
1958
+ function sdkRedirectPlugin() {
1959
+ return {
1960
+ name: "sdk-redirect",
1961
+ setup(build) {
1962
+ build.onResolve({ filter: SDK_IMPORT_FILTER }, (args) => ({
1963
+ path: args.path,
1964
+ namespace: "sdk-redirect"
1965
+ }));
1966
+ build.onLoad({
1967
+ filter: /.*/,
1968
+ namespace: "sdk-redirect"
1969
+ }, () => ({
1970
+ contents: `
1971
+ var __proxy = (typeof window !== 'undefined' && window.__sdk)
1972
+ ? window.__sdk
1973
+ : new Proxy({}, {
1974
+ get: function(_t, p) {
1975
+ throw new Error('window.__sdk is not installed — run in a dog-food build. Missing: ' + String(p));
1976
+ }
1977
+ });
1978
+ module.exports = __proxy;
1979
+ `,
1980
+ loader: "js"
1981
+ }));
1982
+ }
1983
+ };
1984
+ }
1985
+ /**
1986
+ * esbuild plugin that intercepts `import … from 'vitest'` and replaces it with
1987
+ * a virtual module that delegates every named import to `globalThis` at ACCESS
1988
+ * time (not at bundle-evaluation time).
1989
+ *
1990
+ * The runtime installs `describe/it/test/expect/beforeAll/afterAll/beforeEach/
1991
+ * afterEach/vi` as globals inside `runTestModule`, which runs AFTER the bundle
1992
+ * IIFE is evaluated. A value-copy redirect (`export var describe =
1993
+ * globalThis.describe`) would therefore capture `undefined` at evaluation time
1994
+ * and the user's `describe(...)` calls would be no-ops — registering zero tests.
1995
+ *
1996
+ * The fix defers the lookup to call time using per-name **getter** exports.
1997
+ * We emit a CommonJS module that:
1998
+ * 1. sets `__esModule = true` so esbuild's `__toESM` interop maps each named
1999
+ * import directly to a property access on the module (NOT wrapped under a
2000
+ * `default` shim — which is what happens for a bare Proxy whose own-keys
2001
+ * are empty, leaving every named import `undefined`);
2002
+ * 2. defines each global name as a getter that reads `globalThis[name]` on
2003
+ * every access. So `import { describe } from 'vitest'` compiles to
2004
+ * `import_vitest.describe`, whose getter returns the real `describe` only
2005
+ * when the factory calls it — after `runTestModule` installs the globals.
2006
+ *
2007
+ * A plain `module.exports = new Proxy(...)` does NOT work here: esbuild routes
2008
+ * the virtual module through `__toESM`, which enumerates own-keys (none on an
2009
+ * empty Proxy target) and therefore exposes zero named exports. Explicit getter
2010
+ * properties give `__toESM` real keys to map while keeping access lazy.
2011
+ */
2012
+ function vitestRedirectPlugin() {
2013
+ return {
2014
+ name: "vitest-redirect",
2015
+ setup(build) {
2016
+ build.onResolve({ filter: /^vitest$/ }, () => ({
2017
+ path: "vitest",
2018
+ namespace: "vitest-redirect"
2019
+ }));
2020
+ build.onLoad({
2021
+ filter: /^vitest$/,
2022
+ namespace: "vitest-redirect"
2023
+ }, () => {
2024
+ return {
2025
+ contents: `Object.defineProperty(exports, '__esModule', { value: true });\n${VITEST_GLOBAL_NAMES.map((name) => `Object.defineProperty(exports, ${JSON.stringify(name)}, { enumerable: true, get: function() { return globalThis[${JSON.stringify(name)}]; } });`).join("\n")}\n`,
2026
+ loader: "js"
2027
+ };
2028
+ });
2029
+ }
2030
+ };
2031
+ }
2032
+ /**
2033
+ * esbuild plugin that transforms the user test file into a module that exports
2034
+ * an async `__userFactory` function. The factory defers the user's top-level
2035
+ * test registration code (describe/it/test calls) so it only runs when
2036
+ * `runTestModule(__userFactory)` explicitly invokes it — AFTER the runtime has
2037
+ * installed describe/it/test/expect as globals.
2038
+ *
2039
+ * Algorithm:
2040
+ * - Import declarations and re-export statements are kept at module top-level
2041
+ * (the only valid ESM position for static `import`). A statement that spans
2042
+ * multiple lines — e.g. a named import with one member per line:
2043
+ * import {
2044
+ * appLogin,
2045
+ * getAnonymousKey,
2046
+ * } from '@apps-in-toss/web-framework';
2047
+ * is tracked as a single block: every line from the opening `import {` /
2048
+ * `export {` through the closing `from '…'` (or side-effect `'…'`) line is
2049
+ * kept together at top-level. This prevents the member lines and the
2050
+ * closing `} from '…'` line from leaking into the factory body, which would
2051
+ * leave an unterminated `import {` at module scope (the #678 env3 failure:
2052
+ * esbuild threw `Expected "as" but found "{"` on multi-line SDK imports).
2053
+ * - All other lines (describe/it/test calls, local declarations, etc.) are
2054
+ * moved into the body of the exported async factory function.
2055
+ *
2056
+ * This preserves SDK import resolution (the sdk-redirect plugin processes
2057
+ * top-level imports normally) while deferring test registration to the factory.
2058
+ */
2059
+ function userFactoryPlugin(absPath) {
2060
+ const NAMESPACE = "user-test-factory";
2061
+ return {
2062
+ name: "user-test-factory",
2063
+ setup(build) {
2064
+ build.onResolve({ filter: /^user-test-factory$/ }, () => ({
2065
+ path: absPath,
2066
+ namespace: NAMESPACE
2067
+ }));
2068
+ build.onLoad({
2069
+ filter: /.*/,
2070
+ namespace: NAMESPACE
2071
+ }, async (args) => {
2072
+ const lines = (await fs.readFile(args.path, "utf8")).split("\n");
2073
+ const topLevelLines = [];
2074
+ const bodyLines = [];
2075
+ const EXPORT_DECLARATION_RE = /^(export\s+)(default\s+|async\s+function\s+|function\s+|class\s+|const\s+|let\s+|var\s+)/;
2076
+ const isImportStart = (trimmed) => trimmed.startsWith("import ") || trimmed.startsWith("import{") || trimmed.startsWith("import'") || trimmed.startsWith("import\"");
2077
+ const endsStatement = (trimmed) => /['"]\s*;?\s*$/.test(trimmed.replace(/\/\/.*$/, "").trimEnd());
2078
+ let inImportBlock = false;
2079
+ for (const line of lines) {
2080
+ const trimmed = line.trimStart();
2081
+ const indent = line.slice(0, line.length - trimmed.length);
2082
+ if (inImportBlock) {
2083
+ topLevelLines.push(line);
2084
+ if (endsStatement(trimmed)) inImportBlock = false;
2085
+ continue;
2086
+ }
2087
+ if (isImportStart(trimmed)) {
2088
+ topLevelLines.push(line);
2089
+ if (!endsStatement(trimmed)) inImportBlock = true;
2090
+ } else if (trimmed.startsWith("export ")) if (trimmed.match(EXPORT_DECLARATION_RE)) bodyLines.push(indent + trimmed.slice(7));
2091
+ else {
2092
+ topLevelLines.push(line);
2093
+ if (/\bfrom\b/.test(trimmed) ? !endsStatement(trimmed) : trimmed.endsWith("{")) inImportBlock = true;
2094
+ }
2095
+ else bodyLines.push(line);
2096
+ }
2097
+ return {
2098
+ contents: [
2099
+ ...topLevelLines,
2100
+ "",
2101
+ "// biome-ignore lint: generated factory wrapper",
2102
+ "export default async function __userFactory(): Promise<void> {",
2103
+ ...bodyLines.map((l) => ` ${l}`),
2104
+ "}"
2105
+ ].join("\n"),
2106
+ loader: "ts",
2107
+ resolveDir: path.dirname(absPath)
2108
+ };
2109
+ });
2110
+ }
2111
+ };
2112
+ }
2113
+ /**
2114
+ * Returns the absolute path to the test-runner runtime module.
2115
+ *
2116
+ * Searches candidates in priority order:
2117
+ * 1. Co-located `runtime.ts` / `runtime.js` — covers the source tree
2118
+ * (tsx / ts-node) and the `dist/test-runner/` entry.
2119
+ * 2. `../test-runner/runtime.js` — covers the `dist/mcp/cli.js` entry,
2120
+ * where `import.meta.url` resolves to `dist/mcp/` (a sibling directory
2121
+ * of `dist/test-runner/`). Without this second candidate the MCP entry
2122
+ * point would look for `dist/mcp/runtime.js`, which does not exist, and
2123
+ * every `run_tests` call would fail with an esbuild "Could not resolve"
2124
+ * error (#678).
2125
+ *
2126
+ * Returns the first candidate that exists on disk. Falls back to the
2127
+ * co-located `runtime.js` path so esbuild produces a clear "file not found"
2128
+ * error rather than a cryptic failure.
2129
+ */
2130
+ function getRuntimePath() {
2131
+ const dir = path.dirname(fileURLToPath(import.meta.url));
2132
+ const candidates = [
2133
+ path.join(dir, "runtime.ts"),
2134
+ path.join(dir, "runtime.js"),
2135
+ path.join(dir, "..", "test-runner", "runtime.js")
2136
+ ];
2137
+ for (const candidate of candidates) try {
2138
+ accessSync(candidate);
2139
+ return candidate;
2140
+ } catch {}
2141
+ return path.join(dir, "runtime.js");
2142
+ }
2143
+ /**
2144
+ * Bundles `absPath` into a single IIFE string suitable for `Runtime.evaluate`.
2145
+ *
2146
+ * The IIFE installs `window.__testBundle` (or the custom `globalName`) with:
2147
+ * - `runTestModule` — the runtime entry (from `runtime.ts`).
2148
+ * - `__userFactory` — an async function wrapping the user's test registration
2149
+ * code so it runs AFTER `runTestModule` installs the globals.
2150
+ *
2151
+ * Callers (rpc.ts) invoke:
2152
+ * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
2153
+ *
2154
+ * @param absPath - Absolute path to the user test file.
2155
+ * @param opts - Optional bundling overrides.
2156
+ */
2157
+ async function bundleTestFile(absPath, opts) {
2158
+ const globalName = opts?.globalName ?? "__testBundle";
2159
+ const extraExternals = opts?.extraExternals ?? [];
2160
+ const esbuild = await import("esbuild");
2161
+ const runtimePath = getRuntimePath();
2162
+ const wrapperContent = [
2163
+ `import { runTestModule } from ${JSON.stringify(runtimePath)};`,
2164
+ `import __userFactory from "user-test-factory";`,
2165
+ `export { runTestModule, __userFactory };`
2166
+ ].join("\n");
2167
+ const result = await esbuild.build({
2168
+ stdin: {
2169
+ contents: wrapperContent,
2170
+ loader: "ts",
2171
+ resolveDir: path.dirname(absPath)
2172
+ },
2173
+ bundle: true,
2174
+ format: "iife",
2175
+ globalName,
2176
+ platform: "browser",
2177
+ target: "es2022",
2178
+ write: false,
2179
+ plugins: [
2180
+ userFactoryPlugin(absPath),
2181
+ vitestRedirectPlugin(),
2182
+ sdkRedirectPlugin()
2183
+ ],
2184
+ external: extraExternals,
2185
+ treeShaking: true,
2186
+ footer: { js: `globalThis[${JSON.stringify(globalName)}] = ${globalName};` }
2187
+ });
2188
+ const warnings = result.warnings.map((w) => `${path.relative(process.cwd(), w.location?.file ?? "")}:${w.location?.line ?? "?"}: ${w.text}`);
2189
+ const outputFile = result.outputFiles?.[0];
2190
+ if (!outputFile) throw new Error("bundleTestFile: esbuild produced no output — check entryPoints");
2191
+ return {
2192
+ code: outputFile.text,
2193
+ warnings
2194
+ };
2195
+ }
2196
+ //#endregion
2197
+ //#region src/test-runner/rpc.ts
2198
+ /** Maximum milliseconds to wait for a single evaluate round-trip. */
2199
+ const DEFAULT_TIMEOUT_MS = 3e4;
2200
+ /**
2201
+ * Wraps bundle code in a self-executing IIFE that:
2202
+ * 1. Evaluates the bundle (registering describe/it/test).
2203
+ * 2. Calls `__testBundle.runTestModule(...)` — the entry the runtime exports.
2204
+ * 3. Returns a JSON-serialised `RunReport` string.
2205
+ *
2206
+ * The double-serialisation (RunReport → JSON string → returnByValue string)
2207
+ * is intentional: CDP `returnByValue` reliably transports strings; deeply
2208
+ * nested objects can lose fidelity across the Chii relay.
2209
+ *
2210
+ * SECRET-HANDLING: `bundleCode` MUST NOT be logged by callers.
2211
+ */
2212
+ function buildRunTestsExpression(bundleCode) {
2213
+ return `(async () => { try { ${bundleCode} } catch(e) { return JSON.stringify({ok:false,error:'bundle-eval: ' + String(e && e.message || e)}); } if (typeof globalThis.__testBundle !== 'object' || typeof globalThis.__testBundle.runTestModule !== 'function' || typeof globalThis.__testBundle.__userFactory !== 'function') { return JSON.stringify({ok:false,error:'bundle-missing-export: __testBundle.runTestModule or __userFactory is not a function'}); } try { const report = await globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory); return JSON.stringify({ok:true,value:report}); } catch(e) { return JSON.stringify({ok:false,error:'test-run: ' + String(e && e.message || e)}); }})()`;
2214
+ }
2215
+ /**
2216
+ * Parses the raw CDP `returnByValue` result from a `buildRunTestsExpression`
2217
+ * evaluate call into a typed `RpcRunResult`.
2218
+ *
2219
+ * Throws only on parse failure — an `ok:false` envelope is a normal result.
2220
+ *
2221
+ * SECRET-HANDLING: `rawValue` is not included in error messages.
2222
+ */
2223
+ function parseRunTestsResult(rawValue) {
2224
+ if (typeof rawValue !== "string") throw new Error(`rpc.parseRunTestsResult: unexpected return type "${typeof rawValue}" — expected JSON string`);
2225
+ let parsed;
2226
+ try {
2227
+ parsed = JSON.parse(rawValue);
2228
+ } catch {
2229
+ throw new Error("rpc.parseRunTestsResult: bridge returned non-JSON string");
2230
+ }
2231
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("rpc.parseRunTestsResult: parsed result is not an object");
2232
+ const obj = parsed;
2233
+ if (obj.ok === true) return {
2234
+ ok: true,
2235
+ report: obj.value
2236
+ };
2237
+ if (obj.ok === false) return {
2238
+ ok: false,
2239
+ error: typeof obj.error === "string" ? obj.error : String(obj.error)
2240
+ };
2241
+ throw new Error("rpc.parseRunTestsResult: result missing \"ok\" field");
2242
+ }
2243
+ /**
2244
+ * Injects `bundleCode` into the attached page and awaits test execution.
2245
+ *
2246
+ * Uses `Runtime.evaluate` with `awaitPromise: true` to wait for the
2247
+ * async IIFE to settle. The 30-second CDP command timeout covers even
2248
+ * long-running test suites; split into smaller files if you hit it.
2249
+ *
2250
+ * @param connection - Active CDP connection (relay or local).
2251
+ * @param bundleCode - IIFE bundle string from `bundleTestFile`.
2252
+ * @param timeoutMs - Override the default 30 s timeout.
2253
+ *
2254
+ * SECRET-HANDLING: `bundleCode` and the raw CDP result value are never logged.
2255
+ */
2256
+ async function injectAndRunBundle(connection, bundleCode, timeoutMs = DEFAULT_TIMEOUT_MS) {
2257
+ const expression = buildRunTestsExpression(bundleCode);
2258
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error(`rpc: evaluate timed out after ${timeoutMs}ms`)), timeoutMs));
2259
+ const evalPromise = connection.send("Runtime.evaluate", {
2260
+ expression,
2261
+ returnByValue: true,
2262
+ awaitPromise: true
2263
+ });
2264
+ const cdpResult = await Promise.race([evalPromise, timeoutPromise]);
2265
+ if (cdpResult.exceptionDetails) {
2266
+ const msg = cdpResult.exceptionDetails.exception?.description ?? cdpResult.exceptionDetails.text ?? "Runtime.evaluate threw an exception";
2267
+ throw new Error(`rpc.injectAndRunBundle: ${msg}`);
2268
+ }
2269
+ return parseRunTestsResult(cdpResult.result.value);
2270
+ }
2271
+ //#endregion
2272
+ //#region src/test-runner/relay-worker.ts
2273
+ /**
2274
+ * Runs all `files` sequentially over the given CDP `connection`.
2275
+ *
2276
+ * For each file:
2277
+ * 1. Bundle with esbuild (includes SDK shim + runtime).
2278
+ * 2. Inject into the attached page via `Runtime.evaluate`.
2279
+ * 3. Await the `RunReport` JSON response.
2280
+ * 4. Accumulate results.
2281
+ *
2282
+ * Returns a `RelayRunReport` with per-file results and flattened totals.
2283
+ *
2284
+ * This function does NOT open or manage the relay connection — the caller
2285
+ * is responsible for attaching and closing it.
2286
+ *
2287
+ * TODO (#645): implement the Vitest `PoolRunnerInitializer` interface here
2288
+ * so that `runTestFilesOverRelay` can be used as a Vitest pool entry.
2289
+ *
2290
+ * @param connection - Active CDP connection (relay or local kind).
2291
+ * @param files - Absolute paths to test files, run in order.
2292
+ * @param opts - Optional per-run overrides.
2293
+ */
2294
+ async function runTestFilesOverRelay(connection, files, opts) {
2295
+ const wallStart = Date.now();
2296
+ const startedAt = new Date(wallStart).toISOString();
2297
+ const fileResults = [];
2298
+ for (const file of files) {
2299
+ let fileEntry;
2300
+ try {
2301
+ const { code } = await bundleTestFile(file, opts?.bundleOptions);
2302
+ const rpcResult = await injectAndRunBundle(connection, code, opts?.timeoutMs);
2303
+ if (rpcResult.ok) fileEntry = {
2304
+ file,
2305
+ result: rpcResult.report
2306
+ };
2307
+ else fileEntry = {
2308
+ file,
2309
+ result: { error: rpcResult.error }
2310
+ };
2311
+ } catch (e) {
2312
+ fileEntry = {
2313
+ file,
2314
+ result: { error: e instanceof Error ? e.message : String(e) }
2315
+ };
2316
+ }
2317
+ fileResults.push(fileEntry);
2318
+ }
2319
+ const totals = fileResults.reduce((acc, { result }) => {
2320
+ if ("error" in result) {
2321
+ acc.failed += 1;
2322
+ acc.total += 1;
2323
+ } else {
2324
+ acc.passed += result.passed;
2325
+ acc.failed += result.failed;
2326
+ acc.skipped += result.skipped;
2327
+ acc.total += result.passed + result.failed + result.skipped;
2328
+ }
2329
+ return acc;
2330
+ }, {
2331
+ passed: 0,
2332
+ failed: 0,
2333
+ skipped: 0,
2334
+ total: 0
2335
+ });
2336
+ return {
2337
+ startedAt,
2338
+ duration: Date.now() - wallStart,
2339
+ files: fileResults,
2340
+ totals
2341
+ };
2342
+ }
2343
+ //#endregion
2344
+ //#region src/test-runner/cli.ts
2345
+ /**
2346
+ * `devtools-test` CLI.
2347
+ *
2348
+ * Shares test-file discovery with the `run_tests` MCP tool (`discoverTestFiles`)
2349
+ * and exposes `runWithConnection` — the pure run core that bundles, injects, and
2350
+ * collects each file over a CDP connection. The CLI's `main()` performs a
2351
+ * standalone relay attach (boot relay → QR → phone scan → cell inject → run).
2352
+ *
2353
+ * NOTE: no shebang in this source file — the tsdown entry's `banner` option
2354
+ * injects `#!/usr/bin/env node` into the compiled output (same pattern as
2355
+ * `src/mcp/cli.ts`).
2356
+ */
2357
+ const USAGE = `
2358
+ devtools-test — run mini-app tests on a real device WebView over the CDP relay
2359
+
2360
+ USAGE
2361
+ devtools-test <glob> [<glob> ...] [options]
2362
+
2363
+ OPTIONS
2364
+ --scheme-url <url> intoss-private:// URL from \`ait deploy --scheme-only\`
2365
+ (required for standalone relay attach / env3)
2366
+ --timeout <ms> Per-file evaluate timeout in ms (default: 30000)
2367
+ --cell-sdk-line <line> SDK line to inject as __AIT_CELL__.sdkLine (2.x|3.x)
2368
+ --cell-platform <plat> Platform to inject as __AIT_CELL__.platform
2369
+ (mock|ios|android, default: AIT_CELL_PLATFORM env)
2370
+ --headless Disable browser auto-open (text QR only)
2371
+ --project-root <dir> Project root for .ait_relay secret lookup
2372
+ (default: current working directory)
2373
+ --help, -h Show this help message
2374
+
2375
+ DESCRIPTION
2376
+ Boots a Chii relay + cloudflared tunnel, renders a QR code, waits for a real
2377
+ device to scan and attach, injects the cell globals (__AIT_CELL__), bundles
2378
+ each matched test file with esbuild (SDK imports redirected to window.__sdk),
2379
+ injects the bundle into the attached WebView via Runtime.evaluate, and prints
2380
+ a summary.
2381
+
2382
+ The test files run against the live relay connection started by this process;
2383
+ no separate MCP daemon is required.
2384
+
2385
+ EXAMPLE
2386
+ devtools-test 'src/**/*.ait.test.ts' \\
2387
+ --scheme-url "intoss-private://..." \\
2388
+ --cell-platform ios \\
2389
+ --timeout 60000
2390
+
2391
+ `.trimStart();
2392
+ /**
2393
+ * Runs `files` over `connection` and returns the aggregate report.
2394
+ * This pure function is the testable core of the CLI (and is what the
2395
+ * `run_tests` MCP tool calls against the daemon's attached connection); it is
2396
+ * separate from `main()` so tests can call it without spawning a subprocess.
2397
+ */
2398
+ async function runWithConnection(connection, files, opts) {
2399
+ const report = await runTestFilesOverRelay(connection, files, opts);
2400
+ if (opts?.printSummary) {
2401
+ const { totals } = report;
2402
+ process.stdout.write(`\ndevtools-test: ${totals.passed} passed, ${totals.failed} failed, ${totals.skipped} skipped (${report.duration}ms)\n`);
2403
+ }
2404
+ return report;
2405
+ }
2406
+ /**
2407
+ * CLI entry point.
2408
+ *
2409
+ * Performs a standalone relay attach → run lifecycle:
2410
+ *
2411
+ * 1. Parse args: globs, --timeout, --cell-sdk-line, --cell-platform,
2412
+ * --scheme-url (required for env3), --headless, --project-root.
2413
+ * 2. Discover test files; exit 1 if none.
2414
+ * 3. Load .ait_relay secret into AIT_DEBUG_TOTP_SECRET, then boot relay family.
2415
+ * 4. Assemble AttachDeps (no qrHttpServer → text QR).
2416
+ * 5. prepareAttach(deps, 'relay-dev', { scheme_url }, conn).
2417
+ * 6. renderAndMaybeWait(deps, prep, true, timeoutMs, conn) — text QR + wait.
2418
+ * 7. If cell flags present, injectGlobals({ __AIT_CELL__: cell }) before run.
2419
+ * 8. runWithConnection(conn, files, { timeoutMs, printSummary: true }).
2420
+ * 9. family.stop(); process.exitCode = failed > 0 ? 1 : 0.
2421
+ *
2422
+ * The CLI is not a daemon — no lock, router, SSE, or tools_list is needed.
2423
+ * Attach timeout exits with code 1; test failures exit with code 1.
2424
+ *
2425
+ * SECRET-HANDLING: scheme_url / relay wssUrl / TOTP codes are never written to
2426
+ * stdout/stderr directly. text QR renders via renderAndMaybeWait which encodes
2427
+ * the TOTP `at=` code inside the QR payload (not in plain log lines).
2428
+ */
2429
+ async function main(argv = process.argv.slice(2)) {
2430
+ let parsed;
2431
+ try {
2432
+ parsed = parseArgs({
2433
+ args: argv,
2434
+ options: {
2435
+ help: {
2436
+ type: "boolean",
2437
+ short: "h"
2438
+ },
2439
+ timeout: { type: "string" },
2440
+ "scheme-url": { type: "string" },
2441
+ "cell-sdk-line": { type: "string" },
2442
+ "cell-platform": { type: "string" },
2443
+ headless: { type: "boolean" },
2444
+ "project-root": { type: "string" }
2445
+ },
2446
+ allowPositionals: true
2447
+ });
2448
+ } catch (e) {
2449
+ process.stderr.write(`devtools-test: ${e instanceof Error ? e.message : String(e)}\n`);
2450
+ process.exitCode = 1;
2451
+ return;
2452
+ }
2453
+ if (parsed.values.help || argv.length === 0) {
2454
+ process.stdout.write(USAGE);
2455
+ return;
2456
+ }
2457
+ const vals = parsed.values;
2458
+ const rawTimeout = typeof vals.timeout === "string" ? vals.timeout : void 0;
2459
+ const timeoutMs = rawTimeout !== void 0 ? parseInt(rawTimeout, 10) : 3e4;
2460
+ if (Number.isNaN(timeoutMs) || timeoutMs <= 0) {
2461
+ process.stderr.write(`devtools-test: --timeout must be a positive integer\n`);
2462
+ process.exitCode = 1;
2463
+ return;
2464
+ }
2465
+ const schemeUrl = typeof vals["scheme-url"] === "string" ? vals["scheme-url"] : "";
2466
+ if (schemeUrl === "") {
2467
+ process.stderr.write("devtools-test: --scheme-url is required for standalone relay attach.\n Pass the intoss-private:// URL from `ait deploy --scheme-only`.\n");
2468
+ process.exitCode = 1;
2469
+ return;
2470
+ }
2471
+ const headless = vals.headless === true;
2472
+ const projectRoot = typeof vals["project-root"] === "string" ? vals["project-root"] : process.cwd();
2473
+ const cellSdkLine = typeof vals["cell-sdk-line"] === "string" ? vals["cell-sdk-line"] : void 0;
2474
+ const cellPlatform = typeof vals["cell-platform"] === "string" ? vals["cell-platform"] : process.env.AIT_CELL_PLATFORM;
2475
+ const hasCell = cellSdkLine !== void 0 || cellPlatform !== void 0;
2476
+ const globs = parsed.positionals;
2477
+ if (globs.length === 0) {
2478
+ process.stderr.write(`devtools-test: at least one glob pattern is required\n`);
2479
+ process.stdout.write(USAGE);
2480
+ process.exitCode = 1;
2481
+ return;
2482
+ }
2483
+ const files = await discoverTestFiles(globs, process.cwd());
2484
+ if (files.length === 0) {
2485
+ process.stderr.write(`devtools-test: no test files matched ${globs.join(", ")}\n`);
2486
+ process.exitCode = 1;
2487
+ return;
2488
+ }
2489
+ process.stderr.write(`devtools-test: found ${files.length} test file(s)\n`);
2490
+ const { loadRelaySecretReadOnly } = await import("./relay-secret-store-CmqchhR5.js");
2491
+ await loadRelaySecretReadOnly({ projectRoot });
2492
+ const { bootRelayFamily, buildRelayVerifyAuth } = await import("./debug-server-BvrESnaV.js");
2493
+ let family;
2494
+ try {
2495
+ family = await bootRelayFamily({ verifyAuth: buildRelayVerifyAuth() });
2496
+ } catch (e) {
2497
+ process.stderr.write(`devtools-test: failed to boot relay: ${e instanceof Error ? e.message : String(e)}\n`);
2498
+ process.exitCode = 1;
2499
+ return;
2500
+ }
2501
+ let exitCode = 0;
2502
+ try {
2503
+ const attachDeps = {
2504
+ getTunnelStatus: family.getTunnelStatus ?? (() => ({
2505
+ up: false,
2506
+ wssUrl: null
2507
+ })),
2508
+ getTotpSecret: () => process.env.AIT_DEBUG_TOTP_SECRET,
2509
+ qrHttpServer: void 0,
2510
+ onAttachUrlBuilt: void 0,
2511
+ canOpenBrowser: () => !headless
2512
+ };
2513
+ const prep = await prepareAttach(attachDeps, "relay-dev", { scheme_url: schemeUrl }, family.connection);
2514
+ if (!prep.ok) {
2515
+ const errText = prep.error.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
2516
+ process.stderr.write(`devtools-test: attach preparation failed:\n${errText}\n`);
2517
+ exitCode = 1;
2518
+ return;
2519
+ }
2520
+ const waitResult = await renderAndMaybeWait(attachDeps, prep, true, timeoutMs, family.connection);
2521
+ if (waitResult.isError) {
2522
+ const errText = waitResult.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
2523
+ process.stderr.write(`devtools-test: attach timed out or failed:\n${errText}\n`);
2524
+ exitCode = 1;
2525
+ return;
2526
+ }
2527
+ for (const chunk of waitResult.content) if (chunk.type === "text") process.stdout.write(`${chunk.text}\n`);
2528
+ await injectDebugIndicator(family.connection);
2529
+ if (hasCell) {
2530
+ const cell = {};
2531
+ if (cellSdkLine !== void 0) cell.sdkLine = cellSdkLine;
2532
+ if (cellPlatform !== void 0) cell.platform = cellPlatform;
2533
+ process.stderr.write(`devtools-test: injecting __AIT_CELL__ = ${JSON.stringify(cell)}\n`);
2534
+ await injectGlobals(family.connection, { __AIT_CELL__: cell });
2535
+ }
2536
+ exitCode = (await runWithConnection(family.connection, files, {
2537
+ timeoutMs,
2538
+ printSummary: true
2539
+ })).totals.failed > 0 ? 1 : 0;
2540
+ } finally {
2541
+ family.stop();
2542
+ process.exitCode = exitCode;
2543
+ }
2544
+ }
2545
+ if (import.meta.url === new URL(process.argv[1], "file://").href) main().catch((e) => {
2546
+ process.stderr.write(`devtools-test: unexpected error: ${e instanceof Error ? e.message : String(e)}\n`);
2547
+ process.exitCode = 1;
2548
+ });
2549
+ //#endregion
2550
+ export { START_ATTACH_SEGMENT_MS as a, generateAttachToken as c, startQuickTunnel as d, startTunnelHealthProbe as f, START_ATTACH_REMINT_THRESHOLD_MS as i, makeTunnelStatus as l, logInfo as m, runWithConnection as n, extractDeploymentId as o, logError as p, RELAY_SANDBOX_STALE_PAGE_MS as r, isSandboxPageFresh as s, main as t, printAttachBanner as u };
2551
+
2552
+ //# sourceMappingURL=cli-CvUNQKqw.js.map