@adelin-io/cli 0.1.5 → 0.1.7

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.
@@ -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();