@adelin-io/cli 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "packageName": "@adelin-io/cli",
4
- "version": "0.1.4",
4
+ "version": "0.1.6",
5
5
  "compilerVersion": "6.0.3",
6
6
  "hostProtocol": 1,
7
7
  "files": {
@@ -17,7 +17,7 @@
17
17
  "skill/authoring/content-binding.md": "124090ebdd6011bdd7c5f9c94f715ab15ad2af7741fae90fc5d3e2c7a2f442a8",
18
18
  "skill/authoring/i18n.md": "a264167e27b9ea02c76647146601ee0d1d9a83e9d33d7cd60d9d0b39d9ee1f60",
19
19
  "skill/authoring/language.md": "533d597b785f6df99234f7e83be80d8ea1818cd24062b4f51ec5e4091a2db393",
20
- "skill/authoring/local-workflow.md": "ed62d79e0a83a209d4643274e541a484f9a45d89c24379e769e016e1793ebb44",
20
+ "skill/authoring/local-workflow.md": "9a989715d7a84c7a6520009cf9a2eeff532efbe051085a702ae93d6f29e0b6d9",
21
21
  "skill/authoring/offline/connectivity.md": "e00cb804cfdcda2950cb190432e8f36cd13d99b36075b5ceec71438671393e81",
22
22
  "skill/authoring/offline/example.md": "2e79d91f05d7a55b4a3f136f0db28d02e458c9fc24b77ab0e074fff7ab635447",
23
23
  "skill/authoring/offline/history-sync.md": "65652b536a84c47ddf04519e3dac35a9bed836fba67043fd43dabd77af3cd3ec",
@@ -170,5 +170,5 @@
170
170
  "types/adelin-worklets.d.ts": "f56edc56715df189933f180605ee8c41a785d11ad0c0d454258f1c1f71159ab9",
171
171
  "workspace-tsconfig.json": "a1321a0ea06e5fb9d4e3c1a7d92045e730b44114ab10553172142cb978b9147a"
172
172
  },
173
- "contractId": "d18f24298680a780f6afa478aba7c752ea2c8105f2fae8e603f15594dfdbfe8d"
173
+ "contractId": "ac1c6146c29893957efa89a9c96a60870ceccc09bca4f408ff1ca2ec92cfc686"
174
174
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@adelin-io/cli",
3
3
  "private": false,
4
- "version": "0.1.4",
4
+ "version": "0.1.6",
5
5
  "description": "Adelin CLI, local app builder, and agent skill",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -1,9 +1,9 @@
1
1
  {
2
- "scripts/adelin.mjs": "25d4b3eb2ef76064a3b943b46fe0d38c1a2a7e1d9dff5e3f74604a4c36bb13b2",
2
+ "scripts/adelin.mjs": "0f32c49e80aade2bec981bed622292bfebc819c25bc0a38fbf9582850426f6da",
3
3
  "scripts/assemble-checkout.mjs": "3f35e00a76075b3b0e8c72b5477184a986b15ae1e933317ceaad9a08cbeb589c",
4
4
  "scripts/local-save.mjs": "c8b4f81ffdf2bbc87d47edf4f97438b4381fe9b10a98c9ba28e288c5fe6d7eed",
5
5
  "scripts/materialize.mjs": "8c00ec43de43698c5d7ef918e6d2f0c2f4eb01c51172b67ea36f7544cfe5b03f",
6
- "scripts/runtime.mjs": "2b8539f29cf638151bebe6a5fab8a904852bb95839d526116c9d17cfeb0b972a",
6
+ "scripts/runtime.mjs": "311b6f780b0c2d1206bdd63013bc671420c60fd7f9a0985e233c953091260c2d",
7
7
  "scripts/typecheck.mjs": "2ed3b248bd1d8f8152cda2a57f8975da39028e5eb63a7475678af6fc5117042c",
8
8
  "scripts/workspace-state.mjs": "e8a2a8d85ac0add04a5a19fcb20183cdc0929387c4487f7747b81baa1ae2ecff"
9
9
  }
@@ -72,6 +72,289 @@ var PRODUCTION_MCP_URL, init_cli_server = __esm({
72
72
  }
73
73
  });
74
74
 
