@ait-co/devtools 0.1.40 → 0.1.43

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.
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":[],"sources":["../../src/mcp/ait-http-source.ts","../../src/mcp/tools.ts","../../src/mcp/server.ts"],"sourcesContent":["/**\n * Dev-mode `AitSource` — backed by the Vite dev server's mock-state endpoint.\n *\n * The dev server already exposes the live browser mock state at\n * `GET /api/ait-devtools/state` (registered by the unplugin with `mcp: true`).\n * Phase 3 aligns dev mode and debug mode on the same `AIT.*` tool surface, so\n * dev mode serves those tools off this one HTTP source instead of a CDP channel:\n *\n * - `AIT.getMockState` → the full state snapshot (verbatim).\n * - `AIT.getOperationalEnvironment` → derived from the snapshot's\n * `environment` + `appVersion` fields.\n * - `AIT.getSdkCallHistory` → empty (the dev endpoint does not record\n * an SDK call trace — honest, not faked).\n *\n * An AI agent thus sees the same `AIT.getMockState` tool whether attached to a\n * phone (debug) or a dev browser (dev). Tests inject a fake `fetch`.\n */\n\nimport type {\n AitMethodMap,\n AitMethodName,\n AitMockState,\n AitOperationalEnvironment,\n AitSdkCallHistory,\n AitSource,\n} from './ait-source.js';\n\n/** Minimal `fetch` shape this source needs (injectable in tests). */\nexport type FetchLike = (url: string) => Promise<{\n ok: boolean;\n status: number;\n statusText: string;\n json(): Promise<unknown>;\n}>;\n\nexport interface HttpAitSourceOptions {\n /** Full URL of the mock-state endpoint, e.g. `http://localhost:5173/api/ait-devtools/state`. */\n stateEndpoint: string;\n /** Injected for tests; defaults to global `fetch`. */\n fetchImpl?: FetchLike;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nexport class HttpAitSource implements AitSource {\n private readonly stateEndpoint: string;\n private readonly fetchImpl: FetchLike;\n\n constructor(options: HttpAitSourceOptions) {\n this.stateEndpoint = options.stateEndpoint;\n this.fetchImpl = options.fetchImpl ?? ((url) => fetch(url));\n }\n\n private async fetchState(): Promise<AitMockState> {\n const res = await this.fetchImpl(this.stateEndpoint);\n if (!res.ok) {\n throw new Error(\n `Failed to fetch mock state from ${this.stateEndpoint}: HTTP ${res.status} ${res.statusText}. ` +\n 'Ensure the Vite dev server is running with the @ait-co/devtools unplugin option `mcp: true`.',\n );\n }\n const body = await res.json();\n return isObject(body) ? body : {};\n }\n\n async get<M extends AitMethodName>(method: M): Promise<AitMethodMap[M]> {\n switch (method) {\n case 'AIT.getMockState': {\n const state = await this.fetchState();\n return state as AitMethodMap[M];\n }\n case 'AIT.getOperationalEnvironment': {\n const state = await this.fetchState();\n const environment = typeof state.environment === 'string' ? state.environment : 'unknown';\n const sdkVersion = typeof state.appVersion === 'string' ? state.appVersion : null;\n const result: AitOperationalEnvironment = { environment, sdkVersion };\n return result as AitMethodMap[M];\n }\n case 'AIT.getSdkCallHistory': {\n // sdkCallLog slice is now part of the mock state pushed by the browser panel.\n // Read it from the state snapshot rather than returning an empty stub.\n const state = await this.fetchState();\n const raw = state.sdkCallLog;\n const calls = Array.isArray(raw) ? (raw as AitSdkCallHistory['calls']) : [];\n const result: AitSdkCallHistory = { calls };\n return result as AitMethodMap[M];\n }\n default:\n throw new Error(`Unknown AIT method: ${String(method)}`);\n }\n }\n}\n","/**\n * Debug-mode MCP tools (Phase 1–3 + safe-area probe).\n *\n * Read-only tools that normalize CDP / AIT data into `chrome-devtools-mcp`-\n * compatible shapes. The tools never touch a websocket or HTTP endpoint\n * directly — they read from an injected `CdpConnection` (CDP events/commands)\n * or `AitSource` (AIT.* domain), which is what makes them unit-testable with a\n * fake. No phone and no running dev server are needed in tests.\n *\n * Phase 1 (CDP events):\n * - `list_console_messages` ← Runtime.consoleAPICalled\n * - `list_network_requests` ← Network.requestWillBeSent + responseReceived\n * - `list_pages` ← Chii relay target list + tunnel status\n * Phase 2 (CDP commands):\n * - `get_dom_document` ← DOM.getDocument\n * - `take_snapshot` ← DOMSnapshot.captureSnapshot\n * - `take_screenshot` ← Page.captureScreenshot\n * - `measure_safe_area` ← Runtime.evaluate (safe-area probe)\n * Phase 3 (AIT.* domain — CDP can't cover these):\n * - `AIT.getSdkCallHistory`\n * - `AIT.getMockState`\n * - `AIT.getOperationalEnvironment`\n */\n\nimport type {\n AitMockState,\n AitOperationalEnvironment,\n AitSdkCallHistory,\n AitSource,\n} from './ait-source.js';\nimport type {\n CdpConnection,\n CdpRemoteObject,\n ConsoleApiCalledEvent,\n DomGetDocumentResult,\n DomSnapshotResult,\n NetworkRequestWillBeSentEvent,\n NetworkResponseReceivedEvent,\n} from './cdp-connection.js';\nimport { buildDeepLinkAttachUrl, validateSchemeAuthority } from './deeplink.js';\n\n/** Tunnel state surfaced by `list_pages`. */\nexport interface TunnelStatus {\n /** Whether the cloudflared quick tunnel is up. */\n up: boolean;\n /** Public `wss://*.trycloudflare.com` relay URL the phone attaches to. */\n wssUrl: string | null;\n}\n\n/** Static MCP tool descriptors (name + JSONSchema) for the full debug tool surface. */\nexport const DEBUG_TOOL_DEFINITIONS = [\n {\n name: 'list_console_messages',\n description:\n 'Lists recent console messages (console.log/warn/error/info) captured from the attached ' +\n 'mini-app page over CDP (Runtime.consoleAPICalled). Read-only. Returns level, text, ' +\n 'timestamp, and stringified args, oldest-first.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'list_network_requests',\n description:\n 'Lists recent network requests (XHR/fetch) captured from the attached mini-app page over ' +\n 'CDP (Network.requestWillBeSent + Network.responseReceived). Read-only. Returns url, ' +\n 'method, status, and timing, oldest-first.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'list_pages',\n description:\n 'Lists the mini-app page(s) the Chii relay currently sees attached, plus whether the ' +\n 'cloudflared tunnel is up and the public wss relay URL the phone uses to attach. ' +\n 'Call this first to confirm a page is attached before reading console/network.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'build_attach_url',\n description:\n \"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. \" +\n 'Turns an `ait deploy --scheme-only` URL (intoss-private://…?_deploymentId=<uuid>) into a ' +\n 'self-attaching deep link by splicing in debug=1 and the live relay URL for this session. ' +\n 'Returns the deep link JSON and a unicode QR of that deep link. Scan the QR with the phone ' +\n 'camera to open the mini-app and attach it to this debug session (QR is the single entry ' +\n 'path — no USB cable or platform CLI needed). Requires the tunnel to be up — call ' +\n 'list_pages first. Set wait_for_attach=true to block until the phone scans and a page ' +\n 'attaches (polls listTargets up to 90 s), then returns the attached page info too. ' +\n 'When open_in_browser=true (default), saves the QR as a PNG and opens it in the OS default ' +\n 'browser — only works when the MCP server runs on a local GUI machine (not headless/remote containers).',\n inputSchema: {\n type: 'object',\n properties: {\n scheme_url: {\n type: 'string',\n description:\n 'The intoss-private:// scheme URL from `ait deploy --scheme-only` (must carry _deploymentId). ' +\n 'The authority (host) must be the app name (e.g. intoss-private://aitc-sdk-example?_deploymentId=…). ' +\n 'Generic values like \"web\" or an empty host indicate a malformed URL.',\n },\n wait_for_attach: {\n type: 'boolean',\n description:\n 'If true, block after returning the QR until a page attaches to the relay (polls ' +\n 'listTargets ~1 s interval, timeout 90 s). On attach, the response includes the ' +\n 'attached page list. On timeout, returns an error with a list_pages retry hint.',\n },\n open_in_browser: {\n type: 'boolean',\n description:\n 'If true (default), render the QR as a PNG and open it in the OS default browser. ' +\n 'Only works when the MCP server is running on a local GUI machine — headless or ' +\n 'remote container environments should set this to false to use the text QR fallback.',\n },\n },\n required: ['scheme_url'],\n },\n },\n {\n name: 'get_dom_document',\n description:\n 'Returns the DOM tree of the attached mini-app page over CDP (DOM.getDocument). Read-only. ' +\n 'Use for structural/layout regression diagnosis (e.g. confirming an element exists, ' +\n 'inspecting attributes). Returns the document root node with children.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'take_snapshot',\n description:\n 'Captures a serialized snapshot of the attached page over CDP (DOMSnapshot.captureSnapshot). ' +\n 'Read-only. Returns the documents + interned strings table for visual-regression diagnosis ' +\n '(e.g. checking computed CSS custom properties like --sat against the live layout).',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'take_screenshot',\n description:\n 'Captures a PNG screenshot of the attached mini-app page over CDP (Page.captureScreenshot) ' +\n 'so the agent can see the phone screen directly. Read-only. Returns an image content block.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'measure_safe_area',\n description:\n 'Runs a safe-area probe on the attached mini-app page via Runtime.evaluate and returns ' +\n 'normalized safe-area insets, viewport geometry, device pixel ratio, and User-Agent. ' +\n 'Read-only — does not modify page state. ' +\n 'Use in a relay session (phone attached) to get ground-truth values for upgrading a ' +\n 'viewport preset from extrapolated/placeholder to measured. ' +\n 'Requires the relay to be attached — call list_pages first.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'evaluate',\n description:\n 'Evaluates an arbitrary JavaScript expression on the attached mini-app page via ' +\n 'CDP Runtime.evaluate (returnByValue: true) and returns the result. ' +\n 'NOT read-only — the expression can have side effects (DOM mutations, SDK calls, ' +\n 'state changes). Requires the relay to be attached — call list_pages first. ' +\n 'Throws if the evaluation throws an exception on the page.',\n inputSchema: {\n type: 'object',\n properties: {\n expression: {\n type: 'string',\n description: 'JavaScript expression to evaluate in the page context.',\n },\n },\n required: ['expression'],\n },\n },\n {\n name: 'call_sdk',\n description:\n 'Calls a dogfood SDK method via the window.__sdkCall bridge ' +\n '(exported by @apps-in-toss/web-framework only in __DEBUG_BUILD__ bundles). ' +\n 'NOT read-only — SDK calls have side effects (navigation, payments, permissions, etc.). ' +\n 'On env 2/3 (real device relay) this hits the real SDK; on env 1 (local mock) it hits ' +\n 'the mock SDK. Requires the relay to be attached — call list_pages first. ' +\n 'Returns {ok: true, value} on success or {ok: false, error} on failure. ' +\n 'Returns a clear error if window.__sdkCall is not available (non-dogfood bundle).',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'SDK method name to call (e.g. \"getOperationalEnvironment\").',\n },\n args: {\n type: 'array',\n description: 'Arguments to pass to the SDK method (optional, default []).',\n items: {},\n },\n },\n required: ['name'],\n },\n },\n {\n name: 'AIT.getSdkCallHistory',\n description:\n 'Returns the recent Apps In Toss SDK call trace (method, args, result/error, timestamp) that ' +\n 'raw CDP cannot observe. Read-only. Use to confirm an SDK call fired and how it resolved ' +\n '(e.g. a saveBase64Data permission regression).',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'AIT.getMockState',\n description:\n 'Returns the devtools mock state snapshot (window.__ait) — environment, permissions, location, ' +\n 'auth, network, IAP, and more. Read-only. In dev mode this is the live browser mock state; in ' +\n 'debug mode the in-app side reports it over the AIT domain.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'AIT.getOperationalEnvironment',\n description:\n 'Returns getOperationalEnvironment() plus the resolved SDK version — metadata raw CDP cannot ' +\n 'observe. Read-only.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n] as const;\n\nexport type DebugToolName = (typeof DEBUG_TOOL_DEFINITIONS)[number]['name'];\n\nconst DEBUG_TOOL_NAMES = new Set<string>(DEBUG_TOOL_DEFINITIONS.map((t) => t.name));\n\nexport function isDebugToolName(name: string): name is DebugToolName {\n return DEBUG_TOOL_NAMES.has(name);\n}\n\n/**\n * Tool names that are available before any page attaches (bootstrap tier).\n *\n * `build_attach_url` — pure URL synthesis, no attach needed.\n * `list_pages` — reports tunnel status + empty pages even pre-attach.\n *\n * All other tools require an attached page (`enableDomains` must succeed) and\n * are only advertised in `tools/list` once a target appears.\n */\nexport const BOOTSTRAP_TOOL_NAMES: ReadonlySet<string> = new Set<string>([\n 'build_attach_url',\n 'list_pages',\n]);\n\n/** Normalized console message returned by `list_console_messages`. */\nexport interface ConsoleMessage {\n level: string;\n text: string;\n timestamp: number;\n args: string[];\n}\n\n/** Normalized network request returned by `list_network_requests`. */\nexport interface NetworkRequest {\n requestId: string;\n url: string;\n method: string;\n /** HTTP status once a response was seen, else null (still in-flight). */\n status: number | null;\n statusText: string | null;\n /** Request start (CDP timestamp). */\n startTime: number;\n /** Response received (CDP timestamp), else null. */\n endTime: number | null;\n}\n\n/** Renders a CDP `RemoteObject` console arg to a stable display string. */\nfunction renderRemoteObject(arg: CdpRemoteObject): string {\n if (arg.value !== undefined) {\n if (typeof arg.value === 'string') return arg.value;\n try {\n return JSON.stringify(arg.value);\n } catch {\n return String(arg.value);\n }\n }\n if (arg.description !== undefined) return arg.description;\n if (arg.className !== undefined) return arg.className;\n return arg.subtype ?? arg.type;\n}\n\nexport function normalizeConsoleMessage(event: ConsoleApiCalledEvent): ConsoleMessage {\n const args = event.args.map(renderRemoteObject);\n return {\n level: event.type,\n text: args.join(' '),\n timestamp: event.timestamp,\n args,\n };\n}\n\nexport function listConsoleMessages(connection: CdpConnection): ConsoleMessage[] {\n return connection\n .getBufferedEvents('Runtime.consoleAPICalled')\n .map((event) => normalizeConsoleMessage(event));\n}\n\nexport function listNetworkRequests(connection: CdpConnection): NetworkRequest[] {\n const requests = connection.getBufferedEvents('Network.requestWillBeSent');\n const responses = connection.getBufferedEvents('Network.responseReceived');\n\n const responseByRequestId = new Map<string, NetworkResponseReceivedEvent>();\n for (const response of responses) {\n responseByRequestId.set(response.requestId, response);\n }\n\n return requests.map((request: NetworkRequestWillBeSentEvent) => {\n const response = responseByRequestId.get(request.requestId);\n return {\n requestId: request.requestId,\n url: request.request.url,\n method: request.request.method,\n status: response ? response.response.status : null,\n statusText: response ? response.response.statusText : null,\n startTime: request.timestamp,\n endTime: response ? response.timestamp : null,\n };\n });\n}\n\n/** Result of `list_pages`: attach status + tunnel state. */\nexport interface ListPagesResult {\n pages: ReturnType<CdpConnection['listTargets']>;\n tunnel: TunnelStatus;\n}\n\nexport function listPages(connection: CdpConnection, tunnel: TunnelStatus): ListPagesResult {\n return { pages: connection.listTargets(), tunnel };\n}\n\n/** A `build_attach_url` result: the spliced deep link the phone should open. */\nexport interface BuildAttachUrlResult {\n /** The scheme URL with `debug=1&relay=<wss>` spliced in. */\n attachUrl: string;\n /** The relay URL that was spliced in (this session's quick tunnel). */\n relayUrl: string;\n /**\n * Non-fatal warning about the scheme URL's authority being missing or\n * suspicious (e.g. \"web\", \"localhost\"). Callers should surface this to\n * help the user catch a malformed URL early.\n */\n authorityWarning?: string;\n}\n\n/**\n * Builds a self-attaching dogfood deep link from an `ait deploy --scheme-only`\n * URL plus this session's live relay. Throws if the tunnel is not up yet (no\n * relay URL to splice in) — the caller surfaces that as a tool error.\n *\n * Also validates the scheme URL's authority. A suspicious authority (empty,\n * \"web\", \"localhost\", etc.) is surfaced as a non-fatal `authorityWarning` on\n * the result so the caller can show a helpful hint without blocking the link\n * generation (the warning is consistent with how other validation in\n * `buildDeepLinkAttachUrl` works — hard errors for relay, soft warning for\n * the scheme authority which is in the caller's input, not ours to own).\n */\nexport function buildAttachUrl(schemeUrl: string, tunnel: TunnelStatus): BuildAttachUrlResult {\n if (!tunnel.up || tunnel.wssUrl === null) {\n throw new Error(\n 'No relay URL yet — the cloudflared quick tunnel is not up. ' +\n 'Call list_pages to check tunnel status.',\n );\n }\n const authorityWarning = validateSchemeAuthority(schemeUrl) ?? undefined;\n return {\n attachUrl: buildDeepLinkAttachUrl(schemeUrl, tunnel.wssUrl),\n relayUrl: tunnel.wssUrl,\n ...(authorityWarning !== undefined ? { authorityWarning } : {}),\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* QR PNG rendering + browser open */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Heuristic: can this process open a GUI browser?\n *\n * Returns `true` when we think a GUI is available:\n * - On macOS (`darwin`) we assume yes (MCP normally runs on the user's Mac).\n * - On Linux we check for `DISPLAY` or `WAYLAND_DISPLAY`.\n * - On Windows we assume yes.\n * - In a CI environment (`CI=true`) we assume no.\n */\nexport function canOpenBrowser(): boolean {\n if (process.env.CI === 'true' || process.env.CI === '1') return false;\n const platform = process.platform;\n if (platform === 'darwin' || platform === 'win32') return true;\n if (platform === 'linux') {\n return Boolean(process.env.DISPLAY ?? process.env.WAYLAND_DISPLAY);\n }\n return false;\n}\n\n/**\n * Result of `openQrInBrowser`.\n *\n * HTTP URL 기반으로 재구현 — tmp 파일 없음. `httpUrl`이 브라우저에 전달되는 URL이다.\n * SECRET-HANDLING: `httpUrl`은 127.0.0.1 로컬 전용이며 at= 코드 값을 직접 담지 않는다\n * (attachUrl은 /attach?u= query로 전달되어 서버 메모리에서만 처리).\n */\nexport interface OpenQrInBrowserResult {\n /** `true` if the browser was successfully opened. */\n opened: boolean;\n /** `http://127.0.0.1:<port>/attach?u=...` — 브라우저에 전달된 URL. */\n httpUrl: string;\n /** `http://127.0.0.1:<port>/qr.png?u=...` — PNG fallback URL. */\n pngUrl: string;\n /** Error message if `opened` is false (browser spawn failed). */\n error?: string;\n /** Captured stderr from failed spawn attempts (at= 값은 redact됨). */\n stderrSummary?: string;\n}\n\n/** platform별 browser open 명령 후보 목록 — 앞에서부터 순차 시도. */\nfunction getBrowserCandidates(httpUrl: string): Array<{ cmd: string; args: string[] }> {\n const platform = process.platform;\n if (platform === 'darwin') {\n return [\n { cmd: 'open', args: [httpUrl] },\n { cmd: 'open', args: ['-a', 'Safari', httpUrl] },\n { cmd: 'open', args: ['-a', 'Google Chrome', httpUrl] },\n { cmd: 'open', args: ['-a', 'Firefox', httpUrl] },\n ];\n }\n if (platform === 'win32') {\n return [\n { cmd: 'cmd', args: ['/c', 'start', '', httpUrl] },\n { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler', httpUrl] },\n ];\n }\n // linux + fallback\n return [\n { cmd: 'xdg-open', args: [httpUrl] },\n { cmd: 'sensible-browser', args: [httpUrl] },\n { cmd: 'x-www-browser', args: [httpUrl] },\n { cmd: 'firefox', args: [httpUrl] },\n { cmd: 'google-chrome', args: [httpUrl] },\n { cmd: 'chromium', args: [httpUrl] },\n ];\n}\n\n/** stderr에서 at= TOTP 코드 값을 redact한다. */\nfunction redactSecrets(text: string): string {\n // at=<value> 패턴에서 값 부분을 redact — TOTP 코드가 노출되지 않도록.\n return text.replace(/\\bat=([^&\\s\"']+)/g, 'at=<redacted>');\n}\n\n/** spawnSync exit 0이어도 stderr에 launch 실패 시그널이 있으면 실패로 판단한다. */\nconst LAUNCH_FAILURE_PATTERNS = [\n /LSOpenURLsWithRole\\(\\) failed/,\n /kLSApplicationNotFoundErr/,\n /No application/,\n /Unable to find application/,\n /xdg-open: not found/,\n /command not found/,\n];\n\nfunction isLaunchFailureStderr(stderr: string): boolean {\n return LAUNCH_FAILURE_PATTERNS.some((p) => p.test(stderr));\n}\n\n/**\n * 로컬 HTTP 서버 URL(`http://127.0.0.1:<port>/attach?u=...`)을 OS 기본 브라우저로 연다.\n *\n * platform별 fallback chain으로 시도하며, 모두 실패해도 `opened: false` + `httpUrl`을\n * 반환해 사용자가 직접 브라우저에 붙여넣을 수 있게 한다.\n *\n * SECRET-HANDLING:\n * - tmp 파일을 만들지 않는다 (HTML/PNG는 HTTP 서버가 메모리에서 응답).\n * - httpUrl/pngUrl은 127.0.0.1 로컬 전용.\n * - stderr 캡처 결과에서 at= 코드 값을 redact한 후 stderrSummary에 포함.\n * - attachUrl, deploymentId, TOTP 코드를 stdout/stderr/로그에 직접 출력 금지.\n *\n * @param httpUrl - `http://127.0.0.1:<port>/attach?u=<encoded>` HTTP URL.\n * @param pngUrl - `http://127.0.0.1:<port>/qr.png?u=<encoded>` PNG fallback URL.\n */\nexport async function openQrInBrowser(\n httpUrl: string,\n pngUrl: string,\n): Promise<OpenQrInBrowserResult> {\n const { spawnSync } = await import('node:child_process');\n\n const candidates = getBrowserCandidates(httpUrl);\n const stderrLines: string[] = [];\n\n for (const { cmd, args } of candidates) {\n const result = spawnSync(cmd, args, { encoding: 'utf8', timeout: 5000 });\n\n if (result.error) {\n // 명령 자체를 실행하지 못한 경우 (ENOENT 등) — 다음 후보로.\n stderrLines.push(`${cmd}: ${result.error.message}`);\n continue;\n }\n\n const stderr = typeof result.stderr === 'string' ? result.stderr : '';\n if (stderr) {\n stderrLines.push(`${cmd}: ${redactSecrets(stderr.trim())}`);\n }\n\n // exit 0이어도 stderr에 launch 실패 패턴이 있으면 실패로 취급.\n if (result.status === 0 && !isLaunchFailureStderr(stderr)) {\n return { opened: true, httpUrl, pngUrl };\n }\n }\n\n const stderrSummary = stderrLines.length > 0 ? stderrLines.join('\\n') : undefined;\n return {\n opened: false,\n httpUrl,\n pngUrl,\n error: '모든 브라우저 실행 후보가 실패했습니다.',\n stderrSummary,\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Phase 2 — DOM / snapshot / screenshot (CDP commands) */\n/* -------------------------------------------------------------------------- */\n\n/** Returns the DOM tree of the attached page (`DOM.getDocument`). */\nexport function getDomDocument(connection: CdpConnection): Promise<DomGetDocumentResult> {\n // `pierce: true` flattens shadow roots; depth -1 returns the whole subtree so\n // a single call yields the full tree for structural diagnosis.\n return connection.send('DOM.getDocument', { depth: -1, pierce: true });\n}\n\n/** Returns a serialized page snapshot (`DOMSnapshot.captureSnapshot`). */\nexport function takeSnapshot(connection: CdpConnection): Promise<DomSnapshotResult> {\n return connection.send('DOMSnapshot.captureSnapshot', {});\n}\n\n/** A `take_screenshot` result: the raw base64 PNG plus a ready-to-use data URI. */\nexport interface ScreenshotResult {\n /** Base64-encoded PNG bytes (no data-URI prefix). */\n data: string;\n /** `data:image/png;base64,…` form for clients that render a URI. */\n dataUri: string;\n mimeType: 'image/png';\n}\n\n/** Captures a PNG screenshot of the attached page (`Page.captureScreenshot`). */\nexport async function takeScreenshot(connection: CdpConnection): Promise<ScreenshotResult> {\n const { data } = await connection.send('Page.captureScreenshot', { format: 'png' });\n return { data, dataUri: `data:image/png;base64,${data}`, mimeType: 'image/png' };\n}\n\n/* -------------------------------------------------------------------------- */\n/* measure_safe_area — Runtime.evaluate probe */\n/* -------------------------------------------------------------------------- */\n\n/**\n * The JS probe injected via `Runtime.evaluate`. It reads:\n * 1. `env(safe-area-inset-*)` via a temporary element with padding set to\n * those CSS env vars, then `getComputedStyle`.\n * 2. `window.__sdk.SafeAreaInsets.get()` (1st priority) or\n * `window.__sdk.getSafeAreaInsets()` (2nd priority) — both surfaces\n * confirmed live on iPhone 15 Pro relay. `window.__sdk` is only present\n * in dogfood (__DEBUG_BUILD__) bundles; outside those it is undefined.\n * If both paths fail the result carries `sdkInsetsError` explaining why.\n * 3. nav bar geometry: the SDK does not expose navBar height as a standalone\n * API — `.ait-navbar` DOM height is read as a cross-check, and\n * `navBarHeightSource` records where it came from.\n * 4. `innerWidth`, `innerHeight`, `devicePixelRatio`, `navigator.userAgent`.\n *\n * Returns a plain JSON-serialisable object so `returnByValue: true` works.\n *\n * NOTE: This expression is evaluated in the page context on the real device.\n * It does not mutate any page state — the temporary element is removed after\n * reading. No secret or auth token is read or returned.\n */\nexport const SAFE_AREA_PROBE_EXPRESSION = `\n(function() {\n var el = document.createElement('div');\n el.style.cssText = 'position:fixed;top:0;left:0;width:0;height:0;visibility:hidden;' +\n 'padding-top:env(safe-area-inset-top,0px);' +\n 'padding-right:env(safe-area-inset-right,0px);' +\n 'padding-bottom:env(safe-area-inset-bottom,0px);' +\n 'padding-left:env(safe-area-inset-left,0px)';\n document.documentElement.appendChild(el);\n var cs = window.getComputedStyle(el);\n var cssEnv = {\n top: parseFloat(cs.paddingTop) || 0,\n right: parseFloat(cs.paddingRight) || 0,\n bottom: parseFloat(cs.paddingBottom) || 0,\n left: parseFloat(cs.paddingLeft) || 0\n };\n document.documentElement.removeChild(el);\n var sdkInsets = null;\n var sdkInsetsError = undefined;\n try {\n var sdk = window.__sdk;\n if (sdk && sdk.SafeAreaInsets && typeof sdk.SafeAreaInsets.get === 'function') {\n sdkInsets = sdk.SafeAreaInsets.get();\n } else if (sdk && typeof sdk.getSafeAreaInsets === 'function') {\n sdkInsets = sdk.getSafeAreaInsets();\n } else if (!sdk) {\n sdkInsetsError = 'window.__sdk not available (non-dogfood bundle)';\n } else {\n sdkInsetsError = 'neither SafeAreaInsets.get nor getSafeAreaInsets found on window.__sdk';\n }\n } catch(e) {\n sdkInsetsError = String(e && e.message || e);\n }\n var navBarHeight = null;\n var navBarHeightSource = 'not-exposed-by-sdk';\n try {\n var nb = document.querySelector('.ait-navbar');\n if (nb) {\n navBarHeight = nb.getBoundingClientRect().height;\n navBarHeightSource = 'dom-.ait-navbar';\n }\n } catch(_) {}\n var result = {\n cssEnv: cssEnv,\n sdkInsets: sdkInsets,\n navBarHeight: navBarHeight,\n navBarHeightSource: navBarHeightSource,\n innerWidth: window.innerWidth,\n innerHeight: window.innerHeight,\n devicePixelRatio: window.devicePixelRatio,\n userAgent: navigator.userAgent\n };\n if (sdkInsetsError !== undefined) result.sdkInsetsError = sdkInsetsError;\n return JSON.stringify(result);\n})()\n`.trim();\n\n/**\n * Normalized result returned by `measure_safe_area`.\n *\n * All inset values are in CSS pixels as reported by the real device.\n * `userAgent` is included for device identification; it never contains\n * authentication secrets or session tokens.\n */\nexport interface SafeAreaMeasurement {\n /**\n * `env(safe-area-inset-*)` values read via `getComputedStyle` on the device.\n * On iOS inside the Toss host WebView this is typically all-zero because the\n * WebView viewport is placed below the physical notch by the host app.\n */\n cssEnv: { top: number; right: number; bottom: number; left: number };\n /**\n * `window.__sdk.SafeAreaInsets.get()` (1st priority) or\n * `window.__sdk.getSafeAreaInsets()` (2nd priority) result from the native\n * SDK. `null` when both paths fail — see `sdkInsetsError` for the reason.\n * In the Toss host WebView `top` is the nav bar height and `bottom` is the\n * home-indicator height.\n */\n sdkInsets: { top: number; right: number; bottom: number; left: number } | null;\n /**\n * Populated when the SDK inset lookup failed (both paths absent or threw).\n * `undefined` when `sdkInsets` is non-null (i.e. the lookup succeeded).\n *\n * Example values:\n * - `\"window.__sdk not available (non-dogfood bundle)\"`\n * - `\"neither SafeAreaInsets.get nor getSafeAreaInsets found on window.__sdk\"`\n * - `\"TypeError: ...\"`\n */\n sdkInsetsError?: string;\n /**\n * Height of the `.ait-navbar` element (px) if present, else `null`.\n * The SDK does not expose navBar height as a standalone API; this DOM\n * measurement is used to cross-validate `sdkInsets.top`.\n */\n navBarHeight: number | null;\n /**\n * Describes where `navBarHeight` came from:\n * - `\"dom-.ait-navbar\"` — read from the `.ait-navbar` element's bounding rect.\n * - `\"not-exposed-by-sdk\"` — the SDK has no standalone navBar height API and\n * no `.ait-navbar` element was found in the DOM.\n */\n navBarHeightSource: string;\n /** CSS viewport width (`window.innerWidth`). */\n innerWidth: number;\n /** CSS viewport height (`window.innerHeight`). */\n innerHeight: number;\n /**\n * Device pixel ratio (`window.devicePixelRatio`).\n * Note: `window.devicePixelRatio` is read-only in the browser, so devtools\n * cannot emulate DPR locally — this is the ground-truth value from the device.\n */\n devicePixelRatio: number;\n /**\n * `navigator.userAgent` string for device identification.\n * Does not contain authentication secrets.\n */\n userAgent: string;\n}\n\n/**\n * Parses a raw `Runtime.evaluate` result value into a `SafeAreaMeasurement`.\n * The probe returns a JSON string (because `returnByValue:true` with a plain\n * object works unreliably across Chii relay versions — stringifying is safer).\n *\n * Throws if the result is missing, contains an exception, or cannot be parsed.\n */\nexport function normalizeSafeAreaResult(rawValue: unknown): SafeAreaMeasurement {\n if (typeof rawValue !== 'string') {\n throw new Error(\n `measure_safe_area: probe returned unexpected type \"${typeof rawValue}\" — expected JSON string`,\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawValue);\n } catch {\n throw new Error(`measure_safe_area: probe returned non-JSON string: ${rawValue}`);\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('measure_safe_area: parsed result is not an object');\n }\n const obj = parsed as Record<string, unknown>;\n\n function requireInsets(\n key: string,\n ): { top: number; right: number; bottom: number; left: number } | null {\n const v = obj[key];\n if (v === null || v === undefined) return null;\n if (typeof v !== 'object') return null;\n const r = v as Record<string, unknown>;\n return {\n top: typeof r.top === 'number' ? r.top : 0,\n right: typeof r.right === 'number' ? r.right : 0,\n bottom: typeof r.bottom === 'number' ? r.bottom : 0,\n left: typeof r.left === 'number' ? r.left : 0,\n };\n }\n\n const cssEnv = requireInsets('cssEnv') ?? { top: 0, right: 0, bottom: 0, left: 0 };\n const sdkInsets = requireInsets('sdkInsets');\n const sdkInsetsError = typeof obj.sdkInsetsError === 'string' ? obj.sdkInsetsError : undefined;\n const navBarHeight = typeof obj.navBarHeight === 'number' ? obj.navBarHeight : null;\n const navBarHeightSource =\n typeof obj.navBarHeightSource === 'string' ? obj.navBarHeightSource : 'not-exposed-by-sdk';\n const innerWidth = typeof obj.innerWidth === 'number' ? obj.innerWidth : 0;\n const innerHeight = typeof obj.innerHeight === 'number' ? obj.innerHeight : 0;\n const devicePixelRatio = typeof obj.devicePixelRatio === 'number' ? obj.devicePixelRatio : 1;\n const userAgent = typeof obj.userAgent === 'string' ? obj.userAgent : '';\n\n return {\n cssEnv,\n sdkInsets,\n ...(sdkInsetsError !== undefined ? { sdkInsetsError } : {}),\n navBarHeight,\n navBarHeightSource,\n innerWidth,\n innerHeight,\n devicePixelRatio,\n userAgent,\n };\n}\n\n/**\n * Runs the safe-area probe on the attached page and returns a normalized\n * `SafeAreaMeasurement`. Read-only — does not mutate page state.\n *\n * Throws on CDP error, probe exception, or result parse failure.\n */\nexport async function measureSafeArea(connection: CdpConnection): Promise<SafeAreaMeasurement> {\n const result = await connection.send('Runtime.evaluate', {\n expression: SAFE_AREA_PROBE_EXPRESSION,\n returnByValue: true,\n awaitPromise: false,\n });\n if (result.exceptionDetails) {\n const msg =\n result.exceptionDetails.exception?.description ??\n result.exceptionDetails.text ??\n 'Runtime.evaluate threw an exception';\n throw new Error(`measure_safe_area: probe threw — ${msg}`);\n }\n return normalizeSafeAreaResult(result.result.value);\n}\n\n/* -------------------------------------------------------------------------- */\n/* evaluate — arbitrary JS via Runtime.evaluate */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Result returned by the `evaluate` tool.\n *\n * `value` holds the `returnByValue` result from CDP — it may be any\n * JSON-serialisable type. Treat it as opaque for logging purposes (it could\n * carry sensitive data from the page context).\n *\n * SECRET-HANDLING: do NOT write `value` to any log or stderr — return it to\n * the agent via the tool result only.\n */\nexport interface EvaluateResult {\n /** The evaluated result value (`returnByValue: true`). */\n value: unknown;\n /** CDP type string of the result (e.g. \"string\", \"number\", \"object\"). */\n type: string;\n}\n\n/**\n * Evaluates an arbitrary JS expression on the attached page via\n * `Runtime.evaluate`. NOT read-only — the expression may have side effects.\n *\n * Throws if the evaluation produced a CDP exception.\n *\n * SECRET-HANDLING: expression and result value are NOT written to any log.\n */\nexport async function evaluate(\n connection: CdpConnection,\n expression: string,\n): Promise<EvaluateResult> {\n const result = await connection.send('Runtime.evaluate', {\n expression,\n returnByValue: true,\n awaitPromise: false,\n });\n if (result.exceptionDetails) {\n // Surface only the engine error string — never the expression or result value.\n const msg =\n result.exceptionDetails.exception?.description ??\n result.exceptionDetails.text ??\n 'Runtime.evaluate threw an exception';\n throw new Error(`evaluate failed: ${msg}`);\n }\n return { value: result.result.value, type: result.result.type };\n}\n\n/* -------------------------------------------------------------------------- */\n/* call_sdk — window.__sdkCall bridge via Runtime.evaluate */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Result returned by the `call_sdk` tool.\n * The bridge call wraps success/failure in a JSON envelope so cross-Chii\n * stringification is reliable (same approach as `measure_safe_area`).\n */\nexport type CallSdkResult = { ok: true; value: unknown } | { ok: false; error: string };\n\n/**\n * Builds the Runtime.evaluate expression that calls `window.__sdkCall` with\n * the given method name and args, awaits the promise, and returns a JSON\n * envelope `{ok, value/error}` as a string.\n *\n * Name and args are embedded via `JSON.stringify` so they are safely escaped.\n * The expression checks for `window.__sdkCall` and returns a clear error if\n * it is absent (non-dogfood bundle).\n *\n * SECRET-HANDLING: the expression is built here and MUST NOT be written to\n * any log or stderr by the caller.\n */\nexport function buildCallSdkExpression(name: string, args: unknown[]): string {\n const safeName = JSON.stringify(name);\n const safeArgs = JSON.stringify(args);\n return (\n `(async () => {` +\n ` if (typeof window.__sdkCall !== 'function') {` +\n ` return JSON.stringify({ok:false,error:'window.__sdkCall is not available — is this a dogfood (__DEBUG_BUILD__) bundle?'});` +\n ` }` +\n ` try {` +\n ` const r = await window.__sdkCall(${safeName}, ...${safeArgs});` +\n ` return JSON.stringify({ok:true,value:r});` +\n ` } catch(e) {` +\n ` return JSON.stringify({ok:false,error:String(e && e.message || e)});` +\n ` }` +\n `})()`\n );\n}\n\n/**\n * Parses the JSON envelope string returned by the `call_sdk` expression.\n * Returns a typed `CallSdkResult`.\n *\n * Throws only on parse failure (not on ok:false — that is a normal result).\n */\nexport function normalizeCallSdkResult(rawValue: unknown): CallSdkResult {\n if (typeof rawValue !== 'string') {\n throw new Error(\n `call_sdk: bridge returned unexpected type \"${typeof rawValue}\" — expected JSON string`,\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawValue);\n } catch {\n // Do NOT include rawValue in the error message — it could contain secrets.\n throw new Error('call_sdk: bridge returned non-JSON string');\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('call_sdk: parsed result is not an object');\n }\n const obj = parsed as Record<string, unknown>;\n if (obj.ok === true) {\n return { ok: true, value: obj.value };\n }\n if (obj.ok === false) {\n return { ok: false, error: typeof obj.error === 'string' ? obj.error : String(obj.error) };\n }\n throw new Error('call_sdk: bridge result missing \"ok\" field');\n}\n\n/**\n * Calls a dogfood SDK method via `window.__sdkCall` on the attached page.\n * NOT read-only — SDK calls may have side effects.\n *\n * On env 2/3 (real device relay) this hits the real SDK; on env 1 (local\n * mock) it hits the mock SDK.\n *\n * Throws on CDP error or result parse failure. Returns `{ok:false, error}`\n * for bridge-level errors (method not found, SDK threw, bridge absent).\n *\n * SECRET-HANDLING: name, args, and the result value are NOT written to any log.\n */\nexport async function callSdk(\n connection: CdpConnection,\n name: string,\n args: unknown[],\n): Promise<CallSdkResult> {\n const expression = buildCallSdkExpression(name, args);\n const result = await connection.send('Runtime.evaluate', {\n expression,\n returnByValue: true,\n awaitPromise: true,\n });\n if (result.exceptionDetails) {\n // Surface only the engine error string — never name, args, or result value.\n const msg =\n result.exceptionDetails.exception?.description ??\n result.exceptionDetails.text ??\n 'Runtime.evaluate threw an exception';\n throw new Error(`call_sdk threw: ${msg}`);\n }\n return normalizeCallSdkResult(result.result.value);\n}\n\n/* -------------------------------------------------------------------------- */\n/* Phase 3 — AIT.* domain (CDP can't cover these) */\n/* -------------------------------------------------------------------------- */\n\n/** Set of tool names served by the AIT source rather than the CDP connection. */\nconst AIT_TOOL_NAMES = new Set<string>([\n 'AIT.getSdkCallHistory',\n 'AIT.getMockState',\n 'AIT.getOperationalEnvironment',\n]);\n\n/** True for the Phase 3 AIT.* tools (served by an `AitSource`, not CDP). */\nexport function isAitToolName(name: string): boolean {\n return AIT_TOOL_NAMES.has(name);\n}\n\n/** Returns the recent SDK call trace (`AIT.getSdkCallHistory`). */\nexport function getSdkCallHistory(source: AitSource): Promise<AitSdkCallHistory> {\n return source.get('AIT.getSdkCallHistory');\n}\n\n/** Returns the devtools mock-state snapshot (`AIT.getMockState`). */\nexport function getMockState(source: AitSource): Promise<AitMockState> {\n return source.get('AIT.getMockState');\n}\n\n/** Returns the operational environment + SDK version (`AIT.getOperationalEnvironment`). */\nexport function getOperationalEnvironment(source: AitSource): Promise<AitOperationalEnvironment> {\n return source.get('AIT.getOperationalEnvironment');\n}\n","/**\n * @ait-co/devtools dev-mode MCP server (stdio).\n *\n * Exposes the live browser mock state from a running Vite dev server to AI\n * coding agents via the Model Context Protocol (MCP).\n *\n * Architecture:\n * Browser (aitState) → Vite dev server endpoint (/api/ait-devtools/state)\n * ← HTTP GET ← this stdio MCP server ← AI agent\n *\n * The Vite endpoint is registered by the unplugin when `mcp: true` is set in\n * the plugin options (see `src/unplugin/index.ts`).\n *\n * Phase 3 tool-surface alignment: dev mode and debug mode now expose the same\n * `AIT.*` tools (`AIT.getMockState`, `AIT.getOperationalEnvironment`,\n * `AIT.getSdkCallHistory`). In dev mode they are backed by the HTTP mock-state\n * endpoint (see `HttpAitSource`); in debug mode by the Chii channel. So an AI\n * sees a coherent tool whether attached to a phone (debug) or a dev browser\n * (dev). `devtools_get_mock_state` (the original devtools#130 name) is kept as a\n * backward-compatible alias of `AIT.getMockState`.\n *\n * This module is reached via the `devtools-mcp --mode=dev` CLI entry (see\n * `cli.ts`); the default (no flag) bin mode is the debug-mode CDP/Chii server.\n *\n * Usage (in your MCP client config, e.g. Claude Desktop):\n * {\n * \"mcpServers\": {\n * \"ait-devtools\": {\n * \"command\": \"pnpm\",\n * \"args\": [\"exec\", \"devtools-mcp\", \"--mode=dev\"],\n * \"env\": { \"AIT_DEVTOOLS_URL\": \"http://localhost:5173\" }\n * }\n * }\n * }\n */\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport { HttpAitSource } from './ait-http-source.js';\nimport type { AitSource } from './ait-source.js';\nimport {\n getMockState,\n getOperationalEnvironment,\n getSdkCallHistory,\n isAitToolName,\n} from './tools.js';\n\n/** Tool descriptors served by the dev-mode server. */\nconst DEV_TOOL_DEFINITIONS = [\n {\n name: 'AIT.getMockState',\n description:\n 'Returns the devtools mock state snapshot (window.__ait) from the running browser session — ' +\n 'environment, permissions, location, auth, network, IAP, and more. Read-only. ' +\n 'Requires the Vite dev server running with the @ait-co/devtools unplugin option `mcp: true`. ' +\n 'Same tool as in debug mode, where the in-app side reports it over the AIT domain.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'AIT.getOperationalEnvironment',\n description:\n 'Returns the operational environment + SDK/app version derived from the dev mock state. ' +\n 'Read-only.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'AIT.getSdkCallHistory',\n description:\n 'Returns the SDK call trace. In dev mode the HTTP mock-state endpoint records no trace, so ' +\n 'this returns an empty list; in debug mode it is populated over the AIT domain. Read-only.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n {\n name: 'devtools_get_mock_state',\n description:\n 'Backward-compatible alias of AIT.getMockState (the original devtools#130 name). Returns the ' +\n 'current AIT DevTools mock state snapshot. Read-only. Prefer AIT.getMockState in new configs.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n },\n] as const;\n\nconst DEV_TOOL_NAMES = new Set<string>(DEV_TOOL_DEFINITIONS.map((t) => t.name));\n\nexport interface CreateDevServerDeps {\n /** AIT source for the dev tools. Defaults to an HTTP source over the dev server. */\n aitSource?: AitSource;\n}\n\n/** Builds the dev-mode MCP server (does not connect a transport). */\nexport function createDevServer(deps: CreateDevServerDeps = {}): Server {\n const devtoolsUrl = process.env.AIT_DEVTOOLS_URL ?? 'http://localhost:5173';\n const stateEndpoint = `${devtoolsUrl}/api/ait-devtools/state`;\n const aitSource = deps.aitSource ?? new HttpAitSource({ stateEndpoint });\n\n const server = new Server(\n { name: 'ait-devtools', version: __VERSION__ },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: DEV_TOOL_DEFINITIONS.map((tool) => ({ ...tool })),\n }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const name = request.params.name;\n if (!DEV_TOOL_NAMES.has(name)) {\n return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n\n try {\n // `devtools_get_mock_state` is an alias of `AIT.getMockState`.\n const effective = name === 'devtools_get_mock_state' ? 'AIT.getMockState' : name;\n if (!isAitToolName(effective)) {\n return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n switch (effective) {\n case 'AIT.getMockState':\n return jsonResult(await getMockState(aitSource));\n case 'AIT.getOperationalEnvironment':\n return jsonResult(await getOperationalEnvironment(aitSource));\n case 'AIT.getSdkCallHistory':\n return jsonResult(await getSdkCallHistory(aitSource));\n default:\n return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return {\n content: [\n {\n type: 'text',\n text:\n `${message}\\n` +\n 'Is the Vite dev server running with the @ait-co/devtools unplugin option `mcp: true`? ' +\n 'Is AIT_DEVTOOLS_URL set correctly?',\n },\n ],\n isError: true,\n };\n }\n });\n\n return server;\n}\n\nfunction jsonResult(value: unknown) {\n return { content: [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }] };\n}\n\n/** Builds the dev-mode server and connects it over stdio. */\nexport async function runDevServer(): Promise<void> {\n const server = createDevServer();\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n"],"mappings":";;;;;AA0CA,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU;;AAGhD,IAAa,gBAAb,MAAgD;CAC9C;CACA;CAEA,YAAY,SAA+B;AACzC,OAAK,gBAAgB,QAAQ;AAC7B,OAAK,YAAY,QAAQ,eAAe,QAAQ,MAAM,IAAI;;CAG5D,MAAc,aAAoC;EAChD,MAAM,MAAM,MAAM,KAAK,UAAU,KAAK,cAAc;AACpD,MAAI,CAAC,IAAI,GACP,OAAM,IAAI,MACR,mCAAmC,KAAK,cAAc,SAAS,IAAI,OAAO,GAAG,IAAI,WAAW,kGAE7F;EAEH,MAAM,OAAO,MAAM,IAAI,MAAM;AAC7B,SAAO,SAAS,KAAK,GAAG,OAAO,EAAE;;CAGnC,MAAM,IAA6B,QAAqC;AACtE,UAAQ,QAAR;GACE,KAAK,mBAEH,QADc,MAAM,KAAK,YAAY;GAGvC,KAAK,iCAAiC;IACpC,MAAM,QAAQ,MAAM,KAAK,YAAY;AAIrC,WAD0C;KAAE,aAFxB,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc;KAEvB,YADtC,OAAO,MAAM,eAAe,WAAW,MAAM,aAAa;KACR;;GAGvE,KAAK,yBAAyB;IAI5B,MAAM,OADQ,MAAM,KAAK,YAAY,EACnB;AAGlB,WADkC,EAAE,OADtB,MAAM,QAAQ,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,UAAO;IACL,SAAS,CACP;KACE,MAAM;KACN,MACE,GANQ,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,CAM7C;KAGd,CACF;IACD,SAAS;IACV;;GAEH;AAEF,QAAO;;AAGT,SAAS,WAAW,OAAgB;AAClC,QAAO,EAAE,SAAS,CAAC;EAAE,MAAM;EAAiB,MAAM,KAAK,UAAU,OAAO,MAAM,EAAE;EAAE,CAAC,EAAE;;;AAIvF,eAAsB,eAA8B;CAClD,MAAM,SAAS,iBAAiB;CAChC,MAAM,YAAY,IAAI,sBAAsB;AAC5C,OAAM,OAAO,QAAQ,UAAU"}
1
+ {"version":3,"file":"server.js","names":["isObject"],"sources":["../../src/mcp/ait-http-source.ts","../../src/mcp/sdk-signatures.ts","../../src/mcp/tools.ts","../../src/mcp/server.ts"],"sourcesContent":["/**\n * Dev-mode `AitSource` — backed by the Vite dev server's mock-state endpoint.\n *\n * The dev server already exposes the live browser mock state at\n * `GET /api/ait-devtools/state` (registered by the unplugin with `mcp: true`).\n * Phase 3 aligns dev mode and debug mode on the same `AIT.*` tool surface, so\n * dev mode serves those tools off this one HTTP source instead of a CDP channel:\n *\n * - `AIT.getMockState` → the full state snapshot (verbatim).\n * - `AIT.getOperationalEnvironment` → derived from the snapshot's\n * `environment` + `appVersion` fields.\n * - `AIT.getSdkCallHistory` → empty (the dev endpoint does not record\n * an SDK call trace — honest, not faked).\n *\n * An AI agent thus sees the same `AIT.getMockState` tool whether attached to a\n * phone (debug) or a dev browser (dev). Tests inject a fake `fetch`.\n */\n\nimport type {\n AitMethodMap,\n AitMethodName,\n AitMockState,\n AitOperationalEnvironment,\n AitSdkCallHistory,\n AitSource,\n} from './ait-source.js';\n\n/** Minimal `fetch` shape this source needs (injectable in tests). */\nexport type FetchLike = (url: string) => Promise<{\n ok: boolean;\n status: number;\n statusText: string;\n json(): Promise<unknown>;\n}>;\n\nexport interface HttpAitSourceOptions {\n /** Full URL of the mock-state endpoint, e.g. `http://localhost:5173/api/ait-devtools/state`. */\n stateEndpoint: string;\n /** Injected for tests; defaults to global `fetch`. */\n fetchImpl?: FetchLike;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nexport class HttpAitSource implements AitSource {\n private readonly stateEndpoint: string;\n private readonly fetchImpl: FetchLike;\n\n constructor(options: HttpAitSourceOptions) {\n this.stateEndpoint = options.stateEndpoint;\n this.fetchImpl = options.fetchImpl ?? ((url) => fetch(url));\n }\n\n private async fetchState(): Promise<AitMockState> {\n const res = await this.fetchImpl(this.stateEndpoint);\n if (!res.ok) {\n throw new Error(\n `Failed to fetch mock state from ${this.stateEndpoint}: HTTP ${res.status} ${res.statusText}. ` +\n 'Ensure the Vite dev server is running with the @ait-co/devtools unplugin option `mcp: true`.',\n );\n }\n const body = await res.json();\n return isObject(body) ? body : {};\n }\n\n async get<M extends AitMethodName>(method: M): Promise<AitMethodMap[M]> {\n switch (method) {\n case 'AIT.getMockState': {\n const state = await this.fetchState();\n return state as AitMethodMap[M];\n }\n case 'AIT.getOperationalEnvironment': {\n const state = await this.fetchState();\n const environment = typeof state.environment === 'string' ? state.environment : 'unknown';\n const sdkVersion = typeof state.appVersion === 'string' ? state.appVersion : null;\n const result: AitOperationalEnvironment = { environment, sdkVersion };\n return result as AitMethodMap[M];\n }\n case 'AIT.getSdkCallHistory': {\n // sdkCallLog slice is now part of the mock state pushed by the browser panel.\n // Read it from the state snapshot rather than returning an empty stub.\n const state = await this.fetchState();\n const raw = state.sdkCallLog;\n const calls = Array.isArray(raw) ? (raw as AitSdkCallHistory['calls']) : [];\n const result: AitSdkCallHistory = { calls };\n return result as AitMethodMap[M];\n }\n default:\n throw new Error(`Unknown AIT method: ${String(method)}`);\n }\n }\n}\n","/**\n * call_sdk 인자 시그니처 레지스트리\n *\n * 잘 알려진 SDK 메서드의 인자 schema를 수동으로 등록한다.\n * 목적: 잘못된 인자가 native bridge에 도달하기 전에 MCP 레이어에서 reject하여\n * 토스 앱 crash(Swift/Kotlin 측에서 `.type` 등을 undefined로 읽는 경우)를 예방.\n *\n * 등록되지 않은 메서드는 passthrough — 알 수 없는 메서드에 대해 stderr 경고 1회.\n *\n * 시그니처 출처:\n * - `src/__typecheck.ts` — Original SDK 타입 호환성 검증\n * - `src/mock/navigation/index.ts` — mock 구현의 함수 시그니처\n * - `src/mock/device/` — device mock 시그니처\n *\n * 새 메서드 추가 방법:\n * 1. `src/__typecheck.ts` 또는 mock 구현에서 시그니처 확인\n * 2. 아래 SIGNATURES 배열에 `SdkSignature` 항목 추가\n * 3. `src/__tests__/call-sdk-validation.test.ts`에 ok + bad 케이스 추가\n */\n\n/** 단일 메서드에 대한 인자 검증 결과 */\nexport type ValidationResult = { ok: true } | { ok: false; expected: string; received: string };\n\n/** 등록된 SDK 메서드 시그니처 */\nexport interface SdkSignature {\n /** SDK 메서드 이름 (예: \"setDeviceOrientation\") */\n name: string;\n /**\n * 인자 배열을 검증하는 함수.\n * `args[0]` 등 필요한 인자를 `unknown` 타입으로 받아 type guard로 검증.\n */\n validateArgs(args: unknown[]): ValidationResult;\n /**\n * 에러 메시지에 포함할 올바른 호출 예시.\n * 예: `call_sdk('setDeviceOrientation', [{ type: 'landscape' }])`\n */\n example: string;\n}\n\n/* -------------------------------------------------------------------------- */\n/* 헬퍼 — 공통 type guard */\n/* -------------------------------------------------------------------------- */\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction describeArgs(args: unknown[]): string {\n try {\n return JSON.stringify(args);\n } catch {\n return String(args);\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* 시그니처 레지스트리 */\n/* -------------------------------------------------------------------------- */\n\n/**\n * 등록된 메서드 목록.\n *\n * 시그니처 출처 확인:\n * - 함수가 인자를 받지 않으면 args[0] 없음 → `args.length === 0`을 체크하지 않고\n * 그냥 통과시킨다(args 무시하는 stub가 많아서 noArgs 체크가 noise).\n * - 실 SDK 시그니처는 `src/__typecheck.ts`의 `Assert<Mock, Original>` 줄로 보장.\n */\nconst SIGNATURES: SdkSignature[] = [\n // --- setDeviceOrientation ---\n // 실 시그니처: setDeviceOrientation(options: { type: 'portrait' | 'landscape' }): Promise<void>\n // 출처: src/mock/navigation/index.ts:40 / src/__typecheck.ts:55\n {\n name: 'setDeviceOrientation',\n validateArgs(args) {\n const arg = args[0];\n if (!isObject(arg)) {\n return {\n ok: false,\n expected: \"{ type: 'portrait' | 'landscape' }\",\n received: describeArgs(args),\n };\n }\n const type = arg.type;\n if (type !== 'portrait' && type !== 'landscape') {\n return {\n ok: false,\n expected: \"{ type: 'portrait' | 'landscape' }\",\n received: describeArgs(args),\n };\n }\n return { ok: true };\n },\n example: \"call_sdk('setDeviceOrientation', [{ type: 'landscape' }])\",\n },\n\n // --- setIosSwipeGestureEnabled ---\n // 실 시그니처: setIosSwipeGestureEnabled(options: { isEnabled: boolean }): Promise<void>\n // 출처: src/mock/navigation/index.ts:32 / src/__typecheck.ts:51\n {\n name: 'setIosSwipeGestureEnabled',\n validateArgs(args) {\n const arg = args[0];\n if (!isObject(arg) || typeof arg.isEnabled !== 'boolean') {\n return {\n ok: false,\n expected: '{ isEnabled: boolean }',\n received: describeArgs(args),\n };\n }\n return { ok: true };\n },\n example: \"call_sdk('setIosSwipeGestureEnabled', [{ isEnabled: false }])\",\n },\n\n // --- setSecureScreen ---\n // 실 시그니처: setSecureScreen(options: { enabled: boolean }): Promise<{ enabled: boolean }>\n // 출처: src/mock/navigation/index.ts:66 / src/__typecheck.ts:46\n {\n name: 'setSecureScreen',\n validateArgs(args) {\n const arg = args[0];\n if (!isObject(arg) || typeof arg.enabled !== 'boolean') {\n return {\n ok: false,\n expected: '{ enabled: boolean }',\n received: describeArgs(args),\n };\n }\n return { ok: true };\n },\n example: \"call_sdk('setSecureScreen', [{ enabled: true }])\",\n },\n\n // --- setScreenAwakeMode ---\n // 실 시그니처: setScreenAwakeMode(options: { enabled: boolean }): Promise<{ enabled: boolean }>\n // 출처: src/mock/navigation/index.ts:57 / src/__typecheck.ts:47\n {\n name: 'setScreenAwakeMode',\n validateArgs(args) {\n const arg = args[0];\n if (!isObject(arg) || typeof arg.enabled !== 'boolean') {\n return {\n ok: false,\n expected: '{ enabled: boolean }',\n received: describeArgs(args),\n };\n }\n return { ok: true };\n },\n example: \"call_sdk('setScreenAwakeMode', [{ enabled: true }])\",\n },\n\n // --- getOperationalEnvironment ---\n // 실 시그니처: getOperationalEnvironment(): 'toss' | 'sandbox'\n // 인자 없음 — args는 무시 (SDK 자체가 인자를 무시함)\n // 출처: src/mock/navigation/index.ts:88 / src/__typecheck.ts:62\n {\n name: 'getOperationalEnvironment',\n validateArgs(_args) {\n return { ok: true };\n },\n example: \"call_sdk('getOperationalEnvironment', [])\",\n },\n\n // --- getPlatformOS ---\n // 실 시그니처: getPlatformOS(): 'ios' | 'android'\n // 출처: src/mock/navigation/index.ts:84 / src/__typecheck.ts:61\n {\n name: 'getPlatformOS',\n validateArgs(_args) {\n return { ok: true };\n },\n example: \"call_sdk('getPlatformOS', [])\",\n },\n\n // --- getDeviceId ---\n // 실 시그니처: getDeviceId(): string\n // 출처: src/mock/navigation/index.ts:119 / src/__typecheck.ts:74\n {\n name: 'getDeviceId',\n validateArgs(_args) {\n return { ok: true };\n },\n example: \"call_sdk('getDeviceId', [])\",\n },\n\n // --- getLocale ---\n // 실 시그니처: getLocale(): string\n // 출처: src/mock/navigation/index.ts:115 / src/__typecheck.ts:72\n {\n name: 'getLocale',\n validateArgs(_args) {\n return { ok: true };\n },\n example: \"call_sdk('getLocale', [])\",\n },\n\n // --- getNetworkStatus ---\n // 실 시그니처: getNetworkStatus(): Promise<NetworkStatus>\n // 출처: src/mock/navigation/index.ts:127 / src/__typecheck.ts:73\n {\n name: 'getNetworkStatus',\n validateArgs(_args) {\n return { ok: true };\n },\n example: \"call_sdk('getNetworkStatus', [])\",\n },\n\n // --- getSchemeUri ---\n // 실 시그니처: getSchemeUri(): string\n // 출처: src/mock/navigation/index.ts:111 / src/__typecheck.ts:71\n {\n name: 'getSchemeUri',\n validateArgs(_args) {\n return { ok: true };\n },\n example: \"call_sdk('getSchemeUri', [])\",\n },\n\n // --- requestReview ---\n // 실 시그니처: requestReview(): Promise<void>\n // 출처: src/mock/navigation/index.ts:75 / src/__typecheck.ts:76\n {\n name: 'requestReview',\n validateArgs(_args) {\n return { ok: true };\n },\n example: \"call_sdk('requestReview', [])\",\n },\n\n // --- closeView ---\n // 실 시그니처: closeView(): Promise<void>\n // 출처: src/mock/navigation/index.ts:10 / src/__typecheck.ts:42\n {\n name: 'closeView',\n validateArgs(_args) {\n return { ok: true };\n },\n example: \"call_sdk('closeView', [])\",\n },\n];\n\n/* -------------------------------------------------------------------------- */\n/* 레지스트리 공개 API */\n/* -------------------------------------------------------------------------- */\n\nconst SIGNATURE_MAP = new Map<string, SdkSignature>(SIGNATURES.map((s) => [s.name, s]));\n\n/** 세션 내 passthrough 경고를 한 번만 emit하기 위한 Set */\nconst _warnedPassthrough = new Set<string>();\n\n/**\n * 메서드 이름으로 시그니처를 조회한다.\n * 등록된 메서드이면 `SdkSignature`를 반환하고, 미등록이면 `undefined`.\n */\nexport function lookupSignature(name: string): SdkSignature | undefined {\n return SIGNATURE_MAP.get(name);\n}\n\n/**\n * 미등록 메서드에 대해 stderr에 passthrough 경고를 1회 출력한다.\n * 세션 내 동일 메서드 이름은 최초 1회만 출력.\n */\nexport function warnPassthrough(name: string): void {\n if (_warnedPassthrough.has(name)) return;\n _warnedPassthrough.add(name);\n process.stderr.write(`[ait-debug] call_sdk: \"${name}\" 시그니처가 등록되지 않음 — passthrough\\n`);\n}\n\n/**\n * 테스트에서 passthrough 경고 Set을 초기화하기 위한 헬퍼.\n * 프로덕션 코드에서는 호출하지 않는다.\n */\nexport function _resetWarnedPassthroughForTest(): void {\n _warnedPassthrough.clear();\n}\n\n/**\n * 등록된 메서드 이름 목록 — tool description 생성 등에서 사용.\n */\nexport const REGISTERED_METHOD_NAMES: ReadonlyArray<string> = SIGNATURES.map((s) => s.name);\n","/**\n * Debug-mode MCP tools (Phase 1–3 + safe-area probe).\n *\n * Read-only tools that normalize CDP / AIT data into `chrome-devtools-mcp`-\n * compatible shapes. The tools never touch a websocket or HTTP endpoint\n * directly — they read from an injected `CdpConnection` (CDP events/commands)\n * or `AitSource` (AIT.* domain), which is what makes them unit-testable with a\n * fake. No phone and no running dev server are needed in tests.\n *\n * Phase 1 (CDP events):\n * - `list_console_messages` ← Runtime.consoleAPICalled\n * - `list_network_requests` ← Network.requestWillBeSent + responseReceived\n * - `list_pages` ← Chii relay target list + tunnel status\n * Phase 2 (CDP commands):\n * - `get_dom_document` ← DOM.getDocument\n * - `take_snapshot` ← DOMSnapshot.captureSnapshot\n * - `take_screenshot` ← Page.captureScreenshot\n * - `measure_safe_area` ← Runtime.evaluate (safe-area probe)\n * Phase 3 (AIT.* domain — CDP can't cover these):\n * - `AIT.getSdkCallHistory`\n * - `AIT.getMockState`\n * - `AIT.getOperationalEnvironment`\n */\n\nimport type {\n AitMockState,\n AitOperationalEnvironment,\n AitSdkCallHistory,\n AitSource,\n} from './ait-source.js';\nimport type {\n CdpCallFrame,\n CdpConnection,\n CdpRemoteObject,\n ConsoleApiCalledEvent,\n DomGetDocumentResult,\n DomSnapshotResult,\n NetworkRequestWillBeSentEvent,\n NetworkResponseReceivedEvent,\n RuntimeExceptionThrownEvent,\n} from './cdp-connection.js';\nimport { buildDeepLinkAttachUrl, validateSchemeAuthority } from './deeplink.js';\nimport type { McpEnvironment } from './environment.js';\nimport { lookupSignature, warnPassthrough } from './sdk-signatures.js';\n\n/** Tunnel state surfaced by `list_pages`. */\nexport interface TunnelStatus {\n /** Whether the cloudflared quick tunnel is up. */\n up: boolean;\n /** Public `wss://*.trycloudflare.com` relay URL the phone attaches to. */\n wssUrl: string | null;\n}\n\n/**\n * Tier classification per RFC #277 (\"MCP tool surface fidelity\"):\n *\n * - **Tier A** (`mock` only) — mock-internal state dials with no real-device\n * equivalent. Hidden when env is `relay`.\n * - **Tier B** (`relay` only) — relay infrastructure tools that have no mock\n * equivalent (e.g. `build_attach_url` needs a cloudflared tunnel URL). Hidden\n * when env is `mock`.\n * - **Tier C** (`both`) — fidelity-parallel tools that produce semantically\n * equivalent results across mock and relay. The agent sees the same tool with\n * the same shape; only the `source` provenance field (where applicable)\n * differs.\n */\nexport type ToolAvailability = 'mock' | 'relay' | 'both';\n\n/** Static MCP tool descriptors (name + JSONSchema) for the full debug tool surface. */\nexport const DEBUG_TOOL_DEFINITIONS = [\n {\n name: 'list_console_messages',\n description:\n 'Lists recent console messages (console.log/warn/error/info) captured from the attached ' +\n 'mini-app page over CDP (Runtime.consoleAPICalled). Read-only. Returns level, text, ' +\n 'timestamp, and stringified args, oldest-first.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'list_network_requests',\n description:\n 'Lists recent network requests (XHR/fetch) captured from the attached mini-app page over ' +\n 'CDP (Network.requestWillBeSent + Network.responseReceived). Read-only. Returns url, ' +\n 'method, status, and timing, oldest-first.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'list_pages',\n description:\n 'Returns the single active page (at most one) the relay sees attached. ' +\n 'When a second page attaches, the previous one is evicted (last-attach wins — ' +\n 'single-attach model). The result includes `singleAttachModel: true` so the agent ' +\n 'knows the array is always 0 or 1 entries. ' +\n 'Also returns whether the cloudflared tunnel is up and the public wss relay URL. ' +\n 'Each page entry includes a `lastSeenAt` ISO timestamp (last inbound CDP message from ' +\n 'that target — useful to detect stale entries when the phone app backgrounded). ' +\n 'The result also includes `crashDetectedAt` (ISO timestamp or null): when non-null, ' +\n 'a page crash was detected via Inspector.targetCrashed / Target.targetDestroyed since ' +\n 'the last attach, the pages list will be empty, and `crashWarning` shows a Korean hint ' +\n 'to re-attach. ' +\n 'Call this first to confirm a page is attached before reading console/network.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'build_attach_url',\n description:\n \"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. \" +\n 'Turns an `ait deploy --scheme-only` URL (intoss-private://…?_deploymentId=<uuid>) into a ' +\n 'self-attaching deep link by splicing in debug=1 and the live relay URL for this session. ' +\n 'Returns the deep link JSON and a unicode QR of that deep link. Scan the QR with the phone ' +\n 'camera to open the mini-app and attach it to this debug session (QR is the single entry ' +\n 'path — no USB cable or platform CLI needed). Requires the tunnel to be up — call ' +\n 'list_pages first. Set wait_for_attach=true to block until the phone scans and a page ' +\n 'attaches (polls listTargets up to 90 s), then returns the attached page info too. ' +\n 'When open_in_browser=true (default), saves the QR as a PNG and opens it in the OS default ' +\n 'browser — only works when the MCP server runs on a local GUI machine (not headless/remote containers).',\n inputSchema: {\n type: 'object',\n properties: {\n scheme_url: {\n type: 'string',\n description:\n 'The intoss-private:// scheme URL from `ait deploy --scheme-only` (must carry _deploymentId). ' +\n 'The authority (host) must be the app name (e.g. intoss-private://aitc-sdk-example?_deploymentId=…). ' +\n 'Generic values like \"web\" or an empty host indicate a malformed URL.',\n },\n wait_for_attach: {\n type: 'boolean',\n description:\n 'If true, block after returning the QR until a page attaches to the relay (polls ' +\n 'listTargets ~1 s interval, timeout 90 s). On attach, the response includes the ' +\n 'attached page list. On timeout, returns an error with a list_pages retry hint.',\n },\n open_in_browser: {\n type: 'boolean',\n description:\n 'If true (default), render the QR as a PNG and open it in the OS default browser. ' +\n 'Only works when the MCP server is running on a local GUI machine — headless or ' +\n 'remote container environments should set this to false to use the text QR fallback.',\n },\n },\n required: ['scheme_url'],\n },\n // Tier B per RFC #277 — the URL synthesis requires a live cloudflared\n // tunnel + relay, which only exists in the `relay` environment.\n availableIn: 'relay' as ToolAvailability,\n },\n {\n name: 'get_dom_document',\n description:\n 'Returns the DOM tree of the attached mini-app page over CDP (DOM.getDocument). Read-only. ' +\n 'Use for structural/layout regression diagnosis (e.g. confirming an element exists, ' +\n 'inspecting attributes). Returns the document root node with children.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'take_snapshot',\n description:\n 'Captures a serialized snapshot of the attached page over CDP (DOMSnapshot.captureSnapshot). ' +\n 'Read-only. Returns the documents + interned strings table for visual-regression diagnosis ' +\n '(e.g. checking computed CSS custom properties like --sat against the live layout).',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'take_screenshot',\n description:\n 'Captures a PNG screenshot of the attached mini-app page over CDP (Page.captureScreenshot) ' +\n 'so the agent can see the phone screen directly. Read-only. Returns an image content block.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'measure_safe_area',\n description:\n 'Runs a safe-area probe on the attached mini-app page via Runtime.evaluate and returns ' +\n 'normalized safe-area insets, viewport geometry, device pixel ratio, and User-Agent. ' +\n 'Read-only — does not modify page state. ' +\n 'Tier C per RFC #277: the same Runtime.evaluate probe runs in both `mock` (devtools panel ' +\n 'page with window.__ait state) and `relay` (real-device WebView with window.__sdk). ' +\n 'The result includes a `source: \"mock\" | \"relay\"` field so consumers can identify ' +\n 'provenance without inspecting payload values. ' +\n 'Use in a relay session (phone attached) to get ground-truth values for upgrading a ' +\n 'viewport preset from extrapolated/placeholder to measured. ' +\n 'Requires a page to be attached — call list_pages first.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'evaluate',\n description:\n 'Evaluates an arbitrary JavaScript expression on the attached mini-app page via ' +\n 'CDP Runtime.evaluate (returnByValue: true) and returns the result. ' +\n 'NOT read-only — the expression can have side effects (DOM mutations, SDK calls, ' +\n 'state changes). Requires the relay to be attached — call list_pages first. ' +\n 'Throws if the evaluation throws an exception on the page.',\n inputSchema: {\n type: 'object',\n properties: {\n expression: {\n type: 'string',\n description: 'JavaScript expression to evaluate in the page context.',\n },\n },\n required: ['expression'],\n },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'list_exceptions',\n description:\n 'Lists JS-level exceptions captured via `Runtime.exceptionThrown` from the relay attached ' +\n 'page. Includes timestamp, exception text, source URL/line, and stack trace. ' +\n 'Use to root-cause SDK throws that may precede a Toss app crash (#265 / #267). ' +\n 'The buffer holds up to 50 most recent exceptions and survives target ' +\n 'replaced/crashed/destroyed events so an exception just before a crash is preserved. ' +\n 'Returns up to 50 most recent by default.',\n inputSchema: {\n type: 'object',\n properties: {\n limit: {\n type: 'number',\n description: 'Maximum number of exceptions to return (default 50, max 50).',\n },\n },\n required: [],\n },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'call_sdk',\n description:\n 'Calls a dogfood SDK method via the window.__sdkCall bridge ' +\n '(exported by @apps-in-toss/web-framework only in __DEBUG_BUILD__ bundles). ' +\n 'NOT read-only — SDK calls have side effects (navigation, payments, permissions, etc.). ' +\n 'On env 2/3 (real device relay) this hits the real SDK; on env 1 (local mock) it hits ' +\n 'the mock SDK. Requires the relay to be attached — call list_pages first. ' +\n 'Returns {ok: true, value} on success or {ok: false, error} on failure. ' +\n 'If a Runtime.exceptionThrown event was observed within [callStart-50ms, callEnd+200ms], ' +\n 'the result also includes `recentException` for crash triage. ' +\n 'Returns a clear error if window.__sdkCall is not available (non-dogfood bundle).\\n\\n' +\n 'IMPORTANT — 인자 시그니처 (잘못된 인자로 호출하면 토스 앱 crash 위험):\\n' +\n ' setDeviceOrientation: call_sdk(\"setDeviceOrientation\", [{ type: \"landscape\" }]) // NOT \"landscape\"\\n' +\n ' setIosSwipeGestureEnabled: call_sdk(\"setIosSwipeGestureEnabled\", [{ isEnabled: false }])\\n' +\n ' setSecureScreen: call_sdk(\"setSecureScreen\", [{ enabled: true }])\\n' +\n ' setScreenAwakeMode: call_sdk(\"setScreenAwakeMode\", [{ enabled: true }])\\n' +\n ' getOperationalEnvironment: call_sdk(\"getOperationalEnvironment\", [])\\n' +\n ' getPlatformOS: call_sdk(\"getPlatformOS\", [])\\n' +\n ' getDeviceId: call_sdk(\"getDeviceId\", [])\\n' +\n ' getLocale: call_sdk(\"getLocale\", [])\\n' +\n ' getNetworkStatus: call_sdk(\"getNetworkStatus\", [])\\n' +\n ' getSchemeUri: call_sdk(\"getSchemeUri\", [])\\n' +\n ' requestReview: call_sdk(\"requestReview\", [])\\n' +\n ' closeView: call_sdk(\"closeView\", [])',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'SDK method name to call (e.g. \"getOperationalEnvironment\").',\n },\n args: {\n type: 'array',\n description: 'Arguments to pass to the SDK method (optional, default []).',\n items: {},\n },\n },\n required: ['name'],\n },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'AIT.getSdkCallHistory',\n description:\n 'Returns the recent Apps In Toss SDK call trace (method, args, result/error, timestamp) that ' +\n 'raw CDP cannot observe. Read-only. Use to confirm an SDK call fired and how it resolved ' +\n '(e.g. a saveBase64Data permission regression).',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'AIT.getMockState',\n description:\n 'Returns the devtools mock state snapshot (window.__ait) — environment, permissions, location, ' +\n 'auth, network, IAP, and more. Read-only. In dev mode this is the live browser mock state; in ' +\n 'debug mode the in-app side reports it over the AIT domain.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'AIT.getOperationalEnvironment',\n description:\n 'Returns getOperationalEnvironment() plus the resolved SDK version — metadata raw CDP cannot ' +\n 'observe. Read-only.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n] as const;\n\nexport type DebugToolName = (typeof DEBUG_TOOL_DEFINITIONS)[number]['name'];\n\nconst DEBUG_TOOL_NAMES = new Set<string>(DEBUG_TOOL_DEFINITIONS.map((t) => t.name));\n\nexport function isDebugToolName(name: string): name is DebugToolName {\n return DEBUG_TOOL_NAMES.has(name);\n}\n\n/**\n * Returns the `ToolAvailability` declared on a registered debug tool, or\n * `undefined` when the name is not a known debug tool. Used by the tool\n * registry to filter `tools/list` by current env and by the call handler to\n * reject env-mismatch invocations.\n */\nexport function getToolAvailability(name: string): ToolAvailability | undefined {\n for (const t of DEBUG_TOOL_DEFINITIONS) {\n if (t.name === name) return t.availableIn;\n }\n return undefined;\n}\n\n/**\n * Returns true when the named tool is available in the given environment.\n * Unknown tools return `false` — callers should reject them as unknown rather\n * than as env-mismatched.\n */\nexport function isToolAvailableIn(name: string, env: McpEnvironment): boolean {\n const availability = getToolAvailability(name);\n if (availability === undefined) return false;\n if (availability === 'both') return true;\n return availability === env;\n}\n\n/**\n * Filters a `DEBUG_TOOL_DEFINITIONS`-shaped list to those whose `availableIn`\n * matches the given env. Pure — preserves order; both Tier C (\"both\") and the\n * matching single-env tier pass through.\n */\nexport function filterToolsByEnvironment<T extends { name: string; availableIn: ToolAvailability }>(\n tools: ReadonlyArray<T>,\n env: McpEnvironment,\n): T[] {\n return tools.filter((t) => t.availableIn === 'both' || t.availableIn === env);\n}\n\n/**\n * Tool names that are available before any page attaches (bootstrap tier).\n *\n * `build_attach_url` — pure URL synthesis, no attach needed.\n * `list_pages` — reports tunnel status + empty pages even pre-attach.\n *\n * All other tools require an attached page (`enableDomains` must succeed) and\n * are only advertised in `tools/list` once a target appears.\n */\nexport const BOOTSTRAP_TOOL_NAMES: ReadonlySet<string> = new Set<string>([\n 'build_attach_url',\n 'list_pages',\n]);\n\n/** Normalized console message returned by `list_console_messages`. */\nexport interface ConsoleMessage {\n level: string;\n text: string;\n timestamp: number;\n args: string[];\n}\n\n/** Normalized network request returned by `list_network_requests`. */\nexport interface NetworkRequest {\n requestId: string;\n url: string;\n method: string;\n /** HTTP status once a response was seen, else null (still in-flight). */\n status: number | null;\n statusText: string | null;\n /** Request start (CDP timestamp). */\n startTime: number;\n /** Response received (CDP timestamp), else null. */\n endTime: number | null;\n}\n\n/** Renders a CDP `RemoteObject` console arg to a stable display string. */\nfunction renderRemoteObject(arg: CdpRemoteObject): string {\n if (arg.value !== undefined) {\n if (typeof arg.value === 'string') return arg.value;\n try {\n return JSON.stringify(arg.value);\n } catch {\n return String(arg.value);\n }\n }\n if (arg.description !== undefined) return arg.description;\n if (arg.className !== undefined) return arg.className;\n return arg.subtype ?? arg.type;\n}\n\nexport function normalizeConsoleMessage(event: ConsoleApiCalledEvent): ConsoleMessage {\n const args = event.args.map(renderRemoteObject);\n return {\n level: event.type,\n text: args.join(' '),\n timestamp: event.timestamp,\n args,\n };\n}\n\nexport function listConsoleMessages(connection: CdpConnection): ConsoleMessage[] {\n return connection\n .getBufferedEvents('Runtime.consoleAPICalled')\n .map((event) => normalizeConsoleMessage(event));\n}\n\nexport function listNetworkRequests(connection: CdpConnection): NetworkRequest[] {\n const requests = connection.getBufferedEvents('Network.requestWillBeSent');\n const responses = connection.getBufferedEvents('Network.responseReceived');\n\n const responseByRequestId = new Map<string, NetworkResponseReceivedEvent>();\n for (const response of responses) {\n responseByRequestId.set(response.requestId, response);\n }\n\n return requests.map((request: NetworkRequestWillBeSentEvent) => {\n const response = responseByRequestId.get(request.requestId);\n return {\n requestId: request.requestId,\n url: request.request.url,\n method: request.request.method,\n status: response ? response.response.status : null,\n statusText: response ? response.response.statusText : null,\n startTime: request.timestamp,\n endTime: response ? response.timestamp : null,\n };\n });\n}\n\n/* -------------------------------------------------------------------------- */\n/* list_exceptions — Runtime.exceptionThrown ring buffer */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Normalized exception returned by `list_exceptions`.\n *\n * Flattens the CDP `Runtime.ExceptionDetails` shape into the most useful\n * fields. The `raw` field carries the original event for callers that need\n * the full payload.\n */\nexport interface BufferedException {\n /** Wall-clock ms since epoch (CDP `Runtime.Timestamp`). */\n timestamp: number;\n /** Short summary text from `exceptionDetails.text`. */\n text: string;\n /** Source URL where the exception was thrown, if known. */\n url?: string;\n /** 0-based line number in the source file, if known. */\n lineNumber?: number;\n /** 0-based column number in the source file, if known. */\n columnNumber?: number;\n /** `description` of the thrown `RemoteObject` (e.g. \"TypeError: …\"). */\n exceptionText?: string;\n /**\n * Formatted stack trace: `at fn (url:line:col)` lines joined by `\\n`.\n * Omitted when no `stackTrace.callFrames` are available.\n */\n stack?: string;\n /** Full original `Runtime.exceptionThrown` event payload. */\n raw: RuntimeExceptionThrownEvent;\n}\n\n/** Formats a single CDP call frame into `at fn (url:line:col)`. */\nfunction formatCallFrame(frame: CdpCallFrame): string {\n const fn = frame.functionName || '(anonymous)';\n return `at ${fn} (${frame.url}:${frame.lineNumber}:${frame.columnNumber})`;\n}\n\n/** Normalizes a raw `Runtime.exceptionThrown` event into a `BufferedException`. */\nexport function normalizeException(event: RuntimeExceptionThrownEvent): BufferedException {\n const { timestamp, exceptionDetails } = event;\n const frames = exceptionDetails.stackTrace?.callFrames;\n const stack = frames && frames.length > 0 ? frames.map(formatCallFrame).join('\\n') : undefined;\n const exceptionText = exceptionDetails.exception?.description ?? undefined;\n\n const result: BufferedException = {\n timestamp,\n text: exceptionDetails.text,\n raw: event,\n };\n if (exceptionDetails.url !== undefined) result.url = exceptionDetails.url;\n if (exceptionDetails.lineNumber !== undefined) result.lineNumber = exceptionDetails.lineNumber;\n if (exceptionDetails.columnNumber !== undefined)\n result.columnNumber = exceptionDetails.columnNumber;\n if (exceptionText !== undefined) result.exceptionText = exceptionText;\n if (stack !== undefined) result.stack = stack;\n return result;\n}\n\n/**\n * Returns the most recent buffered `Runtime.exceptionThrown` events, normalized.\n * Oldest-first; limited to `limit` entries (default 50, max 50).\n */\nexport function listExceptions(connection: CdpConnection, limit = 50): BufferedException[] {\n const cap = Math.min(Math.max(1, limit), 50);\n const events = connection.getBufferedEvents('Runtime.exceptionThrown');\n // Slice from the tail to respect the cap while preserving oldest-first order.\n const sliced = events.length > cap ? events.slice(events.length - cap) : events;\n return sliced.map((e) => normalizeException(e));\n}\n\n/** A page entry in the `list_pages` result, extended with freshness info. */\nexport interface ListPagesEntry {\n id: string;\n title: string;\n url: string;\n /** ISO timestamp of the last inbound CDP message from this target, or null. */\n lastSeenAt: string | null;\n}\n\n/** Result of `list_pages`: attach status + tunnel state + crash info. */\nexport interface ListPagesResult {\n /**\n * The single active page, or an empty array when nothing is attached.\n * Under the single-attach model this is always 0 or 1 entries.\n */\n pages: ListPagesEntry[];\n tunnel: TunnelStatus;\n /**\n * ISO timestamp of the most recent crash / targetDestroyed / detachedFromTarget\n * event detected since the last `enableDomains()`, or `null` if none.\n * When non-null, all attached pages have been removed from the relay map and\n * a new `enableDomains()` call is required to resume debugging.\n */\n crashDetectedAt: string | null;\n /** Korean warning line shown in tool output when a crash was detected. */\n crashWarning: string | null;\n /**\n * Always `true` — signals to the agent that at most one page is ever present.\n * When a second page attaches, the previous one is evicted (last-attach wins).\n */\n singleAttachModel: true;\n}\n\n/**\n * Duck-type interface for the crash-detection extras exposed by `ChiiCdpConnection`.\n * The base `CdpConnection` interface is kept minimal (fake-friendly); the extras\n * are opt-in so tests without them continue to compile.\n */\ninterface CrashAwareCdpConnection extends CdpConnection {\n getLastCrashDetectedAt(): number | null;\n getTargetLastSeenAt(targetId: string): number | null;\n}\n\nfunction isCrashAware(conn: CdpConnection): conn is CrashAwareCdpConnection {\n return (\n typeof (conn as CrashAwareCdpConnection).getLastCrashDetectedAt === 'function' &&\n typeof (conn as CrashAwareCdpConnection).getTargetLastSeenAt === 'function'\n );\n}\n\nexport function listPages(connection: CdpConnection, tunnel: TunnelStatus): ListPagesResult {\n const rawTargets = connection.listTargets();\n const pages: ListPagesEntry[] = rawTargets.map((t) => {\n const lastSeenMs = isCrashAware(connection) ? connection.getTargetLastSeenAt(t.id) : null;\n return {\n id: t.id,\n title: t.title,\n url: t.url,\n lastSeenAt: lastSeenMs !== null ? new Date(lastSeenMs).toISOString() : null,\n };\n });\n\n const crashMs = isCrashAware(connection) ? connection.getLastCrashDetectedAt() : null;\n const crashDetectedAt = crashMs !== null ? new Date(crashMs).toISOString() : null;\n const crashWarning = crashDetectedAt\n ? `[ait-debug] page crash 감지됨 — 새 attach 필요 (관측 시각: ${crashDetectedAt})`\n : null;\n\n return { pages, tunnel, crashDetectedAt, crashWarning, singleAttachModel: true };\n}\n\n/** A `build_attach_url` result: the spliced deep link the phone should open. */\nexport interface BuildAttachUrlResult {\n /** The scheme URL with `debug=1&relay=<wss>` spliced in. */\n attachUrl: string;\n /** The relay URL that was spliced in (this session's quick tunnel). */\n relayUrl: string;\n /**\n * Non-fatal warning about the scheme URL's authority being missing or\n * suspicious (e.g. \"web\", \"localhost\"). Callers should surface this to\n * help the user catch a malformed URL early.\n */\n authorityWarning?: string;\n}\n\n/**\n * Builds a self-attaching dogfood deep link from an `ait deploy --scheme-only`\n * URL plus this session's live relay. Throws if the tunnel is not up yet (no\n * relay URL to splice in) — the caller surfaces that as a tool error.\n *\n * Also validates the scheme URL's authority. A suspicious authority (empty,\n * \"web\", \"localhost\", etc.) is surfaced as a non-fatal `authorityWarning` on\n * the result so the caller can show a helpful hint without blocking the link\n * generation (the warning is consistent with how other validation in\n * `buildDeepLinkAttachUrl` works — hard errors for relay, soft warning for\n * the scheme authority which is in the caller's input, not ours to own).\n */\nexport function buildAttachUrl(schemeUrl: string, tunnel: TunnelStatus): BuildAttachUrlResult {\n if (!tunnel.up || tunnel.wssUrl === null) {\n throw new Error(\n 'No relay URL yet — the cloudflared quick tunnel is not up. ' +\n 'Call list_pages to check tunnel status.',\n );\n }\n const authorityWarning = validateSchemeAuthority(schemeUrl) ?? undefined;\n return {\n attachUrl: buildDeepLinkAttachUrl(schemeUrl, tunnel.wssUrl),\n relayUrl: tunnel.wssUrl,\n ...(authorityWarning !== undefined ? { authorityWarning } : {}),\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* QR PNG rendering + browser open */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Heuristic: can this process open a GUI browser?\n *\n * Returns `true` when we think a GUI is available:\n * - On macOS (`darwin`) we assume yes (MCP normally runs on the user's Mac).\n * - On Linux we check for `DISPLAY` or `WAYLAND_DISPLAY`.\n * - On Windows we assume yes.\n * - In a CI environment (`CI=true`) we assume no.\n */\nexport function canOpenBrowser(): boolean {\n if (process.env.CI === 'true' || process.env.CI === '1') return false;\n const platform = process.platform;\n if (platform === 'darwin' || platform === 'win32') return true;\n if (platform === 'linux') {\n return Boolean(process.env.DISPLAY ?? process.env.WAYLAND_DISPLAY);\n }\n return false;\n}\n\n/**\n * Result of `openQrInBrowser`.\n *\n * HTTP URL 기반으로 재구현 — tmp 파일 없음. `httpUrl`이 브라우저에 전달되는 URL이다.\n * SECRET-HANDLING: `httpUrl`은 127.0.0.1 로컬 전용이며 at= 코드 값을 직접 담지 않는다\n * (attachUrl은 /attach?u= query로 전달되어 서버 메모리에서만 처리).\n */\nexport interface OpenQrInBrowserResult {\n /** `true` if the browser was successfully opened. */\n opened: boolean;\n /** `http://127.0.0.1:<port>/attach?u=...` — 브라우저에 전달된 URL. */\n httpUrl: string;\n /** `http://127.0.0.1:<port>/qr.png?u=...` — PNG fallback URL. */\n pngUrl: string;\n /** Error message if `opened` is false (browser spawn failed). */\n error?: string;\n /** Captured stderr from failed spawn attempts (at= 값은 redact됨). */\n stderrSummary?: string;\n}\n\n/** platform별 browser open 명령 후보 목록 — 앞에서부터 순차 시도. */\nfunction getBrowserCandidates(httpUrl: string): Array<{ cmd: string; args: string[] }> {\n const platform = process.platform;\n if (platform === 'darwin') {\n return [\n { cmd: 'open', args: [httpUrl] },\n { cmd: 'open', args: ['-a', 'Safari', httpUrl] },\n { cmd: 'open', args: ['-a', 'Google Chrome', httpUrl] },\n { cmd: 'open', args: ['-a', 'Firefox', httpUrl] },\n ];\n }\n if (platform === 'win32') {\n return [\n { cmd: 'cmd', args: ['/c', 'start', '', httpUrl] },\n { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler', httpUrl] },\n ];\n }\n // linux + fallback\n return [\n { cmd: 'xdg-open', args: [httpUrl] },\n { cmd: 'sensible-browser', args: [httpUrl] },\n { cmd: 'x-www-browser', args: [httpUrl] },\n { cmd: 'firefox', args: [httpUrl] },\n { cmd: 'google-chrome', args: [httpUrl] },\n { cmd: 'chromium', args: [httpUrl] },\n ];\n}\n\n/** stderr에서 at= TOTP 코드 값을 redact한다. */\nfunction redactSecrets(text: string): string {\n // at=<value> 패턴에서 값 부분을 redact — TOTP 코드가 노출되지 않도록.\n return text.replace(/\\bat=([^&\\s\"']+)/g, 'at=<redacted>');\n}\n\n/** spawnSync exit 0이어도 stderr에 launch 실패 시그널이 있으면 실패로 판단한다. */\nconst LAUNCH_FAILURE_PATTERNS = [\n /LSOpenURLsWithRole\\(\\) failed/,\n /kLSApplicationNotFoundErr/,\n /No application/,\n /Unable to find application/,\n /xdg-open: not found/,\n /command not found/,\n];\n\nfunction isLaunchFailureStderr(stderr: string): boolean {\n return LAUNCH_FAILURE_PATTERNS.some((p) => p.test(stderr));\n}\n\n/**\n * 로컬 HTTP 서버 URL(`http://127.0.0.1:<port>/attach?u=...`)을 OS 기본 브라우저로 연다.\n *\n * platform별 fallback chain으로 시도하며, 모두 실패해도 `opened: false` + `httpUrl`을\n * 반환해 사용자가 직접 브라우저에 붙여넣을 수 있게 한다.\n *\n * SECRET-HANDLING:\n * - tmp 파일을 만들지 않는다 (HTML/PNG는 HTTP 서버가 메모리에서 응답).\n * - httpUrl/pngUrl은 127.0.0.1 로컬 전용.\n * - stderr 캡처 결과에서 at= 코드 값을 redact한 후 stderrSummary에 포함.\n * - attachUrl, deploymentId, TOTP 코드를 stdout/stderr/로그에 직접 출력 금지.\n *\n * @param httpUrl - `http://127.0.0.1:<port>/attach?u=<encoded>` HTTP URL.\n * @param pngUrl - `http://127.0.0.1:<port>/qr.png?u=<encoded>` PNG fallback URL.\n */\nexport async function openQrInBrowser(\n httpUrl: string,\n pngUrl: string,\n): Promise<OpenQrInBrowserResult> {\n const { spawnSync } = await import('node:child_process');\n\n const candidates = getBrowserCandidates(httpUrl);\n const stderrLines: string[] = [];\n\n for (const { cmd, args } of candidates) {\n const result = spawnSync(cmd, args, { encoding: 'utf8', timeout: 5000 });\n\n if (result.error) {\n // 명령 자체를 실행하지 못한 경우 (ENOENT 등) — 다음 후보로.\n stderrLines.push(`${cmd}: ${result.error.message}`);\n continue;\n }\n\n const stderr = typeof result.stderr === 'string' ? result.stderr : '';\n if (stderr) {\n stderrLines.push(`${cmd}: ${redactSecrets(stderr.trim())}`);\n }\n\n // exit 0이어도 stderr에 launch 실패 패턴이 있으면 실패로 취급.\n if (result.status === 0 && !isLaunchFailureStderr(stderr)) {\n return { opened: true, httpUrl, pngUrl };\n }\n }\n\n const stderrSummary = stderrLines.length > 0 ? stderrLines.join('\\n') : undefined;\n return {\n opened: false,\n httpUrl,\n pngUrl,\n error: '모든 브라우저 실행 후보가 실패했습니다.',\n stderrSummary,\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Phase 2 — DOM / snapshot / screenshot (CDP commands) */\n/* -------------------------------------------------------------------------- */\n\n/** Returns the DOM tree of the attached page (`DOM.getDocument`). */\nexport function getDomDocument(connection: CdpConnection): Promise<DomGetDocumentResult> {\n // `pierce: true` flattens shadow roots; depth -1 returns the whole subtree so\n // a single call yields the full tree for structural diagnosis.\n return connection.send('DOM.getDocument', { depth: -1, pierce: true });\n}\n\n/** Returns a serialized page snapshot (`DOMSnapshot.captureSnapshot`). */\nexport function takeSnapshot(connection: CdpConnection): Promise<DomSnapshotResult> {\n return connection.send('DOMSnapshot.captureSnapshot', {});\n}\n\n/** A `take_screenshot` result: the raw base64 PNG plus a ready-to-use data URI. */\nexport interface ScreenshotResult {\n /** Base64-encoded PNG bytes (no data-URI prefix). */\n data: string;\n /** `data:image/png;base64,…` form for clients that render a URI. */\n dataUri: string;\n mimeType: 'image/png';\n}\n\n/** Captures a PNG screenshot of the attached page (`Page.captureScreenshot`). */\nexport async function takeScreenshot(connection: CdpConnection): Promise<ScreenshotResult> {\n const { data } = await connection.send('Page.captureScreenshot', { format: 'png' });\n return { data, dataUri: `data:image/png;base64,${data}`, mimeType: 'image/png' };\n}\n\n/* -------------------------------------------------------------------------- */\n/* measure_safe_area — Runtime.evaluate probe */\n/* -------------------------------------------------------------------------- */\n\n/**\n * The JS probe injected via `Runtime.evaluate`. It reads:\n * 1. `env(safe-area-inset-*)` via a temporary element with padding set to\n * those CSS env vars, then `getComputedStyle`.\n * 2. SDK insets via a priority chain so the SAME probe works on both relay\n * (real device) and mock (devtools panel page):\n * a. `window.__sdk.SafeAreaInsets.get()` — dogfood bundle on real device.\n * b. `window.__sdk.getSafeAreaInsets()` — dogfood bundle (deprecated).\n * c. `window.__ait.state.safeAreaInsets` — devtools mock state (mock env).\n * The probe records `sdkInsetsSource` = `'window.__sdk'` | `'window.__ait'`\n * | `null`. If all paths fail the result carries `sdkInsetsError`.\n * 3. nav bar geometry: the SDK does not expose navBar height as a standalone\n * API — `.ait-navbar` DOM height is read as a cross-check, and\n * `navBarHeightSource` records where it came from.\n * 4. `innerWidth`, `innerHeight`, `devicePixelRatio`, `navigator.userAgent`.\n *\n * Returns a plain JSON-serialisable object so `returnByValue: true` works.\n *\n * NOTE: This expression is evaluated in the page context — on the real device\n * (relay) or on the mock panel page. It does not mutate any page state — the\n * temporary element is removed after reading. No secret or auth token is read\n * or returned.\n *\n * RFC #277 Tier C parity: the SAME probe string runs in both envs. Mock fidelity\n * comes from the panel's `applyViewport` / `computeSafeAreaInsets` correctly\n * setting `window.__ait.state.safeAreaInsets` (#275). When that is correct,\n * the cssEnv + sdkInsets pair returned here matches the relay's shape.\n */\nexport const SAFE_AREA_PROBE_EXPRESSION = `\n(function() {\n var el = document.createElement('div');\n el.style.cssText = 'position:fixed;top:0;left:0;width:0;height:0;visibility:hidden;' +\n 'padding-top:env(safe-area-inset-top,0px);' +\n 'padding-right:env(safe-area-inset-right,0px);' +\n 'padding-bottom:env(safe-area-inset-bottom,0px);' +\n 'padding-left:env(safe-area-inset-left,0px)';\n document.documentElement.appendChild(el);\n var cs = window.getComputedStyle(el);\n var cssEnv = {\n top: parseFloat(cs.paddingTop) || 0,\n right: parseFloat(cs.paddingRight) || 0,\n bottom: parseFloat(cs.paddingBottom) || 0,\n left: parseFloat(cs.paddingLeft) || 0\n };\n document.documentElement.removeChild(el);\n var sdkInsets = null;\n var sdkInsetsSource = null;\n var sdkInsetsError = undefined;\n try {\n var sdk = window.__sdk;\n var ait = window.__ait;\n if (sdk && sdk.SafeAreaInsets && typeof sdk.SafeAreaInsets.get === 'function') {\n sdkInsets = sdk.SafeAreaInsets.get();\n sdkInsetsSource = 'window.__sdk';\n } else if (sdk && typeof sdk.getSafeAreaInsets === 'function') {\n sdkInsets = sdk.getSafeAreaInsets();\n sdkInsetsSource = 'window.__sdk';\n } else if (ait && ait.state && ait.state.safeAreaInsets &&\n typeof ait.state.safeAreaInsets.top === 'number') {\n var s = ait.state.safeAreaInsets;\n sdkInsets = { top: s.top, bottom: s.bottom, left: s.left, right: s.right };\n sdkInsetsSource = 'window.__ait';\n } else if (!sdk && !ait) {\n sdkInsetsError = 'neither window.__sdk (relay) nor window.__ait (mock) available';\n } else if (sdk) {\n sdkInsetsError = 'neither SafeAreaInsets.get nor getSafeAreaInsets found on window.__sdk';\n } else {\n sdkInsetsError = 'window.__ait.state.safeAreaInsets is missing or malformed';\n }\n } catch(e) {\n sdkInsetsError = String(e && e.message || e);\n }\n var navBarHeight = null;\n var navBarHeightSource = 'not-exposed-by-sdk';\n try {\n var nb = document.querySelector('.ait-navbar');\n if (nb) {\n navBarHeight = nb.getBoundingClientRect().height;\n navBarHeightSource = 'dom-.ait-navbar';\n }\n } catch(_) {}\n var result = {\n cssEnv: cssEnv,\n sdkInsets: sdkInsets,\n sdkInsetsSource: sdkInsetsSource,\n navBarHeight: navBarHeight,\n navBarHeightSource: navBarHeightSource,\n innerWidth: window.innerWidth,\n innerHeight: window.innerHeight,\n devicePixelRatio: window.devicePixelRatio,\n userAgent: navigator.userAgent\n };\n if (sdkInsetsError !== undefined) result.sdkInsetsError = sdkInsetsError;\n return JSON.stringify(result);\n})()\n`.trim();\n\n/**\n * Where the SDK insets came from. `null` when the lookup failed (in which case\n * `sdkInsetsError` is populated).\n *\n * - `'window.__sdk'` — real-device dogfood bundle (relay env).\n * - `'window.__ait'` — devtools mock state (mock env).\n * - `null` — both paths absent or threw.\n */\nexport type SdkInsetsSource = 'window.__sdk' | 'window.__ait' | null;\n\n/**\n * Normalized result returned by `measure_safe_area`.\n *\n * All inset values are in CSS pixels as reported by the page context.\n * `userAgent` is included for device identification; it never contains\n * authentication secrets or session tokens.\n */\nexport interface SafeAreaMeasurement {\n /**\n * MCP environment this measurement was taken in — `'mock'` for the dev\n * browser panel, `'relay'` for the real-device WebView. Set by the caller\n * (`measureSafeArea`) from the env detection SSoT (`getEnvironment`).\n */\n source: McpEnvironment;\n /**\n * `env(safe-area-inset-*)` values read via `getComputedStyle` on the page.\n * On iOS inside the Toss host WebView this is typically all-zero because the\n * WebView viewport is placed below the physical notch by the host app.\n */\n cssEnv: { top: number; right: number; bottom: number; left: number };\n /**\n * SDK insets from one of three paths (in priority order):\n * - `window.__sdk.SafeAreaInsets.get()` (relay, dogfood bundle)\n * - `window.__sdk.getSafeAreaInsets()` (relay, deprecated)\n * - `window.__ait.state.safeAreaInsets` (mock, devtools panel state)\n *\n * `null` when all paths fail — see `sdkInsetsError` for the reason.\n * In the Toss host WebView `top` is the nav bar height and `bottom` is the\n * home-indicator height.\n */\n sdkInsets: { top: number; right: number; bottom: number; left: number } | null;\n /**\n * Which path resolved `sdkInsets` — useful for diagnosis of fidelity gaps\n * between mock and relay. `null` when `sdkInsets` is `null`.\n */\n sdkInsetsSource: SdkInsetsSource;\n /**\n * Populated when the SDK inset lookup failed (all paths absent or threw).\n * `undefined` when `sdkInsets` is non-null (i.e. the lookup succeeded).\n *\n * Example values:\n * - `\"neither window.__sdk (relay) nor window.__ait (mock) available\"`\n * - `\"neither SafeAreaInsets.get nor getSafeAreaInsets found on window.__sdk\"`\n * - `\"window.__ait.state.safeAreaInsets is missing or malformed\"`\n * - `\"TypeError: ...\"`\n */\n sdkInsetsError?: string;\n /**\n * Height of the `.ait-navbar` element (px) if present, else `null`.\n * The SDK does not expose navBar height as a standalone API; this DOM\n * measurement is used to cross-validate `sdkInsets.top`.\n */\n navBarHeight: number | null;\n /**\n * Describes where `navBarHeight` came from:\n * - `\"dom-.ait-navbar\"` — read from the `.ait-navbar` element's bounding rect.\n * - `\"not-exposed-by-sdk\"` — the SDK has no standalone navBar height API and\n * no `.ait-navbar` element was found in the DOM.\n */\n navBarHeightSource: string;\n /** CSS viewport width (`window.innerWidth`). */\n innerWidth: number;\n /** CSS viewport height (`window.innerHeight`). */\n innerHeight: number;\n /**\n * Device pixel ratio (`window.devicePixelRatio`).\n * Note: `window.devicePixelRatio` is read-only in the browser, so devtools\n * cannot emulate DPR locally — this is the ground-truth value from the device.\n */\n devicePixelRatio: number;\n /**\n * `navigator.userAgent` string for device identification.\n * Does not contain authentication secrets.\n */\n userAgent: string;\n}\n\n/**\n * Parses a raw `Runtime.evaluate` result value into a `SafeAreaMeasurement`.\n * The probe returns a JSON string (because `returnByValue:true` with a plain\n * object works unreliably across Chii relay versions — stringifying is safer).\n *\n * `source` is supplied by the caller (`measureSafeArea`) from the env SSoT.\n *\n * Throws if the result is missing, contains an exception, or cannot be parsed.\n */\nexport function normalizeSafeAreaResult(\n rawValue: unknown,\n source: McpEnvironment,\n): SafeAreaMeasurement {\n if (typeof rawValue !== 'string') {\n throw new Error(\n `measure_safe_area: probe returned unexpected type \"${typeof rawValue}\" — expected JSON string`,\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawValue);\n } catch {\n throw new Error(`measure_safe_area: probe returned non-JSON string: ${rawValue}`);\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('measure_safe_area: parsed result is not an object');\n }\n const obj = parsed as Record<string, unknown>;\n\n function requireInsets(\n key: string,\n ): { top: number; right: number; bottom: number; left: number } | null {\n const v = obj[key];\n if (v === null || v === undefined) return null;\n if (typeof v !== 'object') return null;\n const r = v as Record<string, unknown>;\n return {\n top: typeof r.top === 'number' ? r.top : 0,\n right: typeof r.right === 'number' ? r.right : 0,\n bottom: typeof r.bottom === 'number' ? r.bottom : 0,\n left: typeof r.left === 'number' ? r.left : 0,\n };\n }\n\n const cssEnv = requireInsets('cssEnv') ?? { top: 0, right: 0, bottom: 0, left: 0 };\n const sdkInsets = requireInsets('sdkInsets');\n const sdkInsetsSource: SdkInsetsSource =\n obj.sdkInsetsSource === 'window.__sdk' || obj.sdkInsetsSource === 'window.__ait'\n ? obj.sdkInsetsSource\n : null;\n const sdkInsetsError = typeof obj.sdkInsetsError === 'string' ? obj.sdkInsetsError : undefined;\n const navBarHeight = typeof obj.navBarHeight === 'number' ? obj.navBarHeight : null;\n const navBarHeightSource =\n typeof obj.navBarHeightSource === 'string' ? obj.navBarHeightSource : 'not-exposed-by-sdk';\n const innerWidth = typeof obj.innerWidth === 'number' ? obj.innerWidth : 0;\n const innerHeight = typeof obj.innerHeight === 'number' ? obj.innerHeight : 0;\n const devicePixelRatio = typeof obj.devicePixelRatio === 'number' ? obj.devicePixelRatio : 1;\n const userAgent = typeof obj.userAgent === 'string' ? obj.userAgent : '';\n\n return {\n source,\n cssEnv,\n sdkInsets,\n sdkInsetsSource,\n ...(sdkInsetsError !== undefined ? { sdkInsetsError } : {}),\n navBarHeight,\n navBarHeightSource,\n innerWidth,\n innerHeight,\n devicePixelRatio,\n userAgent,\n };\n}\n\n/**\n * Runs the safe-area probe on the attached page and returns a normalized\n * `SafeAreaMeasurement`. Read-only — does not mutate page state.\n *\n * `source` is supplied by the caller from the env detection SSoT (see\n * `src/mcp/environment.ts`). The same `Runtime.evaluate` call runs in both\n * envs — the probe expression tries `window.__sdk` first (relay) then\n * `window.__ait` (mock), so mock fidelity is enforced by the panel's\n * `applyViewport`/`computeSafeAreaInsets` keeping `__ait.state.safeAreaInsets`\n * correct (RFC #277 Tier C parity, #275 model).\n *\n * Throws on CDP error, probe exception, or result parse failure.\n */\nexport async function measureSafeArea(\n connection: CdpConnection,\n source: McpEnvironment,\n): Promise<SafeAreaMeasurement> {\n const result = await connection.send('Runtime.evaluate', {\n expression: SAFE_AREA_PROBE_EXPRESSION,\n returnByValue: true,\n awaitPromise: false,\n });\n if (result.exceptionDetails) {\n const msg =\n result.exceptionDetails.exception?.description ??\n result.exceptionDetails.text ??\n 'Runtime.evaluate threw an exception';\n throw new Error(`measure_safe_area: probe threw — ${msg}`);\n }\n return normalizeSafeAreaResult(result.result.value, source);\n}\n\n/* -------------------------------------------------------------------------- */\n/* evaluate — arbitrary JS via Runtime.evaluate */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Result returned by the `evaluate` tool.\n *\n * `value` holds the `returnByValue` result from CDP — it may be any\n * JSON-serialisable type. Treat it as opaque for logging purposes (it could\n * carry sensitive data from the page context).\n *\n * SECRET-HANDLING: do NOT write `value` to any log or stderr — return it to\n * the agent via the tool result only.\n */\nexport interface EvaluateResult {\n /** The evaluated result value (`returnByValue: true`). */\n value: unknown;\n /** CDP type string of the result (e.g. \"string\", \"number\", \"object\"). */\n type: string;\n}\n\n/**\n * Evaluates an arbitrary JS expression on the attached page via\n * `Runtime.evaluate`. NOT read-only — the expression may have side effects.\n *\n * Throws if the evaluation produced a CDP exception.\n *\n * SECRET-HANDLING: expression and result value are NOT written to any log.\n */\nexport async function evaluate(\n connection: CdpConnection,\n expression: string,\n): Promise<EvaluateResult> {\n const result = await connection.send('Runtime.evaluate', {\n expression,\n returnByValue: true,\n awaitPromise: false,\n });\n if (result.exceptionDetails) {\n // Surface only the engine error string — never the expression or result value.\n const msg =\n result.exceptionDetails.exception?.description ??\n result.exceptionDetails.text ??\n 'Runtime.evaluate threw an exception';\n throw new Error(`evaluate failed: ${msg}`);\n }\n return { value: result.result.value, type: result.result.type };\n}\n\n/* -------------------------------------------------------------------------- */\n/* call_sdk — window.__sdkCall bridge via Runtime.evaluate */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Result returned by the `call_sdk` tool.\n * The bridge call wraps success/failure in a JSON envelope so cross-Chii\n * stringification is reliable (same approach as `measure_safe_area`).\n *\n * `recentException` is populated when a `Runtime.exceptionThrown` event was\n * observed within the heuristic triage window [callStart-50ms, callEnd+200ms].\n * This helps correlate an SDK throw with the bridge result, especially when\n * the SDK throws synchronously before the promise resolves.\n */\nexport type CallSdkResult =\n | { ok: true; value: unknown; recentException?: BufferedException }\n | { ok: false; error: string; recentException?: BufferedException };\n\n/**\n * Builds the Runtime.evaluate expression that calls `window.__sdkCall` with\n * the given method name and args, awaits the promise, and returns a JSON\n * envelope `{ok, value/error}` as a string.\n *\n * Name and args are embedded via `JSON.stringify` so they are safely escaped.\n * The expression checks for `window.__sdkCall` and returns a clear error if\n * it is absent (non-dogfood bundle).\n *\n * SECRET-HANDLING: the expression is built here and MUST NOT be written to\n * any log or stderr by the caller.\n */\nexport function buildCallSdkExpression(name: string, args: unknown[]): string {\n const safeName = JSON.stringify(name);\n const safeArgs = JSON.stringify(args);\n return (\n `(async () => {` +\n ` if (typeof window.__sdkCall !== 'function') {` +\n ` return JSON.stringify({ok:false,error:'window.__sdkCall is not available — is this a dogfood (__DEBUG_BUILD__) bundle?'});` +\n ` }` +\n ` try {` +\n ` const r = await window.__sdkCall(${safeName}, ...${safeArgs});` +\n ` return JSON.stringify({ok:true,value:r});` +\n ` } catch(e) {` +\n ` return JSON.stringify({ok:false,error:String(e && e.message || e)});` +\n ` }` +\n `})()`\n );\n}\n\n/**\n * Parses the JSON envelope string returned by the `call_sdk` expression.\n * Returns a typed `CallSdkResult`.\n *\n * Throws only on parse failure (not on ok:false — that is a normal result).\n */\nexport function normalizeCallSdkResult(rawValue: unknown): CallSdkResult {\n if (typeof rawValue !== 'string') {\n throw new Error(\n `call_sdk: bridge returned unexpected type \"${typeof rawValue}\" — expected JSON string`,\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawValue);\n } catch {\n // Do NOT include rawValue in the error message — it could contain secrets.\n throw new Error('call_sdk: bridge returned non-JSON string');\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('call_sdk: parsed result is not an object');\n }\n const obj = parsed as Record<string, unknown>;\n if (obj.ok === true) {\n return { ok: true, value: obj.value };\n }\n if (obj.ok === false) {\n return { ok: false, error: typeof obj.error === 'string' ? obj.error : String(obj.error) };\n }\n throw new Error('call_sdk: bridge result missing \"ok\" field');\n}\n\n/**\n * Looks up the most recent exception from the buffer that falls within the\n * triage window [windowStart, windowEnd]. Returns `undefined` if none found.\n *\n * The heuristic window is:\n * - windowStart = callStart - 50ms (catch sync throws before bridge fires)\n * - windowEnd = callEnd + 200ms (catch async throws resolved soon after)\n *\n * Only the most recent exception within the window is returned (the one most\n * likely to be causally related to the SDK call).\n */\nfunction findRecentException(\n connection: CdpConnection,\n windowStart: number,\n windowEnd: number,\n): BufferedException | undefined {\n const events = connection.getBufferedEvents('Runtime.exceptionThrown');\n // Scan from the tail (most recent) to find the closest-in-time exception.\n for (let i = events.length - 1; i >= 0; i--) {\n const e = events[i];\n if (e.timestamp >= windowStart && e.timestamp <= windowEnd) {\n return normalizeException(e);\n }\n }\n return undefined;\n}\n\n/**\n * Calls a dogfood SDK method via `window.__sdkCall` on the attached page.\n * NOT read-only — SDK calls may have side effects.\n *\n * On env 2/3 (real device relay) this hits the real SDK; on env 1 (local\n * mock) it hits the mock SDK.\n *\n * 인자 시그니처 검증: 등록된 메서드는 bridge 호출 전에 인자를 검증하고, mismatch면\n * `{ok:false, error}` MCP 오류 결과를 반환한다(bridge에 도달하지 않음).\n * 미등록 메서드는 passthrough + stderr 경고 1회.\n *\n * Throws on CDP error or result parse failure. Returns `{ok:false, error}`\n * for bridge-level errors (method not found, SDK threw, bridge absent) or\n * argument schema violations.\n *\n * If a `Runtime.exceptionThrown` event was observed within the triage window\n * [callStart-50ms, callEnd+200ms], the result includes `recentException` for\n * crash triage. This window is a heuristic — it catches the common case of an\n * SDK throw immediately before/after the bridge resolves.\n *\n * SECRET-HANDLING: name, args, and the result value are NOT written to any log.\n */\nexport async function callSdk(\n connection: CdpConnection,\n name: string,\n args: unknown[],\n): Promise<CallSdkResult> {\n // 인자 시그니처 검증 — bridge 호출 전에 reject하여 native crash를 예방한다.\n const signature = lookupSignature(name);\n if (signature !== undefined) {\n const validation = signature.validateArgs(args);\n if (!validation.ok) {\n // isError: true 형태로 반환 — bridge에 도달하지 않음.\n const errorText =\n `call_sdk(\"${name}\") 인자 시그니처 오류.\\n` +\n `받음: ${validation.received}\\n` +\n `기대: ${validation.expected}\\n` +\n `올바른 예시: ${signature.example}`;\n return { ok: false, error: errorText };\n }\n } else {\n // 미등록 메서드 — passthrough하지만 stderr에 경고 1회.\n warnPassthrough(name);\n }\n\n const callStart = Date.now();\n const expression = buildCallSdkExpression(name, args);\n const result = await connection.send('Runtime.evaluate', {\n expression,\n returnByValue: true,\n awaitPromise: true,\n });\n const callEnd = Date.now();\n\n if (result.exceptionDetails) {\n // Surface only the engine error string — never name, args, or result value.\n const msg =\n result.exceptionDetails.exception?.description ??\n result.exceptionDetails.text ??\n 'Runtime.evaluate threw an exception';\n throw new Error(`call_sdk threw: ${msg}`);\n }\n\n const sdkResult = normalizeCallSdkResult(result.result.value);\n\n // Triage window: [callStart - 50ms, callEnd + 200ms].\n // -50ms: catches sync throws that fire just before the bridge call is sent.\n // +200ms: catches async throws resolved shortly after the bridge returns.\n const recentException = findRecentException(connection, callStart - 50, callEnd + 200);\n\n if (recentException !== undefined) {\n return { ...sdkResult, recentException };\n }\n return sdkResult;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Phase 3 — AIT.* domain (CDP can't cover these) */\n/* -------------------------------------------------------------------------- */\n\n/** Set of tool names served by the AIT source rather than the CDP connection. */\nconst AIT_TOOL_NAMES = new Set<string>([\n 'AIT.getSdkCallHistory',\n 'AIT.getMockState',\n 'AIT.getOperationalEnvironment',\n]);\n\n/** True for the Phase 3 AIT.* tools (served by an `AitSource`, not CDP). */\nexport function isAitToolName(name: string): boolean {\n return AIT_TOOL_NAMES.has(name);\n}\n\n/** Returns the recent SDK call trace (`AIT.getSdkCallHistory`). */\nexport function getSdkCallHistory(source: AitSource): Promise<AitSdkCallHistory> {\n return source.get('AIT.getSdkCallHistory');\n}\n\n/** Returns the devtools mock-state snapshot (`AIT.getMockState`). */\nexport function getMockState(source: AitSource): Promise<AitMockState> {\n return source.get('AIT.getMockState');\n}\n\n/** Returns the operational environment + SDK version (`AIT.getOperationalEnvironment`). */\nexport function getOperationalEnvironment(source: AitSource): Promise<AitOperationalEnvironment> {\n return source.get('AIT.getOperationalEnvironment');\n}\n","/**\n * @ait-co/devtools dev-mode MCP server (stdio).\n *\n * Exposes the live browser mock state from a running Vite dev server to AI\n * coding agents via the Model Context Protocol (MCP).\n *\n * Architecture:\n * Browser (aitState) → Vite dev server endpoint (/api/ait-devtools/state)\n * ← HTTP GET ← this stdio MCP server ← AI agent\n *\n * The Vite endpoint is registered by the unplugin when `mcp: true` is set in\n * the plugin options (see `src/unplugin/index.ts`).\n *\n * Phase 3 tool-surface alignment: dev mode and debug mode now expose the same\n * `AIT.*` tools (`AIT.getMockState`, `AIT.getOperationalEnvironment`,\n * `AIT.getSdkCallHistory`). In dev mode they are backed by the HTTP mock-state\n * endpoint (see `HttpAitSource`); in debug mode by the Chii channel. So an AI\n * sees a coherent tool whether attached to a phone (debug) or a dev browser\n * (dev). `devtools_get_mock_state` (the original devtools#130 name) is kept as a\n * backward-compatible alias of `AIT.getMockState`.\n *\n * This module is reached via the `devtools-mcp --mode=dev` CLI entry (see\n * `cli.ts`); the default (no flag) bin mode is the debug-mode CDP/Chii server.\n *\n * Usage (in your MCP client config, e.g. Claude Desktop):\n * {\n * \"mcpServers\": {\n * \"ait-devtools\": {\n * \"command\": \"pnpm\",\n * \"args\": [\"exec\", \"devtools-mcp\", \"--mode=dev\"],\n * \"env\": { \"AIT_DEVTOOLS_URL\": \"http://localhost:5173\" }\n * }\n * }\n * }\n */\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport { HttpAitSource } from './ait-http-source.js';\nimport type { AitSource } from './ait-source.js';\nimport {\n getMockState,\n getOperationalEnvironment,\n getSdkCallHistory,\n isAitToolName,\n type ToolAvailability,\n} from './tools.js';\n\n/**\n * Tool descriptors served by the dev-mode server.\n *\n * All dev-mode tools are Tier C (both envs) per RFC #277 — the dev-mode server\n * itself is the mock-side embodiment of those Tier C tools. `availableIn` is\n * declared so the surface stays consistent with the debug-mode registry.\n */\nconst DEV_TOOL_DEFINITIONS = [\n {\n name: 'AIT.getMockState',\n description:\n 'Returns the devtools mock state snapshot (window.__ait) from the running browser session — ' +\n 'environment, permissions, location, auth, network, IAP, and more. Read-only. ' +\n 'Requires the Vite dev server running with the @ait-co/devtools unplugin option `mcp: true`. ' +\n 'Same tool as in debug mode, where the in-app side reports it over the AIT domain.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'AIT.getOperationalEnvironment',\n description:\n 'Returns the operational environment + SDK/app version derived from the dev mock state. ' +\n 'Read-only.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'AIT.getSdkCallHistory',\n description:\n 'Returns the SDK call trace. In dev mode the HTTP mock-state endpoint records no trace, so ' +\n 'this returns an empty list; in debug mode it is populated over the AIT domain. Read-only.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n {\n name: 'devtools_get_mock_state',\n description:\n 'Backward-compatible alias of AIT.getMockState (the original devtools#130 name). Returns the ' +\n 'current AIT DevTools mock state snapshot. Read-only. Prefer AIT.getMockState in new configs.',\n inputSchema: { type: 'object', properties: {}, required: [] },\n availableIn: 'both' as ToolAvailability,\n },\n] as const;\n\nconst DEV_TOOL_NAMES = new Set<string>(DEV_TOOL_DEFINITIONS.map((t) => t.name));\n\nexport interface CreateDevServerDeps {\n /** AIT source for the dev tools. Defaults to an HTTP source over the dev server. */\n aitSource?: AitSource;\n}\n\n/** Builds the dev-mode MCP server (does not connect a transport). */\nexport function createDevServer(deps: CreateDevServerDeps = {}): Server {\n const devtoolsUrl = process.env.AIT_DEVTOOLS_URL ?? 'http://localhost:5173';\n const stateEndpoint = `${devtoolsUrl}/api/ait-devtools/state`;\n const aitSource = deps.aitSource ?? new HttpAitSource({ stateEndpoint });\n\n const server = new Server(\n { name: 'ait-devtools', version: __VERSION__ },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: DEV_TOOL_DEFINITIONS.map((tool) => ({ ...tool })),\n }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const name = request.params.name;\n if (!DEV_TOOL_NAMES.has(name)) {\n return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n\n try {\n // `devtools_get_mock_state` is an alias of `AIT.getMockState`.\n const effective = name === 'devtools_get_mock_state' ? 'AIT.getMockState' : name;\n if (!isAitToolName(effective)) {\n return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n switch (effective) {\n case 'AIT.getMockState':\n return jsonResult(await getMockState(aitSource));\n case 'AIT.getOperationalEnvironment':\n return jsonResult(await getOperationalEnvironment(aitSource));\n case 'AIT.getSdkCallHistory':\n return jsonResult(await getSdkCallHistory(aitSource));\n default:\n return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return {\n content: [\n {\n type: 'text',\n text:\n `${message}\\n` +\n 'Is the Vite dev server running with the @ait-co/devtools unplugin option `mcp: true`? ' +\n 'Is AIT_DEVTOOLS_URL set correctly?',\n },\n ],\n isError: true,\n };\n }\n });\n\n return server;\n}\n\nfunction jsonResult(value: unknown) {\n return { content: [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }] };\n}\n\n/** Builds the dev-mode server and connects it over stdio. */\nexport async function runDevServer(): Promise<void> {\n const server = createDevServer();\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n"],"mappings":";;;;;AA0CA,SAASA,WAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU;;AAGhD,IAAa,gBAAb,MAAgD;CAC9C;CACA;CAEA,YAAY,SAA+B;AACzC,OAAK,gBAAgB,QAAQ;AAC7B,OAAK,YAAY,QAAQ,eAAe,QAAQ,MAAM,IAAI;;CAG5D,MAAc,aAAoC;EAChD,MAAM,MAAM,MAAM,KAAK,UAAU,KAAK,cAAc;AACpD,MAAI,CAAC,IAAI,GACP,OAAM,IAAI,MACR,mCAAmC,KAAK,cAAc,SAAS,IAAI,OAAO,GAAG,IAAI,WAAW,kGAE7F;EAEH,MAAM,OAAO,MAAM,IAAI,MAAM;AAC7B,SAAOA,WAAS,KAAK,GAAG,OAAO,EAAE;;CAGnC,MAAM,IAA6B,QAAqC;AACtE,UAAQ,QAAR;GACE,KAAK,mBAEH,QADc,MAAM,KAAK,YAAY;GAGvC,KAAK,iCAAiC;IACpC,MAAM,QAAQ,MAAM,KAAK,YAAY;AAIrC,WAD0C;KAAE,aAFxB,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc;KAEvB,YADtC,OAAO,MAAM,eAAe,WAAW,MAAM,aAAa;KACR;;GAGvE,KAAK,yBAAyB;IAI5B,MAAM,OADQ,MAAM,KAAK,YAAY,EACnB;AAGlB,WADkC,EAAE,OADtB,MAAM,QAAQ,IAAI,GAAI,MAAqC,EAAE,EAChC;;GAG7C,QACE,OAAM,IAAI,MAAM,uBAAuB,OAAO,OAAO,GAAG;;;;;;AC/ChE,SAAS,SAAS,GAA0C;AAC1D,QAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,M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AA8B;CAClD,MAAM,SAAS,iBAAiB;CAChC,MAAM,YAAY,IAAI,sBAAsB;AAC5C,OAAM,OAAO,QAAQ,UAAU"}
@@ -252,8 +252,6 @@ type ViewportOrientation = 'auto' | 'portrait' | 'landscape';
252
252
  * SDK가 받을 수 있는 값과 일치하므로 portrait/landscape만 허용.
253
253
  */
254
254
  type AppOrientation = 'portrait' | 'landscape' | null;
255
- /** Landscape 시 노치/Dynamic Island가 어느 쪽으로 가는지. iOS 기본은 landscape-left. */
256
- type LandscapeSide = 'left' | 'right';
257
255
  /**
258
256
  * Apps in Toss host nav bar 변형. SDK `webViewProps.type`과 의미 일치.
259
257
  * - `partner` (기본): 흰 배경, 뒤로가기 + 앱 아이콘/이름 + ⋯ + ×.
@@ -269,8 +267,6 @@ interface ViewportState {
269
267
  * `orientation === 'auto'`일 때 실제 화면 방향 결정에 쓰인다. 초기값 `null`.
270
268
  */
271
269
  appOrientation: AppOrientation;
272
- /** Landscape 시 노치/Dynamic Island가 어느 쪽으로 갈지. */
273
- landscapeSide: LandscapeSide;
274
270
  customWidth: number;
275
271
  customHeight: number;
276
272
  frame: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/mock/ads/index.ts","../../src/mock/analytics/index.ts","../../src/mock/auth/index.ts","../../src/mock/device/_helpers.ts","../../src/mock/types.ts","../../src/mock/device/camera.ts","../../src/mock/device/clipboard.ts","../../src/mock/device/contacts.ts","../../src/mock/device/haptic.ts","../../src/mock/device/location.ts","../../src/mock/device/pdf.ts","../../src/mock/device/storage.ts","../../src/mock/game/index.ts","../../src/mock/iap/index.ts","../../src/mock/navigation/index.ts","../../src/mock/notification.ts","../../src/mock/partner/index.ts","../../src/mock/permissions.ts","../../src/mcp/ait-source.ts","../../src/mock/state.ts","../../src/mock/presets.ts","../../src/mock/preset-store.ts"],"mappings":";cAyCa,WAAA;;cAMK,IAAA;MAAQ,IAAA;MAAc,IAAA;IAAA;cACtB,KAAA,EAAO,K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AAA,GAAO,OAAA,CAAQ,gBAAA;EACf,GAAA;IAAQ,UAAA,GAAa,gBAAA;EAAA;EACrB,GAAA,GAAM,OAAA,CAAQ,gBAAA;EACd,OAAA,GAAU,OAAA,CAAQ,gBAAA;AAAA;AAAA,UAGH,UAAA;EACf,EAAA;EACA,KAAA;EACA,WAAA;EACA,KAAA,EAAO,eAAA;AAAA;AAAA,cAGI,cAAA,WAAyB,UAAA;ApBiEtC;;;;;AAAA,iBoBoDgB,WAAA,CAAY,KAAA,EAAO,eAAA;;;;;;;;iBAwCnB,aAAA,CAAc,QAAA,EAAU,gBAAA,EAAkB,MAAA,EAAQ,eAAA;;;;iBAyClD,mBAAA,CAAoB,QAAA,EAAU,gBAAA,GAAmB,eAAA;;;iBC1LjD,eAAA,CAAA,GAAmB,UAAA;;;;;;;;;;iBAwBnB,cAAA,CACd,KAAA,UACA,KAAA,EAAO,eAAA,EACP,WAAA,YACC,UAAA;AAAA,iBAkBa,gBAAA,CAAiB,EAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/mock/ads/index.ts","../../src/mock/analytics/index.ts","../../src/mock/auth/index.ts","../../src/mock/device/_helpers.ts","../../src/mock/types.ts","../../src/mock/device/camera.ts","../../src/mock/device/clipboard.ts","../../src/mock/device/contacts.ts","../../src/mock/device/haptic.ts","../../src/mock/device/location.ts","../../src/mock/device/pdf.ts","../../src/mock/device/storage.ts","../../src/mock/game/index.ts","../../src/mock/iap/index.ts","../../src/mock/navigation/index.ts","../../src/mock/notification.ts","../../src/mock/partner/index.ts","../../src/mock/permissions.ts","../../src/mcp/ait-source.ts","../../src/mock/state.ts","../../src/mock/presets.ts","../../src/mock/preset-store.ts"],"mappings":";cAyCa,WAAA;;cAMK,IAAA;MAAQ,IAAA;MAAc,IAAA;IAAA;cACtB,KAAA,EAAO,KAAA;;MACL,SAAA;IAAA;EAAA;;;;cAoBF,IAAA;MAAQ,IAAA;MAAc,IAAA;IAAA;cACtB,KAAA,EAAO,KA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,gBAAA;AAAA;AAAA,UAGH,UAAA;EACf,EAAA;EACA,KAAA;EACA,WAAA;EACA,KAAA,EAAO,eAAA;AAAA;AAAA,cAGI,cAAA,WAAyB,UAAA;ApBiEtC;;;;;AAAA,iBoBoDgB,WAAA,CAAY,KAAA,EAAO,eAAA;;;;;;;;iBAwCnB,aAAA,CAAc,QAAA,EAAU,gBAAA,EAAkB,MAAA,EAAQ,eAAA;;;;iBAyClD,mBAAA,CAAoB,QAAA,EAAU,gBAAA,GAAmB,eAAA;;;iBC1LjD,eAAA,CAAA,GAAmB,UAAA;;;;;;;;;;iBAwBnB,cAAA,CACd,KAAA,UACA,KAAA,EAAO,eAAA,EACP,WAAA,YACC,UAAA;AAAA,iBAkBa,gBAAA,CAAiB,EAAA"}
@@ -107,7 +107,6 @@ const DEFAULT_STATE = {
107
107
  preset: "none",
108
108
  orientation: "auto",
109
109
  appOrientation: null,
110
- landscapeSide: "left",
111
110
  customWidth: 402,
112
111
  customHeight: 874,
113
112
  frame: false,