@ait-co/devtools 0.1.117 → 0.1.119
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.
- package/dist/attach-orchestrator-CFotueL3.js +1749 -0
- package/dist/attach-orchestrator-CFotueL3.js.map +1 -0
- package/dist/attach-orchestrator-CII9Gl5m.js +2797 -0
- package/dist/attach-orchestrator-CII9Gl5m.js.map +1 -0
- package/dist/attach-orchestrator-C_6xb_L5.js +3 -0
- package/dist/attach-orchestrator-DEJfLm7V.js +1749 -0
- package/dist/attach-orchestrator-DEJfLm7V.js.map +1 -0
- package/dist/{cli-CvUNQKqw.js → attach-orchestrator-qFEMBUwb.js} +3 -805
- package/dist/attach-orchestrator-qFEMBUwb.js.map +1 -0
- package/dist/{bundle-KFs4t-wc.d.ts → bundle-CA1TCXED.d.ts} +1 -1
- package/dist/bundle-CA1TCXED.d.ts.map +1 -0
- package/dist/capture-BmK_cBqQ.d.ts +58 -0
- package/dist/capture-BmK_cBqQ.d.ts.map +1 -0
- package/dist/{cdp-connection-C0AP0tH2.d.ts → cdp-connection-DB2zgthr.d.ts} +1 -1
- package/dist/{cdp-connection-C0AP0tH2.d.ts.map → cdp-connection-DB2zgthr.d.ts.map} +1 -1
- package/dist/cell-BJiaGlVu.js +3 -0
- package/dist/cell-BPWZUm_X.js +85 -0
- package/dist/cell-BPWZUm_X.js.map +1 -0
- package/dist/cell-Cv3e_qwn.js +84 -0
- package/dist/cell-Cv3e_qwn.js.map +1 -0
- package/dist/cell-bLwQ4gTq.js +85 -0
- package/dist/cell-bLwQ4gTq.js.map +1 -0
- package/dist/cell-nrWFeqvG.js +84 -0
- package/dist/cell-nrWFeqvG.js.map +1 -0
- package/dist/cli-RhzASQef.js +1057 -0
- package/dist/cli-RhzASQef.js.map +1 -0
- package/dist/debug-server-BhHVy3XT.js +1191 -0
- package/dist/debug-server-BhHVy3XT.js.map +1 -0
- package/dist/{debug-server-jrI9U_f4.js → debug-server-Bi6jLuY6.js} +467 -2989
- package/dist/debug-server-Bi6jLuY6.js.map +1 -0
- package/dist/debug-server-Buc8yoa7.js +1909 -0
- package/dist/debug-server-Buc8yoa7.js.map +1 -0
- package/dist/{debug-server-BvrESnaV.js → debug-server-C_5ag9jj.js} +5 -3
- package/dist/debug-server-C_5ag9jj.js.map +1 -0
- package/dist/mcp/cli.js +3 -2
- package/dist/mcp/cli.js.map +1 -1
- package/dist/mcp/server.js +1 -1
- package/dist/panel/index.js +1 -1
- package/dist/{pool-htlVnEFl.d.ts → pool-U9FrxEuR.d.ts} +5 -5
- package/dist/{pool-htlVnEFl.d.ts.map → pool-U9FrxEuR.d.ts.map} +1 -1
- package/dist/relay-factory-DVI7TrX4.js +69 -0
- package/dist/relay-factory-DVI7TrX4.js.map +1 -0
- package/dist/relay-secret-store-BcVrWwTq.js +153 -0
- package/dist/relay-secret-store-BcVrWwTq.js.map +1 -0
- package/dist/{relay-secret-store-BHcOmaNK.js → relay-secret-store-BlFEhqwb.js} +1 -1
- package/dist/{relay-secret-store-CmqchhR5.js → relay-secret-store-CFc9n0OA.js} +1 -1
- package/dist/{relay-secret-store-CmqchhR5.js.map → relay-secret-store-CFc9n0OA.js.map} +1 -1
- package/dist/{relay-secret-store-CkA7KNUb.js → relay-secret-store-CmDDfZMh.js} +2 -2
- package/dist/{relay-secret-store-CkA7KNUb.js.map → relay-secret-store-CmDDfZMh.js.map} +1 -1
- package/dist/relay-secret-store-DNPJKHNs.js +153 -0
- package/dist/relay-secret-store-DNPJKHNs.js.map +1 -0
- package/dist/relay-url-store-CdA58fgw.js +122 -0
- package/dist/relay-url-store-CdA58fgw.js.map +1 -0
- package/dist/{relay-url-store-C0qukm3R.js → relay-url-store-CnL2zwbH.js} +2 -2
- package/dist/{relay-url-store-C0qukm3R.js.map → relay-url-store-CnL2zwbH.js.map} +1 -1
- package/dist/{relay-url-store-NDtEcOE-.js → relay-url-store-DGQ-HPQC.js} +2 -2
- package/dist/{relay-url-store-NDtEcOE-.js.map → relay-url-store-DGQ-HPQC.js.map} +1 -1
- package/dist/relay-url-store-Dv5HSzwb.js +122 -0
- package/dist/relay-url-store-Dv5HSzwb.js.map +1 -0
- package/dist/{relay-worker-DWW4vZxU.d.ts → relay-worker-D-3aAyDO.d.ts} +28 -4
- package/dist/relay-worker-D-3aAyDO.d.ts.map +1 -0
- package/dist/{runtime-BU-iMHz6.d.ts → runtime-D57Rtnsd.d.ts} +1 -1
- package/dist/{runtime-BU-iMHz6.d.ts.map → runtime-D57Rtnsd.d.ts.map} +1 -1
- package/dist/test-runner/bundle.d.ts +1 -1
- package/dist/test-runner/bundle.js +45 -27
- package/dist/test-runner/bundle.js.map +1 -1
- package/dist/test-runner/capture.d.ts +2 -0
- package/dist/test-runner/capture.js +44 -0
- package/dist/test-runner/capture.js.map +1 -0
- package/dist/test-runner/cli.d.ts +85 -12
- package/dist/test-runner/cli.d.ts.map +1 -1
- package/dist/test-runner/cli.js +2 -2
- package/dist/test-runner/config.d.ts +76 -2
- package/dist/test-runner/config.d.ts.map +1 -1
- package/dist/test-runner/config.js +4 -2
- package/dist/test-runner/config.js.map +1 -1
- package/dist/test-runner/pool.d.ts +1 -1
- package/dist/test-runner/relay-factory.d.ts +11136 -0
- package/dist/test-runner/relay-factory.d.ts.map +1 -0
- package/dist/test-runner/relay-factory.js +69 -0
- package/dist/test-runner/relay-factory.js.map +1 -0
- package/dist/test-runner/relay-worker.d.ts +1 -1
- package/dist/test-runner/relay-worker.js +66 -20
- package/dist/test-runner/relay-worker.js.map +1 -1
- package/dist/test-runner/report.d.ts +106 -0
- package/dist/test-runner/report.d.ts.map +1 -0
- package/dist/test-runner/report.js +139 -0
- package/dist/test-runner/report.js.map +1 -0
- package/dist/test-runner/rpc.d.ts +2 -2
- package/dist/test-runner/runtime.d.ts +1 -1
- package/dist/test-runner/task-graph.d.ts +1 -1
- package/dist/{totp-D70zD5tJ.js → totp-0bvlo9Yb.js} +1 -1
- package/dist/{totp-D70zD5tJ.js.map → totp-0bvlo9Yb.js.map} +1 -1
- package/dist/totp-DfekTBk3.js +211 -0
- package/dist/totp-DfekTBk3.js.map +1 -0
- package/dist/totp-zGIlDsZS.js +3 -0
- package/package.json +1 -1
- package/dist/bundle-KFs4t-wc.d.ts.map +0 -1
- package/dist/cli-CvUNQKqw.js.map +0 -1
- package/dist/debug-server-BvrESnaV.js.map +0 -1
- package/dist/debug-server-jrI9U_f4.js.map +0 -1
- package/dist/relay-worker-DWW4vZxU.d.ts.map +0 -1
- package/dist/totp-D104cJQN.js +0 -3
|
@@ -0,0 +1,1749 @@
|
|
|
1
|
+
import { r as generateTotp } from "./totp-DfekTBk3.js";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { Tunnel, bin, install } from "cloudflared";
|
|
4
|
+
//#region src/mcp/deeplink.ts
|
|
5
|
+
/**
|
|
6
|
+
* URL of the AITC Sandbox launcher PWA.
|
|
7
|
+
*
|
|
8
|
+
* Declared here (not imported from `src/unplugin/tunnel.ts`) to respect the
|
|
9
|
+
* mcp → unplugin layering boundary. unplugin/tunnel.ts declares its own copy
|
|
10
|
+
* for the same reason — keep the two in sync when the URL changes.
|
|
11
|
+
*/
|
|
12
|
+
const LAUNCHER_URL = "https://devtools.aitc.dev/launcher/";
|
|
13
|
+
/**
|
|
14
|
+
* Builds a launcher PWA deep-link for env-2 MCP-attach (issue #378).
|
|
15
|
+
*
|
|
16
|
+
* The launcher at {@link LAUNCHER_URL} renders tunnelUrl in a full-viewport
|
|
17
|
+
* iframe. `&debug=1&relay=<wssUrl>` is forwarded onto the iframe src so the
|
|
18
|
+
* framed page's in-app debug gate (Layer C) is satisfied and a Chii target.js
|
|
19
|
+
* is injected. `&at=<totpCode>` is added only when a code is provided (same
|
|
20
|
+
* conditional as {@link buildDeepLinkAttachUrl}).
|
|
21
|
+
*
|
|
22
|
+
* When `opts.name` is given (non-blank), it is added as `&name=` so the
|
|
23
|
+
* launcher partner bar shows the app name instead of the generic default (#498).
|
|
24
|
+
* When `opts.icon` is an absolute https:// URL, it is added as `&icon=` so the
|
|
25
|
+
* launcher can render an icon next to the title (#498).
|
|
26
|
+
*
|
|
27
|
+
* Unlike `buildDeepLinkAttachUrl` (which splices onto a non-special scheme URL
|
|
28
|
+
* via raw string manipulation), this function uses WHATWG `encodeURIComponent`
|
|
29
|
+
* because the target is a standard `https:` URL.
|
|
30
|
+
*
|
|
31
|
+
* SECRET-HANDLING: `totpCode` (when provided) is placed into the `at=` param
|
|
32
|
+
* only — never logged or returned separately. Callers must NOT log the result
|
|
33
|
+
* of this function to stdout/stderr.
|
|
34
|
+
*
|
|
35
|
+
* @param tunnelUrl - The `https://*.trycloudflare.com` app tunnel URL
|
|
36
|
+
* (`AIT_TUNNEL_BASE_URL`). This is the URL the launcher frames.
|
|
37
|
+
* @param wssUrl - The `wss://` relay URL the framed page will attach to.
|
|
38
|
+
* @param totpCode - Optional current TOTP code (6 digits). When provided, it
|
|
39
|
+
* is appended as `at=<totpCode>`. Must be computed at call time — it rotates
|
|
40
|
+
* every 30 s. Omit when TOTP is disabled.
|
|
41
|
+
* @param opts - Optional app identity hints: `name`, `icon`, and `selfdebug`
|
|
42
|
+
* (#498, #543).
|
|
43
|
+
* @returns The launcher deep-link URL with `?url=<enc>&debug=1&relay=<enc>
|
|
44
|
+
* [&at=<code>][&name=<enc>][&icon=<enc>][&selfdebug=1]` params.
|
|
45
|
+
*/
|
|
46
|
+
function buildLauncherAttachUrl(tunnelUrl, wssUrl, totpCode, opts) {
|
|
47
|
+
let url = `${LAUNCHER_URL}?url=${encodeURIComponent(tunnelUrl)}&debug=1&relay=${encodeURIComponent(wssUrl)}`;
|
|
48
|
+
if (totpCode !== void 0 && totpCode !== "") url += `&at=${encodeURIComponent(totpCode)}`;
|
|
49
|
+
if (opts?.name !== void 0 && opts.name.trim() !== "") url += `&name=${encodeURIComponent(opts.name.trim())}`;
|
|
50
|
+
if (opts?.icon !== void 0) {
|
|
51
|
+
let iconParsed;
|
|
52
|
+
try {
|
|
53
|
+
iconParsed = new URL(opts.icon);
|
|
54
|
+
} catch {
|
|
55
|
+
iconParsed = null;
|
|
56
|
+
}
|
|
57
|
+
if (iconParsed?.protocol === "https:") url += `&icon=${encodeURIComponent(opts.icon)}`;
|
|
58
|
+
}
|
|
59
|
+
if (opts?.selfdebug === true) url += "&selfdebug=1";
|
|
60
|
+
return url;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Build a self-attaching dog-food deep-link.
|
|
64
|
+
*
|
|
65
|
+
* `ait deploy --scheme-only` prints an `intoss-private://…?_deploymentId=<uuid>`
|
|
66
|
+
* URL that opens a dog-food bundle on a phone. The in-app debug gate
|
|
67
|
+
* (`src/in-app/gate.ts`) auto-attaches when the entry URL also carries
|
|
68
|
+
* `debug=1` and `relay=<wss-url>`. This helper splices those params (plus
|
|
69
|
+
* `at=<code>` when TOTP is enabled) into the scheme URL; rendering the result
|
|
70
|
+
* as a QR code and scanning it with the phone camera opens the mini-app and
|
|
71
|
+
* attaches it to the live Chii relay. QR is the single entry path — it needs
|
|
72
|
+
* no USB cable, platform CLI, or driver, and works the same on iOS/Android.
|
|
73
|
+
*
|
|
74
|
+
* The Toss app propagates extra query params from the entry deep link into the
|
|
75
|
+
* mini-app WebView's `location.search` (confirmed behavior), so the gate reads
|
|
76
|
+
* them at attach time.
|
|
77
|
+
*
|
|
78
|
+
* TOTP `at=` param:
|
|
79
|
+
* When a TOTP secret is active, `buildDeepLinkAttachUrl` accepts an optional
|
|
80
|
+
* `totpCode` argument and splices `at=<code>` alongside `debug` and `relay`.
|
|
81
|
+
* The code must be computed by the caller at call time — do NOT pre-compute
|
|
82
|
+
* and cache it, because the 30-second window expires quickly. The in-app gate
|
|
83
|
+
* (`src/in-app/gate.ts` Layer C) validates this code against the baked secret.
|
|
84
|
+
*
|
|
85
|
+
* Why not `URL`/`URLSearchParams`: `intoss-private:` is a non-special scheme.
|
|
86
|
+
* The WHATWG `URL` parser treats such schemes opaquely (no host/path/query
|
|
87
|
+
* decomposition you can rely on across runtimes), so query manipulation via
|
|
88
|
+
* `url.searchParams` is not portable here. We splice the query string directly
|
|
89
|
+
* on the raw string instead, which keeps the scheme, authority, path, and any
|
|
90
|
+
* pre-existing params (notably `_deploymentId`) byte-for-byte intact.
|
|
91
|
+
*/
|
|
92
|
+
/**
|
|
93
|
+
* Suspicious/generic authority values that indicate a malformed or placeholder
|
|
94
|
+
* scheme URL. These are host strings that will almost certainly cause the Toss
|
|
95
|
+
* app to fail with "bundle not found" silently.
|
|
96
|
+
*
|
|
97
|
+
* The expected form from `ait deploy --scheme-only` is:
|
|
98
|
+
* intoss-private://<appName>?_deploymentId=<uuid>
|
|
99
|
+
* where `<appName>` is a non-generic string like `aitc-sdk-example`.
|
|
100
|
+
*/
|
|
101
|
+
const SUSPICIOUS_AUTHORITIES = new Set([
|
|
102
|
+
"",
|
|
103
|
+
"web",
|
|
104
|
+
"localhost",
|
|
105
|
+
"127.0.0.1",
|
|
106
|
+
"app"
|
|
107
|
+
]);
|
|
108
|
+
/**
|
|
109
|
+
* Validates the authority (host) portion of a scheme URL.
|
|
110
|
+
*
|
|
111
|
+
* Returns a warning message if the authority is missing or looks like a
|
|
112
|
+
* placeholder, or `null` if the authority looks valid.
|
|
113
|
+
*
|
|
114
|
+
* Expected form: `intoss-private://<appName>?_deploymentId=<uuid>`
|
|
115
|
+
* The authority must be a non-empty, non-generic app name (e.g. `aitc-sdk-example`).
|
|
116
|
+
*/
|
|
117
|
+
function validateSchemeAuthority(schemeUrl) {
|
|
118
|
+
const afterScheme = schemeUrl.replace(/^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//, "");
|
|
119
|
+
if (afterScheme === schemeUrl) return "scheme_url does not look like a scheme URL (expected `intoss-private://<appName>?_deploymentId=<uuid>`). Use the URL printed by `ait deploy --scheme-only`.";
|
|
120
|
+
const authorityEnd = afterScheme.search(/[/?#]/);
|
|
121
|
+
const authority = authorityEnd === -1 ? afterScheme : afterScheme.slice(0, authorityEnd);
|
|
122
|
+
if (SUSPICIOUS_AUTHORITIES.has(authority.toLowerCase())) return `scheme_url authority ${authority === "" ? "(empty)" : `"${authority}"`} looks like a placeholder. Expected an app name like \`intoss-private://aitc-sdk-example?_deploymentId=<uuid>\`. Use the URL printed by \`ait deploy --scheme-only\` — it includes the correct app name as the host.`;
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
function stripExisting(query, key) {
|
|
126
|
+
if (query === "") return "";
|
|
127
|
+
return query.split("&").filter((pair) => pair !== "" && pair.split("=")[0] !== key).join("&");
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Splices `debug=1`, `relay=<wssUrl>`, and (optionally) `at=<totpCode>` into a
|
|
131
|
+
* scheme URL's query string, preserving everything else (scheme, authority,
|
|
132
|
+
* path, hash, and the existing `_deploymentId` param). If any of the spliced
|
|
133
|
+
* params is already present it is replaced so the helper is idempotent.
|
|
134
|
+
*
|
|
135
|
+
* @param schemeUrl - The `intoss-private://…?_deploymentId=<uuid>` URL printed
|
|
136
|
+
* by `ait deploy --scheme-only`. Must already carry `_deploymentId` (Layer B
|
|
137
|
+
* of the gate); this helper does not invent one.
|
|
138
|
+
* @param wssUrl - The live relay URL (`wss://…trycloudflare.com`) from the
|
|
139
|
+
* running debug MCP server's quick tunnel.
|
|
140
|
+
* @param totpCode - Optional current TOTP code (6 digits). When provided, it
|
|
141
|
+
* is spliced as `at=<totpCode>`. Must be computed at call time — it rotates
|
|
142
|
+
* every 30 s. Pass `undefined` or omit when TOTP is disabled.
|
|
143
|
+
* @returns The same URL with `debug=1&relay=<encoded wssUrl>[&at=<totpCode>]`
|
|
144
|
+
* appended.
|
|
145
|
+
* @throws If `wssUrl` is not a `wss:` URL (the gate rejects anything else, so
|
|
146
|
+
* producing such a link would be a silent dead end).
|
|
147
|
+
*/
|
|
148
|
+
function buildDeepLinkAttachUrl(schemeUrl, wssUrl, totpCode) {
|
|
149
|
+
let relay;
|
|
150
|
+
try {
|
|
151
|
+
relay = new URL(wssUrl);
|
|
152
|
+
} catch {
|
|
153
|
+
throw new Error(`relay URL is not a valid URL: ${wssUrl}`);
|
|
154
|
+
}
|
|
155
|
+
if (relay.protocol !== "wss:") throw new Error(`relay URL must use the wss: scheme, got ${relay.protocol} (${wssUrl})`);
|
|
156
|
+
const hashIndex = schemeUrl.indexOf("#");
|
|
157
|
+
const hash = hashIndex === -1 ? "" : schemeUrl.slice(hashIndex);
|
|
158
|
+
const beforeHash = hashIndex === -1 ? schemeUrl : schemeUrl.slice(0, hashIndex);
|
|
159
|
+
const queryIndex = beforeHash.indexOf("?");
|
|
160
|
+
const base = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
|
|
161
|
+
let query = queryIndex === -1 ? "" : beforeHash.slice(queryIndex + 1);
|
|
162
|
+
const appended = [["debug", "1"], ["relay", wssUrl]];
|
|
163
|
+
if (totpCode !== void 0 && totpCode !== "") appended.push(["at", totpCode]);
|
|
164
|
+
query = stripExisting(query, "at");
|
|
165
|
+
for (const [key] of appended) query = stripExisting(query, key);
|
|
166
|
+
for (const [key, value] of appended) {
|
|
167
|
+
const pair = `${key}=${encodeURIComponent(value)}`;
|
|
168
|
+
query = query === "" ? pair : `${query}&${pair}`;
|
|
169
|
+
}
|
|
170
|
+
return `${base}?${query}${hash}`;
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/mcp/errors.ts
|
|
174
|
+
/**
|
|
175
|
+
* 한국어 한 줄 "원인 + 다음 행동" 포맷으로 에러 결과를 빌드한다.
|
|
176
|
+
*
|
|
177
|
+
* @param message - 사용자에게 보여줄 에러 본문 (원인 + 다음 행동 포함).
|
|
178
|
+
*/
|
|
179
|
+
function mcpError(message) {
|
|
180
|
+
return {
|
|
181
|
+
content: [{
|
|
182
|
+
type: "text",
|
|
183
|
+
text: message
|
|
184
|
+
}],
|
|
185
|
+
isError: true
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* 상태 1: tunnel 미가동 — cloudflared 터널이 아직 뜨지 않았다.
|
|
190
|
+
*
|
|
191
|
+
* `start_attach` 호출 시 tunnel.up === false 인 경우.
|
|
192
|
+
*/
|
|
193
|
+
function tunnelDownError() {
|
|
194
|
+
return mcpError("cloudflared 터널이 안 떠 있습니다. MCP 서버를 재시작하거나 잠시 후 list_pages로 터널 상태를 다시 확인하세요.");
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* 상태 3: page crash — 연결됐던 페이지가 crash/destroy됐다.
|
|
198
|
+
*
|
|
199
|
+
* chii-connection 이 'replaced-by-new-attach' / 'targetCrashed' / 'targetDestroyed' 를
|
|
200
|
+
* 던질 때 이 메시지를 사용한다.
|
|
201
|
+
*/
|
|
202
|
+
function pageCrashError(toolName) {
|
|
203
|
+
return mcpError(`${toolName ? `${toolName}: ` : ""}페이지가 crash됐습니다. 토스 앱을 재실행한 뒤 start_attach → QR 스캔으로 재attach하세요.`);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* 상태 4: SDK 부재 — window.__sdkCall이 주입되지 않았다.
|
|
207
|
+
*
|
|
208
|
+
* call_sdk 호출 시 브리지가 없을 때. 같은 "브리지 부재"라도 다음 행동은
|
|
209
|
+
* connection 종류에 따라 정반대다 (issue #360):
|
|
210
|
+
* - relay(`--target` 없는 intoss / env-2): dog-food 빌드가 아니다 → dog-food
|
|
211
|
+
* 채널로 재배포 후 QR 재스캔.
|
|
212
|
+
* - local(`--target=local`, env 1 로컬 브라우저): 재배포가 아니라 dev 서버를
|
|
213
|
+
* `pnpm dev`로 띄웠는지 + unplugin alias가 `@apps-in-toss/web-framework`를
|
|
214
|
+
* devtools mock으로 resolve하는지 확인. dev 빌드면 `import.meta.env.DEV`
|
|
215
|
+
* 경로로 `window.__sdkCall`이 자동 설치된다.
|
|
216
|
+
*
|
|
217
|
+
* `isLocal`이 생략되면 relay 안내(이전 동작)를 유지한다.
|
|
218
|
+
*/
|
|
219
|
+
function sdkAbsentError(toolName, isLocal = false) {
|
|
220
|
+
const prefix = toolName ? `${toolName}: ` : "";
|
|
221
|
+
if (isLocal) return mcpError(`${prefix}window.__sdkCall이 주입되지 않았습니다 (로컬 dev 브리지 부재). sdk-example을 \`pnpm dev\`로 띄웠는지, 그리고 unplugin alias가 \`@apps-in-toss/web-framework\`를 devtools mock으로 resolve하는지 확인하세요. dev 빌드(\`import.meta.env.DEV\`)면 \`window.__sdkCall\`이 자동 설치됩니다.`);
|
|
222
|
+
return mcpError(`${prefix}window.__sdkCall이 주입되지 않았습니다 (dog-food 빌드가 아닙니다). dog-food 채널(intoss-private)로 재배포 후 QR을 다시 스캔하세요: \`ait build && aitcc app deploy\`.`);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* relay WebSocket 연결이 끊겼을 때 — 크래시가 아닌 네트워크/프로세스 종료.
|
|
226
|
+
*/
|
|
227
|
+
function relayDisconnectError(toolName) {
|
|
228
|
+
return mcpError(`${toolName ? `${toolName}: ` : ""}relay 연결이 끊겼습니다. list_pages로 상태를 확인하고, 필요하면 앱을 재실행 후 재attach하세요.`);
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* CDP/AIT 명령 중 발생한 예외를 4상태로 분류해 적절한 에러 결과를 반환한다.
|
|
232
|
+
*
|
|
233
|
+
* - SDK 부재 패턴 (`window.__sdkCall is not available`) → sdkAbsentError
|
|
234
|
+
* - crash 패턴 (`replaced-by-new-attach`, `targetCrashed`, `targetDestroyed`) → pageCrashError
|
|
235
|
+
* - 연결 끊김 패턴 (`relay에 연결되어 있지 않습니다`, `relay WebSocket`) → relayDisconnectError
|
|
236
|
+
* - 그 외 (일반 에러) → 원본 메시지를 포함한 mcpError
|
|
237
|
+
*/
|
|
238
|
+
function classifyToolError(err, toolName, isLocal = false) {
|
|
239
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
240
|
+
if (message.startsWith("tunnel-down:") || message.includes("터널이 안 떠 있습니다")) return tunnelDownError();
|
|
241
|
+
if (message.startsWith("sdk-absent:") || message.includes("__sdkCall이 주입되지 않았습니다") || message.includes("window.__sdkCall is not available") || message.includes("__sdkCall") && message.includes("not available")) return sdkAbsentError(toolName, isLocal);
|
|
242
|
+
if (message.includes("replaced-by-new-attach") || message.includes("targetCrashed") || message.includes("targetDestroyed") || message.includes("detachedFromTarget")) return pageCrashError(toolName);
|
|
243
|
+
if (message.includes("relay에 연결되어 있지 않습니다") || message.includes("relay WebSocket")) return relayDisconnectError(toolName);
|
|
244
|
+
return mcpError(`${toolName} 실패: ${message}\nlist_pages로 미니앱이 relay에 attach됐는지 확인하세요.`);
|
|
245
|
+
}
|
|
246
|
+
//#endregion
|
|
247
|
+
//#region src/mcp/log.ts
|
|
248
|
+
/**
|
|
249
|
+
* Allowed field keys that may pass through to a log line.
|
|
250
|
+
* Unknown keys are dropped. Values are still redact-scanned.
|
|
251
|
+
*/
|
|
252
|
+
const ALLOWED_KEYS = new Set([
|
|
253
|
+
"ts",
|
|
254
|
+
"level",
|
|
255
|
+
"event",
|
|
256
|
+
"msg",
|
|
257
|
+
"port",
|
|
258
|
+
"totpEnabled",
|
|
259
|
+
"env",
|
|
260
|
+
"tool",
|
|
261
|
+
"deploymentId",
|
|
262
|
+
"errorKind",
|
|
263
|
+
"reason",
|
|
264
|
+
"prevTargetId",
|
|
265
|
+
"mode",
|
|
266
|
+
"fileCount",
|
|
267
|
+
"passed",
|
|
268
|
+
"failed",
|
|
269
|
+
"skipped"
|
|
270
|
+
]);
|
|
271
|
+
/**
|
|
272
|
+
* Patterns that match secret values.
|
|
273
|
+
* Match order matters — more-specific patterns first.
|
|
274
|
+
*
|
|
275
|
+
* #268 redact script covers: relay=wss://…, at=<TOTP>, _deploymentId=<uuid>.
|
|
276
|
+
* Here we extend to in-process value-level patterns used in server logs.
|
|
277
|
+
*/
|
|
278
|
+
const SECRET_PATTERNS = [
|
|
279
|
+
/^\d{6}$/,
|
|
280
|
+
/^(aitcc_|AITCC_)/i,
|
|
281
|
+
/^[A-Za-z0-9_-]+=.{4,}/,
|
|
282
|
+
/^wss:\/\//,
|
|
283
|
+
/(?:^|[?&])at=[A-Z0-9]{6}/i
|
|
284
|
+
];
|
|
285
|
+
/**
|
|
286
|
+
* Returns `true` when the string value matches any known-secret pattern.
|
|
287
|
+
* Only string values are tested — numbers/booleans are always safe.
|
|
288
|
+
*/
|
|
289
|
+
function isSecretValue(value) {
|
|
290
|
+
return SECRET_PATTERNS.some((re) => re.test(value));
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Redacts a single scalar value.
|
|
294
|
+
* - strings: return "***" if the value matches a secret pattern.
|
|
295
|
+
* - other: return as-is.
|
|
296
|
+
*/
|
|
297
|
+
function redactValue(value) {
|
|
298
|
+
if (typeof value === "string" && isSecretValue(value)) return "***";
|
|
299
|
+
return value;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Builds a safe log payload from raw fields.
|
|
303
|
+
*
|
|
304
|
+
* - Only keys in `ALLOWED_KEYS` are included.
|
|
305
|
+
* - String values are scanned for secret patterns and replaced with "***".
|
|
306
|
+
* - `ts` and `level` and `event` are always included (they are injected by the
|
|
307
|
+
* logger functions below, not by callers).
|
|
308
|
+
*/
|
|
309
|
+
function buildPayload(level, event, fields) {
|
|
310
|
+
const out = {
|
|
311
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
312
|
+
level,
|
|
313
|
+
event
|
|
314
|
+
};
|
|
315
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
316
|
+
if (!ALLOWED_KEYS.has(key)) continue;
|
|
317
|
+
if (key === "ts" || key === "level" || key === "event") continue;
|
|
318
|
+
out[key] = redactValue(value);
|
|
319
|
+
}
|
|
320
|
+
return out;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Writes a single JSON log line to stderr.
|
|
324
|
+
* MCP stdio transport uses stdout; all diagnostics go to stderr.
|
|
325
|
+
*/
|
|
326
|
+
function writeLog(level, event, fields = {}) {
|
|
327
|
+
const payload = buildPayload(level, event, fields);
|
|
328
|
+
process.stderr.write(`${JSON.stringify(payload)}\n`);
|
|
329
|
+
}
|
|
330
|
+
/** Log an informational structured event. */
|
|
331
|
+
function logInfo(event, fields = {}) {
|
|
332
|
+
writeLog("info", event, fields);
|
|
333
|
+
}
|
|
334
|
+
/** Log an error structured event. */
|
|
335
|
+
function logError(event, fields = {}) {
|
|
336
|
+
writeLog("error", event, fields);
|
|
337
|
+
}
|
|
338
|
+
//#endregion
|
|
339
|
+
//#region src/mcp/sdk-signatures.ts
|
|
340
|
+
function isObject(v) {
|
|
341
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
342
|
+
}
|
|
343
|
+
function describeArgs(args) {
|
|
344
|
+
try {
|
|
345
|
+
return JSON.stringify(args);
|
|
346
|
+
} catch {
|
|
347
|
+
return String(args);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* 등록된 메서드 목록.
|
|
352
|
+
*
|
|
353
|
+
* 시그니처 출처 확인:
|
|
354
|
+
* - 함수가 인자를 받지 않으면 args[0] 없음 → `args.length === 0`을 체크하지 않고
|
|
355
|
+
* 그냥 통과시킨다(args 무시하는 stub가 많아서 noArgs 체크가 noise).
|
|
356
|
+
* - 실 SDK 시그니처는 `src/__typecheck.ts`의 `Assert<Mock, Original>` 줄로 보장.
|
|
357
|
+
*/
|
|
358
|
+
const SIGNATURES = [
|
|
359
|
+
{
|
|
360
|
+
name: "setDeviceOrientation",
|
|
361
|
+
validateArgs(args) {
|
|
362
|
+
const arg = args[0];
|
|
363
|
+
if (!isObject(arg)) return {
|
|
364
|
+
ok: false,
|
|
365
|
+
expected: "{ type: 'portrait' | 'landscape' }",
|
|
366
|
+
received: describeArgs(args)
|
|
367
|
+
};
|
|
368
|
+
const type = arg.type;
|
|
369
|
+
if (type !== "portrait" && type !== "landscape") return {
|
|
370
|
+
ok: false,
|
|
371
|
+
expected: "{ type: 'portrait' | 'landscape' }",
|
|
372
|
+
received: describeArgs(args)
|
|
373
|
+
};
|
|
374
|
+
return { ok: true };
|
|
375
|
+
},
|
|
376
|
+
example: "call_sdk('setDeviceOrientation', [{ type: 'landscape' }])"
|
|
377
|
+
},
|
|
378
|
+
{
|
|
379
|
+
name: "setIosSwipeGestureEnabled",
|
|
380
|
+
validateArgs(args) {
|
|
381
|
+
const arg = args[0];
|
|
382
|
+
if (!isObject(arg) || typeof arg.isEnabled !== "boolean") return {
|
|
383
|
+
ok: false,
|
|
384
|
+
expected: "{ isEnabled: boolean }",
|
|
385
|
+
received: describeArgs(args)
|
|
386
|
+
};
|
|
387
|
+
return { ok: true };
|
|
388
|
+
},
|
|
389
|
+
example: "call_sdk('setIosSwipeGestureEnabled', [{ isEnabled: false }])"
|
|
390
|
+
},
|
|
391
|
+
{
|
|
392
|
+
name: "setSecureScreen",
|
|
393
|
+
validateArgs(args) {
|
|
394
|
+
const arg = args[0];
|
|
395
|
+
if (!isObject(arg) || typeof arg.enabled !== "boolean") return {
|
|
396
|
+
ok: false,
|
|
397
|
+
expected: "{ enabled: boolean }",
|
|
398
|
+
received: describeArgs(args)
|
|
399
|
+
};
|
|
400
|
+
return { ok: true };
|
|
401
|
+
},
|
|
402
|
+
example: "call_sdk('setSecureScreen', [{ enabled: true }])"
|
|
403
|
+
},
|
|
404
|
+
{
|
|
405
|
+
name: "setScreenAwakeMode",
|
|
406
|
+
validateArgs(args) {
|
|
407
|
+
const arg = args[0];
|
|
408
|
+
if (!isObject(arg) || typeof arg.enabled !== "boolean") return {
|
|
409
|
+
ok: false,
|
|
410
|
+
expected: "{ enabled: boolean }",
|
|
411
|
+
received: describeArgs(args)
|
|
412
|
+
};
|
|
413
|
+
return { ok: true };
|
|
414
|
+
},
|
|
415
|
+
example: "call_sdk('setScreenAwakeMode', [{ enabled: true }])"
|
|
416
|
+
},
|
|
417
|
+
{
|
|
418
|
+
name: "getOperationalEnvironment",
|
|
419
|
+
validateArgs(_args) {
|
|
420
|
+
return { ok: true };
|
|
421
|
+
},
|
|
422
|
+
example: "call_sdk('getOperationalEnvironment', [])"
|
|
423
|
+
},
|
|
424
|
+
{
|
|
425
|
+
name: "getPlatformOS",
|
|
426
|
+
validateArgs(_args) {
|
|
427
|
+
return { ok: true };
|
|
428
|
+
},
|
|
429
|
+
example: "call_sdk('getPlatformOS', [])"
|
|
430
|
+
},
|
|
431
|
+
{
|
|
432
|
+
name: "getDeviceId",
|
|
433
|
+
validateArgs(_args) {
|
|
434
|
+
return { ok: true };
|
|
435
|
+
},
|
|
436
|
+
example: "call_sdk('getDeviceId', [])"
|
|
437
|
+
},
|
|
438
|
+
{
|
|
439
|
+
name: "getLocale",
|
|
440
|
+
validateArgs(_args) {
|
|
441
|
+
return { ok: true };
|
|
442
|
+
},
|
|
443
|
+
example: "call_sdk('getLocale', [])"
|
|
444
|
+
},
|
|
445
|
+
{
|
|
446
|
+
name: "getNetworkStatus",
|
|
447
|
+
validateArgs(_args) {
|
|
448
|
+
return { ok: true };
|
|
449
|
+
},
|
|
450
|
+
example: "call_sdk('getNetworkStatus', [])"
|
|
451
|
+
},
|
|
452
|
+
{
|
|
453
|
+
name: "getSchemeUri",
|
|
454
|
+
validateArgs(_args) {
|
|
455
|
+
return { ok: true };
|
|
456
|
+
},
|
|
457
|
+
example: "call_sdk('getSchemeUri', [])"
|
|
458
|
+
},
|
|
459
|
+
{
|
|
460
|
+
name: "requestReview",
|
|
461
|
+
validateArgs(_args) {
|
|
462
|
+
return { ok: true };
|
|
463
|
+
},
|
|
464
|
+
example: "call_sdk('requestReview', [])"
|
|
465
|
+
},
|
|
466
|
+
{
|
|
467
|
+
name: "closeView",
|
|
468
|
+
validateArgs(_args) {
|
|
469
|
+
return { ok: true };
|
|
470
|
+
},
|
|
471
|
+
example: "call_sdk('closeView', [])"
|
|
472
|
+
}
|
|
473
|
+
];
|
|
474
|
+
new Map(SIGNATURES.map((s) => [s.name, s]));
|
|
475
|
+
SIGNATURES.map((s) => s.name);
|
|
476
|
+
new Set([
|
|
477
|
+
{
|
|
478
|
+
name: "list_console_messages",
|
|
479
|
+
description: "Lists recent console messages (console.log/warn/error/info) captured from the attached mini-app page over CDP (Runtime.consoleAPICalled). Read-only. Returns level, text, timestamp, and stringified args, oldest-first.",
|
|
480
|
+
inputSchema: {
|
|
481
|
+
type: "object",
|
|
482
|
+
properties: {},
|
|
483
|
+
required: []
|
|
484
|
+
},
|
|
485
|
+
availableIn: "both"
|
|
486
|
+
},
|
|
487
|
+
{
|
|
488
|
+
name: "list_network_requests",
|
|
489
|
+
description: "Lists recent network requests (XHR/fetch) captured from the attached mini-app page over CDP (Network.requestWillBeSent + Network.responseReceived). Read-only. Returns url, method, status, and timing, oldest-first.",
|
|
490
|
+
inputSchema: {
|
|
491
|
+
type: "object",
|
|
492
|
+
properties: {},
|
|
493
|
+
required: []
|
|
494
|
+
},
|
|
495
|
+
availableIn: "both"
|
|
496
|
+
},
|
|
497
|
+
{
|
|
498
|
+
name: "list_pages",
|
|
499
|
+
description: "Returns the single active page (at most one) the relay sees attached. When a second page attaches, the previous one is evicted (last-attach wins — single-attach model). The result includes `singleAttachModel: true` so the agent knows the array is always 0 or 1 entries. Also returns whether the cloudflared tunnel is up and the public wss relay URL. The `tunnel` field includes `droppedAt` (ISO timestamp or null/undefined): when non-null the tunnel has permanently dropped after 3 failed reissue attempts — restart the debug server with `npx @ait-co/devtools devtools-mcp`. Each page entry includes a `lastSeenAt` ISO timestamp (last inbound CDP message from that target — useful to detect stale entries when the phone app backgrounded). The result also includes `crashDetectedAt` (ISO timestamp or null): when non-null, a page crash was detected via Inspector.targetCrashed / Target.targetDestroyed since the last attach, the pages list will be empty, and `crashWarning` shows a Korean hint to re-attach. Call this first to confirm a page is attached before reading console/network. When a page attaches or detaches the server emits notifications/tools/list_changed — call tools/list again to get the full updated tool surface.",
|
|
500
|
+
inputSchema: {
|
|
501
|
+
type: "object",
|
|
502
|
+
properties: {},
|
|
503
|
+
required: []
|
|
504
|
+
},
|
|
505
|
+
availableIn: "both"
|
|
506
|
+
},
|
|
507
|
+
{
|
|
508
|
+
name: "start_attach",
|
|
509
|
+
description: "The tool result already shows the QR to the user directly (Claude Code renders MCP tool output to the user's screen; they press Ctrl+O to expand if it's collapsed). Do NOT re-print or re-render the QR in your reply — that just wastes output tokens. Simply tell the user to scan the QR shown in this tool's output with their phone camera. Single entry point to attach a real device: switches the debug mode (if `mode` is given), builds the self-attaching deep-link QR for the active relay environment, and waits for the phone to attach — all in one call (replaces the old attach-URL + start_debug two-step). Scan the QR with the phone camera to open the mini-app and attach it to this debug session (QR is the single entry path — no USB cable or platform CLI needed).\n\nmode (optional): pass \"relay-sandbox\" (env 2) or \"relay-staging\" (env 3) to switch the active environment first. When omitted, the current relay environment is used as-is (no switch). Passing \"local-browser\" returns an error — start_attach is relay-only (env 2/3). When the session is already in the requested mode, the switch is skipped.\n\nEnvironment-specific behaviour:\n • env 3 / relay-staging: requires scheme_url — the intoss-private://…?_deploymentId=<uuid> URL from `ait deploy --scheme-only`. Splices debug=1 + relay URL into the scheme URL.\n • env 2 / relay-sandbox: scheme_url is NOT used. Instead, reads AIT_TUNNEL_BASE_URL (the https://*.trycloudflare.com app tunnel from `tunnel:{cdp:true}`) and builds a launcher PWA deep-link (https://devtools.aitc.dev/launcher/?url=…&debug=1&relay=…). When projectRoot is given, the app name from <projectRoot>/package.json is added as name= so the launcher partner bar shows it.\n\nWaits for a page to attach by default (up to wait_timeout_seconds, default 60 s). The server automatically opens the QR dashboard in the OS default browser when running on a local GUI machine — headless/remote environments fall back to the text QR in the tool output.\n\nTOTP auto re-mint: when AIT_DEBUG_TOTP_SECRET is set on the MCP server, the attachUrl carries a one-time code (at=<code>) valid for ~3 minutes (the relay gate accepts ±6 TOTP steps). While waiting, start_attach AUTOMATICALLY re-mints a fresh code before the current one expires and refreshes the dashboard QR in place (no browser re-open). You do NOT need to re-call start_attach every time the code would expire — a single call covers the whole wait window. The response includes a `totp` field with `expiresAt` and a `reminted` count of how many fresh codes were issued during the wait. Without AIT_DEBUG_TOTP_SECRET, the attachUrl has no expiry.\n\nselfdebug (env 2 / relay-sandbox only): pass selfdebug=true to add &selfdebug=1 to the launcher deep-link. The launcher PWA then registers its own document as the CDP target instead of the framed mini-app. SINGLE-ATTACH MODEL: attaching the launcher self-target evicts any currently-attached mini-app target — use this mode exclusively for diagnosing the launcher document itself (DOM, safe-area, console). Not applicable in env 3 (relay-staging) — passing selfdebug=true there returns an error.",
|
|
510
|
+
inputSchema: {
|
|
511
|
+
type: "object",
|
|
512
|
+
properties: {
|
|
513
|
+
mode: {
|
|
514
|
+
type: "string",
|
|
515
|
+
enum: [
|
|
516
|
+
"local-browser",
|
|
517
|
+
"relay-sandbox",
|
|
518
|
+
"relay-staging"
|
|
519
|
+
],
|
|
520
|
+
description: "Optional debug mode to switch into before attaching. \"relay-sandbox\" = env 2 (launcher PWA), \"relay-staging\" = env 3 (intoss-private dog-food). \"local-browser\" returns an error (start_attach is relay-only). Omit to keep the current relay environment."
|
|
521
|
+
},
|
|
522
|
+
scheme_url: {
|
|
523
|
+
type: "string",
|
|
524
|
+
description: "The intoss-private:// scheme URL from `ait deploy --scheme-only` (must carry _deploymentId). Required for env 3/relay-staging mode. Not used in env 2/relay-sandbox mode (use AIT_TUNNEL_BASE_URL instead). The authority (host) must be the app name (e.g. intoss-private://aitc-sdk-example?_deploymentId=…). Generic values like \"web\" or an empty host indicate a malformed URL."
|
|
525
|
+
},
|
|
526
|
+
wait_timeout_seconds: {
|
|
527
|
+
type: "number",
|
|
528
|
+
description: "Maximum seconds to wait for a page to attach (default 60, range 1–600). Values outside the range or invalid inputs (0, negative, NaN) fall back to the default silently. During the wait the TOTP code is auto re-minted as needed, so a single call covers the whole window."
|
|
529
|
+
},
|
|
530
|
+
projectRoot: {
|
|
531
|
+
type: "string",
|
|
532
|
+
description: "Absolute path to the mini-app project root (the directory containing its package.json and .ait_urls). When AIT_TUNNEL_BASE_URL is unset (env 2 / relay-mobile only), the daemon reads the app tunnel URL from <projectRoot>/.ait_urls written by the dev server (tunnel:{cdp:true}). Pass this because the daemon's own cwd is fixed at launch. Omit when AIT_TUNNEL_BASE_URL is set explicitly."
|
|
533
|
+
},
|
|
534
|
+
selfdebug: {
|
|
535
|
+
type: "boolean",
|
|
536
|
+
description: "Env 2 / relay-sandbox only. When true, adds &selfdebug=1 to the launcher deep-link so the launcher PWA registers its own document as the CDP target (launcher diagnostics mode). SINGLE-ATTACH MODEL: self-target attach evicts any currently-attached mini-app target. Use only when you need to inspect the launcher itself (DOM, safe-area, console). Passing selfdebug=true in env 3 (relay-staging) returns an error. Default: false (omitted)."
|
|
537
|
+
}
|
|
538
|
+
},
|
|
539
|
+
required: []
|
|
540
|
+
},
|
|
541
|
+
availableIn: "relay"
|
|
542
|
+
},
|
|
543
|
+
{
|
|
544
|
+
name: "get_dom_document",
|
|
545
|
+
description: "Returns the DOM tree of the attached mini-app page over CDP (DOM.getDocument). Read-only. Use for structural/layout regression diagnosis (e.g. confirming an element exists, inspecting attributes). Returns the document root node with children.",
|
|
546
|
+
inputSchema: {
|
|
547
|
+
type: "object",
|
|
548
|
+
properties: {},
|
|
549
|
+
required: []
|
|
550
|
+
},
|
|
551
|
+
availableIn: "both"
|
|
552
|
+
},
|
|
553
|
+
{
|
|
554
|
+
name: "take_snapshot",
|
|
555
|
+
description: "Captures a serialized snapshot of the attached page over CDP (DOMSnapshot.captureSnapshot). Read-only. Returns the documents + interned strings table for visual-regression diagnosis (e.g. checking computed CSS custom properties like --sat against the live layout).",
|
|
556
|
+
inputSchema: {
|
|
557
|
+
type: "object",
|
|
558
|
+
properties: {},
|
|
559
|
+
required: []
|
|
560
|
+
},
|
|
561
|
+
availableIn: "both"
|
|
562
|
+
},
|
|
563
|
+
{
|
|
564
|
+
name: "take_screenshot",
|
|
565
|
+
description: "Captures a PNG screenshot of the attached mini-app page over CDP (Page.captureScreenshot) so the agent can see the phone screen directly. Read-only. Returns an image content block — this is the only debug tool that returns an image; all other debug tools return text (JSON).",
|
|
566
|
+
inputSchema: {
|
|
567
|
+
type: "object",
|
|
568
|
+
properties: {},
|
|
569
|
+
required: []
|
|
570
|
+
},
|
|
571
|
+
availableIn: "both"
|
|
572
|
+
},
|
|
573
|
+
{
|
|
574
|
+
name: "measure_safe_area",
|
|
575
|
+
description: "Runs a safe-area probe on the attached mini-app page via Runtime.evaluate and returns normalized safe-area insets, viewport geometry, device pixel ratio, and User-Agent. Read-only — does not modify page state. Tier C per RFC #277: the same Runtime.evaluate probe runs in both `mock` (devtools panel page with window.__ait state) and `relay` (real-device WebView with window.__sdk). The result includes a `source: \"mock\" | \"relay-dev\" | \"relay-mobile\"` field so consumers can identify provenance without inspecting payload values. (`relay-mobile` = env 2 real-device PWA over an external relay; `relay-dev` = env 3 dog-food WebView; relay-live/env 4 removed #665.) Use in a relay session (phone attached) to get ground-truth values for upgrading a viewport preset from extrapolated/placeholder to measured. Requires a page to be attached — call list_pages first.",
|
|
576
|
+
inputSchema: {
|
|
577
|
+
type: "object",
|
|
578
|
+
properties: {},
|
|
579
|
+
required: []
|
|
580
|
+
},
|
|
581
|
+
availableIn: "both"
|
|
582
|
+
},
|
|
583
|
+
{
|
|
584
|
+
name: "evaluate",
|
|
585
|
+
description: "Evaluates an arbitrary JavaScript expression on the attached mini-app page via CDP Runtime.evaluate (returnByValue: true) and returns the result. NOT read-only — the expression can have side effects (DOM mutations, SDK calls, state changes). Requires the relay to be attached — call list_pages first. Throws if the evaluation throws an exception on the page.\n\nSECURITY: expression and result are not redacted — never include secrets or auth tokens in the expression.\n\nPositive-allowlist kill-switch (#665): this tool is blocked when the attached page is on a non-debug host (apps.tossmini.com / env 4). Only localhost, *.trycloudflare.com, and *.private-apps.tossmini.com are allowed. relay-live (env 4) and the LIVE confirm guard are removed.",
|
|
586
|
+
inputSchema: {
|
|
587
|
+
type: "object",
|
|
588
|
+
properties: { expression: {
|
|
589
|
+
type: "string",
|
|
590
|
+
description: "JavaScript expression to evaluate in the page context."
|
|
591
|
+
} },
|
|
592
|
+
required: ["expression"]
|
|
593
|
+
},
|
|
594
|
+
availableIn: "both"
|
|
595
|
+
},
|
|
596
|
+
{
|
|
597
|
+
name: "list_exceptions",
|
|
598
|
+
description: "Lists JS-level exceptions captured via `Runtime.exceptionThrown` from the relay attached page. Includes timestamp, exception text, source URL/line, and stack trace. Use to root-cause SDK throws that may precede a Toss app crash (#265 / #267). The buffer holds up to 50 most recent exceptions and survives target replaced/crashed/destroyed events so an exception just before a crash is preserved. Returns up to 50 most recent by default.",
|
|
599
|
+
inputSchema: {
|
|
600
|
+
type: "object",
|
|
601
|
+
properties: { limit: {
|
|
602
|
+
type: "number",
|
|
603
|
+
description: "Maximum number of exceptions to return (default 50, max 50)."
|
|
604
|
+
} },
|
|
605
|
+
required: []
|
|
606
|
+
},
|
|
607
|
+
availableIn: "both"
|
|
608
|
+
},
|
|
609
|
+
{
|
|
610
|
+
name: "call_sdk",
|
|
611
|
+
description: "Calls a dog-food SDK method via the window.__sdkCall bridge (exported by @apps-in-toss/web-framework only in __DEBUG_BUILD__ bundles). NOT read-only — SDK calls have side effects (navigation, payments, permissions, etc.). On env 3/4 (real device relay) this hits the real SDK; on env 1 (local mock) and env 2 (PWA relay — real WebKit, mock SDK) it hits the mock SDK. Requires the relay to be attached — call list_pages first. Returns {ok: true, value} on success or {ok: false, error} on failure. If a Runtime.exceptionThrown event was observed within [callStart-50ms, callEnd+200ms], the result also includes `recentException` for crash triage. Returns a clear error if window.__sdkCall is not available — on relay (env 3/4) that means a non-dog-food bundle (redeploy via `ait build && aitcc app deploy`); on local (--target=local, env 1) it means the dev bridge is not installed (start the dev server with `pnpm dev`).\n\nSECURITY: method name, args, and result value are not redacted — never include secrets.\n\nPositive-allowlist kill-switch (#665): blocked when the attached page is on a non-debug host (apps.tossmini.com / env 4). relay-live and the LIVE guard removed.\n\nIMPORTANT — 인자 시그니처 (잘못된 인자로 호출하면 토스 앱 crash 위험):\n setDeviceOrientation: call_sdk(\"setDeviceOrientation\", [{ type: \"landscape\" }]) // NOT \"landscape\"\n setIosSwipeGestureEnabled: call_sdk(\"setIosSwipeGestureEnabled\", [{ isEnabled: false }])\n setSecureScreen: call_sdk(\"setSecureScreen\", [{ enabled: true }])\n setScreenAwakeMode: call_sdk(\"setScreenAwakeMode\", [{ enabled: true }])\n getOperationalEnvironment: call_sdk(\"getOperationalEnvironment\", [])\n getPlatformOS: call_sdk(\"getPlatformOS\", [])\n getDeviceId: call_sdk(\"getDeviceId\", [])\n getLocale: call_sdk(\"getLocale\", [])\n getNetworkStatus: call_sdk(\"getNetworkStatus\", [])\n getSchemeUri: call_sdk(\"getSchemeUri\", [])\n requestReview: call_sdk(\"requestReview\", [])\n closeView: call_sdk(\"closeView\", [])",
|
|
612
|
+
inputSchema: {
|
|
613
|
+
type: "object",
|
|
614
|
+
properties: {
|
|
615
|
+
name: {
|
|
616
|
+
type: "string",
|
|
617
|
+
description: "SDK method name to call (e.g. \"getOperationalEnvironment\")."
|
|
618
|
+
},
|
|
619
|
+
args: {
|
|
620
|
+
type: "array",
|
|
621
|
+
description: "Arguments to pass to the SDK method (optional, default []).",
|
|
622
|
+
items: {}
|
|
623
|
+
}
|
|
624
|
+
},
|
|
625
|
+
required: ["name"]
|
|
626
|
+
},
|
|
627
|
+
availableIn: "both"
|
|
628
|
+
},
|
|
629
|
+
{
|
|
630
|
+
name: "AIT.getSdkCallHistory",
|
|
631
|
+
description: "Returns the recent Apps in Toss SDK call trace (method, args, result/error, timestamp) that raw CDP cannot observe. Read-only. Use to confirm an SDK call fired and how it resolved (e.g. a saveBase64Data permission regression).",
|
|
632
|
+
inputSchema: {
|
|
633
|
+
type: "object",
|
|
634
|
+
properties: {},
|
|
635
|
+
required: []
|
|
636
|
+
},
|
|
637
|
+
availableIn: "both"
|
|
638
|
+
},
|
|
639
|
+
{
|
|
640
|
+
name: "AIT.getMockState",
|
|
641
|
+
description: "Returns the devtools mock state snapshot (window.__ait) — environment, permissions, location, auth, network, IAP, and more. Read-only. In dev mode this is the live browser mock state; in debug mode the in-app side reports it over the AIT domain.",
|
|
642
|
+
inputSchema: {
|
|
643
|
+
type: "object",
|
|
644
|
+
properties: {},
|
|
645
|
+
required: []
|
|
646
|
+
},
|
|
647
|
+
availableIn: "both"
|
|
648
|
+
},
|
|
649
|
+
{
|
|
650
|
+
name: "AIT.getOperationalEnvironment",
|
|
651
|
+
description: "Returns getOperationalEnvironment() plus the resolved SDK version — metadata raw CDP cannot observe. Read-only.",
|
|
652
|
+
inputSchema: {
|
|
653
|
+
type: "object",
|
|
654
|
+
properties: {},
|
|
655
|
+
required: []
|
|
656
|
+
},
|
|
657
|
+
availableIn: "both"
|
|
658
|
+
},
|
|
659
|
+
{
|
|
660
|
+
name: "start_debug",
|
|
661
|
+
description: "Switches the active debug environment in-place (issue #348) — no Claude Code restart and no MCP re-handshake. One daemon holds both a local (env 1, mock SDK in a Chromium) and a relay (env 2/3, real-device over the Chii relay + cloudflared tunnel) connection at once; this tool flips which one every other tool reads from, lazily booting the requested family's infra on first use and keeping the inactive one warm so an existing attach survives the switch. After switching it emits notifications/tools/list_changed — call tools/list again to see the updated tool surface for the new environment.\n\nPositive-allowlist kill-switch (#665): relay sessions on apps.tossmini.com (env 4, released production) are silently blocked at both the in-app gate and this MCP layer — relay-live and the LIVE guard have been removed. Only localhost/loopback (env 1), *.trycloudflare.com (env 2), and *.private-apps.tossmini.com (env 3) are allowed.\n\nmodes:\n local-browser — env 1: desktop Chromium with the mock SDK and a local CDP attach. Side-effect tools (call_sdk/evaluate) run unguarded against the mock; nothing touches a real device or real users. No prerequisites — the default, always-available environment for state/contract and visual-layout work.\n relay-sandbox — env 2: a real-device PWA (real WebKit engine, mock SDK) over an external Chii relay. CDP covers real-device WebKit DOM, console, exceptions, and safe-area observation; call_sdk still hits the mock (SDK fidelity needs relay-staging). Side-effect tools run unguarded against the mock. Only the dual-connection daemon can enter relay-sandbox in-place; a single-connection session rejects it with \"동적 전환할 수 없습니다 … relay-sandbox 모드로 재시작하세요\" — follow that hint and restart the MCP server in relay-sandbox mode rather than retrying. Prerequisites: both AIT_RELAY_BASE_URL (the relay base the unplugin emits when started with tunnel:{cdp:true}, used for the CDP attach) and AIT_TUNNEL_BASE_URL (the dev-server tunnel host, required by start_attach to render the launcher QR) must be set before the MCP server starts — the unplugin does not auto-forward either; set them explicitly. Both carry relay/tunnel hosts (secret-class) — keep them out of logs.\n relay-staging — env 3: a real-device Toss WebView dog-food build with the REAL SDK over the intoss-private relay. The first environment where call_sdk exercises the genuine native bridge. Side-effect tools run unguarded (dog-food, not released to real users). Prerequisite: a dog-food candidate bundle built with `RELEASE_CHANNEL=dogfood ait build`, then uploaded with `ait deploy` (add `--scheme-only` to print the resulting intoss-private://…?_deploymentId=… deep-link); open that deep-link/QR on the device to cold-load the bundle with the relay injected. Unlike env 2, env 3 is NOT a dev-server tunnel — it is a deployed bundle reached via the intoss-private scheme, so `pnpm dev` plays no part here.\n\nFor a relay mode (relay-sandbox/relay-staging), also pass projectRoot — the absolute mini-app project root — so the daemon can read the relay auth secret from <projectRoot>/.ait_relay (read-only; the daemon never mints it). Omit it for local-browser.",
|
|
662
|
+
inputSchema: {
|
|
663
|
+
type: "object",
|
|
664
|
+
properties: {
|
|
665
|
+
mode: {
|
|
666
|
+
type: "string",
|
|
667
|
+
enum: [
|
|
668
|
+
"local-browser",
|
|
669
|
+
"relay-sandbox",
|
|
670
|
+
"relay-staging"
|
|
671
|
+
],
|
|
672
|
+
description: "Target environment to switch to. relay-live (env 4) has been removed (#665) — use relay-staging (env 3) for dog-food debugging."
|
|
673
|
+
},
|
|
674
|
+
projectRoot: {
|
|
675
|
+
type: "string",
|
|
676
|
+
description: "Absolute path to the mini-app project root (the directory containing its package.json and .ait_relay). The daemon reads the relay auth secret from <projectRoot>/.ait_relay (read-only) when switching to a relay environment (relay-staging/relay-sandbox). Pass this because the daemon's own cwd is fixed at launch and may not be the project being debugged. Omit for mode=local-browser (no secret needed)."
|
|
677
|
+
}
|
|
678
|
+
},
|
|
679
|
+
required: ["mode"]
|
|
680
|
+
},
|
|
681
|
+
availableIn: "both"
|
|
682
|
+
},
|
|
683
|
+
{
|
|
684
|
+
name: "get_debug_status",
|
|
685
|
+
description: "Reports the current debug session state — which environment/mode is active, whether a page is attached, and a full diagnostic snapshot — in one call. Use this any time to answer \"what mode am I in right now?\" or \"why is this not working?\" without chaining tools. Fields: mcpVersion (MCP SDK version), devtoolsVersion (@ait-co/devtools package version), tunnel (up/wssUrl/pid/startedAt), pages (list_pages result + lastSeenAt stats), lastAttachAt, lastDetachAt, recentErrors (last N server-side errors, PII/secret redacted), authRejects ({count, lastAt} — relay TOTP 401 rejections, secret-free; count > 0 with empty pages means the phone reached the relay but its code was rejected), environment (kind: mock|relay-dev|relay-mobile, env: mock|relay backward-compat, reason, liveGuardActive: always false — relay-live and LIVE guard removed (#665); start_debug mode→kind mapping: relay-sandbox→relay-mobile, relay-staging→relay-dev, local-browser→mock), serverLockHolder (pid + startedAt from the lock file, or null), nextRecommendedAction ({tool, reason} or null — the single next tool to call; in local-target mode tunnel.up=false is normal so \"restart\" is never recommended). All fields are nullable — missing data is null, not an error. debug-mode only — dev-mode (--mode=dev) does not support relay diagnostics. Tier C (both mock and relay).",
|
|
686
|
+
inputSchema: {
|
|
687
|
+
type: "object",
|
|
688
|
+
properties: { recent_errors_limit: {
|
|
689
|
+
type: "number",
|
|
690
|
+
description: "Maximum number of recent server-side errors to include (default 10, max 50)."
|
|
691
|
+
} },
|
|
692
|
+
required: []
|
|
693
|
+
},
|
|
694
|
+
availableIn: "both"
|
|
695
|
+
},
|
|
696
|
+
{
|
|
697
|
+
name: "run_tests",
|
|
698
|
+
description: "Runs mini-app test files on the attached page over CDP (Runtime.evaluate). Each matched file is bundled with esbuild (SDK imports redirected to the live mock/SDK), injected into the attached WebView, and executed; returns per-file results plus flattened totals (passed/failed/skipped/total). When there is no attached page and the current environment is relay (env 3), this tool automatically shows the QR dashboard and waits for a phone to connect before running (scheme_url required for env 3 relay-dev). Files run SEQUENTIALLY (single-attach model: the relay/local target serves one page), and one run_tests call runs at a time (a concurrent call is rejected). Test verification (assert/snapshot) is delegated to the in-page Vitest runtime; this tool is the transport + report. The per-file results array is the progress record — on partial failure you see exactly which files passed/failed/timed-out. Positive-allowlist kill-switch (#665): blocked when the attached page is on a non-debug host. debug-mode only — dev-mode (--mode=dev) has no CDP. Tier C (both mock/local and relay).",
|
|
699
|
+
inputSchema: {
|
|
700
|
+
type: "object",
|
|
701
|
+
properties: {
|
|
702
|
+
files: {
|
|
703
|
+
type: "array",
|
|
704
|
+
items: { type: "string" },
|
|
705
|
+
description: "Glob patterns or file paths to run (e.g. [\"src/**/*.ait.test.ts\"]). Resolved relative to projectRoot when given, else the daemon cwd. Required, non-empty."
|
|
706
|
+
},
|
|
707
|
+
projectRoot: {
|
|
708
|
+
type: "string",
|
|
709
|
+
description: "Absolute path to the mini-app project root used as the glob base. Pass this because the daemon's cwd is fixed at launch. Optional."
|
|
710
|
+
},
|
|
711
|
+
timeout_ms: {
|
|
712
|
+
type: "number",
|
|
713
|
+
description: "Per-file evaluate timeout in ms (default 30000, range 1000–600000). Out-of-range/invalid values fall back to the default."
|
|
714
|
+
},
|
|
715
|
+
scheme_url: {
|
|
716
|
+
type: "string",
|
|
717
|
+
description: "intoss-private:// deep-link URL from `ait deploy --scheme-only` (env 3 relay-dev only). Required when there is no attached page and the environment is relay-dev — the tool uses it to build the QR attach URL and wait for the phone to connect. Ignored when a page is already attached."
|
|
718
|
+
},
|
|
719
|
+
cell: {
|
|
720
|
+
type: "object",
|
|
721
|
+
description: "Optional cell object to inject into globalThis BEFORE running tests (e.g. { \"__AIT_CELL__\": { \"sdkLine\": \"2.x\", \"platform\": \"ios\" } }). Applied only on the auto-attach path (no-page → attach → inject → run). When a page is already attached the caller is responsible for any prior injection. Ignored when empty or absent. Values must be JSON-serialisable.",
|
|
722
|
+
additionalProperties: true
|
|
723
|
+
}
|
|
724
|
+
},
|
|
725
|
+
required: ["files"]
|
|
726
|
+
},
|
|
727
|
+
availableIn: "both"
|
|
728
|
+
}
|
|
729
|
+
].map((t) => t.name));
|
|
730
|
+
function isCrashAware(conn) {
|
|
731
|
+
return typeof conn.getLastCrashDetectedAt === "function" && typeof conn.getTargetLastSeenAt === "function";
|
|
732
|
+
}
|
|
733
|
+
function listPages(connection, tunnel) {
|
|
734
|
+
const pages = connection.listTargets().map((t) => {
|
|
735
|
+
const lastSeenMs = isCrashAware(connection) ? connection.getTargetLastSeenAt(t.id) : null;
|
|
736
|
+
return {
|
|
737
|
+
id: t.id,
|
|
738
|
+
title: t.title,
|
|
739
|
+
url: redactAtParam(t.url),
|
|
740
|
+
lastSeenAt: lastSeenMs !== null ? new Date(lastSeenMs).toISOString() : null
|
|
741
|
+
};
|
|
742
|
+
});
|
|
743
|
+
const crashMs = isCrashAware(connection) ? connection.getLastCrashDetectedAt() : null;
|
|
744
|
+
const crashDetectedAt = crashMs !== null ? new Date(crashMs).toISOString() : null;
|
|
745
|
+
return {
|
|
746
|
+
pages,
|
|
747
|
+
tunnel,
|
|
748
|
+
crashDetectedAt,
|
|
749
|
+
crashWarning: crashDetectedAt ? `[ait-debug] page crash 감지됨 — 새 attach 필요 (관측 시각: ${crashDetectedAt})` : null,
|
|
750
|
+
singleAttachModel: true
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Heuristic: can this process open a GUI browser?
|
|
755
|
+
*
|
|
756
|
+
* Returns `true` when we think a GUI is available:
|
|
757
|
+
* - On macOS (`darwin`) we assume yes (MCP normally runs on the user's Mac).
|
|
758
|
+
* - On Linux we check for `DISPLAY` or `WAYLAND_DISPLAY`.
|
|
759
|
+
* - On Windows we assume yes.
|
|
760
|
+
* - In a CI environment (`CI=true`) we assume no.
|
|
761
|
+
*/
|
|
762
|
+
function canOpenBrowser() {
|
|
763
|
+
if (process.env.CI === "true" || process.env.CI === "1") return false;
|
|
764
|
+
const platform = process.platform;
|
|
765
|
+
if (platform === "darwin" || platform === "win32") return true;
|
|
766
|
+
if (platform === "linux") return Boolean(process.env.DISPLAY ?? process.env.WAYLAND_DISPLAY);
|
|
767
|
+
return false;
|
|
768
|
+
}
|
|
769
|
+
/** platform별 browser open 명령 후보 목록 — 앞에서부터 순차 시도. */
|
|
770
|
+
function getBrowserCandidates(httpUrl) {
|
|
771
|
+
const platform = process.platform;
|
|
772
|
+
if (platform === "darwin") return [
|
|
773
|
+
{
|
|
774
|
+
cmd: "open",
|
|
775
|
+
args: [httpUrl]
|
|
776
|
+
},
|
|
777
|
+
{
|
|
778
|
+
cmd: "open",
|
|
779
|
+
args: [
|
|
780
|
+
"-a",
|
|
781
|
+
"Safari",
|
|
782
|
+
httpUrl
|
|
783
|
+
]
|
|
784
|
+
},
|
|
785
|
+
{
|
|
786
|
+
cmd: "open",
|
|
787
|
+
args: [
|
|
788
|
+
"-a",
|
|
789
|
+
"Google Chrome",
|
|
790
|
+
httpUrl
|
|
791
|
+
]
|
|
792
|
+
},
|
|
793
|
+
{
|
|
794
|
+
cmd: "open",
|
|
795
|
+
args: [
|
|
796
|
+
"-a",
|
|
797
|
+
"Firefox",
|
|
798
|
+
httpUrl
|
|
799
|
+
]
|
|
800
|
+
}
|
|
801
|
+
];
|
|
802
|
+
if (platform === "win32") return [{
|
|
803
|
+
cmd: "cmd",
|
|
804
|
+
args: [
|
|
805
|
+
"/c",
|
|
806
|
+
"start",
|
|
807
|
+
"",
|
|
808
|
+
httpUrl
|
|
809
|
+
]
|
|
810
|
+
}, {
|
|
811
|
+
cmd: "rundll32",
|
|
812
|
+
args: ["url.dll,FileProtocolHandler", httpUrl]
|
|
813
|
+
}];
|
|
814
|
+
return [
|
|
815
|
+
{
|
|
816
|
+
cmd: "xdg-open",
|
|
817
|
+
args: [httpUrl]
|
|
818
|
+
},
|
|
819
|
+
{
|
|
820
|
+
cmd: "sensible-browser",
|
|
821
|
+
args: [httpUrl]
|
|
822
|
+
},
|
|
823
|
+
{
|
|
824
|
+
cmd: "x-www-browser",
|
|
825
|
+
args: [httpUrl]
|
|
826
|
+
},
|
|
827
|
+
{
|
|
828
|
+
cmd: "firefox",
|
|
829
|
+
args: [httpUrl]
|
|
830
|
+
},
|
|
831
|
+
{
|
|
832
|
+
cmd: "google-chrome",
|
|
833
|
+
args: [httpUrl]
|
|
834
|
+
},
|
|
835
|
+
{
|
|
836
|
+
cmd: "chromium",
|
|
837
|
+
args: [httpUrl]
|
|
838
|
+
}
|
|
839
|
+
];
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Redacts ONLY the `at=<value>` (TOTP) query param to `at=<redacted>`, leaving
|
|
843
|
+
* every other query param (_deploymentId, debug, relay) intact. SECRET-HANDLING:
|
|
844
|
+
* the TOTP code is the single short-lived secret carried in a CDP page url.
|
|
845
|
+
*/
|
|
846
|
+
function redactAtParam(text) {
|
|
847
|
+
return text.replace(/\bat=([^&\s"']+)/g, "at=<redacted>");
|
|
848
|
+
}
|
|
849
|
+
/** stderr에서 at= TOTP 코드 값을 redact한다. */
|
|
850
|
+
function redactSecrets(text) {
|
|
851
|
+
return redactAtParam(text);
|
|
852
|
+
}
|
|
853
|
+
/** spawnSync exit 0이어도 stderr에 launch 실패 시그널이 있으면 실패로 판단한다. */
|
|
854
|
+
const LAUNCH_FAILURE_PATTERNS = [
|
|
855
|
+
/LSOpenURLsWithRole\(\) failed/,
|
|
856
|
+
/kLSApplicationNotFoundErr/,
|
|
857
|
+
/No application/,
|
|
858
|
+
/Unable to find application/,
|
|
859
|
+
/xdg-open: not found/,
|
|
860
|
+
/command not found/
|
|
861
|
+
];
|
|
862
|
+
function isLaunchFailureStderr(stderr) {
|
|
863
|
+
return LAUNCH_FAILURE_PATTERNS.some((p) => p.test(stderr));
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* 로컬 HTTP 서버 루트 URL(`http://127.0.0.1:<port>/`)을 OS 기본 브라우저로 연다 (#595).
|
|
867
|
+
*
|
|
868
|
+
* platform별 fallback chain으로 시도하며, 모두 실패하면 1회 retry를 수행한다
|
|
869
|
+
* (ephemeral process launch 타이밍 문제 대응). retry까지 실패해도 `opened: false` +
|
|
870
|
+
* `httpUrl`을 반환해 사용자가 직접 브라우저에 붙여넣을 수 있게 한다.
|
|
871
|
+
*
|
|
872
|
+
* SECRET-HANDLING:
|
|
873
|
+
* - tmp 파일을 만들지 않는다 (HTML/PNG는 HTTP 서버가 메모리에서 응답).
|
|
874
|
+
* - httpUrl은 `http://127.0.0.1:<port>/`(루트, 시크릿 없음). pngUrl은 127.0.0.1 로컬 전용.
|
|
875
|
+
* - stderr 캡처 결과에서 at= 코드 값을 redact한 후 stderrSummary에 포함.
|
|
876
|
+
* - attachUrl, deploymentId, TOTP 코드를 stdout/stderr/로그에 직접 출력 금지.
|
|
877
|
+
*
|
|
878
|
+
* @param httpUrl - `http://127.0.0.1:<port>/` 루트 URL (시크릿 없음, #595).
|
|
879
|
+
* @param pngUrl - `http://127.0.0.1:<port>/qr.png?u=<encoded>` PNG fallback URL.
|
|
880
|
+
*/
|
|
881
|
+
async function openQrInBrowser(httpUrl, pngUrl) {
|
|
882
|
+
const { spawnSync } = await import("node:child_process");
|
|
883
|
+
/**
|
|
884
|
+
* 한 번의 fallback chain 시도. 성공하면 열린 후보 cmd를 반환, 실패하면 null.
|
|
885
|
+
* stderrLines에 각 후보의 stderr를 누적한다.
|
|
886
|
+
*/
|
|
887
|
+
function tryOnce(stderrLines) {
|
|
888
|
+
const candidates = getBrowserCandidates(httpUrl);
|
|
889
|
+
for (const { cmd, args } of candidates) {
|
|
890
|
+
const result = spawnSync(cmd, args, {
|
|
891
|
+
encoding: "utf8",
|
|
892
|
+
timeout: 5e3
|
|
893
|
+
});
|
|
894
|
+
if (result.error) {
|
|
895
|
+
stderrLines.push(`${cmd}: ${result.error.message}`);
|
|
896
|
+
continue;
|
|
897
|
+
}
|
|
898
|
+
const stderr = typeof result.stderr === "string" ? result.stderr : "";
|
|
899
|
+
if (stderr) stderrLines.push(`${cmd}: ${redactSecrets(stderr.trim())}`);
|
|
900
|
+
if (result.status === 0 && !isLaunchFailureStderr(stderr)) return true;
|
|
901
|
+
}
|
|
902
|
+
return false;
|
|
903
|
+
}
|
|
904
|
+
const stderrLines = [];
|
|
905
|
+
if (tryOnce(stderrLines)) return {
|
|
906
|
+
opened: true,
|
|
907
|
+
httpUrl,
|
|
908
|
+
pngUrl
|
|
909
|
+
};
|
|
910
|
+
if (tryOnce(stderrLines)) return {
|
|
911
|
+
opened: true,
|
|
912
|
+
httpUrl,
|
|
913
|
+
pngUrl,
|
|
914
|
+
retried: true
|
|
915
|
+
};
|
|
916
|
+
return {
|
|
917
|
+
opened: false,
|
|
918
|
+
httpUrl,
|
|
919
|
+
pngUrl,
|
|
920
|
+
error: "모든 브라우저 실행 후보가 실패했습니다.",
|
|
921
|
+
stderrSummary: stderrLines.length > 0 ? stderrLines.join("\n") : void 0
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
`
|
|
925
|
+
(function() {
|
|
926
|
+
var el = document.createElement('div');
|
|
927
|
+
el.style.cssText = 'position:fixed;top:0;left:0;width:0;height:0;visibility:hidden;' +
|
|
928
|
+
'padding-top:env(safe-area-inset-top,0px);' +
|
|
929
|
+
'padding-right:env(safe-area-inset-right,0px);' +
|
|
930
|
+
'padding-bottom:env(safe-area-inset-bottom,0px);' +
|
|
931
|
+
'padding-left:env(safe-area-inset-left,0px)';
|
|
932
|
+
document.documentElement.appendChild(el);
|
|
933
|
+
var cs = window.getComputedStyle(el);
|
|
934
|
+
var cssEnv = {
|
|
935
|
+
top: parseFloat(cs.paddingTop) || 0,
|
|
936
|
+
right: parseFloat(cs.paddingRight) || 0,
|
|
937
|
+
bottom: parseFloat(cs.paddingBottom) || 0,
|
|
938
|
+
left: parseFloat(cs.paddingLeft) || 0
|
|
939
|
+
};
|
|
940
|
+
document.documentElement.removeChild(el);
|
|
941
|
+
var sdkInsets = null;
|
|
942
|
+
var sdkInsetsSource = null;
|
|
943
|
+
var sdkInsetsError = undefined;
|
|
944
|
+
try {
|
|
945
|
+
var sdk = window.__sdk;
|
|
946
|
+
var ait = window.__ait;
|
|
947
|
+
if (sdk && sdk.SafeAreaInsets && typeof sdk.SafeAreaInsets.get === 'function') {
|
|
948
|
+
sdkInsets = sdk.SafeAreaInsets.get();
|
|
949
|
+
sdkInsetsSource = 'window.__sdk';
|
|
950
|
+
} else if (sdk && typeof sdk.getSafeAreaInsets === 'function') {
|
|
951
|
+
sdkInsets = sdk.getSafeAreaInsets();
|
|
952
|
+
sdkInsetsSource = 'window.__sdk';
|
|
953
|
+
} else if (ait && ait.state && ait.state.safeAreaInsets &&
|
|
954
|
+
typeof ait.state.safeAreaInsets.top === 'number') {
|
|
955
|
+
var s = ait.state.safeAreaInsets;
|
|
956
|
+
sdkInsets = { top: s.top, bottom: s.bottom, left: s.left, right: s.right };
|
|
957
|
+
sdkInsetsSource = 'window.__ait';
|
|
958
|
+
} else if (!sdk && !ait) {
|
|
959
|
+
sdkInsetsError = 'neither window.__sdk (relay) nor window.__ait (mock) available';
|
|
960
|
+
} else if (sdk) {
|
|
961
|
+
sdkInsetsError = 'neither SafeAreaInsets.get nor getSafeAreaInsets found on window.__sdk';
|
|
962
|
+
} else {
|
|
963
|
+
sdkInsetsError = 'window.__ait.state.safeAreaInsets is missing or malformed';
|
|
964
|
+
}
|
|
965
|
+
} catch(e) {
|
|
966
|
+
sdkInsetsError = String(e && e.message || e);
|
|
967
|
+
}
|
|
968
|
+
var navBarHeight = null;
|
|
969
|
+
var navBarHeightSource = 'not-exposed-by-sdk';
|
|
970
|
+
try {
|
|
971
|
+
var nb = document.querySelector('.ait-navbar');
|
|
972
|
+
if (nb) {
|
|
973
|
+
navBarHeight = nb.getBoundingClientRect().height;
|
|
974
|
+
navBarHeightSource = 'dom-.ait-navbar';
|
|
975
|
+
}
|
|
976
|
+
} catch(_) {}
|
|
977
|
+
var result = {
|
|
978
|
+
cssEnv: cssEnv,
|
|
979
|
+
sdkInsets: sdkInsets,
|
|
980
|
+
sdkInsetsSource: sdkInsetsSource,
|
|
981
|
+
navBarHeight: navBarHeight,
|
|
982
|
+
navBarHeightSource: navBarHeightSource,
|
|
983
|
+
innerWidth: window.innerWidth,
|
|
984
|
+
innerHeight: window.innerHeight,
|
|
985
|
+
devicePixelRatio: window.devicePixelRatio,
|
|
986
|
+
userAgent: navigator.userAgent
|
|
987
|
+
};
|
|
988
|
+
if (sdkInsetsError !== undefined) result.sdkInsetsError = sdkInsetsError;
|
|
989
|
+
return JSON.stringify(result);
|
|
990
|
+
})()
|
|
991
|
+
`.trim();
|
|
992
|
+
//#endregion
|
|
993
|
+
//#region src/mcp/tunnel.ts
|
|
994
|
+
/**
|
|
995
|
+
* cloudflared quick tunnel + attach banner for the debug-mode MCP server.
|
|
996
|
+
*
|
|
997
|
+
* On spawn, the debug server opens an accountless `*.trycloudflare.com` quick
|
|
998
|
+
* tunnel to the local Chii relay so the phone can attach over a public wss URL,
|
|
999
|
+
* then prints a unicode half-block QR + attach instructions. When TOTP auth is
|
|
1000
|
+
* enabled (`AIT_DEBUG_TOTP_SECRET` is set), the QR encodes only the base relay
|
|
1001
|
+
* URL — the TOTP code (`at=`) is NOT included because it rotates every 30 s
|
|
1002
|
+
* and would be stale by the time a human scans. The in-app deep-link builder
|
|
1003
|
+
* splices the live code at attach time.
|
|
1004
|
+
*
|
|
1005
|
+
* Tunnel health probe (`TunnelHealthProbe`):
|
|
1006
|
+
* After the tunnel is up, a periodic HTTP HEAD probe hits the tunnel's
|
|
1007
|
+
* `https://` URL every `probeIntervalMs` (default 60 s). Two consecutive
|
|
1008
|
+
* failures trigger a reissue attempt (spawn a new cloudflared quick tunnel
|
|
1009
|
+
* and redirect traffic). After `MAX_REISSUE_ATTEMPTS` (3) consecutive
|
|
1010
|
+
* reissue failures, the probe gives up and marks the tunnel permanently
|
|
1011
|
+
* dropped — `tunnelStatus.up` becomes false with `droppedAt` set. The caller
|
|
1012
|
+
* should surface this to the agent so the user knows to restart the server.
|
|
1013
|
+
*
|
|
1014
|
+
* SECRET-HANDLING: The TOTP secret and computed code values MUST NOT appear
|
|
1015
|
+
* in any output from this module.
|
|
1016
|
+
*
|
|
1017
|
+
* Node-only: spawns the cloudflared binary and writes to stdout/stderr.
|
|
1018
|
+
*/
|
|
1019
|
+
/** Generates a 32-byte hex attach token shown as a pairing hint (relay-side validation is a later phase). */
|
|
1020
|
+
function generateAttachToken() {
|
|
1021
|
+
return randomBytes(32).toString("hex");
|
|
1022
|
+
}
|
|
1023
|
+
/** Ensures the cloudflared binary is installed (downloads + caches on first run). */
|
|
1024
|
+
async function ensureCloudflaredBin() {
|
|
1025
|
+
const { existsSync } = await import("node:fs");
|
|
1026
|
+
if (!existsSync(bin)) await install(bin);
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* Opens a cloudflared quick tunnel to the local relay port and resolves once
|
|
1030
|
+
* the public URL is assigned.
|
|
1031
|
+
*
|
|
1032
|
+
* FIX 1 (issue #571): after URL resolution the returned `QuickTunnel` object
|
|
1033
|
+
* watches the cloudflared child process for unexpected exits and calls any
|
|
1034
|
+
* registered `onUnexpectedExit` callback so the health probe can immediately
|
|
1035
|
+
* trigger reissue instead of waiting for the next poll interval.
|
|
1036
|
+
*/
|
|
1037
|
+
async function startQuickTunnel(localPort) {
|
|
1038
|
+
await ensureCloudflaredBin();
|
|
1039
|
+
const tunnel = Tunnel.quick(`http://127.0.0.1:${localPort}`);
|
|
1040
|
+
const url = await new Promise((resolve, reject) => {
|
|
1041
|
+
const onUrl = (assigned) => {
|
|
1042
|
+
cleanup();
|
|
1043
|
+
resolve(assigned);
|
|
1044
|
+
};
|
|
1045
|
+
const onError = (err) => {
|
|
1046
|
+
cleanup();
|
|
1047
|
+
reject(err);
|
|
1048
|
+
};
|
|
1049
|
+
const onExit = (code) => {
|
|
1050
|
+
cleanup();
|
|
1051
|
+
reject(/* @__PURE__ */ new Error(`cloudflared exited before assigning a URL (code ${code})`));
|
|
1052
|
+
};
|
|
1053
|
+
const cleanup = () => {
|
|
1054
|
+
tunnel.off("url", onUrl);
|
|
1055
|
+
tunnel.off("error", onError);
|
|
1056
|
+
tunnel.off("exit", onExit);
|
|
1057
|
+
};
|
|
1058
|
+
tunnel.once("url", onUrl);
|
|
1059
|
+
tunnel.once("error", onError);
|
|
1060
|
+
tunnel.once("exit", onExit);
|
|
1061
|
+
});
|
|
1062
|
+
let intentionalStop = false;
|
|
1063
|
+
let unexpectedExitCb = null;
|
|
1064
|
+
tunnel.once("exit", (code) => {
|
|
1065
|
+
if (!intentionalStop && unexpectedExitCb !== null) unexpectedExitCb(code);
|
|
1066
|
+
});
|
|
1067
|
+
return {
|
|
1068
|
+
url,
|
|
1069
|
+
wssUrl: url.replace(/^https/, "wss"),
|
|
1070
|
+
childPid: tunnel.process?.pid,
|
|
1071
|
+
onUnexpectedExit(cb) {
|
|
1072
|
+
unexpectedExitCb = cb;
|
|
1073
|
+
},
|
|
1074
|
+
stop() {
|
|
1075
|
+
intentionalStop = true;
|
|
1076
|
+
tunnel.stop();
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* Renders a pure unicode half-block QR string for the given text.
|
|
1082
|
+
*
|
|
1083
|
+
* Uses `qrcode` (Node full lib) to get the raw bit matrix, then encodes every
|
|
1084
|
+
* two vertical modules into a single half-block character:
|
|
1085
|
+
* - both dark → `█`
|
|
1086
|
+
* - top only → `▀`
|
|
1087
|
+
* - bottom only → `▄`
|
|
1088
|
+
* - both light → ` ` (space)
|
|
1089
|
+
*
|
|
1090
|
+
* The output contains **zero ANSI escape codes**, so it renders correctly in
|
|
1091
|
+
* every surface (terminal, VS Code, JetBrains, web) and can be scanned by a
|
|
1092
|
+
* phone camera when shown verbatim in an agent response.
|
|
1093
|
+
*
|
|
1094
|
+
* Shared by `renderAttachBanner` (relay wssUrl QR) and the `start_attach`
|
|
1095
|
+
* MCP tool response (attach deep-link QR).
|
|
1096
|
+
*/
|
|
1097
|
+
async function renderQr(text) {
|
|
1098
|
+
const { default: QRCode } = await import("qrcode");
|
|
1099
|
+
const qr = QRCode.create(text, { errorCorrectionLevel: "M" });
|
|
1100
|
+
const size = qr.modules.size;
|
|
1101
|
+
const data = qr.modules.data;
|
|
1102
|
+
const isDark = (x, y) => {
|
|
1103
|
+
if (x < 0 || y < 0 || x >= size || y >= size) return false;
|
|
1104
|
+
return data[y * size + x] === 1;
|
|
1105
|
+
};
|
|
1106
|
+
const QUIET = 1;
|
|
1107
|
+
const lines = [];
|
|
1108
|
+
for (let y = -QUIET; y < size + QUIET; y += 2) {
|
|
1109
|
+
let line = "";
|
|
1110
|
+
for (let x = -QUIET; x < size + QUIET; x++) {
|
|
1111
|
+
const top = isDark(x, y);
|
|
1112
|
+
const bot = isDark(x, y + 1);
|
|
1113
|
+
line += top && bot ? "█" : top ? "▀" : bot ? "▄" : " ";
|
|
1114
|
+
}
|
|
1115
|
+
lines.push(line);
|
|
1116
|
+
}
|
|
1117
|
+
return `${lines.join("\n")}\n`;
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Renders the attach banner (relay URL + unicode half-block QR) as a string.
|
|
1121
|
+
*
|
|
1122
|
+
* The QR is produced by `renderQr` (a half-block matrix, not the
|
|
1123
|
+
* `qrcode-terminal` ASCII art used by the unplugin banner) and encodes the
|
|
1124
|
+
* base `wssUrl` only. When `totpEnabled` is true, a note
|
|
1125
|
+
* is added that attach URLs generated by `start_attach` will include a
|
|
1126
|
+
* live TOTP code (`at=`) appended at call time.
|
|
1127
|
+
*
|
|
1128
|
+
* SECRET-HANDLING: no secret value, TOTP code, or intermediate value is
|
|
1129
|
+
* included in this output.
|
|
1130
|
+
*/
|
|
1131
|
+
async function renderAttachBanner(input) {
|
|
1132
|
+
const qr = await renderQr(input.wssUrl);
|
|
1133
|
+
const authNote = input.totpEnabled ? " auth: TOTP enabled — attach URLs include a rotating code (at=)." : " auth: none (set AIT_DEBUG_TOTP_SECRET to enable TOTP).";
|
|
1134
|
+
return [
|
|
1135
|
+
"",
|
|
1136
|
+
"AIT debug — attach a mini-app to this session",
|
|
1137
|
+
"",
|
|
1138
|
+
` relay (wss): ${input.wssUrl}`,
|
|
1139
|
+
authNote,
|
|
1140
|
+
"",
|
|
1141
|
+
" Use start_attach to generate a deep link with the current TOTP code.",
|
|
1142
|
+
" Scan the QR to locate the relay (open the dog-food URL separately with",
|
|
1143
|
+
" ?debug=1&relay=<wss>&at=<code> or use the start_attach tool):",
|
|
1144
|
+
"",
|
|
1145
|
+
qr
|
|
1146
|
+
].join("\n");
|
|
1147
|
+
}
|
|
1148
|
+
/** Prints the attach banner to stderr (stdout is the MCP stdio channel). */
|
|
1149
|
+
async function printAttachBanner(input) {
|
|
1150
|
+
const banner = await renderAttachBanner(input);
|
|
1151
|
+
process.stderr.write(`${banner}\n`);
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* Probes `https://` URL with an HTTP HEAD request.
|
|
1155
|
+
* Returns `true` when the server responds (any HTTP status), `false` on
|
|
1156
|
+
* network error or timeout.
|
|
1157
|
+
*
|
|
1158
|
+
* We treat any HTTP response (including 4xx/5xx) as "tunnel alive" because
|
|
1159
|
+
* cloudflared itself responds to the HEAD — if the tunnel process died, the
|
|
1160
|
+
* request fails at the network level rather than returning a status code.
|
|
1161
|
+
*
|
|
1162
|
+
* @param httpsUrl - The `https://` tunnel URL to probe.
|
|
1163
|
+
* @param timeoutMs - Abort timeout in ms. Default 10 000.
|
|
1164
|
+
*/
|
|
1165
|
+
async function probeTunnel(httpsUrl, timeoutMs = 1e4) {
|
|
1166
|
+
const { default: https } = await import("node:https");
|
|
1167
|
+
return new Promise((resolve) => {
|
|
1168
|
+
const url = new URL(httpsUrl);
|
|
1169
|
+
const timer = setTimeout(() => {
|
|
1170
|
+
req.destroy();
|
|
1171
|
+
resolve(false);
|
|
1172
|
+
}, timeoutMs);
|
|
1173
|
+
const req = https.request({
|
|
1174
|
+
hostname: url.hostname,
|
|
1175
|
+
port: 443,
|
|
1176
|
+
path: url.pathname || "/",
|
|
1177
|
+
method: "HEAD"
|
|
1178
|
+
}, (_res) => {
|
|
1179
|
+
clearTimeout(timer);
|
|
1180
|
+
_res.resume();
|
|
1181
|
+
resolve(true);
|
|
1182
|
+
});
|
|
1183
|
+
req.on("error", () => {
|
|
1184
|
+
clearTimeout(timer);
|
|
1185
|
+
resolve(false);
|
|
1186
|
+
});
|
|
1187
|
+
req.end();
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Starts a periodic health probe for a cloudflared quick tunnel.
|
|
1192
|
+
*
|
|
1193
|
+
* Every `probeIntervalMs` the probe sends an HTTP HEAD request to the tunnel's
|
|
1194
|
+
* `https://` URL. When `failuresBeforeReissue` consecutive failures are
|
|
1195
|
+
* detected, it attempts to spawn a new tunnel (up to `MAX_REISSUE_ATTEMPTS`
|
|
1196
|
+
* times). On success the caller is notified via `onReissue`; on permanent
|
|
1197
|
+
* failure via `onPermanentDrop`.
|
|
1198
|
+
*
|
|
1199
|
+
* FIX 1 (issue #571): the probe also subscribes to each tunnel's
|
|
1200
|
+
* `onUnexpectedExit` callback to detect child death *immediately* instead of
|
|
1201
|
+
* waiting for the next probe interval (which could be 60 s away).
|
|
1202
|
+
*
|
|
1203
|
+
* @returns `stop` — call during server shutdown to clear the probe interval.
|
|
1204
|
+
*/
|
|
1205
|
+
function startTunnelHealthProbe(initialTunnel, localPort, options) {
|
|
1206
|
+
const { probeIntervalMs = 6e4, failuresBeforeReissue = 2, onReissue, onPermanentDrop, log = (msg) => process.stderr.write(msg), probe = probeTunnel, spawnTunnel = startQuickTunnel } = options;
|
|
1207
|
+
let currentTunnel = initialTunnel;
|
|
1208
|
+
let consecutiveFailures = 0;
|
|
1209
|
+
let reissueAttempts = 0;
|
|
1210
|
+
let stopped = false;
|
|
1211
|
+
const doReissueOrDrop = async () => {
|
|
1212
|
+
if (stopped) return;
|
|
1213
|
+
reissueAttempts += 1;
|
|
1214
|
+
if (reissueAttempts > 3) return;
|
|
1215
|
+
log(`[ait-debug] tunnel drop detected — reissuing (attempt ${reissueAttempts}/3)\n`);
|
|
1216
|
+
try {
|
|
1217
|
+
const newTunnel = await spawnTunnel(localPort);
|
|
1218
|
+
try {
|
|
1219
|
+
currentTunnel.stop();
|
|
1220
|
+
} catch {}
|
|
1221
|
+
currentTunnel = newTunnel;
|
|
1222
|
+
consecutiveFailures = 0;
|
|
1223
|
+
armChildExitWatch(newTunnel);
|
|
1224
|
+
log(`[ait-debug] tunnel reissued — new relay: ${newTunnel.wssUrl}\n`);
|
|
1225
|
+
onReissue(newTunnel);
|
|
1226
|
+
} catch (err) {
|
|
1227
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1228
|
+
log(`[ait-debug] tunnel reissue attempt ${reissueAttempts} failed: ${message}\n`);
|
|
1229
|
+
if (reissueAttempts >= 3) {
|
|
1230
|
+
clearInterval(handle);
|
|
1231
|
+
stopped = true;
|
|
1232
|
+
const droppedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1233
|
+
log(`[ait-debug] tunnel permanently dropped after 3 reissue attempts — restart the debug server to continue (npx @ait-co/devtools devtools-mcp).
|
|
1234
|
+
`);
|
|
1235
|
+
onPermanentDrop(droppedAt);
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
};
|
|
1239
|
+
const armChildExitWatch = (t) => {
|
|
1240
|
+
t.onUnexpectedExit((code) => {
|
|
1241
|
+
if (stopped) return;
|
|
1242
|
+
log(`[ait-debug] cloudflared child exited unexpectedly (code=${code}) — triggering immediate reissue\n`);
|
|
1243
|
+
consecutiveFailures = failuresBeforeReissue;
|
|
1244
|
+
doReissueOrDrop();
|
|
1245
|
+
});
|
|
1246
|
+
};
|
|
1247
|
+
armChildExitWatch(initialTunnel);
|
|
1248
|
+
const handle = setInterval(() => {
|
|
1249
|
+
(async () => {
|
|
1250
|
+
if (stopped) return;
|
|
1251
|
+
const httpsUrl = currentTunnel.url;
|
|
1252
|
+
if (await probe(httpsUrl)) {
|
|
1253
|
+
if (consecutiveFailures > 0) log("[ait-debug] tunnel health probe: tunnel recovered\n");
|
|
1254
|
+
consecutiveFailures = 0;
|
|
1255
|
+
reissueAttempts = 0;
|
|
1256
|
+
return;
|
|
1257
|
+
}
|
|
1258
|
+
consecutiveFailures += 1;
|
|
1259
|
+
log(`[ait-debug] tunnel health probe: failure ${consecutiveFailures}/${failuresBeforeReissue} (url=${httpsUrl})\n`);
|
|
1260
|
+
if (consecutiveFailures < failuresBeforeReissue) return;
|
|
1261
|
+
await doReissueOrDrop();
|
|
1262
|
+
})();
|
|
1263
|
+
}, probeIntervalMs);
|
|
1264
|
+
return { stop() {
|
|
1265
|
+
stopped = true;
|
|
1266
|
+
clearInterval(handle);
|
|
1267
|
+
} };
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* Builds a `TunnelStatus` snapshot that includes drop state.
|
|
1271
|
+
*
|
|
1272
|
+
* Convenience helper for callers (debug-server) that maintain a mutable
|
|
1273
|
+
* `tunnelStatus` object — keeps the shape construction in one place.
|
|
1274
|
+
*/
|
|
1275
|
+
function makeTunnelStatus(up, wssUrl, droppedAt = null, reissueAttempts = 0) {
|
|
1276
|
+
return {
|
|
1277
|
+
up,
|
|
1278
|
+
wssUrl,
|
|
1279
|
+
droppedAt,
|
|
1280
|
+
reissueAttempts
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
//#endregion
|
|
1284
|
+
//#region src/mcp/attach-orchestrator.ts
|
|
1285
|
+
/**
|
|
1286
|
+
* Maximum age (ms) of a page's `lastSeenAt` before it is treated as a ghost
|
|
1287
|
+
* and excluded from the `wait_for_attach` short-circuit in `start_attach`
|
|
1288
|
+
* (issue #610).
|
|
1289
|
+
*
|
|
1290
|
+
* Rationale: the env-2 relay is owned by the dev server (unplugin), so every
|
|
1291
|
+
* `dev:phone:cdp` restart produces a new quick-tunnel. The old relay goes
|
|
1292
|
+
* offline immediately, but the daemon's warm `ChiiCdpConnection` still lists
|
|
1293
|
+
* the last-seen target — its `lastSeenAt` freezes at the moment the old relay
|
|
1294
|
+
* died. A 5-minute threshold is large enough to be invisible in normal usage
|
|
1295
|
+
* (active CDP sessions see a message every few seconds) while being small
|
|
1296
|
+
* enough to catch a relay that went down before the daemon was re-entered.
|
|
1297
|
+
*
|
|
1298
|
+
* Injectable for tests via {@link AttachDeps.stalePageThresholdMs}.
|
|
1299
|
+
*/
|
|
1300
|
+
const RELAY_SANDBOX_STALE_PAGE_MS = 300 * 1e3;
|
|
1301
|
+
/**
|
|
1302
|
+
* Segment length (ms) of the `start_attach` wait loop (issue #626 — TOTP in-call
|
|
1303
|
+
* re-mint). The single-shot `wait_for_attach` of the old attach tool could
|
|
1304
|
+
* not re-mint a TOTP code mid-wait; `start_attach` decomposes the wait into
|
|
1305
|
+
* SEGMENT_MS slices so it can detect an aging code between slices and re-mint a
|
|
1306
|
+
* fresh one without the agent re-calling the tool. 30 s = one TOTP step.
|
|
1307
|
+
*/
|
|
1308
|
+
const START_ATTACH_SEGMENT_MS = 3e4;
|
|
1309
|
+
/**
|
|
1310
|
+
* Elapsed-since-mint threshold (ms) at which `start_attach` re-mints a fresh
|
|
1311
|
+
* TOTP code during its wait loop (issue #626). The relay gate accepts a code for
|
|
1312
|
+
* `RELAY_VERIFY_SKEW_STEPS` (6) × 30 s = 180 s backwards from issuance; we re-mint
|
|
1313
|
+
* at 150 s to leave a 30 s margin so a phone scan never lands on an expired code.
|
|
1314
|
+
*/
|
|
1315
|
+
const START_ATTACH_REMINT_THRESHOLD_MS = 15e4;
|
|
1316
|
+
/**
|
|
1317
|
+
* Predicate used by `start_attach`'s `wait_for_attach` loop to decide
|
|
1318
|
+
* whether the relay-sandbox connection has a genuinely fresh page attached.
|
|
1319
|
+
*
|
|
1320
|
+
* Stale-ghost gating (issue #610): when the dev server restarts with a new
|
|
1321
|
+
* quick-tunnel, the warm `ChiiCdpConnection` still lists the last-seen target
|
|
1322
|
+
* but its `lastSeenAt` is frozen. A page whose `lastSeenAt` exceeds
|
|
1323
|
+
* `stalePageThresholdMs` is a ghost from the dead relay — it must NOT
|
|
1324
|
+
* short-circuit `wait_for_attach`.
|
|
1325
|
+
*
|
|
1326
|
+
* Rules:
|
|
1327
|
+
* - `pages.length === 0` → false (nothing attached).
|
|
1328
|
+
* - Connection has no `getLastSeenAt` (test fakes, local-browser) → falls back
|
|
1329
|
+
* to `pages.length > 0` (regression-safe).
|
|
1330
|
+
* - `seenMs === null` → treat as fresh (no CDP message received yet, first
|
|
1331
|
+
* message pending — the connection is alive).
|
|
1332
|
+
* - Otherwise: at least one page must satisfy `nowMs - seenMs <=
|
|
1333
|
+
* stalePageThresholdMs`.
|
|
1334
|
+
*
|
|
1335
|
+
* Exported for unit testing.
|
|
1336
|
+
*/
|
|
1337
|
+
function isSandboxPageFresh(pages, getLastSeenAt, nowMs, stalePageThresholdMs) {
|
|
1338
|
+
if (pages.length === 0) return false;
|
|
1339
|
+
if (getLastSeenAt === null) return true;
|
|
1340
|
+
return pages.some((p) => {
|
|
1341
|
+
const seenMs = getLastSeenAt(p.id);
|
|
1342
|
+
if (seenMs === null) return true;
|
|
1343
|
+
return nowMs - seenMs <= stalePageThresholdMs;
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
/**
|
|
1347
|
+
* Parses `_deploymentId` from the query string of a scheme URL.
|
|
1348
|
+
*
|
|
1349
|
+
* Returns `null` when the param is absent or empty — callers treat that as
|
|
1350
|
+
* "no deploymentId filter; match on presence only" and fall back to the
|
|
1351
|
+
* original `attachedPages.length > 0` condition.
|
|
1352
|
+
*
|
|
1353
|
+
* SECRET-HANDLING: deploymentId is a public identifier and may appear in
|
|
1354
|
+
* debug output. Never confuse it with TOTP secrets or relay tunnel URLs.
|
|
1355
|
+
*/
|
|
1356
|
+
function extractDeploymentId(schemeUrl) {
|
|
1357
|
+
try {
|
|
1358
|
+
const qIndex = schemeUrl.indexOf("?");
|
|
1359
|
+
if (qIndex === -1) return null;
|
|
1360
|
+
const id = new URLSearchParams(schemeUrl.slice(qIndex + 1)).get("_deploymentId");
|
|
1361
|
+
return id && id.length > 0 ? id : null;
|
|
1362
|
+
} catch {
|
|
1363
|
+
return null;
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
/** Resolves `deps.stalePageThresholdMs` to its default. */
|
|
1367
|
+
function resolveStalePageThresholdMs(deps) {
|
|
1368
|
+
return deps.stalePageThresholdMs ?? 3e5;
|
|
1369
|
+
}
|
|
1370
|
+
/** Resolves `deps.nowMs` to its default (`Date.now`). */
|
|
1371
|
+
function resolveNowMs(deps) {
|
|
1372
|
+
return deps.nowMs ?? (() => Date.now());
|
|
1373
|
+
}
|
|
1374
|
+
/** Resolves `deps.canOpenBrowser` to the module default. */
|
|
1375
|
+
function resolveCanOpenBrowser(deps) {
|
|
1376
|
+
return deps.canOpenBrowser ?? canOpenBrowser;
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Waits for the first target matching `filterFn` to attach, using the
|
|
1380
|
+
* event-driven `waitForFirstTarget()` when the connection supports it
|
|
1381
|
+
* (interface-optional member, present on `ChiiCdpConnection`), or falling
|
|
1382
|
+
* back to a polling loop for connections that don't implement it (test fakes,
|
|
1383
|
+
* `LocalCdpConnection`).
|
|
1384
|
+
*
|
|
1385
|
+
* This eliminates the polling-only race that previously caused `wait_for_attach`
|
|
1386
|
+
* to resolve before the relay had observed the first inbound CDP message from
|
|
1387
|
+
* the phone.
|
|
1388
|
+
*
|
|
1389
|
+
* Timeout note: callers (e.g. the `start_attach` path) always pass an
|
|
1390
|
+
* explicit `timeoutMs`, sourced from the factory's `waitForAttachTimeoutMs`
|
|
1391
|
+
* (default 60 000). That value is forwarded to `waitForFirstTarget`, so it
|
|
1392
|
+
* overrides that method's own 90 000 signature default — the effective
|
|
1393
|
+
* wait on the tool path is 60 s, not 90 s.
|
|
1394
|
+
*
|
|
1395
|
+
* @param connection - The CDP connection (production or fake).
|
|
1396
|
+
* @param filterFn - Resolves when this predicate is satisfied.
|
|
1397
|
+
* @param timeoutMs - Maximum wait time in ms.
|
|
1398
|
+
* @param pollIntervalMs - Fallback poll interval for connections without waitForFirstTarget.
|
|
1399
|
+
*/
|
|
1400
|
+
function waitForAttachWithEvents(connection, filterFn, timeoutMs, pollIntervalMs = 1e3) {
|
|
1401
|
+
if (connection.waitForFirstTarget) return connection.waitForFirstTarget(filterFn, timeoutMs, pollIntervalMs);
|
|
1402
|
+
return new Promise((resolve, reject) => {
|
|
1403
|
+
const deadline = Date.now() + timeoutMs;
|
|
1404
|
+
let settled = false;
|
|
1405
|
+
const poll = setInterval(() => {
|
|
1406
|
+
const targets = connection.listTargets();
|
|
1407
|
+
if (filterFn(targets)) {
|
|
1408
|
+
settled = true;
|
|
1409
|
+
clearInterval(poll);
|
|
1410
|
+
resolve(targets);
|
|
1411
|
+
} else if (Date.now() >= deadline) {
|
|
1412
|
+
settled = true;
|
|
1413
|
+
clearInterval(poll);
|
|
1414
|
+
reject(/* @__PURE__ */ new Error(`waitForAttachWithEvents: 타임아웃 (${timeoutMs}ms)`));
|
|
1415
|
+
}
|
|
1416
|
+
}, pollIntervalMs);
|
|
1417
|
+
const targets = connection.listTargets();
|
|
1418
|
+
if (!settled && filterFn(targets)) {
|
|
1419
|
+
settled = true;
|
|
1420
|
+
clearInterval(poll);
|
|
1421
|
+
resolve(targets);
|
|
1422
|
+
}
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Synthesizes an attach URL from stored components with a FRESHLY-minted TOTP
|
|
1427
|
+
* code (issue #626 §3/§4 — the single mint point). Reads the late-bound secret
|
|
1428
|
+
* via `deps.getTotpSecret()` so the project-local `.ait_relay` secret loaded by
|
|
1429
|
+
* `switchMode` is visible. SECRET-HANDLING: the minted code rides inside the
|
|
1430
|
+
* URL's `at=` param only — never logged or returned separately.
|
|
1431
|
+
*/
|
|
1432
|
+
function mintAttachUrl(deps, parts) {
|
|
1433
|
+
const secret = deps.getTotpSecret();
|
|
1434
|
+
const code = secret ? generateTotp(secret) : void 0;
|
|
1435
|
+
return parts.kind === "launcher" ? buildLauncherAttachUrl(parts.tunnelHttpUrl, parts.wssUrl, code, {
|
|
1436
|
+
name: parts.appName,
|
|
1437
|
+
...parts.selfdebug ? { selfdebug: true } : {}
|
|
1438
|
+
}) : buildDeepLinkAttachUrl(parts.schemeUrl, parts.wssUrl, code);
|
|
1439
|
+
}
|
|
1440
|
+
/** Builds the fresh TOTP metadata (expiresAt window) for a tool result. */
|
|
1441
|
+
function buildTotpMeta(deps) {
|
|
1442
|
+
const secret = deps.getTotpSecret();
|
|
1443
|
+
if (secret === void 0 || secret === "") return void 0;
|
|
1444
|
+
const STEP_SECONDS = 30;
|
|
1445
|
+
const expiresAtMs = resolveNowMs(deps)() + 6 * STEP_SECONDS * 1e3;
|
|
1446
|
+
return {
|
|
1447
|
+
enabled: true,
|
|
1448
|
+
ttlSeconds: 6 * STEP_SECONDS,
|
|
1449
|
+
expiresAt: new Date(expiresAtMs).toISOString()
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Env-specific validation + component bundle for `start_attach` (issue #626).
|
|
1454
|
+
* Branches on `env`: `relay-mobile` reads AIT_TUNNEL_BASE_URL + builds launcher
|
|
1455
|
+
* parts; `relay-dev` requires scheme_url + builds scheme parts. Returns
|
|
1456
|
+
* `{ ok: false, error }` with a ready McpResult on any failure.
|
|
1457
|
+
*/
|
|
1458
|
+
async function prepareAttach(deps, env, args, conn) {
|
|
1459
|
+
const { getTunnelStatus, getTotpSecret } = deps;
|
|
1460
|
+
const stalePageThresholdMs = resolveStalePageThresholdMs(deps);
|
|
1461
|
+
const nowMs = resolveNowMs(deps);
|
|
1462
|
+
const selfdebug = args?.selfdebug === true;
|
|
1463
|
+
if (selfdebug && env !== "relay-mobile") return {
|
|
1464
|
+
ok: false,
|
|
1465
|
+
error: mcpError("start_attach: selfdebug=true는 env 2 / relay-sandbox 전용 기능입니다. 현재 환경(env 3)에서는 launcher가 없어 self-target 모드를 지원하지 않습니다. launcher self-target이 필요하다면 relay-sandbox 모드로 전환하세요.")
|
|
1466
|
+
};
|
|
1467
|
+
if (env === "relay-mobile") {
|
|
1468
|
+
const rawProjectRoot = args?.projectRoot;
|
|
1469
|
+
const buildProjectRoot = typeof rawProjectRoot === "string" ? rawProjectRoot : void 0;
|
|
1470
|
+
let tunnelHttpUrl = process.env.AIT_TUNNEL_BASE_URL?.trim() ?? "";
|
|
1471
|
+
if (tunnelHttpUrl === "" && buildProjectRoot !== void 0) {
|
|
1472
|
+
const { readRelayUrls } = await import("./relay-url-store-CdA58fgw.js");
|
|
1473
|
+
tunnelHttpUrl = (await readRelayUrls({ projectRoot: buildProjectRoot }))?.tunnelBaseUrl ?? "";
|
|
1474
|
+
}
|
|
1475
|
+
if (tunnelHttpUrl === "") return {
|
|
1476
|
+
ok: false,
|
|
1477
|
+
error: mcpError("start_attach(mobile): AIT_TUNNEL_BASE_URL이 설정되지 않았습니다. dev 서버가 tunnel:{cdp:true}로 기동 중이면 .ait_urls 파일이 자동 생성돼 있어야 합니다. 자동 발견이 되지 않을 경우 앱 HTTP 터널 URL을 AIT_TUNNEL_BASE_URL 환경변수로 직접 전달하세요.")
|
|
1478
|
+
};
|
|
1479
|
+
const tunnelStatus = getTunnelStatus();
|
|
1480
|
+
if (!tunnelStatus.up || tunnelStatus.wssUrl === null) return {
|
|
1481
|
+
ok: false,
|
|
1482
|
+
error: mcpError("start_attach(mobile): relay wssUrl이 아직 설정되지 않았습니다. unplugin tunnel:{cdp:true}가 relay를 완전히 기동할 때까지 잠시 후 다시 시도하세요.")
|
|
1483
|
+
};
|
|
1484
|
+
const secret = getTotpSecret();
|
|
1485
|
+
if (secret === void 0 || secret === "") return {
|
|
1486
|
+
ok: false,
|
|
1487
|
+
error: mcpError("start_attach(relay): TOTP secret(AIT_DEBUG_TOTP_SECRET)이 설정되지 않았습니다. relay 환경은 TOTP 인증이 필수입니다 — relay를 secret과 함께 재기동하세요.")
|
|
1488
|
+
};
|
|
1489
|
+
let launcherAppName;
|
|
1490
|
+
if (buildProjectRoot !== void 0) try {
|
|
1491
|
+
const { readFileSync } = await import("node:fs");
|
|
1492
|
+
const pkgRaw = readFileSync(`${buildProjectRoot}/package.json`, "utf8");
|
|
1493
|
+
const pkg = JSON.parse(pkgRaw);
|
|
1494
|
+
const rawName = typeof pkg.name === "string" ? pkg.name : "";
|
|
1495
|
+
launcherAppName = (rawName.includes("/") ? rawName.slice(rawName.indexOf("/") + 1) : rawName).trim() || void 0;
|
|
1496
|
+
} catch {}
|
|
1497
|
+
const parts = {
|
|
1498
|
+
kind: "launcher",
|
|
1499
|
+
tunnelHttpUrl,
|
|
1500
|
+
wssUrl: tunnelStatus.wssUrl,
|
|
1501
|
+
appName: launcherAppName,
|
|
1502
|
+
...selfdebug ? { selfdebug: true } : {}
|
|
1503
|
+
};
|
|
1504
|
+
const connAsAny = conn;
|
|
1505
|
+
const getLastSeenAt = typeof connAsAny.getTargetLastSeenAt === "function" ? (id) => connAsAny.getTargetLastSeenAt(id) : null;
|
|
1506
|
+
const callNow = nowMs();
|
|
1507
|
+
const isMatchingPage = (pages) => isSandboxPageFresh(pages, getLastSeenAt, callNow, stalePageThresholdMs);
|
|
1508
|
+
const buildTimeoutError = (baseText, timeoutSec, observed) => {
|
|
1509
|
+
const observedUrls = observed.slice(0, 3).map((p) => p.url.slice(0, 80)).join(", ");
|
|
1510
|
+
return `${baseText}\n\nNo page attached within ${timeoutSec}s${observed.length > 0 ? ` — previously attached pages: [${observedUrls}]` : ""} — launcher QR을 폰 카메라로 스캔한 뒤 call list_pages를 다시 호출하세요.`;
|
|
1511
|
+
};
|
|
1512
|
+
return {
|
|
1513
|
+
ok: true,
|
|
1514
|
+
parts,
|
|
1515
|
+
isMatchingPage,
|
|
1516
|
+
buildTimeoutError,
|
|
1517
|
+
authorityWarning: void 0,
|
|
1518
|
+
totpMeta: buildTotpMeta(deps)
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1521
|
+
const schemeUrl = args?.scheme_url;
|
|
1522
|
+
if (typeof schemeUrl !== "string" || schemeUrl === "") return {
|
|
1523
|
+
ok: false,
|
|
1524
|
+
error: mcpError("start_attach: scheme_url이 비어 있습니다. `ait deploy --scheme-only`가 출력하는 intoss-private:// URL을 인자로 전달하세요. 환경 2(mobile)라면 scheme_url 대신 AIT_TUNNEL_BASE_URL을 설정하세요.")
|
|
1525
|
+
};
|
|
1526
|
+
{
|
|
1527
|
+
const relaySecret = getTotpSecret();
|
|
1528
|
+
if (relaySecret === void 0 || relaySecret === "") return {
|
|
1529
|
+
ok: false,
|
|
1530
|
+
error: mcpError("start_attach(relay): TOTP secret(AIT_DEBUG_TOTP_SECRET)이 설정되지 않았습니다. relay 환경은 TOTP 인증이 필수입니다 — relay를 secret과 함께 재기동하세요.")
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
const tunnelForBuild = getTunnelStatus();
|
|
1534
|
+
if (!tunnelForBuild.up || tunnelForBuild.wssUrl === null) return {
|
|
1535
|
+
ok: false,
|
|
1536
|
+
error: classifyToolError(/* @__PURE__ */ new Error("tunnel-down:"), "start_attach")
|
|
1537
|
+
};
|
|
1538
|
+
const authorityWarning = validateSchemeAuthority(schemeUrl) ?? void 0;
|
|
1539
|
+
const parts = {
|
|
1540
|
+
kind: "scheme",
|
|
1541
|
+
schemeUrl,
|
|
1542
|
+
wssUrl: tunnelForBuild.wssUrl
|
|
1543
|
+
};
|
|
1544
|
+
const deploymentId = extractDeploymentId(schemeUrl);
|
|
1545
|
+
if (!deploymentId) logInfo("tool.call", {
|
|
1546
|
+
tool: "start_attach",
|
|
1547
|
+
msg: "no _deploymentId in scheme_url; matching on presence only"
|
|
1548
|
+
});
|
|
1549
|
+
const isMatchingPage = (pages) => {
|
|
1550
|
+
if (pages.length === 0) return false;
|
|
1551
|
+
if (deploymentId === null) return true;
|
|
1552
|
+
return pages.some((p) => p.url.includes(deploymentId));
|
|
1553
|
+
};
|
|
1554
|
+
const buildTimeoutError = (baseText, timeoutSec, observed) => {
|
|
1555
|
+
const observedUrls = observed.slice(0, 3).map((p) => p.url.slice(0, 80)).join(", ");
|
|
1556
|
+
const observedNote = observed.length > 0 ? ` — previously attached pages: [${observedUrls}]` : "";
|
|
1557
|
+
return `${baseText}\n\nNo page${deploymentId ? ` matching deploymentId=${deploymentId}` : ""} attached within ${timeoutSec}s${observedNote} — call list_pages to retry.`;
|
|
1558
|
+
};
|
|
1559
|
+
return {
|
|
1560
|
+
ok: true,
|
|
1561
|
+
parts,
|
|
1562
|
+
isMatchingPage,
|
|
1563
|
+
buildTimeoutError,
|
|
1564
|
+
authorityWarning,
|
|
1565
|
+
totpMeta: buildTotpMeta(deps)
|
|
1566
|
+
};
|
|
1567
|
+
}
|
|
1568
|
+
/**
|
|
1569
|
+
* QR render + browser open + segmented attach wait with in-call TOTP re-mint
|
|
1570
|
+
* (issue #626 §3). Shared by env-2 and env-3 (4 render paths:
|
|
1571
|
+
* headless / browser-opened / browser-open-failed / no-http-server).
|
|
1572
|
+
*
|
|
1573
|
+
* The wait is decomposed into `START_ATTACH_SEGMENT_MS` slices. Between slices,
|
|
1574
|
+
* if the current TOTP code has aged past `START_ATTACH_REMINT_THRESHOLD_MS`,
|
|
1575
|
+
* a fresh URL is minted via `mintAttachUrl` and pushed to the dashboard via
|
|
1576
|
+
* `onAttachUrlBuilt` (SSE refresh — NO browser re-open). The `reminted` count
|
|
1577
|
+
* rides in the success/timeout result.
|
|
1578
|
+
*
|
|
1579
|
+
* SECRET-HANDLING: attachUrl encodes tunnel/scheme host + the TOTP `at=` code
|
|
1580
|
+
* in the QR payload only. The browser is opened on a 127.0.0.1 URL only. The
|
|
1581
|
+
* tool result carries `totp.expiresAt` + `reminted` count — never the code.
|
|
1582
|
+
*/
|
|
1583
|
+
async function renderAndMaybeWait(deps, prep, waitForAttach, callTimeoutMs, conn) {
|
|
1584
|
+
const { getTunnelStatus, qrHttpServer, onAttachUrlBuilt } = deps;
|
|
1585
|
+
const nowMs = resolveNowMs(deps);
|
|
1586
|
+
const canOpenBrowserFn = resolveCanOpenBrowser(deps);
|
|
1587
|
+
const { parts, isMatchingPage, buildTimeoutError, authorityWarning, totpMeta } = prep;
|
|
1588
|
+
let attachUrl = mintAttachUrl(deps, parts);
|
|
1589
|
+
onAttachUrlBuilt?.(parts);
|
|
1590
|
+
let totpIssuedAt = nowMs();
|
|
1591
|
+
let reminted = 0;
|
|
1592
|
+
const relayUrl = parts.wssUrl;
|
|
1593
|
+
const header = "This tool result is shown to the user directly — do NOT re-print the QR below in your reply (it wastes output tokens). Just tell the user to scan the QR in this output (Ctrl+O to expand if collapsed).";
|
|
1594
|
+
const warningPrefix = authorityWarning ? `⚠️ scheme_url 경고: ${authorityWarning}\n\n` : "";
|
|
1595
|
+
const guiAvailable = canOpenBrowserFn();
|
|
1596
|
+
/** Builds the totp object surfaced in results (fresh expiresAt + reminted). */
|
|
1597
|
+
const totpResult = () => {
|
|
1598
|
+
if (!totpMeta) return void 0;
|
|
1599
|
+
const expiresAtMs = totpIssuedAt + 180 * 1e3;
|
|
1600
|
+
return {
|
|
1601
|
+
enabled: true,
|
|
1602
|
+
ttlSeconds: totpMeta.ttlSeconds,
|
|
1603
|
+
expiresAt: new Date(expiresAtMs).toISOString(),
|
|
1604
|
+
...reminted > 0 ? { reminted } : {}
|
|
1605
|
+
};
|
|
1606
|
+
};
|
|
1607
|
+
/**
|
|
1608
|
+
* Segmented wait with TOTP re-mint (issue #626 §3). Resolves with the
|
|
1609
|
+
* attached page list, or rejects on timeout. Between SEGMENT_MS slices it
|
|
1610
|
+
* re-mints when the code has aged past the threshold (max ~4 re-mints over
|
|
1611
|
+
* 600 s). Returns immediately once a matching page attaches (no re-mint).
|
|
1612
|
+
*/
|
|
1613
|
+
async function waitWithRemint() {
|
|
1614
|
+
const deadline = nowMs() + callTimeoutMs;
|
|
1615
|
+
if (isMatchingPage(conn.listTargets())) return conn.listTargets();
|
|
1616
|
+
for (;;) {
|
|
1617
|
+
const remaining = deadline - nowMs();
|
|
1618
|
+
if (remaining <= 0) throw new Error(`start_attach: 타임아웃 (${callTimeoutMs}ms)`);
|
|
1619
|
+
const segmentMs = Math.min(START_ATTACH_SEGMENT_MS, remaining);
|
|
1620
|
+
try {
|
|
1621
|
+
return await waitForAttachWithEvents(conn, isMatchingPage, segmentMs);
|
|
1622
|
+
} catch {
|
|
1623
|
+
if (totpMeta && nowMs() - totpIssuedAt >= 15e4) {
|
|
1624
|
+
attachUrl = mintAttachUrl(deps, parts);
|
|
1625
|
+
onAttachUrlBuilt?.(parts);
|
|
1626
|
+
totpIssuedAt = nowMs();
|
|
1627
|
+
reminted += 1;
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* Assembles the success result after a page attaches. `baseText` carries the
|
|
1634
|
+
* QR + pre-wait JSON block (the QR the user already scanned). The attach
|
|
1635
|
+
* itself ends the wait, so the QR is moot — what matters now is the final
|
|
1636
|
+
* TOTP state. If the segmented wait re-minted (issue #626 §3), surface the
|
|
1637
|
+
* post-wait `totp` block (fresh `expiresAt` + `reminted` count) so the result
|
|
1638
|
+
* reflects how many times the code rotated during the wait. SECRET-HANDLING:
|
|
1639
|
+
* the totp block carries expiresAt + reminted only — never the code value.
|
|
1640
|
+
*/
|
|
1641
|
+
const successResult = (baseText) => {
|
|
1642
|
+
const pagesResult = listPages(conn, getTunnelStatus());
|
|
1643
|
+
const finalTotp = totpResult();
|
|
1644
|
+
const remintNote = finalTotp && reminted > 0 ? `\n\n${JSON.stringify({ totp: finalTotp }, null, 2)}` : "";
|
|
1645
|
+
return { content: [{
|
|
1646
|
+
type: "text",
|
|
1647
|
+
text: `${baseText}\n\n${JSON.stringify(pagesResult, null, 2)}${remintNote}`
|
|
1648
|
+
}] };
|
|
1649
|
+
};
|
|
1650
|
+
/** Runs the wait (when requested) and returns success/timeout result. */
|
|
1651
|
+
const runWait = async (baseText) => {
|
|
1652
|
+
if (!waitForAttach) return { content: [{
|
|
1653
|
+
type: "text",
|
|
1654
|
+
text: baseText
|
|
1655
|
+
}] };
|
|
1656
|
+
try {
|
|
1657
|
+
await waitWithRemint();
|
|
1658
|
+
} catch {
|
|
1659
|
+
const observed = conn.listTargets();
|
|
1660
|
+
return {
|
|
1661
|
+
content: [{
|
|
1662
|
+
type: "text",
|
|
1663
|
+
text: buildTimeoutError(baseText, callTimeoutMs / 1e3, observed)
|
|
1664
|
+
}],
|
|
1665
|
+
isError: true
|
|
1666
|
+
};
|
|
1667
|
+
}
|
|
1668
|
+
return successResult(baseText);
|
|
1669
|
+
};
|
|
1670
|
+
if (!guiAvailable) {
|
|
1671
|
+
const headlessNote = "GUI 환경이 감지되지 않았습니다 (headless/remote 환경). 텍스트 QR을 폰 카메라로 스캔하거나, 로컬 GUI 환경에서 실행하세요.\n\n";
|
|
1672
|
+
const qr = await renderQr(attachUrl);
|
|
1673
|
+
return runWait(`${warningPrefix}${headlessNote}${header}\n${JSON.stringify({
|
|
1674
|
+
attachUrl,
|
|
1675
|
+
relayUrl,
|
|
1676
|
+
...totpResult() ? { totp: totpResult() } : {}
|
|
1677
|
+
}, null, 2)}\n\n${qr}`);
|
|
1678
|
+
}
|
|
1679
|
+
if (guiAvailable && qrHttpServer) {
|
|
1680
|
+
const browserResult = await openQrInBrowser(qrHttpServer.buildAttachPageUrl(attachUrl), `http://127.0.0.1:${qrHttpServer.port}/qr.png?u=${encodeURIComponent(attachUrl)}`);
|
|
1681
|
+
if (browserResult.opened) {
|
|
1682
|
+
const retriedNote = browserResult.retried ? " (1회 retry 후 성공)" : "";
|
|
1683
|
+
const openResult = {
|
|
1684
|
+
attempted: true,
|
|
1685
|
+
succeeded: true,
|
|
1686
|
+
...browserResult.retried ? { retried: true } : {}
|
|
1687
|
+
};
|
|
1688
|
+
return runWait(`${warningPrefix}${header}\n${JSON.stringify({
|
|
1689
|
+
relayUrl,
|
|
1690
|
+
openResult,
|
|
1691
|
+
...totpResult() ? { totp: totpResult() } : {}
|
|
1692
|
+
}, null, 2)}\n\n브라우저에서 QR을 열었습니다${retriedNote}. 폰 카메라로 스캔하세요.\nURL: ${browserResult.httpUrl}`);
|
|
1693
|
+
}
|
|
1694
|
+
const openResult = {
|
|
1695
|
+
attempted: true,
|
|
1696
|
+
succeeded: false,
|
|
1697
|
+
failureReason: browserResult.error ?? "브라우저 실행 후보 모두 실패",
|
|
1698
|
+
pngUrl: browserResult.pngUrl,
|
|
1699
|
+
...browserResult.stderrSummary ? { stderrSummary: browserResult.stderrSummary } : {}
|
|
1700
|
+
};
|
|
1701
|
+
const stderrNote = browserResult.stderrSummary ? `\nstderr: ${browserResult.stderrSummary}` : "";
|
|
1702
|
+
const fallbackNote = `브라우저 자동 열기에 실패했습니다. 다음 URL을 직접 브라우저에서 여세요:\n${browserResult.httpUrl}\n또는 PNG로 받기: ${browserResult.pngUrl}` + stderrNote + "\n\n";
|
|
1703
|
+
const qr = await renderQr(attachUrl);
|
|
1704
|
+
return runWait(`${warningPrefix}${fallbackNote}${header}\n${JSON.stringify({
|
|
1705
|
+
attachUrl,
|
|
1706
|
+
relayUrl,
|
|
1707
|
+
openResult,
|
|
1708
|
+
...totpResult() ? { totp: totpResult() } : {}
|
|
1709
|
+
}, null, 2)}\n\n${qr}`);
|
|
1710
|
+
}
|
|
1711
|
+
const qr = await renderQr(attachUrl);
|
|
1712
|
+
return runWait(`${warningPrefix}${header}\n${JSON.stringify({
|
|
1713
|
+
attachUrl,
|
|
1714
|
+
relayUrl,
|
|
1715
|
+
...totpResult() ? { totp: totpResult() } : {}
|
|
1716
|
+
}, null, 2)}\n\n${qr}`);
|
|
1717
|
+
}
|
|
1718
|
+
/**
|
|
1719
|
+
* Builds a self-contained IIFE DOM expression that renders a dismissible
|
|
1720
|
+
* "Debugger Connected" badge on the bottom-left of the phone screen.
|
|
1721
|
+
*
|
|
1722
|
+
* **Pure function** — returns a JS expression string; does NOT inject it.
|
|
1723
|
+
* Injection is performed by {@link injectDebugIndicator} in `cell.ts`.
|
|
1724
|
+
*
|
|
1725
|
+
* The expression, when evaluated on the page, does the following:
|
|
1726
|
+
* 1. Early-returns if `#__ait_debug_indicator` already exists (idempotent —
|
|
1727
|
+
* prevents duplicate badges on re-injection after page reload).
|
|
1728
|
+
* 2. Appends a fixed-position `<div id="__ait_debug_indicator">` at the
|
|
1729
|
+
* bottom-left, accounting for safe-area insets.
|
|
1730
|
+
* 3. Attaches a `{ once: true }` `pointerdown` listener that removes the
|
|
1731
|
+
* badge on first touch — one-tap dismiss.
|
|
1732
|
+
*
|
|
1733
|
+
* The expression intentionally contains NO relay URLs, wss addresses, TOTP
|
|
1734
|
+
* codes, or any other secrets. It is pure DOM UI text only.
|
|
1735
|
+
*
|
|
1736
|
+
* SECRET-HANDLING: this expression contains no secrets, relay URLs, wss
|
|
1737
|
+
* addresses, or TOTP codes whatsoever — DOM label text only.
|
|
1738
|
+
*
|
|
1739
|
+
* @param opts.label - Badge text (default: `'Debugger Connected'`).
|
|
1740
|
+
* @returns A JS expression string suitable for `Runtime.evaluate`.
|
|
1741
|
+
*/
|
|
1742
|
+
function buildIndicatorExpression(opts) {
|
|
1743
|
+
const label = opts?.label ?? "Debugger Connected";
|
|
1744
|
+
return `(() => {if (document.getElementById('__ait_debug_indicator')) return;const el = document.createElement('div');el.id = '__ait_debug_indicator';el.style.cssText = ['position:fixed','left:max(12px,calc(env(safe-area-inset-left,0px) + 8px))','bottom:max(12px,calc(env(safe-area-inset-bottom,0px) + 8px))','z-index:2147483647','background:#e5484d','color:#fff','font:bold 11px/1 system-ui,sans-serif','padding:5px 9px','border-radius:6px','pointer-events:auto','user-select:none',].join(';');el.textContent = ${JSON.stringify(label)};el.addEventListener('pointerdown', () => el.remove(), { once: true });document.body.appendChild(el);})()`;
|
|
1745
|
+
}
|
|
1746
|
+
//#endregion
|
|
1747
|
+
export { RELAY_SANDBOX_STALE_PAGE_MS, START_ATTACH_REMINT_THRESHOLD_MS, START_ATTACH_SEGMENT_MS, startTunnelHealthProbe as a, buildIndicatorExpression, extractDeploymentId, startQuickTunnel as i, isSandboxPageFresh, makeTunnelStatus as n, logError as o, prepareAttach, printAttachBanner as r, renderAndMaybeWait, logInfo as s, generateAttachToken as t };
|
|
1748
|
+
|
|
1749
|
+
//# sourceMappingURL=attach-orchestrator-CFotueL3.js.map
|