75
+ // skills/adelin-app-generation/scripts/cli-auth.mjs
76
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
77
+ import { spawn } from "node:child_process";
78
+ import { createServer } from "node:http";
79
+ import { createServer as createLockServer } from "node:net";
80
+ import {
81
+ closeSync,
82
+ constants,
83
+ existsSync as existsSync2,
84
+ fsyncSync,
85
+ lstatSync,
86
+ mkdirSync,
87
+ openSync,
88
+ readFileSync as readFileSync2,
89
+ realpathSync,
90
+ renameSync,
91
+ unlinkSync,
92
+ writeFileSync
93
+ } from "node:fs";
94
+ import { homedir } from "node:os";
95
+ import { basename, dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
96
+ import { setTimeout as delay } from "node:timers/promises";
97
+ function configPath() {
98
+ let base = process.platform === "win32" ? process.env.APPDATA || join2(homedir(), "AppData", "Roaming") : process.env.XDG_CONFIG_HOME || join2(homedir(), ".config");
99
+ return join2(resolve2(base), "adelin", "auth.json");
100
+ }
101
+ function privateFile(path) {
102
+ if (!existsSync2(path)) return !1;
103
+ let stat2 = lstatSync(path);
104
+ if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > MAX_FILE_BYTES || process.platform !== "win32" && (stat2.mode & 63) !== 0)
105
+ throw new Error("Adelin credential file is not private.");
106
+ return !0;
107
+ }
108
+ function privateDirectory(path) {
109
+ mkdirSync(path, { recursive: !0, mode: 448 });
110
+ let stat2 = lstatSync(path);
111
+ if (!stat2.isDirectory() || stat2.isSymbolicLink() || process.platform !== "win32" && (stat2.mode & 63) !== 0)
112
+ throw new Error("Adelin credential directory is not private.");
113
+ }
114
+ function readServers(path) {
115
+ if (!privateFile(path)) return {};
116
+ let value = JSON.parse(readFileSync2(path, "utf8"));
117
+ if (value?.schema !== 2) return {};
118
+ if (!value.servers || typeof value.servers != "object" || Array.isArray(value.servers) || Object.values(value.servers).some((entry) => !entry || typeof entry.clientId != "string" || typeof entry.accessToken != "string" || typeof entry.refreshToken != "string" || !Number.isSafeInteger(entry.expiresAt)))
119
+ throw new Error("Adelin credential file is invalid.");
120
+ return value.servers;
121
+ }
122
+ function readCredential(path, mcpUrl) {
123
+ let servers = readServers(path);
124
+ return Object.hasOwn(servers, mcpUrl) ? { mcpUrl, ...servers[mcpUrl] } : null;
125
+ }
126
+ function writeServers(path, servers) {
127
+ if (!Object.keys(servers).length) {
128
+ privateFile(path) && unlinkSync(path);
129
+ return;
130
+ }
131
+ privateDirectory(dirname2(path)), privateFile(path);
132
+ let stage = `${path}.${randomBytes(12).toString("hex")}.tmp`, fd = openSync(stage, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 384);
133
+ try {
134
+ writeFileSync(fd, JSON.stringify({ schema: 2, servers }) + `
135
+ `), fsyncSync(fd);
136
+ } finally {
137
+ closeSync(fd);
138
+ }
139
+ try {
140
+ renameSync(stage, path);
141
+ } finally {
142
+ existsSync2(stage) && unlinkSync(stage);
143
+ }
144
+ }
145
+ function saveCredential(path, { mcpUrl, ...entry }) {
146
+ writeServers(path, { ...readServers(path), [mcpUrl]: entry });
147
+ }
148
+ async function withCredentialLock(path, work) {
149
+ privateDirectory(dirname2(path));
150
+ let identity = join2(realpathSync(dirname2(path)), basename(path));
151
+ (process.platform === "darwin" || process.platform === "win32") && (identity = identity.normalize("NFC").toLowerCase());
152
+ let port = 49152 + createHash("sha256").update(identity).digest().readUInt32BE(0) % 16384, deadline = performance.now() + 3e4;
153
+ for (; ; ) {
154
+ let lock = createLockServer((socket) => socket.destroy());
155
+ try {
156
+ await new Promise((resolveListen, reject) => {
157
+ lock.once("error", reject), lock.listen({ host: LOOPBACK, port, exclusive: !0 }, resolveListen);
158
+ });
159
+ } catch (error) {
160
+ if (error.code !== "EADDRINUSE")
161
+ throw new Error(`Cannot lock Adelin credentials through loopback (${error.code ?? "listen failed"}).`, { cause: error });
162
+ if (performance.now() >= deadline)
163
+ throw new Error("Adelin credential lock is busy (another operation or local port collision). Retry shortly.");
164
+ await delay(25);
165
+ continue;
166
+ }
167
+ try {
168
+ return await work();
169
+ } finally {
170
+ await new Promise((resolveClose, reject) => lock.close((error) => error ? reject(error) : resolveClose()));
171
+ }
172
+ }
173
+ }
174
+ function tokenFields(value, previous) {
175
+ if (!value || value.token_type !== "Bearer" || typeof value.access_token != "string" || !value.access_token || typeof value.refresh_token != "string" || !value.refresh_token || !Number.isInteger(value.expires_in) || value.expires_in < 1 || value.expires_in > 3600)
176
+ throw new Error("Adelin returned an invalid OAuth token response.");
177
+ return {
178
+ mcpUrl: previous.mcpUrl,
179
+ clientId: previous.clientId,
180
+ accessToken: value.access_token,
181
+ refreshToken: value.refresh_token,
182
+ expiresAt: Date.now() + value.expires_in * 1e3
183
+ };
184
+ }
185
+ async function readJson(response2, limit3 = MAX_AUTH_BYTES) {
186
+ if (!response2.ok) throw new Error(`Adelin OAuth request failed (${response2.status}).`);
187
+ let bytes = await response2.arrayBuffer();
188
+ if (bytes.byteLength > limit3) throw new Error("Adelin OAuth response is too large.");
189
+ return JSON.parse(Buffer.from(bytes).toString("utf8"));
190
+ }
191
+ function openBrowser(url) {
192
+ let command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open", args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url], child2 = spawn(command, args, { detached: !0, stdio: "ignore" });
193
+ child2.on("error", () => {
194
+ }), child2.unref();
195
+ }
196
+ var MAX_AUTH_BYTES, MAX_FILE_BYTES, LOGIN_TIMEOUT_MS, LOOPBACK, CliAuth, init_cli_auth = __esm({
197
+ "skills/adelin-app-generation/scripts/cli-auth.mjs"() {
198
+ init_cli_server();
199
+ MAX_AUTH_BYTES = 16 * 1024, MAX_FILE_BYTES = 64 * 1024, LOGIN_TIMEOUT_MS = 5 * 6e4, LOOPBACK = "127.0.0.1";
200
+ CliAuth = class {
201
+ constructor(mcpUrl, {
202
+ path = configPath(),
203
+ fetcher = fetch,
204
+ browser = openBrowser,
205
+ onUrl = () => {
206
+ }
207
+ } = {}) {
208
+ this.mcpUrl = validateMcpUrl(mcpUrl), this.path = path, this.fetcher = fetcher, this.browser = browser, this.onUrl = onUrl, this.refreshing = null;
209
+ }
210
+ status() {
211
+ let value = readCredential(this.path, this.mcpUrl);
212
+ return { signedIn: !!value, expiresAt: value?.expiresAt ?? null };
213
+ }
214
+ async login() {
215
+ let callback = createServer();
216
+ await new Promise((resolveListen, reject) => {
217
+ callback.once("error", reject), callback.listen(0, LOOPBACK, resolveListen);
218
+ });
219
+ let address = callback.address();
220
+ if (!address || typeof address == "string") throw new Error("Could not start OAuth callback.");
221
+ let redirectUri = `http://${LOOPBACK}:${address.port}/callback`, origin = new URL(this.mcpUrl).origin, loginTimer;
222
+ try {
223
+ let registration = await readJson(await this.fetcher(`${origin}/oauth/register`, {
224
+ method: "POST",
225
+ redirect: "error",
226
+ headers: { "Content-Type": "application/json" },
227
+ body: JSON.stringify({
228
+ application_type: "native",
229
+ client_name: "Adelin CLI",
230
+ adelin_capabilities: ["local-transfer", "live-credentials"],
231
+ grant_types: ["authorization_code", "refresh_token"],
232
+ response_types: ["code"],
233
+ redirect_uris: [redirectUri],
234
+ scope: "mcp:connect",
235
+ token_endpoint_auth_method: "none"
236
+ }),
237
+ signal: AbortSignal.timeout(15e3)
238
+ }));
239
+ if (typeof registration.client_id != "string" || !registration.client_id)
240
+ throw new Error("Adelin did not register the CLI.");
241
+ let recovery;
242
+ for (let attempt = 0; attempt < 3; attempt++) {
243
+ let verifier = randomBytes(32).toString("base64url"), challenge = createHash("sha256").update(verifier).digest("base64url"), state = randomBytes(32).toString("base64url");
244
+ callback.removeAllListeners("request");
245
+ let authorize = new URL(`${origin}/oauth/authorize`);
246
+ for (let [key3, value] of Object.entries({
247
+ client_id: registration.client_id,
248
+ redirect_uri: redirectUri,
249
+ response_type: "code",
250
+ scope: "mcp:connect",
251
+ code_challenge: challenge,
252
+ code_challenge_method: "S256",
253
+ state,
254
+ resource: this.mcpUrl
255
+ })) authorize.searchParams.set(key3, value);
256
+ recovery && authorize.searchParams.set("adelin_recovery", recovery);
257
+ let answer = await new Promise((resolveCode, reject) => {
258
+ loginTimer = setTimeout(() => reject(new Error("Adelin login timed out.")), LOGIN_TIMEOUT_MS), callback.on("request", (req, res) => {
259
+ let url = new URL(req.url ?? "/", redirectUri), provided = Buffer.from(url.searchParams.get("state") ?? ""), expected = Buffer.from(state), valid = url.pathname === "/callback" && req.method === "GET" && provided.length === expected.length && timingSafeEqual(provided, expected);
260
+ if (res.writeHead(valid ? 200 : 400, {
261
+ "Content-Type": "text/html; charset=utf-8",
262
+ "Cache-Control": "no-store",
263
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'"
264
+ }), res.end(valid ? "<h1>Adelin sign-in complete</h1><p>You can close this tab.</p>" : "<h1>Invalid Adelin sign-in callback</h1>"), !valid) return;
265
+ clearTimeout(loginTimer);
266
+ let receivedCode = url.searchParams.get("code");
267
+ if (url.searchParams.get("error") === "APP_SELECTION_CHANGED" && /^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("error_description") ?? ""))
268
+ return resolveCode({ recovery: url.searchParams.get("error_description") });
269
+ receivedCode ? resolveCode({ code: receivedCode }) : reject(new Error("Adelin login was denied."));
270
+ }), this.onUrl(authorize.href), Promise.resolve(this.browser(authorize.href)).catch(reject);
271
+ });
272
+ if (answer.recovery) {
273
+ recovery = answer.recovery;
274
+ continue;
275
+ }
276
+ let code = answer.code, token = await readJson(await this.fetcher(`${origin}/oauth/token`, {
277
+ method: "POST",
278
+ redirect: "error",
279
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
280
+ body: new URLSearchParams({
281
+ grant_type: "authorization_code",
282
+ code,
283
+ redirect_uri: redirectUri,
284
+ client_id: registration.client_id,
285
+ code_verifier: verifier,
286
+ resource: this.mcpUrl
287
+ }),
288
+ signal: AbortSignal.timeout(15e3)
289
+ }));
290
+ return await withCredentialLock(this.path, () => saveCredential(this.path, tokenFields(
291
+ token,
292
+ { mcpUrl: this.mcpUrl, clientId: registration.client_id }
293
+ ))), { signedIn: !0 };
294
+ }
295
+ throw new Error("App access changed. Start login again.");
296
+ } finally {
297
+ clearTimeout(loginTimer), callback.close();
298
+ }
299
+ }
300
+ async accessToken() {
301
+ let current = readCredential(this.path, this.mcpUrl);
302
+ if (!current) throw new Error("Run adelin login first.");
303
+ return current.expiresAt > Date.now() + 3e4 ? current.accessToken : (this.refreshing || (this.refreshing = this.refresh(current).finally(() => {
304
+ this.refreshing = null;
305
+ })), this.refreshing);
306
+ }
307
+ async refreshNow() {
308
+ let current = readCredential(this.path, this.mcpUrl);
309
+ if (!current) throw new Error("Run adelin login first.");
310
+ return this.refreshing || (this.refreshing = this.refresh(current).finally(() => {
311
+ this.refreshing = null;
312
+ })), this.refreshing;
313
+ }
314
+ async refresh(current) {
315
+ return withCredentialLock(this.path, async () => {
316
+ let latest = readCredential(this.path, this.mcpUrl), expired = () => Object.assign(new Error("Adelin sign-in expired or was revoked. Run adelin login."), { code: "AUTH_EXPIRED" });
317
+ if (!latest || latest.clientId !== current.clientId) throw expired();
318
+ if ((latest.refreshToken !== current.refreshToken || latest.accessToken !== current.accessToken) && latest.expiresAt > Date.now() + 3e4)
319
+ return latest.accessToken;
320
+ current = latest;
321
+ let origin = new URL(this.mcpUrl).origin, response2 = await this.fetcher(`${origin}/oauth/token`, {
322
+ method: "POST",
323
+ redirect: "error",
324
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
325
+ body: new URLSearchParams({
326
+ grant_type: "refresh_token",
327
+ refresh_token: current.refreshToken,
328
+ client_id: current.clientId,
329
+ resource: this.mcpUrl
330
+ }),
331
+ signal: AbortSignal.timeout(15e3)
332
+ });
333
+ if (!response2.ok) {
334
+ let newer = readCredential(this.path, this.mcpUrl);
335
+ if (newer && newer.clientId === current.clientId && newer.refreshToken !== current.refreshToken && newer.expiresAt > Date.now() + 3e4) return newer.accessToken;
336
+ throw response2.status >= 500 || response2.status === 429 ? new Error(`Adelin sign-in service is unavailable (${response2.status}). Retry shortly.`) : expired();
337
+ }
338
+ let next = tokenFields(await readJson(response2), current), saved = readCredential(this.path, this.mcpUrl);
339
+ if (!saved || saved.clientId !== current.clientId) throw expired();
340
+ if (saved.refreshToken !== current.refreshToken || saved.accessToken !== current.accessToken) {
341
+ if (saved.expiresAt > Date.now() + 3e4) return saved.accessToken;
342
+ throw expired();
343
+ }
344
+ return saveCredential(this.path, next), next.accessToken;
345
+ });
346
+ }
347
+ /** Removes only this server's credential. */
348
+ async logout() {
349
+ return withCredentialLock(this.path, () => {
350
+ let { [this.mcpUrl]: _removed, ...rest } = readServers(this.path);
351
+ return writeServers(this.path, rest), { signedIn: !1 };
352
+ });
353
+ }
354
+ };
355
+ }
356
+ });
357
+
75
358
  // skills/adelin-app-generation/scripts/__generated__/library-subtitle-rules.mjs
76
359
  function extensionOf(name) {
77
360
  let dot = name.lastIndexOf(".");
@@ -3713,6 +3996,10 @@ var ACTION, MAX_DEVICE_BYTES, UUID11, STAGING_PATH, R2_HOST, TICKET_HEADERS, SER
3713
3996
  device_status: "device_status",
3714
3997
  device_operation: "device",
3715
3998
  preview_pass: "preview_pass",
3999
+ start_device: "device_start",
4000
+ decline_device: "device_decline",
4001
+ renew_device: "device_renew",
4002
+ stop_device: "device_stop",
3716
4003
  agent_view: "agent_view",
3717
4004
  handover_edit_session: "handover"
3718
4005
  }), MAX_DEVICE_BYTES = 3 * 1024 * 1024;
@@ -3817,6 +4104,74 @@ ${digest3}`), signature = sign2(null, bytes, this.privateKey).toString("base64ur
3817
4104
  }
3818
4105
  });
3819
4106
 
4107
+ // skills/adelin-app-generation/scripts/local-device-approval.mjs
4108
+ import { createServer as createServer3 } from "node:http";
4109
+ import { randomBytes as randomBytes5 } from "node:crypto";
4110
+ async function approveCloudDevice(server, { platform, reason, signal, requestId }, { open = openBrowser, timeoutMs = 3e5 } = {}) {
4111
+ signal?.throwIfAborted();
4112
+ let preferred = platform === "tv" ? "tvos" : platform === "phone" ? "ios" : platform, platforms = [preferred, ...Object.keys(labels).filter((value) => value !== preferred)], message = `Start a cloud device to test this app? This uses your organization's preview minutes.${reason ? ` Reason: ${reason}` : ""}`;
4113
+ if (server?.getClientCapabilities()?.elicitation?.form) {
4114
+ let result = await server.elicitInput(
4115
+ {
4116
+ mode: "form",
4117
+ message,
4118
+ requestedSchema: { type: "object", properties: { platform: {
4119
+ type: "string",
4120
+ title: "Device",
4121
+ enum: platforms,
4122
+ enumNames: platforms.map((value) => labels[value]),
4123
+ default: preferred
4124
+ } }, required: ["platform"] }
4125
+ },
4126
+ { timeout: timeoutMs, signal, ...requestId === void 0 ? {} : { relatedRequestId: requestId } }
4127
+ );
4128
+ if (result.action !== "accept") return null;
4129
+ if (!Object.hasOwn(labels, result.content?.platform)) throw new Error("Invalid device approval.");
4130
+ return result.content.platform;
4131
+ }
4132
+ let token = randomBytes5(24).toString("hex"), finish, answered = new Promise((resolve16) => {
4133
+ finish = resolve16;
4134
+ }), http = createServer3((req, res) => {
4135
+ if (res.setHeader("Cache-Control", "no-store"), res.setHeader("Content-Security-Policy", "default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"), res.setHeader("Referrer-Policy", "same-origin"), req.headers.host !== new URL(url).host || req.url !== `/${token}`) {
4136
+ res.writeHead(404).end();
4137
+ return;
4138
+ }
4139
+ if (req.method === "GET") {
4140
+ res.setHeader("Content-Type", "text/html; charset=utf-8"), res.end(`<!doctype html><html lang="en"><meta charset="utf-8"><title>Adelin device approval</title><h1>Start a cloud device?</h1><p>${escape(message)}</p><form method="post"><label>Device <select name="platform">${platforms.map((value) => `<option value="${value}">${labels[value]}</option>`).join("")}</select></label><button name="answer" value="start">Start device</button><button name="answer" value="decline">Not now</button></form></html>`);
4141
+ return;
4142
+ }
4143
+ if (req.method !== "POST" || req.headers.origin !== new URL(url).origin || req.headers["content-type"]?.split(";")[0] !== "application/x-www-form-urlencoded") {
4144
+ res.writeHead(403).end();
4145
+ return;
4146
+ }
4147
+ let body = "";
4148
+ req.on("data", (chunk) => {
4149
+ body += chunk, body.length > 1024 && req.destroy();
4150
+ }), req.on("end", () => {
4151
+ let form = new URLSearchParams(body), selected = form.get("platform");
4152
+ if (!["start", "decline"].includes(form.get("answer")) || !Object.hasOwn(labels, selected)) {
4153
+ res.writeHead(400).end();
4154
+ return;
4155
+ }
4156
+ res.setHeader("Content-Type", "text/plain; charset=utf-8"), res.end("Answer received. You can close this tab and return to your coding client."), finish(form.get("answer") === "start" ? selected : null);
4157
+ });
4158
+ }), url, timer, abort = () => finish(null);
4159
+ try {
4160
+ return await new Promise((resolve16, reject) => {
4161
+ http.once("error", reject), http.listen(0, "127.0.0.1", resolve16);
4162
+ }), url = `http://127.0.0.1:${http.address().port}/${token}`, timer = setTimeout(() => finish(null), timeoutMs), signal?.addEventListener("abort", abort, { once: !0 }), signal?.throwIfAborted(), process.stderr.write(`Adelin device approval: ${url}
4163
+ `), await open(url), await answered;
4164
+ } finally {
4165
+ clearTimeout(timer), signal?.removeEventListener("abort", abort), http.closeAllConnections(), await new Promise((resolve16) => http.close(resolve16));
4166
+ }
4167
+ }
4168
+ var labels, escape, init_local_device_approval = __esm({
4169
+ "skills/adelin-app-generation/scripts/local-device-approval.mjs"() {
4170
+ init_cli_auth();
4171
+ labels = { tvos: "Apple TV", "android-tv": "Android TV", ios: "iPhone", android: "Android phone" }, escape = (text4) => String(text4).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]);
4172
+ }
4173
+ });
4174
+
3820
4175
  // skills/adelin-app-generation/scripts/cli-mcp-host.mjs
3821
4176
  var cli_mcp_host_exports = {};
3822
4177
  __export(cli_mcp_host_exports, {
@@ -3879,6 +4234,7 @@ async function createMcpHost({
3879
4234
  hostState,
3880
4235
  project,
3881
4236
  release: candidate2,
4237
+ approveDevice: (input) => approveCloudDevice(server, input),
3882
4238
  onToolsChanged: () => {
3883
4239
  try {
3884
4240
  server.sendToolListChanged().catch(() => {
@@ -3961,7 +4317,7 @@ async function createMcpHost({
3961
4317
  server.setRequestHandler(ListToolsRequestSchema, (_request, { signal }) => dispatch(async () => {
3962
4318
  let result = await runtime.listTools();
3963
4319
  return { ...result, tools: [...result.tools.filter((tool) => tool.name !== REFRESH), contextTool] };
3964
- }, signal)), server.setRequestHandler(CallToolRequestSchema, ({ params }, { signal }) => dispatch(async () => {
4320
+ }, signal)), server.setRequestHandler(CallToolRequestSchema, ({ params }, { signal, requestId }) => dispatch(async () => {
3965
4321
  let { name, arguments: args = {} } = params;
3966
4322
  if (name === REFRESH) {
3967
4323
  if (Object.keys(args).length) return response({ error: "INVALID_ARGUMENT", message: "This tool takes no arguments." }, !0);
@@ -3982,7 +4338,7 @@ async function createMcpHost({
3982
4338
  return withNotice(refused("PROJECT_SETUP_REQUIRED"));
3983
4339
  }
3984
4340
  }
3985
- let result = await runtime.callTool(params);
4341
+ let result = await runtime.callTool(params, { signal, requestId });
3986
4342
  return updateRefusal(result) && (blocked = "UPDATE_REQUIRED", nextCheckAt = 0), (name === "reconcile_build" || name === "close_app") && (nextCheckAt = 0), withNotice(result);
3987
4343
  }, signal));
3988
4344
  let timer = setInterval(() => {
@@ -4003,6 +4359,7 @@ var HOST_PROTOCOL, MAX_REQUESTS, REFRESH, CONTINUATIONS, contextTool, messages,
4003
4359
  init_local_build_transport();
4004
4360
  init_cli_update();
4005
4361
  init_cli_project();
4362
+ init_local_device_approval();
4006
4363
  HOST_PROTOCOL = 1, MAX_REQUESTS = 16, REFRESH = "refresh_generation_context", CONTINUATIONS = /* @__PURE__ */ new Set([
4007
4364
  "build_status",
4008
4365
  "reconcile_build",
@@ -4028,294 +4385,14 @@ var HOST_PROTOCOL, MAX_REQUESTS, REFRESH, CONTINUATIONS, contextTool, messages,
4028
4385
  });
4029
4386
 
4030
4387
  // skills/adelin-app-generation/scripts/adelin.mjs
4388
+ init_cli_auth();
4389
+ init_cli_remote();
4390
+ init_cli_server();
4031
4391
  import { readFileSync as readFileSync9, realpathSync as realpathSync9 } from "node:fs";
4032
4392
  import { dirname as dirname11, join as join15, resolve as resolve15 } from "node:path";
4033
4393
  import { fileURLToPath as fileURLToPath4, pathToFileURL as pathToFileURL2 } from "node:url";
4034
4394
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4035
4395
 
4036
- // skills/adelin-app-generation/scripts/cli-auth.mjs
4037
- init_cli_server();
4038
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
4039
- import { spawn } from "node:child_process";
4040
- import { createServer } from "node:http";
4041
- import { createServer as createLockServer } from "node:net";
4042
- import {
4043
- closeSync,
4044
- constants,
4045
- existsSync as existsSync2,
4046
- fsyncSync,
4047
- lstatSync,
4048
- mkdirSync,
4049
- openSync,
4050
- readFileSync as readFileSync2,
4051
- realpathSync,
4052
- renameSync,
4053
- unlinkSync,
4054
- writeFileSync
4055
- } from "node:fs";
4056
- import { homedir } from "node:os";
4057
- import { basename, dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
4058
- import { setTimeout as delay } from "node:timers/promises";
4059
- var MAX_AUTH_BYTES = 16 * 1024, MAX_FILE_BYTES = 64 * 1024, LOGIN_TIMEOUT_MS = 5 * 6e4, LOOPBACK = "127.0.0.1";
4060
- function configPath() {
4061
- let base = process.platform === "win32" ? process.env.APPDATA || join2(homedir(), "AppData", "Roaming") : process.env.XDG_CONFIG_HOME || join2(homedir(), ".config");
4062
- return join2(resolve2(base), "adelin", "auth.json");
4063
- }
4064
- function privateFile(path) {
4065
- if (!existsSync2(path)) return !1;
4066
- let stat2 = lstatSync(path);
4067
- if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > MAX_FILE_BYTES || process.platform !== "win32" && (stat2.mode & 63) !== 0)
4068
- throw new Error("Adelin credential file is not private.");
4069
- return !0;
4070
- }
4071
- function privateDirectory(path) {
4072
- mkdirSync(path, { recursive: !0, mode: 448 });
4073
- let stat2 = lstatSync(path);
4074
- if (!stat2.isDirectory() || stat2.isSymbolicLink() || process.platform !== "win32" && (stat2.mode & 63) !== 0)
4075
- throw new Error("Adelin credential directory is not private.");
4076
- }
4077
- function readServers(path) {
4078
- if (!privateFile(path)) return {};
4079
- let value = JSON.parse(readFileSync2(path, "utf8"));
4080
- if (value?.schema !== 2) return {};
4081
- if (!value.servers || typeof value.servers != "object" || Array.isArray(value.servers) || Object.values(value.servers).some((entry) => !entry || typeof entry.clientId != "string" || typeof entry.accessToken != "string" || typeof entry.refreshToken != "string" || !Number.isSafeInteger(entry.expiresAt)))
4082
- throw new Error("Adelin credential file is invalid.");
4083
- return value.servers;
4084
- }
4085
- function readCredential(path, mcpUrl) {
4086
- let servers = readServers(path);
4087
- return Object.hasOwn(servers, mcpUrl) ? { mcpUrl, ...servers[mcpUrl] } : null;
4088
- }
4089
- function writeServers(path, servers) {
4090
- if (!Object.keys(servers).length) {
4091
- privateFile(path) && unlinkSync(path);
4092
- return;
4093
- }
4094
- privateDirectory(dirname2(path)), privateFile(path);
4095
- let stage = `${path}.${randomBytes(12).toString("hex")}.tmp`, fd = openSync(stage, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 384);
4096
- try {
4097
- writeFileSync(fd, JSON.stringify({ schema: 2, servers }) + `
4098
- `), fsyncSync(fd);
4099
- } finally {
4100
- closeSync(fd);
4101
- }
4102
- try {
4103
- renameSync(stage, path);
4104
- } finally {
4105
- existsSync2(stage) && unlinkSync(stage);
4106
- }
4107
- }
4108
- function saveCredential(path, { mcpUrl, ...entry }) {
4109
- writeServers(path, { ...readServers(path), [mcpUrl]: entry });
4110
- }
4111
- async function withCredentialLock(path, work) {
4112
- privateDirectory(dirname2(path));
4113
- let identity = join2(realpathSync(dirname2(path)), basename(path));
4114
- (process.platform === "darwin" || process.platform === "win32") && (identity = identity.normalize("NFC").toLowerCase());
4115
- let port = 49152 + createHash("sha256").update(identity).digest().readUInt32BE(0) % 16384, deadline = performance.now() + 3e4;
4116
- for (; ; ) {
4117
- let lock = createLockServer((socket) => socket.destroy());
4118
- try {
4119
- await new Promise((resolveListen, reject) => {
4120
- lock.once("error", reject), lock.listen({ host: LOOPBACK, port, exclusive: !0 }, resolveListen);
4121
- });
4122
- } catch (error) {
4123
- if (error.code !== "EADDRINUSE")
4124
- throw new Error(`Cannot lock Adelin credentials through loopback (${error.code ?? "listen failed"}).`, { cause: error });
4125
- if (performance.now() >= deadline)
4126
- throw new Error("Adelin credential lock is busy (another operation or local port collision). Retry shortly.");
4127
- await delay(25);
4128
- continue;
4129
- }
4130
- try {
4131
- return await work();
4132
- } finally {
4133
- await new Promise((resolveClose, reject) => lock.close((error) => error ? reject(error) : resolveClose()));
4134
- }
4135
- }
4136
- }
4137
- function tokenFields(value, previous) {
4138
- if (!value || value.token_type !== "Bearer" || typeof value.access_token != "string" || !value.access_token || typeof value.refresh_token != "string" || !value.refresh_token || !Number.isInteger(value.expires_in) || value.expires_in < 1 || value.expires_in > 3600)
4139
- throw new Error("Adelin returned an invalid OAuth token response.");
4140
- return {
4141
- mcpUrl: previous.mcpUrl,
4142
- clientId: previous.clientId,
4143
- accessToken: value.access_token,
4144
- refreshToken: value.refresh_token,
4145
- expiresAt: Date.now() + value.expires_in * 1e3
4146
- };
4147
- }
4148
- async function readJson(response2, limit3 = MAX_AUTH_BYTES) {
4149
- if (!response2.ok) throw new Error(`Adelin OAuth request failed (${response2.status}).`);
4150
- let bytes = await response2.arrayBuffer();
4151
- if (bytes.byteLength > limit3) throw new Error("Adelin OAuth response is too large.");
4152
- return JSON.parse(Buffer.from(bytes).toString("utf8"));
4153
- }
4154
- function openBrowser(url) {
4155
- let command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open", args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url], child2 = spawn(command, args, { detached: !0, stdio: "ignore" });
4156
- child2.on("error", () => {
4157
- }), child2.unref();
4158
- }
4159
- var CliAuth = class {
4160
- constructor(mcpUrl, {
4161
- path = configPath(),
4162
- fetcher = fetch,
4163
- browser = openBrowser,
4164
- onUrl = () => {
4165
- }
4166
- } = {}) {
4167
- this.mcpUrl = validateMcpUrl(mcpUrl), this.path = path, this.fetcher = fetcher, this.browser = browser, this.onUrl = onUrl, this.refreshing = null;
4168
- }
4169
- status() {
4170
- let value = readCredential(this.path, this.mcpUrl);
4171
- return { signedIn: !!value, expiresAt: value?.expiresAt ?? null };
4172
- }
4173
- async login() {
4174
- let callback = createServer();
4175
- await new Promise((resolveListen, reject) => {
4176
- callback.once("error", reject), callback.listen(0, LOOPBACK, resolveListen);
4177
- });
4178
- let address = callback.address();
4179
- if (!address || typeof address == "string") throw new Error("Could not start OAuth callback.");
4180
- let redirectUri = `http://${LOOPBACK}:${address.port}/callback`, origin = new URL(this.mcpUrl).origin, loginTimer;
4181
- try {
4182
- let registration = await readJson(await this.fetcher(`${origin}/oauth/register`, {
4183
- method: "POST",
4184
- redirect: "error",
4185
- headers: { "Content-Type": "application/json" },
4186
- body: JSON.stringify({
4187
- application_type: "native",
4188
- client_name: "Adelin CLI",
4189
- adelin_capabilities: ["local-transfer", "live-credentials"],
4190
- grant_types: ["authorization_code", "refresh_token"],
4191
- response_types: ["code"],
4192
- redirect_uris: [redirectUri],
4193
- scope: "mcp:connect",
4194
- token_endpoint_auth_method: "none"
4195
- }),
4196
- signal: AbortSignal.timeout(15e3)
4197
- }));
4198
- if (typeof registration.client_id != "string" || !registration.client_id)
4199
- throw new Error("Adelin did not register the CLI.");
4200
- let recovery;
4201
- for (let attempt = 0; attempt < 3; attempt++) {
4202
- let verifier = randomBytes(32).toString("base64url"), challenge = createHash("sha256").update(verifier).digest("base64url"), state = randomBytes(32).toString("base64url");
4203
- callback.removeAllListeners("request");
4204
- let authorize = new URL(`${origin}/oauth/authorize`);
4205
- for (let [key3, value] of Object.entries({
4206
- client_id: registration.client_id,
4207
- redirect_uri: redirectUri,
4208
- response_type: "code",
4209
- scope: "mcp:connect",
4210
- code_challenge: challenge,
4211
- code_challenge_method: "S256",
4212
- state,
4213
- resource: this.mcpUrl
4214
- })) authorize.searchParams.set(key3, value);
4215
- recovery && authorize.searchParams.set("adelin_recovery", recovery);
4216
- let answer = await new Promise((resolveCode, reject) => {
4217
- loginTimer = setTimeout(() => reject(new Error("Adelin login timed out.")), LOGIN_TIMEOUT_MS), callback.on("request", (req, res) => {
4218
- let url = new URL(req.url ?? "/", redirectUri), provided = Buffer.from(url.searchParams.get("state") ?? ""), expected = Buffer.from(state), valid = url.pathname === "/callback" && req.method === "GET" && provided.length === expected.length && timingSafeEqual(provided, expected);
4219
- if (res.writeHead(valid ? 200 : 400, {
4220
- "Content-Type": "text/html; charset=utf-8",
4221
- "Cache-Control": "no-store",
4222
- "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'"
4223
- }), res.end(valid ? "<h1>Adelin sign-in complete</h1><p>You can close this tab.</p>" : "<h1>Invalid Adelin sign-in callback</h1>"), !valid) return;
4224
- clearTimeout(loginTimer);
4225
- let receivedCode = url.searchParams.get("code");
4226
- if (url.searchParams.get("error") === "APP_SELECTION_CHANGED" && /^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("error_description") ?? ""))
4227
- return resolveCode({ recovery: url.searchParams.get("error_description") });
4228
- receivedCode ? resolveCode({ code: receivedCode }) : reject(new Error("Adelin login was denied."));
4229
- }), this.onUrl(authorize.href), Promise.resolve(this.browser(authorize.href)).catch(reject);
4230
- });
4231
- if (answer.recovery) {
4232
- recovery = answer.recovery;
4233
- continue;
4234
- }
4235
- let code = answer.code, token = await readJson(await this.fetcher(`${origin}/oauth/token`, {
4236
- method: "POST",
4237
- redirect: "error",
4238
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
4239
- body: new URLSearchParams({
4240
- grant_type: "authorization_code",
4241
- code,
4242
- redirect_uri: redirectUri,
4243
- client_id: registration.client_id,
4244
- code_verifier: verifier,
4245
- resource: this.mcpUrl
4246
- }),
4247
- signal: AbortSignal.timeout(15e3)
4248
- }));
4249
- return await withCredentialLock(this.path, () => saveCredential(this.path, tokenFields(
4250
- token,
4251
- { mcpUrl: this.mcpUrl, clientId: registration.client_id }
4252
- ))), { signedIn: !0 };
4253
- }
4254
- throw new Error("App access changed. Start login again.");
4255
- } finally {
4256
- clearTimeout(loginTimer), callback.close();
4257
- }
4258
- }
4259
- async accessToken() {
4260
- let current = readCredential(this.path, this.mcpUrl);
4261
- if (!current) throw new Error("Run adelin login first.");
4262
- return current.expiresAt > Date.now() + 3e4 ? current.accessToken : (this.refreshing || (this.refreshing = this.refresh(current).finally(() => {
4263
- this.refreshing = null;
4264
- })), this.refreshing);
4265
- }
4266
- async refreshNow() {
4267
- let current = readCredential(this.path, this.mcpUrl);
4268
- if (!current) throw new Error("Run adelin login first.");
4269
- return this.refreshing || (this.refreshing = this.refresh(current).finally(() => {
4270
- this.refreshing = null;
4271
- })), this.refreshing;
4272
- }
4273
- async refresh(current) {
4274
- return withCredentialLock(this.path, async () => {
4275
- let latest = readCredential(this.path, this.mcpUrl), expired = () => Object.assign(new Error("Adelin sign-in expired or was revoked. Run adelin login."), { code: "AUTH_EXPIRED" });
4276
- if (!latest || latest.clientId !== current.clientId) throw expired();
4277
- if ((latest.refreshToken !== current.refreshToken || latest.accessToken !== current.accessToken) && latest.expiresAt > Date.now() + 3e4)
4278
- return latest.accessToken;
4279
- current = latest;
4280
- let origin = new URL(this.mcpUrl).origin, response2 = await this.fetcher(`${origin}/oauth/token`, {
4281
- method: "POST",
4282
- redirect: "error",
4283
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
4284
- body: new URLSearchParams({
4285
- grant_type: "refresh_token",
4286
- refresh_token: current.refreshToken,
4287
- client_id: current.clientId,
4288
- resource: this.mcpUrl
4289
- }),
4290
- signal: AbortSignal.timeout(15e3)
4291
- });
4292
- if (!response2.ok) {
4293
- let newer = readCredential(this.path, this.mcpUrl);
4294
- if (newer && newer.clientId === current.clientId && newer.refreshToken !== current.refreshToken && newer.expiresAt > Date.now() + 3e4) return newer.accessToken;
4295
- throw response2.status >= 500 || response2.status === 429 ? new Error(`Adelin sign-in service is unavailable (${response2.status}). Retry shortly.`) : expired();
4296
- }
4297
- let next = tokenFields(await readJson(response2), current), saved = readCredential(this.path, this.mcpUrl);
4298
- if (!saved || saved.clientId !== current.clientId) throw expired();
4299
- if (saved.refreshToken !== current.refreshToken || saved.accessToken !== current.accessToken) {
4300
- if (saved.expiresAt > Date.now() + 3e4) return saved.accessToken;
4301
- throw expired();
4302
- }
4303
- return saveCredential(this.path, next), next.accessToken;
4304
- });
4305
- }
4306
- /** Removes only this server's credential. */
4307
- async logout() {
4308
- return withCredentialLock(this.path, () => {
4309
- let { [this.mcpUrl]: _removed, ...rest } = readServers(this.path);
4310
- return writeServers(this.path, rest), { signedIn: !1 };
4311
- });
4312
- }
4313
- };
4314
-
4315
- // skills/adelin-app-generation/scripts/adelin.mjs
4316
- init_cli_remote();
4317
- init_cli_server();
4318
-
4319
4396
  // skills/adelin-app-generation/scripts/cli-setup.mjs
4320
4397
  init_cli_project();
4321
4398
  init_workspace_support();
@@ -450,7 +450,7 @@ var encoder, init_logs = __esm({
450
450
  });
451
451
 
452
452
  // packages/preview-browser/src/install.ts
453
- import { spawn as spawn2 } from "node:child_process";
453
+ import { spawn as spawn3 } from "node:child_process";
454
454
  import { existsSync as existsSync4, readFileSync as readFileSync6 } from "node:fs";
455
455
  import { homedir as homedir3 } from "node:os";
456
456
  import { dirname as dirname7, join as join11 } from "node:path";
@@ -483,7 +483,7 @@ async function defaultLaunchProbe(launch) {
483
483
  }
484
484
  function defaultSpawnInstall(cacheDir, env, signal) {
485
485
  return new Promise((resolve13, reject) => {
486
- let child2 = spawn2(process.execPath, [join11(playwrightCoreDir(), "cli.js"), "install", "--only-shell", "chromium"], {
486
+ let child2 = spawn3(process.execPath, [join11(playwrightCoreDir(), "cli.js"), "install", "--only-shell", "chromium"], {
487
487
  env: { ...env, PLAYWRIGHT_BROWSERS_PATH: cacheDir },
488
488
  stdio: "ignore",
489
489
  signal
@@ -529,7 +529,7 @@ var SHELL_PATHS, INSTALL_TIMEOUT_MS, installs, init_install = __esm({
529
529
  });
530
530
 
531
531
  // packages/preview-browser/src/secretInput.ts
532
- import { randomBytes as randomBytes4 } from "node:crypto";
532
+ import { randomBytes as randomBytes5 } from "node:crypto";
533
533
  function capturePasswords(name) {
534
534
  let win = globalThis, send = win[name], selector = 'input[type="password" i],input[autocomplete~="current-password" i],input[autocomplete~="new-password" i]';
535
535
  if (typeof send != "function") return;
@@ -551,7 +551,7 @@ async function installSecretInputCapture(context, page2, conceal) {
551
551
  return;
552
552
  }
553
553
  targets.add(targetInfo.targetId);
554
- let binding = `adelin_secret_${randomBytes4(12).toString("hex")}`, world = `adelin_secret_world_${randomBytes4(12).toString("hex")}`, source = `(${capturePasswords})(${JSON.stringify(binding)})`;
554
+ let binding = `adelin_secret_${randomBytes5(12).toString("hex")}`, world = `adelin_secret_world_${randomBytes5(12).toString("hex")}`, source = `(${capturePasswords})(${JSON.stringify(binding)})`;
555
555
  cdp.on("Runtime.bindingCalled", (event) => {
556
556
  if (event.name === binding)
557
557
  try {
@@ -2120,7 +2120,7 @@ var DIALOG_TYPES, QUALITY_FLOOR, URL_LIKE, CHOOSER_WINDOW_MS, STATE_CHECK_MS, IN
2120
2120
  });
2121
2121
 
2122
2122
  // packages/preview-browser/src/userInput.ts
2123
- import { randomBytes as randomBytes5 } from "node:crypto";
2123
+ import { randomBytes as randomBytes6 } from "node:crypto";
2124
2124
  function listen(name) {
2125
2125
  let win = globalThis, binding = win[name];
2126
2126
  if (typeof binding != "function" || win.__adelinListening) return;
@@ -2199,10 +2199,10 @@ function installUserInputDetector(host, options2) {
2199
2199
  if (!active) return void cdp.detach().catch(() => {
2200
2200
  });
2201
2201
  sessions.add(cdp);
2202
- let binding = `adelin_${randomBytes5(12).toString("hex")}`;
2202
+ let binding = `adelin_${randomBytes6(12).toString("hex")}`;
2203
2203
  cdp.on("Runtime.bindingCalled", (event) => {
2204
2204
  event.name === binding && onSignal(session, top, event.payload);
2205
- }), await arm(cdp, binding, `adelin_input_${randomBytes5(6).toString("hex")}`);
2205
+ }), await arm(cdp, binding, `adelin_input_${randomBytes6(6).toString("hex")}`);
2206
2206
  }, install = async (session) => {
2207
2207
  if (installed.has(session)) return;
2208
2208
  installed.add(session);
@@ -2599,7 +2599,7 @@ button:disabled{cursor:default;opacity:.5}
2599
2599
  });
2600
2600
 
2601
2601
  // packages/preview-browser/src/localView.ts
2602
- import { createHash as createHash5, randomBytes as randomBytes6, timingSafeEqual } from "node:crypto";
2602
+ import { createHash as createHash5, randomBytes as randomBytes7, timingSafeEqual } from "node:crypto";
2603
2603
  import http, { STATUS_CODES } from "node:http";
2604
2604
  function refuseUpgrade(socket, status2) {
2605
2605
  socket.end(`HTTP/1.1 ${status2} ${STATUS_CODES[status2]}\r
@@ -2615,7 +2615,7 @@ async function startLocalAgentView({
2615
2615
  viewerSocketMs = AGENT_VIEW_CAPS.viewerSocketMs,
2616
2616
  onEvent
2617
2617
  }) {
2618
- let { WebSocketServer: Server2 } = await import("ws"), key4 = randomBytes6(32).toString("base64url"), keyDigest = digest3(key4), viewers = /* @__PURE__ */ new Set(), lastState = null, dashboard = null, dashboardCount = 0, dashboardListeners = /* @__PURE__ */ new Set(), watching = 0, closing = !1, bound2 = 0, emit = (name, fields2 = {}) => {
2618
+ let { WebSocketServer: Server2 } = await import("ws"), key4 = randomBytes7(32).toString("base64url"), keyDigest = digest3(key4), viewers = /* @__PURE__ */ new Set(), lastState = null, dashboard = null, dashboardCount = 0, dashboardListeners = /* @__PURE__ */ new Set(), watching = 0, closing = !1, bound2 = 0, emit = (name, fields2 = {}) => {
2619
2619
  try {
2620
2620
  onEvent?.(name, fields2);
2621
2621
  } catch {
@@ -2756,7 +2756,7 @@ async function startLocalAgentView({
2756
2756
  wss.handleUpgrade(request, socket, head, (ws) => {
2757
2757
  let viewer = {
2758
2758
  ws,
2759
- id: randomBytes6(12).toString("base64url"),
2759
+ id: randomBytes7(12).toString("base64url"),
2760
2760
  origin,
2761
2761
  dashboard: fromDashboard,
2762
2762
  rights: "watch",
@@ -2902,7 +2902,7 @@ var init_src = __esm({
2902
2902
  });
2903
2903
 
2904
2904
  // skills/adelin-app-generation/scripts/local-builder.mjs
2905
- import { randomBytes as randomBytes7, randomUUID as randomUUID7 } from "node:crypto";
2905
+ import { randomBytes as randomBytes8, randomUUID as randomUUID7 } from "node:crypto";
2906
2906
  import { mkdtempSync as mkdtempSync2, mkdirSync as mkdirSync5, realpathSync as realpathSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "node:fs";
2907
2907
  import { tmpdir } from "node:os";
2908
2908
  import { dirname as dirname8, isAbsolute as isAbsolute4, join as join12, relative as relative3, resolve as resolve12, sep as sep3 } from "node:path";
@@ -2974,9 +2974,10 @@ var LocalBuildSession = class {
2974
2974
  idleMs = IDLE_MS,
2975
2975
  fingerprint = workspaceFingerprint,
2976
2976
  wait: wait3 = sleep,
2977
- choiceWaitMs = CHOICE_WAIT_MS
2977
+ choiceWaitMs = CHOICE_WAIT_MS,
2978
+ approveDevice
2978
2979
  } = {}) {
2979
- this.remote = remote2, this.wait = wait3, this.choiceWaitMs = choiceWaitMs, this.now = now, this.idleMs = idleMs, this.fingerprint = fingerprint, this.session = null, this.pending = null, this.busy = !1, this.renewing = !1, this.waits = 0, this.waited = !1, this.state = "closed";
2980
+ this.approveDevice = approveDevice, this.localDevice = null, this.pendingDevice = null, this.remote = remote2, this.wait = wait3, this.choiceWaitMs = choiceWaitMs, this.now = now, this.idleMs = idleMs, this.fingerprint = fingerprint, this.session = null, this.pending = null, this.busy = !1, this.renewing = !1, this.waits = 0, this.waited = !1, this.state = "closed";
2980
2981
  }
2981
2982
  async call(name, args) {
2982
2983
  return toolValue(await this.remote.call(name, args), name === "device_operation" ? 3 * 1024 * 1024 : void 0);
@@ -3038,7 +3039,7 @@ var LocalBuildSession = class {
3038
3039
  }
3039
3040
  /** Runs a builder wait; heartbeats during it, and the first one after it, report editing. */
3040
3041
  async waiting(work) {
3041
- this.waits = (this.waits || 0) + 1;
3042
+ this.waits = (this.waits || 0) + 1, this.session && (this.session.lastActivity = this.now());
3042
3043
  try {
3043
3044
  return await work();
3044
3045
  } finally {
@@ -3064,15 +3065,42 @@ var LocalBuildSession = class {
3064
3065
  return choiceResult(await this.call("record_choice", { request_id: requestId, artifact_id: artifactId, ...note2 ? { note: note2 } : {} }));
3065
3066
  }
3066
3067
  /** Asks the builder for a cloud device, then waits a bounded time for the answer. */
3067
- async requestDevice(platform, reason) {
3068
+ async requestDevice(platform, reason, context = {}) {
3068
3069
  if (!this.session || this.state !== "active") throw new Error("Open an app first.");
3069
3070
  let asked = await this.call("request_device", { platform, ...reason ? { reason } : {} });
3070
3071
  if (asked.state !== "asked") throw new Error(DEVICE_REFUSALS[asked.state] ?? "Adelin could not ask for a device.");
3071
- return this.awaitDevice(asked.requestId);
3072
+ return this.approveDevice ? this.waiting(async () => {
3073
+ let owner = this.session, selected;
3074
+ try {
3075
+ selected = await this.approveDevice({ platform, reason, ...context }), context.signal?.throwIfAborted();
3076
+ } catch (error) {
3077
+ throw this.session === owner && this.state === "active" && await this.call("decline_device", { request_id: asked.requestId }).catch(() => {
3078
+ }), error;
3079
+ }
3080
+ if (owner !== this.session || this.state !== "active") throw new Error("The edit session ended during device approval.");
3081
+ if (selected == null)
3082
+ return (await this.call("decline_device", { request_id: asked.requestId })).state === "answered" ? this.pollDevice(asked.requestId) : { state: "declined", message: "Continue without a cloud device." };
3083
+ if (!["tvos", "android-tv", "ios", "android"].includes(selected)) throw new Error("Invalid device approval.");
3084
+ return this.pendingDevice = { request_id: asked.requestId, platform: selected }, this.startLocalDevice();
3085
+ }) : this.awaitDevice(asked.requestId);
3086
+ }
3087
+ async startLocalDevice() {
3088
+ let device = this.pendingDevice, result = await this.call("start_device", { request_id: device.request_id, platform: device.platform });
3089
+ if (this.pendingDevice !== device || !this.session) return { state: "ended" };
3090
+ if (result.state === "ready") {
3091
+ if (typeof result.controlToken != "string" || !result.controlToken) throw new Error("Invalid device lifecycle credential.");
3092
+ return device.controlToken = result.controlToken, this.localDevice = device, this.pendingDevice = null, this.awaitStarted(device.request_id, result.platform === "tvos" || result.platform === "android-tv" ? "cloud_tv" : "cloud_phone", result.platform);
3093
+ }
3094
+ return result.state === "answered" ? (this.pendingDevice = null, this.pollDevice(device.request_id)) : ((result.state === "ended" || result.state === "declined") && (this.pendingDevice = null), { state: result.state, request_id: device.request_id, ...result.error ? { error: result.error } : {} });
3095
+ }
3096
+ async stopDevice() {
3097
+ if (!this.session || this.state !== "active") throw new Error("Open an app first.");
3098
+ let device = this.localDevice ?? this.pendingDevice, result = await this.call("stop_device", device ? { request_id: device.request_id } : {});
3099
+ return result.state === "ended" && (this.localDevice === device && (this.localDevice = null), this.pendingDevice === device && (this.pendingDevice = null)), result;
3072
3100
  }
3073
3101
  async awaitDevice(requestId) {
3074
3102
  if (!this.session || this.state !== "active") throw new Error("Open an app first.");
3075
- return this.waiting(() => this.pollDevice(requestId));
3103
+ return this.waiting(() => this.pendingDevice?.request_id === requestId ? this.startLocalDevice() : this.pollDevice(requestId));
3076
3104
  }
3077
3105
  async pollDevice(requestId) {
3078
3106
  let deadline = this.now() + this.choiceWaitMs;
@@ -3137,7 +3165,7 @@ var LocalBuildSession = class {
3137
3165
  let waited = !1;
3138
3166
  try {
3139
3167
  let fingerprint = this.fingerprint(session.workspace, session.appId), changed = fingerprint !== session.fingerprint;
3140
- if (changed && (session.fingerprint = fingerprint, session.lastActivity = this.now()), !this.busy && this.now() - session.lastActivity >= this.idleMs)
3168
+ if (changed && (session.fingerprint = fingerprint, session.lastActivity = this.now()), !this.busy && !this.waits && this.now() - session.lastActivity >= this.idleMs)
3141
3169
  return await this.close("idle_expired"), this.status();
3142
3170
  waited = this.waited, this.waited = !1;
3143
3171
  let editing = this.busy || changed || this.waits > 0 || waited, result = await this.call("heartbeat_edit_session", {
@@ -3148,7 +3176,16 @@ var LocalBuildSession = class {
3148
3176
  resume_proof: session.resumeProof,
3149
3177
  activity: editing ? "editing" : "idle"
3150
3178
  });
3151
- return this.session !== session ? this.status() : (ENDED_LEASE.has(result.state) ? (this.session = null, this.remote.detach(), this.state = "lease_lost") : this.state = ACTIVE_LEASE.has(result.state) ? "active" : "disconnected", this.status());
3179
+ if (this.session !== session) return this.status();
3180
+ ENDED_LEASE.has(result.state) ? (this.session = null, this.remote.detach(), this.state = "lease_lost", this.localDevice = null, this.pendingDevice = null) : this.state = ACTIVE_LEASE.has(result.state) ? "active" : "disconnected";
3181
+ let device = this.localDevice;
3182
+ if (this.state === "active" && device?.controlToken)
3183
+ try {
3184
+ let renewed = await this.call("renew_device", { request_id: device.request_id, control_token: device.controlToken });
3185
+ this.localDevice === device && (renewed.state === "ready" && typeof renewed.controlToken == "string" ? device.controlToken = renewed.controlToken : renewed.state === "ended" && (this.localDevice = null));
3186
+ } catch {
3187
+ }
3188
+ return this.status();
3152
3189
  } catch {
3153
3190
  return waited && (this.waited = !0), this.session === session && (this.state = "disconnected"), this.status();
3154
3191
  } finally {
@@ -3219,7 +3256,13 @@ var LocalBuildSession = class {
3219
3256
  return this.pending = null, this.remote.detach(), this.state = state, this.status();
3220
3257
  if (!session) return this.status();
3221
3258
  if (this.busy) throw new Error("A build is still running.");
3222
- this.session = null, this.state = state;
3259
+ if (this.localDevice && await this.stopDevice().catch(() => {
3260
+ }), this.pendingDevice) {
3261
+ let pending = this.pendingDevice;
3262
+ await this.call("stop_device", { request_id: pending.request_id }).catch(() => {
3263
+ });
3264
+ }
3265
+ this.localDevice = null, this.pendingDevice = null, this.session = null, this.state = state;
3223
3266
  try {
3224
3267
  (await this.call("close_edit_session", {
3225
3268
  app_id: session.appId,
@@ -3234,15 +3277,12 @@ var LocalBuildSession = class {
3234
3277
  }
3235
3278
  };
3236
3279
 
3237
- // skills/adelin-app-generation/scripts/local-builder.mjs
3238
- import { MANIFEST as MANIFEST4, assertSafeTarget as assertSafeTarget2, lstatIfPresent as lstatIfPresent4, readSafeFile as readSafeFile5 } from "./workspace-state.mjs";
3280
+ // skills/adelin-app-generation/scripts/local-device-approval.mjs
3281
+ import { createServer } from "node:http";
3282
+ import { randomBytes } from "node:crypto";
3239
3283
 
3240
- // skills/adelin-app-generation/scripts/cli-project.mjs
3241
- import { execFileSync } from "node:child_process";
3242
- import { randomUUID as randomUUID2 } from "node:crypto";
3243
- import { linkSync as linkSync2, mkdirSync, readlinkSync, realpathSync, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
3244
- import { dirname, isAbsolute, join as join3, relative, resolve as resolve3, sep } from "node:path";
3245
- import { parse } from "jsonc-parser";
3284
+ // skills/adelin-app-generation/scripts/cli-auth.mjs
3285
+ import { spawn } from "node:child_process";
3246
3286
 
3247
3287
  // skills/adelin-app-generation/scripts/cli-server.mjs
3248
3288
  function validateMcpUrl(raw) {
@@ -3252,7 +3292,84 @@ function validateMcpUrl(raw) {
3252
3292
  return url.href;
3253
3293
  }
3254
3294
 
3295
+ // skills/adelin-app-generation/scripts/cli-auth.mjs
3296
+ var MAX_AUTH_BYTES = 16 * 1024, MAX_FILE_BYTES = 64 * 1024, LOGIN_TIMEOUT_MS = 5 * 6e4;
3297
+ function openBrowser(url) {
3298
+ let command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open", args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url], child2 = spawn(command, args, { detached: !0, stdio: "ignore" });
3299
+ child2.on("error", () => {
3300
+ }), child2.unref();
3301
+ }
3302
+
3303
+ // skills/adelin-app-generation/scripts/local-device-approval.mjs
3304
+ var labels = { tvos: "Apple TV", "android-tv": "Android TV", ios: "iPhone", android: "Android phone" }, escape = (text4) => String(text4).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]);
3305
+ async function approveCloudDevice(server, { platform, reason, signal, requestId }, { open = openBrowser, timeoutMs = 3e5 } = {}) {
3306
+ signal?.throwIfAborted();
3307
+ let preferred = platform === "tv" ? "tvos" : platform === "phone" ? "ios" : platform, platforms = [preferred, ...Object.keys(labels).filter((value) => value !== preferred)], message = `Start a cloud device to test this app? This uses your organization's preview minutes.${reason ? ` Reason: ${reason}` : ""}`;
3308
+ if (server?.getClientCapabilities()?.elicitation?.form) {
3309
+ let result = await server.elicitInput(
3310
+ {
3311
+ mode: "form",
3312
+ message,
3313
+ requestedSchema: { type: "object", properties: { platform: {
3314
+ type: "string",
3315
+ title: "Device",
3316
+ enum: platforms,
3317
+ enumNames: platforms.map((value) => labels[value]),
3318
+ default: preferred
3319
+ } }, required: ["platform"] }
3320
+ },
3321
+ { timeout: timeoutMs, signal, ...requestId === void 0 ? {} : { relatedRequestId: requestId } }
3322
+ );
3323
+ if (result.action !== "accept") return null;
3324
+ if (!Object.hasOwn(labels, result.content?.platform)) throw new Error("Invalid device approval.");
3325
+ return result.content.platform;
3326
+ }
3327
+ let token2 = randomBytes(24).toString("hex"), finish, answered = new Promise((resolve13) => {
3328
+ finish = resolve13;
3329
+ }), http2 = createServer((req, res) => {
3330
+ if (res.setHeader("Cache-Control", "no-store"), res.setHeader("Content-Security-Policy", "default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"), res.setHeader("Referrer-Policy", "same-origin"), req.headers.host !== new URL(url).host || req.url !== `/${token2}`) {
3331
+ res.writeHead(404).end();
3332
+ return;
3333
+ }
3334
+ if (req.method === "GET") {
3335
+ res.setHeader("Content-Type", "text/html; charset=utf-8"), res.end(`<!doctype html><html lang="en"><meta charset="utf-8"><title>Adelin device approval</title><h1>Start a cloud device?</h1><p>${escape(message)}</p><form method="post"><label>Device <select name="platform">${platforms.map((value) => `<option value="${value}">${labels[value]}</option>`).join("")}</select></label><button name="answer" value="start">Start device</button><button name="answer" value="decline">Not now</button></form></html>`);
3336
+ return;
3337
+ }
3338
+ if (req.method !== "POST" || req.headers.origin !== new URL(url).origin || req.headers["content-type"]?.split(";")[0] !== "application/x-www-form-urlencoded") {
3339
+ res.writeHead(403).end();
3340
+ return;
3341
+ }
3342
+ let body = "";
3343
+ req.on("data", (chunk) => {
3344
+ body += chunk, body.length > 1024 && req.destroy();
3345
+ }), req.on("end", () => {
3346
+ let form = new URLSearchParams(body), selected = form.get("platform");
3347
+ if (!["start", "decline"].includes(form.get("answer")) || !Object.hasOwn(labels, selected)) {
3348
+ res.writeHead(400).end();
3349
+ return;
3350
+ }
3351
+ res.setHeader("Content-Type", "text/plain; charset=utf-8"), res.end("Answer received. You can close this tab and return to your coding client."), finish(form.get("answer") === "start" ? selected : null);
3352
+ });
3353
+ }), url, timer, abort = () => finish(null);
3354
+ try {
3355
+ return await new Promise((resolve13, reject) => {
3356
+ http2.once("error", reject), http2.listen(0, "127.0.0.1", resolve13);
3357
+ }), url = `http://127.0.0.1:${http2.address().port}/${token2}`, timer = setTimeout(() => finish(null), timeoutMs), signal?.addEventListener("abort", abort, { once: !0 }), signal?.throwIfAborted(), process.stderr.write(`Adelin device approval: ${url}
3358
+ `), await open(url), await answered;
3359
+ } finally {
3360
+ clearTimeout(timer), signal?.removeEventListener("abort", abort), http2.closeAllConnections(), await new Promise((resolve13) => http2.close(resolve13));
3361
+ }
3362
+ }
3363
+
3364
+ // skills/adelin-app-generation/scripts/local-builder.mjs
3365
+ import { MANIFEST as MANIFEST4, assertSafeTarget as assertSafeTarget2, lstatIfPresent as lstatIfPresent4, readSafeFile as readSafeFile5 } from "./workspace-state.mjs";
3366
+
3255
3367
  // skills/adelin-app-generation/scripts/cli-project.mjs
3368
+ import { execFileSync } from "node:child_process";
3369
+ import { randomUUID as randomUUID2 } from "node:crypto";
3370
+ import { linkSync as linkSync2, mkdirSync, readlinkSync, realpathSync, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
3371
+ import { dirname, isAbsolute, join as join3, relative, resolve as resolve3, sep } from "node:path";
3372
+ import { parse } from "jsonc-parser";
3256
3373
  import { assertNoSymlinkAncestors as assertNoSymlinkAncestors2, lstatIfPresent as lstatIfPresent2, MANIFEST as MANIFEST3, parseManifest as parseManifest3, readSafeFile as readSafeFile3, sha256 as sha2562, UUID as UUID2 } from "./workspace-state.mjs";
3257
3374
 
3258
3375
  // skills/adelin-app-generation/scripts/workspace-support.mjs
@@ -3652,7 +3769,7 @@ import { join as join5, resolve as resolve6 } from "node:path";
3652
3769
  var ASSET_NAME = /^[a-z0-9][a-z0-9_-]{0,63}\.(png|jpg|jpeg|webp)$/;
3653
3770
 
3654
3771
  // skills/adelin-app-generation/scripts/library-files.mjs
3655
- import { createHash as createHash2, generateKeyPairSync, randomBytes, sign } from "node:crypto";
3772
+ import { createHash as createHash2, generateKeyPairSync, randomBytes as randomBytes2, sign } from "node:crypto";
3656
3773
  import { closeSync as closeSync2, constants as constants2, fstatSync as fstatSync2, linkSync as linkSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, realpathSync as realpathSync3, unlinkSync as unlinkSync4 } from "node:fs";
3657
3774
  import { basename as basename2, dirname as dirname3, join as join4, resolve as resolve5 } from "node:path";
3658
3775
 
@@ -5466,7 +5583,7 @@ function sameFile(path, bytes2) {
5466
5583
  }
5467
5584
  }
5468
5585
  function sink(directory, path, bytes2) {
5469
- let temp = join4(directory, `.${basename2(path)}.${randomBytes(8).toString("hex")}.part`);
5586
+ let temp = join4(directory, `.${basename2(path)}.${randomBytes2(8).toString("hex")}.part`);
5470
5587
  try {
5471
5588
  writePrivateOutput({ directory, path: temp, kind: "library-file", payload: bytes2 });
5472
5589
  } catch {
@@ -5515,7 +5632,7 @@ function filesWorkflow({ remote: remote2, fetcher = fetch, clock = Date.now, tim
5515
5632
  return decodeGrant(result, request, key4);
5516
5633
  }
5517
5634
  async function post(origin, route, grant, privateKey, body, meta, ms) {
5518
- let path = `/v1/agent-files/${route}`, timestamp2 = String(clock()), nonce = randomBytes(24).toString("base64url"), signature = sign(null, Buffer.from(`POST
5635
+ let path = `/v1/agent-files/${route}`, timestamp2 = String(clock()), nonce = randomBytes2(24).toString("base64url"), signature = sign(null, Buffer.from(`POST
5519
5636
  ${path}
5520
5637
  ${timestamp2}
5521
5638
  ${nonce}
@@ -5619,7 +5736,7 @@ var URL_HELP = "", WRITE_HELP = "--file PATH --operation-id <UUID> --expected-re
5619
5736
  };
5620
5737
 
5621
5738
  // skills/adelin-app-generation/scripts/local-build-transport.mjs
5622
- import { createHash as createHash3, generateKeyPairSync as generateKeyPairSync2, randomBytes as randomBytes2, sign as sign2 } from "node:crypto";
5739
+ import { createHash as createHash3, generateKeyPairSync as generateKeyPairSync2, randomBytes as randomBytes3, sign as sign2 } from "node:crypto";
5623
5740
  var ACTION = Object.freeze({
5624
5741
  heartbeat_edit_session: "heartbeat",
5625
5742
  save_app_changes: "build",
@@ -5634,6 +5751,10 @@ var ACTION = Object.freeze({
5634
5751
  device_status: "device_status",
5635
5752
  device_operation: "device",
5636
5753
  preview_pass: "preview_pass",
5754
+ start_device: "device_start",
5755
+ decline_device: "device_decline",
5756
+ renew_device: "device_renew",
5757
+ stop_device: "device_stop",
5637
5758
  agent_view: "agent_view",
5638
5759
  handover_edit_session: "handover"
5639
5760
  }), MAX_DEVICE_BYTES = 3 * 1024 * 1024;
@@ -5730,7 +5851,7 @@ var LocalBuildTransport = class {
5730
5851
  lease_id: this.tuple.leaseId,
5731
5852
  chat_session_id: this.tuple.chatSessionId,
5732
5853
  epoch: this.tuple.epoch
5733
- }, body = Buffer.from(JSON.stringify({ ...tuple, ...args }), "utf8"), timestamp2 = String(Date.now()), nonce = randomBytes2(24).toString("base64url"), digest4 = createHash3("sha256").update(body).digest("hex"), bytes2 = Buffer.from(`POST
5854
+ }, body = Buffer.from(JSON.stringify({ ...tuple, ...args }), "utf8"), timestamp2 = String(Date.now()), nonce = randomBytes3(24).toString("base64url"), digest4 = createHash3("sha256").update(body).digest("hex"), bytes2 = Buffer.from(`POST
5734
5855
  ${path}
5735
5856
  ${timestamp2}
5736
5857
  ${nonce}
@@ -5862,7 +5983,7 @@ function uploadTarget(ticket, file) {
5862
5983
  } catch {
5863
5984
  target2 = null;
5864
5985
  }
5865
- if (!target2 || !(target2.protocol === "https:" || !1) || target2.username || target2.password || target2.hash || ticket.method !== "PUT" || typeof ticket.attachmentId != "string" || !UUID7.test(ticket.attachmentId) || ticket.headers?.["content-type"] !== file.contentType || ticket.headers?.["content-length"] !== String(file.size))
5986
+ if (!target2 || !(target2.protocol === "https:" || !1) || target2.username || target2.password || target2.hash || ticket.method !== "PUT" || typeof ticket.attachmentId != "string" || !UUID7.test(ticket.attachmentId) || ticket.headers?.["content-type"] !== file.contentType || ticket.headers?.["content-length"] !== String(file.size) || typeof ticket.headers?.["if-match"] != "string" || !/^"[!#-~]*"$/.test(ticket.headers["if-match"]))
5866
5987
  throw coded("ADELIN_TOOL_FAILED", "Adelin returned an invalid asset upload.");
5867
5988
  return target2;
5868
5989
  }
@@ -5876,7 +5997,7 @@ async function saveOne({ root, appId, edit, call, fetcher, timeout }, file) {
5876
5997
  redirect: "error",
5877
5998
  body: bytes2,
5878
5999
  signal: timeout(transferDeadlineMs(file.size)),
5879
- headers: { "content-type": file.contentType, "content-length": String(file.size) }
6000
+ headers: { "content-type": file.contentType, "content-length": String(file.size), "if-match": ticket.headers["if-match"] }
5880
6001
  }), await uploaded.body?.cancel();
5881
6002
  } catch {
5882
6003
  throw coded("ASSET_UPLOAD_FAILED", `Uploading ${file.path} did not finish. Build again.`);
@@ -5953,7 +6074,7 @@ import { typecheck } from "./typecheck.mjs";
5953
6074
  import { resolve as resolve11 } from "node:path";
5954
6075
 
5955
6076
  // skills/adelin-app-generation/scripts/media-jobs.mjs
5956
- import { spawn } from "node:child_process";
6077
+ import { spawn as spawn2 } from "node:child_process";
5957
6078
  import { randomUUID as randomUUID5 } from "node:crypto";
5958
6079
  import { existsSync as existsSync3, readFileSync as readFileSync5, readdirSync as readdirSync5, realpathSync as realpathSync5, statSync } from "node:fs";
5959
6080
  import { basename as basename5, dirname as dirname6, join as join10, resolve as resolve10 } from "node:path";
@@ -6841,7 +6962,7 @@ import { fileURLToPath } from "node:url";
6841
6962
  var import_authoring_release = __toESM(require_authoring_release(), 1), CLI_ROOT = resolve7(dirname4(fileURLToPath(import.meta.url)), "..");
6842
6963
 
6843
6964
  // skills/adelin-app-generation/scripts/media-transfer-runner.mjs
6844
- import { createDecipheriv, createHash as createHash4, createPublicKey, diffieHellman, generateKeyPairSync as generateKeyPairSync3, hkdfSync, randomBytes as randomBytes3, randomUUID as randomUUID3 } from "node:crypto";
6965
+ import { createDecipheriv, createHash as createHash4, createPublicKey, diffieHellman, generateKeyPairSync as generateKeyPairSync3, hkdfSync, randomBytes as randomBytes4, randomUUID as randomUUID3 } from "node:crypto";
6845
6966
  import { closeSync as closeSync3, constants as constants4, existsSync, fsyncSync as fsyncSync2, linkSync as linkSync4, lstatSync as lstatSync4, mkdirSync as mkdirSync3, openAsBlob, openSync as openSync3, readFileSync as readFileSync3, readdirSync as readdirSync3, renameSync as renameSync3, unlinkSync as unlinkSync5, writeFileSync as writeFileSync4 } from "node:fs";
6846
6967
  import { homedir } from "node:os";
6847
6968
  import { basename as basename4, dirname as dirname5, join as join8, resolve as resolve8 } from "node:path";
@@ -6942,7 +7063,7 @@ function privateDirectory(path) {
6942
7063
  }
6943
7064
  function writePrivateJson(path, value) {
6944
7065
  privateDirectory(dirname5(path));
6945
- let stage = `${path}.${randomBytes3(12).toString("hex")}.tmp`, fd = openSync3(stage, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384);
7066
+ let stage = `${path}.${randomBytes4(12).toString("hex")}.tmp`, fd = openSync3(stage, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384);
6946
7067
  try {
6947
7068
  writeFileSync4(fd, JSON.stringify(value) + `
6948
7069
  `), fsyncSync2(fd);
@@ -6982,7 +7103,7 @@ function processAlive2(pid) {
6982
7103
  }
6983
7104
  function acquireLock(path, busyCode, isAlive = processAlive2) {
6984
7105
  privateDirectory(dirname5(path));
6985
- let stage = `${path}.${randomBytes3(12).toString("hex")}.tmp`;
7106
+ let stage = `${path}.${randomBytes4(12).toString("hex")}.tmp`;
6986
7107
  writeFileSync4(stage, String(process.pid), { flag: "wx", mode: 384 });
6987
7108
  try {
6988
7109
  for (let attempt = 0; attempt < 2; attempt++)
@@ -7320,7 +7441,7 @@ async function waitJob(dir, jobId, waitSeconds2, { now = Date.now, sleep: sleep2
7320
7441
  return { ...status2, wait: { seconds: waitSeconds2, waitedSeconds: Math.round((now() - start) / 1e3), changed, timedOut: waitSeconds2 > 0 && !changed && !done(status2) } };
7321
7442
  }
7322
7443
  function spawnRunner({ jobId, mcpUrl }) {
7323
- let child2 = spawn(
7444
+ let child2 = spawn2(
7324
7445
  process.execPath,
7325
7446
  [CLI, "media", "upload-worker", "--job", jobId],
7326
7447
  { detached: !0, stdio: "ignore", windowsHide: !0 }
@@ -8449,15 +8570,6 @@ function createLocalPreviewBrowser({ previewPass, env = process.env, load = () =
8449
8570
  };
8450
8571
  }
8451
8572
 
8452
- // skills/adelin-app-generation/scripts/cli-auth.mjs
8453
- import { spawn as spawn3 } from "node:child_process";
8454
- var MAX_AUTH_BYTES = 16 * 1024, MAX_FILE_BYTES = 64 * 1024, LOGIN_TIMEOUT_MS = 5 * 6e4;
8455
- function openBrowser(url) {
8456
- let command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open", args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url], child2 = spawn3(command, args, { detached: !0, stdio: "ignore" });
8457
- child2.on("error", () => {
8458
- }), child2.unref();
8459
- }
8460
-
8461
8573
  // packages/tool-activity/src/appMetadata.ts
8462
8574
  import { z as z3 } from "zod";
8463
8575
  var bytes = (value) => Buffer.byteLength(value, "utf8"), validText = (value) => !value.includes("\0") && Buffer.from(value, "utf8").toString("utf8") === value, APP_CONTEXT_PROJECTION_BYTES = 131072, AppContextProjectionSchema = z3.strictObject({
@@ -8743,6 +8855,12 @@ var UUID13 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-
8743
8855
  annotations: { readOnlyHint: !0 },
8744
8856
  inputSchema: closed5({ request_id: { type: "string", pattern: UUID13 } }, ["request_id"])
8745
8857
  },
8858
+ {
8859
+ name: "stop_device",
8860
+ description: "Stop the current cloud device and end its preview-minute usage. Continue testing in the browser preview.",
8861
+ annotations: { readOnlyHint: !1, destructiveHint: !1, idempotentHint: !0 },
8862
+ inputSchema: noArgs
8863
+ },
8746
8864
  ...previewTools.map(({ name, description: description2, annotations, inputSchema }) => ({ name, description: description2, annotations, inputSchema })),
8747
8865
  {
8748
8866
  name: "show_agent_view",
@@ -9030,7 +9148,7 @@ function createPreviewOwner(session, previewBrowser, viewRetryMs) {
9030
9148
  return registering = registering.then(run, run), registering;
9031
9149
  }, connecting = null, connectView = (appId, browserState) => connecting ??= (async () => {
9032
9150
  let started = await previewBrowser.startView().catch(() => null);
9033
- !started || !session.session || session.session.appId !== appId || (view = { appId, port: started.port, viewId: randomBytes7(24).toString("base64url") }, await registerView(browserState));
9151
+ !started || !session.session || session.session.appId !== appId || (view = { appId, port: started.port, viewId: randomBytes8(24).toString("base64url") }, await registerView(browserState));
9034
9152
  })().finally(() => {
9035
9153
  connecting = null;
9036
9154
  }), onBrowser = (browserState) => {
@@ -9091,7 +9209,7 @@ function createLocalBuilder(remote2, transport, {
9091
9209
  return transport.publicKey;
9092
9210
  },
9093
9211
  call: (name, args) => safeCall(transport, name, args, !0)
9094
- }, session = hostState.session ??= new LocalBuildSession(sessionRemote, options2), preview = hostState.preview ??= createPreviewOwner(
9212
+ }, approveDevice = Object.hasOwn(options2, "approveDevice") ? options2.approveDevice : (input) => approveCloudDevice(null, input), session = hostState.session ??= new LocalBuildSession(sessionRemote, { ...options2, approveDevice }), preview = hostState.preview ??= createPreviewOwner(
9095
9213
  session,
9096
9214
  injectedBrowser ?? createLocalPreviewBrowser({ previewPass: (input) => session.previewPass(input) }),
9097
9215
  viewRetryMs
@@ -9120,7 +9238,7 @@ function createLocalBuilder(remote2, transport, {
9120
9238
  if (standalone) throw new Error(remoteFailed);
9121
9239
  return { tools: localTools };
9122
9240
  }
9123
- }, callTool = async ({ name, arguments: args = {} }) => {
9241
+ }, callTool = async ({ name, arguments: args = {} }, context = {}) => {
9124
9242
  if (exposed.has(name) && !schemas.has(name) && await remoteTools().catch(() => {
9125
9243
  }), name === liveCredentialsTool.name) return response(credentialsCliOnlyRefusal(args), !0);
9126
9244
  let live = liveTools.find((tool2) => tool2.name === name);
@@ -9215,8 +9333,9 @@ function createLocalBuilder(remote2, transport, {
9215
9333
  if (name === "tell_builder") return response(await session.tell(args.message));
9216
9334
  if (name === "ask_builder_to_choose") return response(await session.ask(args.artifact_ids, args.question));
9217
9335
  if (name === "wait_for_choice") return response(await session.awaitChoice(args.request_id));
9218
- if (name === "request_device") return response(await session.requestDevice(args.platform, args.reason));
9336
+ if (name === "request_device") return response(await session.requestDevice(args.platform, args.reason, context));
9219
9337
  if (name === "wait_for_device") return response(await session.awaitDevice(args.request_id));
9338
+ if (name === "stop_device") return response(await session.stopDevice());
9220
9339
  let preview2 = previewTools.find((tool2) => tool2.name === name);
9221
9340
  if (preview2) return await routeAndRun(session, previewBrowser, preview2, args);
9222
9341
  if (name === "show_agent_view") return await showAgentView(session, previewBrowser, openPage);
@@ -9315,7 +9434,7 @@ function createLocalBuilder(remote2, transport, {
9315
9434
  throw new Error("The edit lease could not be verified for the update.");
9316
9435
  return !0;
9317
9436
  }, adopt = () => {
9318
- Object.setPrototypeOf(session, LocalBuildSession.prototype), session.remote = sessionRemote, session.fingerprint = options2.fingerprint ?? workspaceFingerprint;
9437
+ Object.setPrototypeOf(session, LocalBuildSession.prototype), session.remote = sessionRemote, session.approveDevice = approveDevice, session.fingerprint = options2.fingerprint ?? workspaceFingerprint;
9319
9438
  }, close = async () => {
9320
9439
  await pause(), preview.unsubscribe(), await closeBrowser(), (session.session || session.pending) && await session.close().catch(() => {
9321
9440
  });
@@ -9325,7 +9444,7 @@ function createLocalBuilder(remote2, transport, {
9325
9444
  { name: "adelin", version: "1.0.0" },
9326
9445
  { capabilities: { tools: { listChanged: !0 } }, instructions: "Use open_app, check_app, build_app, and close_app. App files move directly through the local CLI. show_agent_view lets the builder watch and control your preview browser." }
9327
9446
  );
9328
- return server.setRequestHandler(ListToolsRequestSchema, listTools), server.setRequestHandler(CallToolRequestSchema, ({ params }) => callTool(params)), notifyTools ??= () => {
9447
+ return session.approveDevice = Object.hasOwn(options2, "approveDevice") ? options2.approveDevice : ((input) => approveCloudDevice(server, input)), server.setRequestHandler(ListToolsRequestSchema, listTools), server.setRequestHandler(CallToolRequestSchema, ({ params }, { signal, requestId }) => callTool(params, { signal, requestId })), notifyTools ??= () => {
9329
9448
  server.sendToolListChanged().catch(() => {
9330
9449
  });
9331
9450
  }, resume(), { ...runtime, server, close: async () => {
@@ -87,7 +87,7 @@ After a build that saved files, the `preview_*` tools work at once on the browse
87
87
 
88
88
  The preview browser runs headless on the builder's computer from `open_app` until `close_app`; it never opens a window. When the builder wants to see or steer the preview, call `show_agent_view`. If App Creator is open on this computer, the builder already watches that same browser there and nothing new opens. Otherwise it opens a local page in the builder's default browser. That page's link grants full control, so the tool never returns it; if no page opened, tell the builder the link is in the Adelin MCP server's log. Their own clicks, scrolls and typing pause your next preview action, and Alt/Option-clicks reach you as "The builder pointed at:" lines; handle both as the [visual review guide](../design/visual-review.md#when-the-builder-shares-the-preview) says.
89
89
 
90
- `request_device` is only for a check on a real cloud TV or phone. You can ask at any point in the session, before or without a build, for example to debug how the app already behaves on a device. Call `request_device(platform)` with an optional one-line reason. Pass `tv` or `phone` to let the builder pick the platform, or an exact one when the check depends on it: `tvos` (Apple TV), `android-tv`, `ios` (iPhone) or `android`. The builder answers in the dashboard, where the platform you asked for comes first, and can start that or another cloud TV or phone, or say not now; cloud devices use their preview minutes. The call waits up to 45 seconds for an answer, then until the started device responds. If it returns `waiting` or `starting`, call `wait_for_device` with its `request_id`; `ended` means the builder turned the device off. Ask once per round of fixes, not before every build. When the answer is `ready`, its `platform` names the device the builder started, and the `preview_*` tools run on it until it ends. A device action refused with "No device is running" means the builder ended the device test or it ran out of minutes; continue on the browser preview and do not ask for a device again in the same round.
90
+ `request_device` is only for a check on a real cloud TV or phone. You can ask at any point in the session, before or without a build, for example to debug how the app already behaves on a device. Call `request_device(platform)` with an optional one-line reason. Pass `tv` or `phone` to let the builder pick the platform, or an exact one when the check depends on it: `tvos` (Apple TV), `android-tv`, `ios` (iPhone) or `android`. Adelin asks the builder to approve locally in the coding client, with the requested platform selected first and a notice that cloud devices use their preview minutes. If the client cannot show approval forms, Adelin opens a one-use approval page on this computer. The builder can pick another cloud platform or decline. Never approve on their behalf. Dashboard answers remain available and the first answer wins. Local approval waits up to five minutes; dismissing or declining starts nothing. After approval, the CLI starts and maintains the device without a dashboard tab, then waits until it responds. If it returns `waiting` or `starting`, call `wait_for_device` with its `request_id`; `ended` means the builder turned the device off. Ask once per round of fixes, not before every build. When the answer is `ready`, its `platform` names the device the builder started, and the `preview_*` tools run on it until it ends. Call `stop_device` when testing is finished to stop using preview minutes; closing the app session also stops a locally started device. A failed platform switch keeps the existing device running. If it returns `STOP_CURRENT_PREVIEW_FIRST`, call `stop_device`, then `wait_for_device` with the new request's `request_id` to continue the already-approved start. A device action refused with "No device is running" means the builder ended the device test or it ran out of minutes; continue on the browser preview and do not ask for a device again in the same round.
91
91
 
92
92
  The builder can stop the session from the dashboard, or take the app back in App Creator. Either ends the lease, so the next heartbeat reports `lease_lost` and later builds are refused. Keep local edits, stop working on the app, and ask in the terminal before reopening it.
93
93