@adelin-io/cli 0.1.2 → 0.1.4

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.
@@ -453,22 +453,22 @@ var encoder, init_logs = __esm({
453
453
  import { spawn as spawn2 } 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
- import { dirname as dirname7, join as join10 } from "node:path";
456
+ import { dirname as dirname7, join as join11 } from "node:path";
457
457
  import { chromium } from "playwright-core";
458
458
  function playwrightCoreDir() {
459
459
  return dirname7(__require.resolve("playwright-core/package.json"));
460
460
  }
461
461
  function headlessShellRevision() {
462
- let shell = JSON.parse(readFileSync6(join10(playwrightCoreDir(), "browsers.json"), "utf8")).browsers.find((browser) => browser.name === "chromium-headless-shell");
462
+ let shell = JSON.parse(readFileSync6(join11(playwrightCoreDir(), "browsers.json"), "utf8")).browsers.find((browser) => browser.name === "chromium-headless-shell");
463
463
  if (!shell) throw new Error("playwright-core lists no chromium-headless-shell");
464
464
  return shell.revision;
465
465
  }
466
466
  function headlessShellPath(cacheDir) {
467
467
  let tokens = SHELL_PATHS[`${process.platform}-${process.arch}`];
468
- return tokens ? join10(cacheDir, `chromium_headless_shell-${headlessShellRevision()}`, ...tokens) : null;
468
+ return tokens ? join11(cacheDir, `chromium_headless_shell-${headlessShellRevision()}`, ...tokens) : null;
469
469
  }
470
470
  function defaultCacheDir(env = process.env) {
471
- return env.ADELIN_BROWSERS_PATH ? env.ADELIN_BROWSERS_PATH : process.platform === "darwin" ? join10(homedir3(), "Library", "Caches", "adelin", "browsers") : process.platform === "win32" ? join10(env.LOCALAPPDATA ?? join10(homedir3(), "AppData", "Local"), "adelin", "browsers") : join10(env.XDG_CACHE_HOME ?? join10(homedir3(), ".cache"), "adelin", "browsers");
471
+ return env.ADELIN_BROWSERS_PATH ? env.ADELIN_BROWSERS_PATH : process.platform === "darwin" ? join11(homedir3(), "Library", "Caches", "adelin", "browsers") : process.platform === "win32" ? join11(env.LOCALAPPDATA ?? join11(homedir3(), "AppData", "Local"), "adelin", "browsers") : join11(env.XDG_CACHE_HOME ?? join11(homedir3(), ".cache"), "adelin", "browsers");
472
472
  }
473
473
  async function defaultLaunchProbe(launch) {
474
474
  try {
@@ -482,13 +482,13 @@ async function defaultLaunchProbe(launch) {
482
482
  }
483
483
  }
484
484
  function defaultSpawnInstall(cacheDir, env, signal) {
485
- return new Promise((resolve12, reject) => {
486
- let child2 = spawn2(process.execPath, [join10(playwrightCoreDir(), "cli.js"), "install", "--only-shell", "chromium"], {
485
+ return new Promise((resolve13, reject) => {
486
+ let child2 = spawn2(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
490
490
  });
491
- child2.once("error", reject), child2.once("exit", (code) => code === 0 ? resolve12() : reject(new Error(`browser install exited with ${code}`)));
491
+ child2.once("error", reject), child2.once("exit", (code) => code === 0 ? resolve13() : reject(new Error(`browser install exited with ${code}`)));
492
492
  });
493
493
  }
494
494
  async function resolveLocalBrowser(options2) {
@@ -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 randomBytes3 } from "node:crypto";
532
+ import { randomBytes as randomBytes4 } 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_${randomBytes3(12).toString("hex")}`, world = `adelin_secret_world_${randomBytes3(12).toString("hex")}`, source = `(${capturePasswords})(${JSON.stringify(binding)})`;
554
+ let binding = `adelin_secret_${randomBytes4(12).toString("hex")}`, world = `adelin_secret_world_${randomBytes4(12).toString("hex")}`, source = `(${capturePasswords})(${JSON.stringify(binding)})`;
555
555
  cdp.on("Runtime.bindingCalled", (event) => {
556
556
  if (event.name === binding)
557
557
  try {
@@ -829,6 +829,60 @@ var PreviewHostError, GRANT_PARAM, JWT, SHORT_SECRET_BOUNDARY, init_host = __esm
829
829
  }
830
830
  });
831
831
 
832
+ // packages/preview-browser/src/blank.ts
833
+ import { inflateSync } from "node:zlib";
834
+ function paeth(a, b, c) {
835
+ let p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
836
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
837
+ }
838
+ function isUniformPng(png) {
839
+ let width = 0, height = 0, channels = 0, offset = 8, data = [];
840
+ for (; offset + 8 <= png.length; ) {
841
+ let length = png.readUInt32BE(offset), type = png.toString("ascii", offset + 4, offset + 8), body = png.subarray(offset + 8, offset + 8 + length);
842
+ if (type === "IHDR") {
843
+ if (body[8] !== 8 || body[12] !== 0 || body[9] !== 2 && body[9] !== 6) return !1;
844
+ width = body.readUInt32BE(0), height = body.readUInt32BE(4), channels = body[9] === 6 ? 4 : 3;
845
+ } else if (type === "IDAT") data.push(body);
846
+ else if (type === "IEND") break;
847
+ offset += 12 + length;
848
+ }
849
+ if (!width || !height || !data.length) return !1;
850
+ let raw = inflateSync(Buffer.concat(data)), stride = width * channels;
851
+ if (raw.length < height * (stride + 1)) return !1;
852
+ let previous = Buffer.alloc(stride), first = [];
853
+ for (let y = 0; y < height; y++) {
854
+ let filter = raw[y * (stride + 1)], line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)));
855
+ for (let x = 0; x < stride; x++) {
856
+ let left = x >= channels ? line[x - channels] : 0, up = previous[x], corner = x >= channels ? previous[x - channels] : 0, add = filter === 1 ? left : filter === 2 ? up : filter === 3 ? left + up >> 1 : filter === 4 ? paeth(left, up, corner) : 0;
857
+ line[x] = line[x] + add & 255;
858
+ let channel = x % channels;
859
+ if (channel !== 3) {
860
+ if (y === 0 && x < 3) first.push(line[x]);
861
+ else if (Math.abs(line[x] - first[channel]) > TOLERANCE) return !1;
862
+ }
863
+ }
864
+ previous = line;
865
+ }
866
+ return !0;
867
+ }
868
+ async function frameLooksBlank(session, viewport) {
869
+ try {
870
+ let cdp = await session.cdp(), { data } = await cdp.send("Page.captureScreenshot", {
871
+ format: "png",
872
+ clip: { x: 0, y: 0, width: viewport.width, height: viewport.height, scale: PROBE_SCALE }
873
+ });
874
+ return isUniformPng(Buffer.from(data, "base64"));
875
+ } catch {
876
+ return null;
877
+ }
878
+ }
879
+ var PROBE_SCALE, TOLERANCE, init_blank = __esm({
880
+ "packages/preview-browser/src/blank.ts"() {
881
+ "use strict";
882
+ PROBE_SCALE = 0.1, TOLERANCE = 8;
883
+ }
884
+ });
885
+
832
886
  // packages/preview-browser/src/snapshot.ts
833
887
  function isBox(value) {
834
888
  if (!value || typeof value != "object") return !1;
@@ -904,9 +958,9 @@ The page is paused until the dialog is handled with preview_alert.`
904
958
  async function unlessDialog(session, work, timeoutMs) {
905
959
  work.catch(() => {
906
960
  });
907
- let timer, poll, stop = new Promise((resolve12) => {
908
- timer = setTimeout(() => resolve12(null), timeoutMs), poll = setInterval(() => {
909
- session.dialogs.current() && resolve12(null);
961
+ let timer, poll, stop = new Promise((resolve13) => {
962
+ timer = setTimeout(() => resolve13(null), timeoutMs), poll = setInterval(() => {
963
+ session.dialogs.current() && resolve13(null);
910
964
  }, 50);
911
965
  });
912
966
  try {
@@ -1030,9 +1084,9 @@ function viewportOf(session) {
1030
1084
  async function settle2(session, maxMs = SETTLE_MS) {
1031
1085
  let quiet = session.page.evaluate((cap) => {
1032
1086
  let g = globalThis;
1033
- return new Promise((resolve12) => {
1087
+ return new Promise((resolve13) => {
1034
1088
  let timer, done = () => {
1035
- observer.disconnect(), g.removeEventListener("scroll", bump, !0), clearTimeout(timer), clearTimeout(limit3), resolve12();
1089
+ observer.disconnect(), g.removeEventListener("scroll", bump, !0), clearTimeout(timer), clearTimeout(limit3), resolve13();
1036
1090
  }, bump = () => {
1037
1091
  clearTimeout(timer), timer = setTimeout(done, 150);
1038
1092
  }, observer = new g.MutationObserver(bump);
@@ -1192,9 +1246,19 @@ async function focusTv(session, ref, select) {
1192
1246
  return acknowledged(reached ? after : unavailable(`Focus could not reach ${ref} with the remote's arrow keys.
1193
1247
  ${after.text}`));
1194
1248
  }
1249
+ async function painted(session) {
1250
+ let frames = session.page.evaluate(
1251
+ () => new Promise((resolve13) => {
1252
+ let g = globalThis;
1253
+ g.requestAnimationFrame(() => g.requestAnimationFrame(() => resolve13()));
1254
+ })
1255
+ );
1256
+ await unlessDialog(session, frames, PAINT_TIMEOUT_MS).catch(() => {
1257
+ });
1258
+ }
1195
1259
  async function screenshot(session) {
1196
1260
  let blocked = { kind: "unavailable", reason: "A dialog is open; read it with preview_alert." };
1197
- if (session.dialogs.current()) return blocked;
1261
+ if (session.dialogs.current() || (await settle2(session, 1e3), await painted(session), await unlessDialog(session, frameLooksBlank(session, viewportOf(session)), PAINT_TIMEOUT_MS).catch(() => null) && !session.dialogs.current() && (await delay(BLANK_RETRY_MS), await settle2(session, 1e3), await painted(session)), session.dialogs.current())) return blocked;
1198
1262
  for (let quality of SCREENSHOT_QUALITIES) {
1199
1263
  let shot = session.page.screenshot({ type: "jpeg", quality, scale: "css", timeout: SCREENSHOT_TIMEOUT_MS }), image = await unlessDialog(session, shot, SCREENSHOT_TIMEOUT_MS + 500).catch(() => null);
1200
1264
  if (!image) return session.dialogs.current() ? blocked : { kind: "unavailable", reason: "The preview did not render a screenshot in time." };
@@ -1386,14 +1450,15 @@ async function runPreviewTool(session, tool2, rawArgs) {
1386
1450
  return notTv(session, tool2) ?? focusTv(session, String(args.ref), !0);
1387
1451
  }
1388
1452
  }
1389
- var SETTLE_MS, ACTION_TIMEOUT_MS, WIND_DOWN_MS, SCREENSHOT_TIMEOUT_MS, SCREENSHOT_LIMIT_BYTES, SCREENSHOT_QUALITIES, LOG_LINE_BYTES, LOG_TOTAL_BYTES, FOCUS_PRESSES, DISTANCE, OPPOSITE, TARGET_LABELS, encoder3, DPAD, ARROW, unavailable, acknowledged, staleRef, init_operations = __esm({
1453
+ var SETTLE_MS, ACTION_TIMEOUT_MS, WIND_DOWN_MS, SCREENSHOT_TIMEOUT_MS, SCREENSHOT_LIMIT_BYTES, SCREENSHOT_QUALITIES, PAINT_TIMEOUT_MS, BLANK_RETRY_MS, LOG_LINE_BYTES, LOG_TOTAL_BYTES, FOCUS_PRESSES, DISTANCE, OPPOSITE, TARGET_LABELS, encoder3, DPAD, ARROW, unavailable, acknowledged, staleRef, init_operations = __esm({
1390
1454
  "packages/preview-browser/src/operations.ts"() {
1391
1455
  "use strict";
1392
1456
  init_previewTools();
1457
+ init_blank();
1393
1458
  init_host();
1394
1459
  init_snapshot();
1395
1460
  init_targets();
1396
- SETTLE_MS = 2e3, ACTION_TIMEOUT_MS = 5e3, WIND_DOWN_MS = 2e3, SCREENSHOT_TIMEOUT_MS = 5e3, SCREENSHOT_LIMIT_BYTES = 2 * 1024 * 1024, SCREENSHOT_QUALITIES = [80, 60, 40, 25], LOG_LINE_BYTES = 2048, LOG_TOTAL_BYTES = 64 * 1024, FOCUS_PRESSES = 30, DISTANCE = { short: 0.25, medium: 0.5, long: 0.75 }, OPPOSITE = { up: "down", down: "up", left: "right", right: "left" }, TARGET_LABELS = { web_desktop: "Web desktop", web_phone: "Web phone" }, encoder3 = new TextEncoder(), DPAD = {
1461
+ SETTLE_MS = 2e3, ACTION_TIMEOUT_MS = 5e3, WIND_DOWN_MS = 2e3, SCREENSHOT_TIMEOUT_MS = 5e3, SCREENSHOT_LIMIT_BYTES = 2 * 1024 * 1024, SCREENSHOT_QUALITIES = [80, 60, 40, 25], PAINT_TIMEOUT_MS = 1e3, BLANK_RETRY_MS = 500, LOG_LINE_BYTES = 2048, LOG_TOTAL_BYTES = 64 * 1024, FOCUS_PRESSES = 30, DISTANCE = { short: 0.25, medium: 0.5, long: 0.75 }, OPPOSITE = { up: "down", down: "up", left: "right", right: "left" }, TARGET_LABELS = { web_desktop: "Web desktop", web_phone: "Web phone" }, encoder3 = new TextEncoder(), DPAD = {
1397
1462
  dpad_up: { key: "ArrowUp", code: "ArrowUp", keyCode: 38 },
1398
1463
  dpad_down: { key: "ArrowDown", code: "ArrowDown", keyCode: 40 },
1399
1464
  dpad_left: { key: "ArrowLeft", code: "ArrowLeft", keyCode: 37 },
@@ -1468,7 +1533,7 @@ function createTurnGate(options2 = {}) {
1468
1533
  } catch {
1469
1534
  }
1470
1535
  }, userHasTurn = () => held || now() - lastInput < quietMs, wake = () => {
1471
- for (let resolve12 of [...wakers]) resolve12();
1536
+ for (let resolve13 of [...wakers]) resolve13();
1472
1537
  }, changed = () => {
1473
1538
  call(changeListeners), wake();
1474
1539
  }, armQuiet = (delay3 = quietMs) => {
@@ -1478,9 +1543,9 @@ function createTurnGate(options2 = {}) {
1478
1543
  if (!held && left > 0) return armQuiet(Math.ceil(left));
1479
1544
  changed();
1480
1545
  }, delay3), quietTimer.unref?.();
1481
- }, sleep2 = (ms) => new Promise((resolve12) => {
1546
+ }, sleep2 = (ms) => new Promise((resolve13) => {
1482
1547
  let done = () => {
1483
- clearTimeout(timer), wakers.delete(done), resolve12();
1548
+ clearTimeout(timer), wakers.delete(done), resolve13();
1484
1549
  }, timer = setTimeout(done, Math.max(1, ms));
1485
1550
  wakers.add(done);
1486
1551
  });
@@ -1775,7 +1840,7 @@ function jpegSize2(jpeg) {
1775
1840
  return null;
1776
1841
  }
1777
1842
  async function within2(work, ms) {
1778
- let timer, expired = new Promise((resolve12) => timer = setTimeout(() => resolve12(!1), ms));
1843
+ let timer, expired = new Promise((resolve13) => timer = setTimeout(() => resolve13(!1), ms));
1779
1844
  try {
1780
1845
  return await Promise.race([Promise.resolve(work).then(() => !0, () => !0), expired]);
1781
1846
  } finally {
@@ -1927,7 +1992,7 @@ async function applyViewerInput(session, raw) {
1927
1992
  let { width, height } = viewportOf2(session);
1928
1993
  if (input.x >= width || input.y >= height) return { applied: !1, reason: "outside_viewport" };
1929
1994
  }
1930
- let seen = choosers(page2), before = seen.count, dialogOpened, opened = new Promise((resolve12) => dialogOpened = resolve12);
1995
+ let seen = choosers(page2), before = seen.count, dialogOpened, opened = new Promise((resolve13) => dialogOpened = resolve13);
1931
1996
  page2.once("dialog", dialogOpened);
1932
1997
  try {
1933
1998
  let action = perform(session, input);
@@ -2055,7 +2120,7 @@ var DIALOG_TYPES, QUALITY_FLOOR, URL_LIKE, CHOOSER_WINDOW_MS, STATE_CHECK_MS, IN
2055
2120
  });
2056
2121
 
2057
2122
  // packages/preview-browser/src/userInput.ts
2058
- import { randomBytes as randomBytes4 } from "node:crypto";
2123
+ import { randomBytes as randomBytes5 } from "node:crypto";
2059
2124
  function listen(name) {
2060
2125
  let win = globalThis, binding = win[name];
2061
2126
  if (typeof binding != "function" || win.__adelinListening) return;
@@ -2134,10 +2199,10 @@ function installUserInputDetector(host, options2) {
2134
2199
  if (!active) return void cdp.detach().catch(() => {
2135
2200
  });
2136
2201
  sessions.add(cdp);
2137
- let binding = `adelin_${randomBytes4(12).toString("hex")}`;
2202
+ let binding = `adelin_${randomBytes5(12).toString("hex")}`;
2138
2203
  cdp.on("Runtime.bindingCalled", (event) => {
2139
2204
  event.name === binding && onSignal(session, top, event.payload);
2140
- }), await arm(cdp, binding, `adelin_input_${randomBytes4(6).toString("hex")}`);
2205
+ }), await arm(cdp, binding, `adelin_input_${randomBytes5(6).toString("hex")}`);
2141
2206
  }, install = async (session) => {
2142
2207
  if (installed.has(session)) return;
2143
2208
  installed.add(session);
@@ -2534,7 +2599,7 @@ button:disabled{cursor:default;opacity:.5}
2534
2599
  });
2535
2600
 
2536
2601
  // packages/preview-browser/src/localView.ts
2537
- import { createHash as createHash4, randomBytes as randomBytes5, timingSafeEqual } from "node:crypto";
2602
+ import { createHash as createHash5, randomBytes as randomBytes6, timingSafeEqual } from "node:crypto";
2538
2603
  import http, { STATUS_CODES } from "node:http";
2539
2604
  function refuseUpgrade(socket, status2) {
2540
2605
  socket.end(`HTTP/1.1 ${status2} ${STATUS_CODES[status2]}\r
@@ -2550,7 +2615,7 @@ async function startLocalAgentView({
2550
2615
  viewerSocketMs = AGENT_VIEW_CAPS.viewerSocketMs,
2551
2616
  onEvent
2552
2617
  }) {
2553
- let { WebSocketServer: Server2 } = await import("ws"), key4 = randomBytes5(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 = 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 = {}) => {
2554
2619
  try {
2555
2620
  onEvent?.(name, fields2);
2556
2621
  } catch {
@@ -2691,7 +2756,7 @@ async function startLocalAgentView({
2691
2756
  wss.handleUpgrade(request, socket, head, (ws) => {
2692
2757
  let viewer = {
2693
2758
  ws,
2694
- id: randomBytes5(12).toString("base64url"),
2759
+ id: randomBytes6(12).toString("base64url"),
2695
2760
  origin,
2696
2761
  dashboard: fromDashboard,
2697
2762
  rights: "watch",
@@ -2705,9 +2770,9 @@ async function startLocalAgentView({
2705
2770
  viewer.closed || (viewer.chain = viewer.chain.then(() => viewer.closed ? void 0 : onMessage(viewer, data, isBinary)).catch(() => closeWith(viewer, "badMessage", "handler")));
2706
2771
  }), ws.on("error", () => ws.terminate()), ws.on("close", () => onClose(viewer));
2707
2772
  });
2708
- }), await new Promise((resolve12, reject) => {
2773
+ }), await new Promise((resolve13, reject) => {
2709
2774
  server.once("error", reject), server.listen(port, BIND, () => {
2710
- server.off("error", reject), resolve12();
2775
+ server.off("error", reject), resolve13();
2711
2776
  });
2712
2777
  }), bound2 = server.address().port;
2713
2778
  let closed6 = null;
@@ -2728,13 +2793,13 @@ async function startLocalAgentView({
2728
2793
  return closed6 ??= (async () => {
2729
2794
  closing = !0, stopOutbound();
2730
2795
  for (let viewer of viewers) end(viewer);
2731
- syncDashboard(), watching > 0 && await toProducer({ t: "watch", count: 0 }), watching = 0, await new Promise((resolve12) => {
2796
+ syncDashboard(), watching > 0 && await toProducer({ t: "watch", count: 0 }), watching = 0, await new Promise((resolve13) => {
2732
2797
  let force = setTimeout(() => {
2733
2798
  for (let viewer of viewers) viewer.ws.terminate();
2734
2799
  server.closeAllConnections();
2735
2800
  }, 1e3);
2736
2801
  server.close(() => {
2737
- clearTimeout(force), resolve12();
2802
+ clearTimeout(force), resolve13();
2738
2803
  }), server.closeIdleConnections();
2739
2804
  }), wss.close();
2740
2805
  })(), closed6;
@@ -2746,7 +2811,7 @@ var BIND, MAX_PAYLOAD, OPEN, MAX_TIMER_MS, digest3, init_localView = __esm({
2746
2811
  "use strict";
2747
2812
  init_agentView();
2748
2813
  init_localViewPage();
2749
- BIND = "127.0.0.1", MAX_PAYLOAD = 8 * 1024, OPEN = 1, MAX_TIMER_MS = 2 ** 31 - 1, digest3 = (value) => createHash4("sha256").update(value).digest();
2814
+ BIND = "127.0.0.1", MAX_PAYLOAD = 8 * 1024, OPEN = 1, MAX_TIMER_MS = 2 ** 31 - 1, digest3 = (value) => createHash5("sha256").update(value).digest();
2750
2815
  }
2751
2816
  });
2752
2817
 
@@ -2840,7 +2905,7 @@ var init_src = __esm({
2840
2905
  import { randomBytes as randomBytes7, randomUUID as randomUUID7 } from "node:crypto";
2841
2906
  import { mkdtempSync as mkdtempSync2, mkdirSync as mkdirSync5, realpathSync as realpathSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "node:fs";
2842
2907
  import { tmpdir } from "node:os";
2843
- import { dirname as dirname8, isAbsolute as isAbsolute4, join as join11, relative as relative3, resolve as resolve11, sep as sep3 } from "node:path";
2908
+ import { dirname as dirname8, isAbsolute as isAbsolute4, join as join12, relative as relative3, resolve as resolve12, sep as sep3 } from "node:path";
2844
2909
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2845
2910
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
2846
2911
  import { AjvJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/ajv";
@@ -2853,7 +2918,7 @@ import { lstatSync, readdirSync, readFileSync } from "node:fs";
2853
2918
  import { join, resolve } from "node:path";
2854
2919
  import { applySave, prepareSave, readPendingSave, reconcileSave, retrySave } from "./local-save.mjs";
2855
2920
  import { MANIFEST, SOURCE_PATH, hashSafeFile, parseManifest, readSafeFile } from "./workspace-state.mjs";
2856
- var HEARTBEAT_MS = 15e3, IDLE_MS = 10 * 6e4, CHOICE_WAIT_MS = 45e3, CHOICE_POLL_MS = 2e3, DEVICE_START_MS = 9e4, DEVICE_POLL_MS = 3e3, sleep = (ms) => new Promise((resolve12) => setTimeout(resolve12, ms));
2921
+ var HEARTBEAT_MS = 15e3, IDLE_MS = 10 * 6e4, CHOICE_WAIT_MS = 45e3, CHOICE_POLL_MS = 2e3, DEVICE_START_MS = 9e4, DEVICE_POLL_MS = 3e3, sleep = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms)), ACTIVE_LEASE = /* @__PURE__ */ new Set(["resumed", "reconnect_grace"]), ENDED_LEASE = /* @__PURE__ */ new Set(["ended", "reaped", "superseded"]);
2857
2922
  function workspaceFingerprint(workspace, appId) {
2858
2923
  let root = resolve(workspace);
2859
2924
  parseManifest(readSafeFile(join(root, MANIFEST)), appId);
@@ -2889,7 +2954,6 @@ function toolValue(result, limit3 = 2 * 1024 * 1024) {
2889
2954
  return value;
2890
2955
  }
2891
2956
  var DEVICE_REFUSALS = {
2892
- not_built: "Save a working version with build_app first; the builder is asked for a device only after a build that saved files.",
2893
2957
  pending: "A device request is already waiting for the builder. Call wait_for_device with its request_id.",
2894
2958
  ended: "This session has ended. Open the app again first.",
2895
2959
  invalid: "Ask for platform tv or phone, with an optional one-line reason."
@@ -2912,7 +2976,7 @@ var LocalBuildSession = class {
2912
2976
  wait: wait3 = sleep,
2913
2977
  choiceWaitMs = CHOICE_WAIT_MS
2914
2978
  } = {}) {
2915
- 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.state = "closed";
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";
2916
2980
  }
2917
2981
  async call(name, args) {
2918
2982
  return toolValue(await this.remote.call(name, args), name === "device_operation" ? 3 * 1024 * 1024 : void 0);
@@ -2970,6 +3034,18 @@ var LocalBuildSession = class {
2970
3034
  /** Polls for the pick until it arrives or the wait ends; waiting counts as activity so the lease stays open. */
2971
3035
  async awaitChoice(requestId) {
2972
3036
  if (!this.session || this.state !== "active") throw new Error("Open an app first.");
3037
+ return this.waiting(() => this.pollChoice(requestId));
3038
+ }
3039
+ /** Runs a builder wait; heartbeats during it, and the first one after it, report editing. */
3040
+ async waiting(work) {
3041
+ this.waits = (this.waits || 0) + 1;
3042
+ try {
3043
+ return await work();
3044
+ } finally {
3045
+ this.waits--, this.waited = !0;
3046
+ }
3047
+ }
3048
+ async pollChoice(requestId) {
2973
3049
  let deadline = this.now() + this.choiceWaitMs;
2974
3050
  for (; ; ) {
2975
3051
  let status2 = await this.call("choice_status", { request_id: requestId });
@@ -2987,7 +3063,7 @@ var LocalBuildSession = class {
2987
3063
  if (!this.session || this.state !== "active") throw new Error("Open an app first.");
2988
3064
  return choiceResult(await this.call("record_choice", { request_id: requestId, artifact_id: artifactId, ...note2 ? { note: note2 } : {} }));
2989
3065
  }
2990
- /** Asks the builder for a cloud device after a working save, then waits a bounded time for the answer. */
3066
+ /** Asks the builder for a cloud device, then waits a bounded time for the answer. */
2991
3067
  async requestDevice(platform, reason) {
2992
3068
  if (!this.session || this.state !== "active") throw new Error("Open an app first.");
2993
3069
  let asked = await this.call("request_device", { platform, ...reason ? { reason } : {} });
@@ -2996,10 +3072,13 @@ var LocalBuildSession = class {
2996
3072
  }
2997
3073
  async awaitDevice(requestId) {
2998
3074
  if (!this.session || this.state !== "active") throw new Error("Open an app first.");
3075
+ return this.waiting(() => this.pollDevice(requestId));
3076
+ }
3077
+ async pollDevice(requestId) {
2999
3078
  let deadline = this.now() + this.choiceWaitMs;
3000
3079
  for (; ; ) {
3001
3080
  let answer = await this.call("device_status", { request_id: requestId });
3002
- if (this.session && (this.session.lastActivity = this.now()), answer.answer === "ready") return this.awaitStarted(requestId, answer.device);
3081
+ if (this.session && (this.session.lastActivity = this.now()), answer.answer === "ready") return this.awaitStarted(requestId, answer.device, answer.platform);
3003
3082
  if (answer.answer === "declined") return { state: "declined", message: "The builder chose not to test now. Continue without a device." };
3004
3083
  if (this.now() + CHOICE_POLL_MS > deadline || !this.session) break;
3005
3084
  await this.wait(CHOICE_POLL_MS);
@@ -3011,16 +3090,16 @@ var LocalBuildSession = class {
3011
3090
  };
3012
3091
  }
3013
3092
  /** A device the builder started still boots and launches the app; answer once it responds to a no-op wait. */
3014
- async awaitStarted(requestId, device) {
3015
- let deadline = this.now() + DEVICE_START_MS;
3093
+ async awaitStarted(requestId, device, platform) {
3094
+ let started = { device, ...platform ? { platform } : {} }, deadline = this.now() + DEVICE_START_MS;
3016
3095
  for (; ; ) {
3017
- let reply = await this.device("wait", { seconds: 0 });
3018
- if (reply?.status === 200) return {
3096
+ let reply2 = await this.device("wait", { seconds: 0 });
3097
+ if (reply2?.status === 200) return {
3019
3098
  state: "ready",
3020
- device,
3099
+ ...started,
3021
3100
  message: "The device is running. Use the preview_* tools, then fix what you find and build again."
3022
3101
  };
3023
- if (reply?.status === 403) return {
3102
+ if (reply2?.status === 403) return {
3024
3103
  state: "ended",
3025
3104
  message: "The builder turned the device off. Call request_device to ask again when you need one."
3026
3105
  };
@@ -3030,21 +3109,21 @@ var LocalBuildSession = class {
3030
3109
  return {
3031
3110
  state: "starting",
3032
3111
  request_id: requestId,
3033
- device,
3112
+ ...started,
3034
3113
  message: "The device is still starting. Call wait_for_device again in a moment."
3035
3114
  };
3036
3115
  }
3037
3116
  /** Runs one device operation; every action counts as activity so the lease stays open while testing. */
3038
3117
  async device(operation, input) {
3039
3118
  if (!this.session || this.state !== "active") throw new Error("Open an app first.");
3040
- let reply = await this.call("device_operation", { operation, input });
3041
- return this.session && (this.session.lastActivity = this.now()), reply;
3119
+ let reply2 = await this.call("device_operation", { operation, input });
3120
+ return this.session && (this.session.lastActivity = this.now()), reply2;
3042
3121
  }
3043
3122
  /** Asks Adelin whether the next preview call runs on the cloud device or the browser preview; counts as activity. */
3044
3123
  async previewPass(input) {
3045
3124
  if (!this.session || this.state !== "active") throw new Error("Open an app first.");
3046
- let reply = await this.call("preview_pass", input);
3047
- return this.session && (this.session.lastActivity = this.now()), reply;
3125
+ let reply2 = await this.call("preview_pass", input);
3126
+ return this.session && (this.session.lastActivity = this.now()), reply2;
3048
3127
  }
3049
3128
  /** Tells Adelin where App Creator can reach this computer's view of the preview browser; null clears it. */
3050
3129
  async registerView(view) {
@@ -3055,34 +3134,43 @@ var LocalBuildSession = class {
3055
3134
  let session = this.session;
3056
3135
  if (!session || this.renewing) return this.status();
3057
3136
  this.renewing = !0;
3137
+ let waited = !1;
3058
3138
  try {
3059
3139
  let fingerprint = this.fingerprint(session.workspace, session.appId), changed = fingerprint !== session.fingerprint;
3060
3140
  if (changed && (session.fingerprint = fingerprint, session.lastActivity = this.now()), !this.busy && this.now() - session.lastActivity >= this.idleMs)
3061
3141
  return await this.close("idle_expired"), this.status();
3062
- let result = await this.call("heartbeat_edit_session", {
3142
+ waited = this.waited, this.waited = !1;
3143
+ let editing = this.busy || changed || this.waits > 0 || waited, result = await this.call("heartbeat_edit_session", {
3063
3144
  app_id: session.appId,
3064
3145
  lease_id: session.leaseId,
3065
3146
  chat_session_id: session.chatSessionId,
3066
3147
  epoch: session.epoch,
3067
3148
  resume_proof: session.resumeProof,
3068
- activity: this.busy || changed ? "editing" : "idle"
3149
+ activity: editing ? "editing" : "idle"
3069
3150
  });
3070
- return this.session !== session ? this.status() : (result.state !== "resumed" ? (this.session = null, this.remote.detach(), this.state = "lease_lost") : this.state = "active", this.status());
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());
3071
3152
  } catch {
3072
- return this.session === session && (this.state = "disconnected"), this.status();
3153
+ return waited && (this.waited = !0), this.session === session && (this.state = "disconnected"), this.status();
3073
3154
  } finally {
3074
3155
  this.renewing = !1;
3075
3156
  }
3076
3157
  }
3077
- async build() {
3158
+ /** Saves workspace images through `assets` first, unless a save is pending, then sends the changed source. */
3159
+ async build({ assets } = {}) {
3078
3160
  let session = this.session;
3079
3161
  if (!session || this.state !== "active" || this.busy) throw new Error("No active edit session. Open the app first.");
3080
3162
  this.busy = !0, session.lastActivity = this.now();
3081
3163
  try {
3082
- let { workspace, appId, leaseId, chatSessionId, epoch } = session, prepared = prepareSave(workspace, appId, { leaseId, chatSessionId, epoch });
3083
- if (prepared.state === "no_changes") return prepared;
3164
+ let { workspace, appId, leaseId, chatSessionId, epoch } = session, saved = null;
3165
+ if (assets && !readPendingSave(workspace, appId)) {
3166
+ let synced = await assets({ workspace, appId, leaseId, chatSessionId, epoch });
3167
+ if (synced && !synced.ok) return synced.result;
3168
+ saved = synced?.report ?? null;
3169
+ }
3170
+ let withAssets = (outcome3) => saved ? { ...outcome3, assets: saved } : outcome3, prepared = prepareSave(workspace, appId, { leaseId, chatSessionId, epoch });
3171
+ if (prepared.state === "no_changes") return withAssets(prepared);
3084
3172
  let request = JSON.parse(readFileSync(prepared.requestPath, "utf8")), result = await this.call("save_app_changes", request), outcome2 = applySave(workspace, appId, result);
3085
- return session.fingerprint = this.fingerprint(workspace, appId), outcome2;
3173
+ return session.fingerprint = this.fingerprint(workspace, appId), withAssets(outcome2);
3086
3174
  } finally {
3087
3175
  this.busy = !1, session.lastActivity = this.now();
3088
3176
  }
@@ -3147,7 +3235,7 @@ var LocalBuildSession = class {
3147
3235
  };
3148
3236
 
3149
3237
  // skills/adelin-app-generation/scripts/local-builder.mjs
3150
- import { MANIFEST as MANIFEST4, assertSafeTarget as assertSafeTarget2, lstatIfPresent as lstatIfPresent3, readSafeFile as readSafeFile4 } from "./workspace-state.mjs";
3238
+ import { MANIFEST as MANIFEST4, assertSafeTarget as assertSafeTarget2, lstatIfPresent as lstatIfPresent4, readSafeFile as readSafeFile5 } from "./workspace-state.mjs";
3151
3239
 
3152
3240
  // skills/adelin-app-generation/scripts/cli-project.mjs
3153
3241
  import { execFileSync } from "node:child_process";
@@ -3555,7 +3643,87 @@ function ignoreSetupArtifacts(root, repository, paths) {
3555
3643
 
3556
3644
  // skills/adelin-app-generation/scripts/local-builder.mjs
3557
3645
  import { readPendingSave as readPendingSave2 } from "./local-save.mjs";
3558
- import { typecheck } from "./typecheck.mjs";
3646
+
3647
+ // skills/adelin-app-generation/scripts/local-assets.mjs
3648
+ import { readdirSync as readdirSync2 } from "node:fs";
3649
+ import { join as join5, resolve as resolve6 } from "node:path";
3650
+
3651
+ // skills/adelin-app-generation/scripts/__generated__/asset-rules.mjs
3652
+ var ASSET_NAME = /^[a-z0-9][a-z0-9_-]{0,63}\.(png|jpg|jpeg|webp)$/;
3653
+
3654
+ // skills/adelin-app-generation/scripts/library-files.mjs
3655
+ import { createHash as createHash2, generateKeyPairSync, randomBytes, sign } from "node:crypto";
3656
+ 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
+ import { basename as basename2, dirname as dirname3, join as join4, resolve as resolve5 } from "node:path";
3658
+
3659
+ // skills/adelin-app-generation/scripts/__generated__/library-artwork-rules.mjs
3660
+ var ARTWORK_SHAPES = {
3661
+ poster: { ratio: [2, 3], min: { width: 400, height: 600 }, plural: "Posters", example: "1000\xD71500" },
3662
+ backdrop: { ratio: [16, 9], min: { width: 1280, height: 720 }, plural: "Backdrops", example: "1920\xD71080" }
3663
+ }, ARTWORK_RATIO_TOLERANCE = 0.02, LOGO_MAX_SIDE = 4096, gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
3664
+ function ratioName({ width, height }) {
3665
+ let divisor2 = gcd(width, height), w = width / divisor2, h = height / divisor2;
3666
+ return w <= 32 && h <= 32 ? ` (${w}:${h})` : "";
3667
+ }
3668
+ function artworkShapeError(slot, size) {
3669
+ let actual = `${size.width}\xD7${size.height}`;
3670
+ if (slot === "logo" && Math.max(size.width, size.height) > LOGO_MAX_SIDE)
3671
+ return `Logos can be up to ${LOGO_MAX_SIDE}\xD7${LOGO_MAX_SIDE}. This one is ${actual}.`;
3672
+ let rule = ARTWORK_SHAPES[slot];
3673
+ if (!rule) return null;
3674
+ let [w, h] = rule.ratio;
3675
+ return Math.abs(size.width / size.height / (w / h) - 1) > ARTWORK_RATIO_TOLERANCE ? `${rule.plural} need a ${w}:${h} image, like ${rule.example}. This one is ${actual}${ratioName(size)}.` : size.width < rule.min.width || size.height < rule.min.height ? `${rule.plural} need to be at least ${rule.min.width}\xD7${rule.min.height}. This one is ${actual}.` : null;
3676
+ }
3677
+ var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10], JPEG_SIGNATURE = [255, 216, 255], ARTWORK_MAX_BYTES = 10 * 1024 * 1024, ARTWORK_EXTENSIONS = ["png", "jpg", "jpeg"], startsWith = (bytes2, signature) => signature.every((byte, index) => bytes2[index] === byte);
3678
+ function artworkFileType(file) {
3679
+ let dot = file.fileName.lastIndexOf("."), extension = dot < 0 ? "" : file.fileName.slice(dot + 1).toLowerCase();
3680
+ return ARTWORK_EXTENSIONS.includes(extension) ? file.bytes.byteLength > ARTWORK_MAX_BYTES ? { ok: !1, code: "LIBRARY_ARTWORK_TOO_LARGE" } : startsWith(file.bytes, PNG_SIGNATURE) ? { ok: !0, type: "png" } : startsWith(file.bytes, JPEG_SIGNATURE) ? { ok: !0, type: "jpg" } : { ok: !1, code: "LIBRARY_ARTWORK_NOT_IMAGE" } : { ok: !1, code: "LIBRARY_ARTWORK_TYPE" };
3681
+ }
3682
+ function pngSize(bytes2) {
3683
+ if (bytes2.length < 24 || !startsWith(bytes2, PNG_SIGNATURE)) return null;
3684
+ let view = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength);
3685
+ return { width: view.getUint32(16), height: view.getUint32(20) };
3686
+ }
3687
+ function exifTurnsSideways(view, start, end) {
3688
+ let tiff = start + 6;
3689
+ if (end - start < 14 || view.getUint32(start) !== 1165519206) return !1;
3690
+ let little = view.getUint16(tiff) === 18761, ifd = tiff + view.getUint32(tiff + 4, little);
3691
+ if (ifd + 2 > end) return !1;
3692
+ let count4 = view.getUint16(ifd, little);
3693
+ for (let index = 0; index < count4; index += 1) {
3694
+ let entry = ifd + 2 + index * 12;
3695
+ if (entry + 12 > end) return !1;
3696
+ if (view.getUint16(entry, little) === 274) return view.getUint16(entry + 8, little) >= 5;
3697
+ }
3698
+ return !1;
3699
+ }
3700
+ function jpegSize(bytes2) {
3701
+ if (bytes2.length < 4 || bytes2[0] !== 255 || bytes2[1] !== 216) return null;
3702
+ let view = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength), sideways = !1, offset = 2;
3703
+ for (; offset + 4 <= bytes2.length; ) {
3704
+ if (bytes2[offset] !== 255) return null;
3705
+ let marker = bytes2[offset + 1];
3706
+ if (marker === 255) {
3707
+ offset += 1;
3708
+ continue;
3709
+ }
3710
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
3711
+ offset += 2;
3712
+ continue;
3713
+ }
3714
+ let length = view.getUint16(offset + 2), segment = offset + 4;
3715
+ if (marker === 225 && (sideways = sideways || exifTurnsSideways(view, segment, Math.min(segment + length - 2, bytes2.length))), marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204 && segment + 5 <= bytes2.length) {
3716
+ let height = view.getUint16(segment + 1), width = view.getUint16(segment + 3);
3717
+ return sideways ? { width: height, height: width } : { width, height };
3718
+ }
3719
+ if (marker === 218 || marker === 217) return null;
3720
+ offset += 2 + length;
3721
+ }
3722
+ return null;
3723
+ }
3724
+ function imageSize(bytes2) {
3725
+ return pngSize(bytes2) ?? jpegSize(bytes2);
3726
+ }
3559
3727
 
3560
3728
  // skills/adelin-app-generation/scripts/__generated__/library-localized-rules.mjs
3561
3729
  var LANGUAGE_TAG_PATTERN = /^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/;
@@ -3627,6 +3795,73 @@ var PARENT_GROUPS = {
3627
3795
  )
3628
3796
  );
3629
3797
 
3798
+ // skills/adelin-app-generation/scripts/__generated__/library-subtitle-rules.mjs
3799
+ var SUBTITLE_LANGUAGE_PATTERN = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
3800
+ var SRT_TIMESTAMP = /(\d{1,2}:\d{2}:\d{2}),(\d{3})/g, VTT_HEADER = /^WEBVTT(?:[ \t][^\n]*)?$/, INVALID = { ok: !1, code: "LIBRARY_SUBTITLE_INVALID" };
3801
+ function extensionOf(name) {
3802
+ let dot = name.lastIndexOf(".");
3803
+ return dot < 0 ? "" : name.slice(dot + 1).toLowerCase();
3804
+ }
3805
+ function subtitleLanguageValid(value) {
3806
+ return typeof value == "string" && value.length <= 35 && SUBTITLE_LANGUAGE_PATTERN.test(value.trim());
3807
+ }
3808
+ function normalizeSubtitleLanguages(value) {
3809
+ if (!value || typeof value != "object" || Array.isArray(value)) return null;
3810
+ let entries2 = Object.entries(value), result = {};
3811
+ if (entries2.length < 1 || entries2.length > 100) return null;
3812
+ for (let [id11, language5] of entries2) {
3813
+ let key4 = id11.toLowerCase();
3814
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id11) || Object.hasOwn(result, key4) || !subtitleLanguageValid(language5)) return null;
3815
+ result[key4] = language5.trim();
3816
+ }
3817
+ return result;
3818
+ }
3819
+ function decodeSubtitleText(bytes2) {
3820
+ let text4;
3821
+ try {
3822
+ text4 = new TextDecoder("utf-8", { fatal: !0, ignoreBOM: !1 }).decode(bytes2);
3823
+ } catch {
3824
+ return { ok: !1, code: "LIBRARY_SUBTITLE_ENCODING" };
3825
+ }
3826
+ return text4.includes("\0") ? { ok: !1, code: "LIBRARY_SUBTITLE_ENCODING" } : { ok: !0, text: text4.replace(/^/, "").replace(/\r\n?/g, `
3827
+ `) };
3828
+ }
3829
+ function normaliseVttText(text4) {
3830
+ let firstLine = text4.split(`
3831
+ `, 1)[0] ?? "";
3832
+ return VTT_HEADER.test(firstLine) ? { ok: !0, vtt: text4.endsWith(`
3833
+ `) ? text4 : `${text4}
3834
+ ` } : INVALID;
3835
+ }
3836
+ function convertSrtText(text4) {
3837
+ let lines = text4.split(`
3838
+ `);
3839
+ if (!lines.some((line) => line.includes("-->"))) return INVALID;
3840
+ let body = lines.map((line) => line.includes("-->") ? line.replace(SRT_TIMESTAMP, "$1.$2") : line).join(`
3841
+ `).replace(/^\n+/, "");
3842
+ return { ok: !0, vtt: `WEBVTT
3843
+
3844
+ ${body.endsWith(`
3845
+ `) ? body : `${body}
3846
+ `}` };
3847
+ }
3848
+ function toStoredVtt(extension, bytes2) {
3849
+ let decoded = decodeSubtitleText(bytes2);
3850
+ if (!decoded.ok) return decoded;
3851
+ let converted = extension === "srt", verdict = converted ? convertSrtText(decoded.text) : normaliseVttText(decoded.text);
3852
+ return verdict.ok ? { ok: !0, vtt: verdict.vtt, converted } : verdict;
3853
+ }
3854
+ function subtitleVerdict(file) {
3855
+ let extension = extensionOf(file.fileName);
3856
+ if (extension !== "vtt" && extension !== "srt") return { ok: !1, code: "LIBRARY_SUBTITLE_TYPE" };
3857
+ let sizeBefore = file.bytes.byteLength;
3858
+ if (sizeBefore > 2097152) return { ok: !1, code: "LIBRARY_SUBTITLE_TOO_LARGE" };
3859
+ let stored = toStoredVtt(extension, file.bytes);
3860
+ if (!stored.ok) return stored;
3861
+ let sizeAfter = new TextEncoder().encode(stored.vtt).byteLength;
3862
+ return sizeAfter > 2097152 ? { ok: !1, code: "LIBRARY_SUBTITLE_TOO_LARGE" } : { ok: !0, extension, vtt: stored.vtt, converted: stored.converted, sizeBefore, sizeAfter };
3863
+ }
3864
+
3630
3865
  // skills/adelin-app-generation/scripts/library-output.mjs
3631
3866
  import { constants, openSync, closeSync, writeFileSync as writeFileSync3, fstatSync, lstatSync as lstatSync2, realpathSync as realpathSync2, fsyncSync, unlinkSync as unlinkSync3 } from "node:fs";
3632
3867
  import { dirname as dirname2, resolve as resolve4, isAbsolute as isAbsolute2, basename } from "node:path";
@@ -3674,7 +3909,7 @@ var fieldKeyValue = (v) => {
3674
3909
  RECONSENT_REQUIRED: "Explicit approval required.",
3675
3910
  APP_SELECTION_CHANGED: "App access changed. Start login again.",
3676
3911
  INTERACTION_COMPLETED: "This approval has already been used.",
3677
- TOOL_UNAVAILABLE: "This tool is not available for this connection. Run adelin login to sign in again.",
3912
+ TOOL_UNAVAILABLE: "This tool is not available for this connection. Run adelin login --force to sign in again.",
3678
3913
  INVALID_CURSOR: "Invalid cursor.",
3679
3914
  STALE_CURSOR: "Library changed. Restart pagination.",
3680
3915
  READ_ITEM_TOO_LARGE: "Item exceeds read limits.",
@@ -4330,73 +4565,6 @@ function decodeSaveProgress(v, input) {
4330
4565
  return (!steps.length || steps.length > 6 || steps.some((s, i) => !order.includes(s) || i > 0 && order.indexOf(s) <= order.indexOf(steps[i - 1])) || v.state === "completed" && v.remainingSteps.length) && fail(), v.warnings !== void 0 && saveWarnings(v.warnings, v.completedSteps, input), v.failedStep !== (v.state === "stopped" ? v.remainingSteps[0] : null) && fail(), /^ASSET_/.test(v.error ?? "") && (!ASSET_STOPS.includes(v.error) || v.failedStep !== "assets") && fail(), v.candidates !== void 0 && (v.error !== "NAME_CHOICE_REQUIRED" && fail(), array(object({ key: fieldKeyValue, name: localized(80) }), 100)(v.candidates)), v.latestState !== null && (object({ app_id: id, entry_id: id, title, description })(v.latestState), (v.latestState.app_id !== input.app_id || v.latestState.entry_id !== v.entryId) && fail()), v.ok ? v : { ...v, error: libraryFailure(v.error).error };
4331
4566
  }
4332
4567
 
4333
- // skills/adelin-app-generation/scripts/__generated__/library-subtitle-rules.mjs
4334
- var SUBTITLE_LANGUAGE_PATTERN = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
4335
- var SRT_TIMESTAMP = /(\d{1,2}:\d{2}:\d{2}),(\d{3})/g, VTT_HEADER = /^WEBVTT(?:[ \t][^\n]*)?$/, INVALID = { ok: !1, code: "LIBRARY_SUBTITLE_INVALID" };
4336
- function extensionOf(name) {
4337
- let dot = name.lastIndexOf(".");
4338
- return dot < 0 ? "" : name.slice(dot + 1).toLowerCase();
4339
- }
4340
- function subtitleLanguageValid(value) {
4341
- return typeof value == "string" && value.length <= 35 && SUBTITLE_LANGUAGE_PATTERN.test(value.trim());
4342
- }
4343
- function normalizeSubtitleLanguages(value) {
4344
- if (!value || typeof value != "object" || Array.isArray(value)) return null;
4345
- let entries2 = Object.entries(value), result = {};
4346
- if (entries2.length < 1 || entries2.length > 100) return null;
4347
- for (let [id11, language5] of entries2) {
4348
- let key4 = id11.toLowerCase();
4349
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id11) || Object.hasOwn(result, key4) || !subtitleLanguageValid(language5)) return null;
4350
- result[key4] = language5.trim();
4351
- }
4352
- return result;
4353
- }
4354
- function decodeSubtitleText(bytes2) {
4355
- let text4;
4356
- try {
4357
- text4 = new TextDecoder("utf-8", { fatal: !0, ignoreBOM: !1 }).decode(bytes2);
4358
- } catch {
4359
- return { ok: !1, code: "LIBRARY_SUBTITLE_ENCODING" };
4360
- }
4361
- return text4.includes("\0") ? { ok: !1, code: "LIBRARY_SUBTITLE_ENCODING" } : { ok: !0, text: text4.replace(/^/, "").replace(/\r\n?/g, `
4362
- `) };
4363
- }
4364
- function normaliseVttText(text4) {
4365
- let firstLine = text4.split(`
4366
- `, 1)[0] ?? "";
4367
- return VTT_HEADER.test(firstLine) ? { ok: !0, vtt: text4.endsWith(`
4368
- `) ? text4 : `${text4}
4369
- ` } : INVALID;
4370
- }
4371
- function convertSrtText(text4) {
4372
- let lines = text4.split(`
4373
- `);
4374
- if (!lines.some((line) => line.includes("-->"))) return INVALID;
4375
- let body = lines.map((line) => line.includes("-->") ? line.replace(SRT_TIMESTAMP, "$1.$2") : line).join(`
4376
- `).replace(/^\n+/, "");
4377
- return { ok: !0, vtt: `WEBVTT
4378
-
4379
- ${body.endsWith(`
4380
- `) ? body : `${body}
4381
- `}` };
4382
- }
4383
- function toStoredVtt(extension, bytes2) {
4384
- let decoded = decodeSubtitleText(bytes2);
4385
- if (!decoded.ok) return decoded;
4386
- let converted = extension === "srt", verdict = converted ? convertSrtText(decoded.text) : normaliseVttText(decoded.text);
4387
- return verdict.ok ? { ok: !0, vtt: verdict.vtt, converted } : verdict;
4388
- }
4389
- function subtitleVerdict(file) {
4390
- let extension = extensionOf(file.fileName);
4391
- if (extension !== "vtt" && extension !== "srt") return { ok: !1, code: "LIBRARY_SUBTITLE_TYPE" };
4392
- let sizeBefore = file.bytes.byteLength;
4393
- if (sizeBefore > 2097152) return { ok: !1, code: "LIBRARY_SUBTITLE_TOO_LARGE" };
4394
- let stored = toStoredVtt(extension, file.bytes);
4395
- if (!stored.ok) return stored;
4396
- let sizeAfter = new TextEncoder().encode(stored.vtt).byteLength;
4397
- return sizeAfter > 2097152 ? { ok: !1, code: "LIBRARY_SUBTITLE_TOO_LARGE" } : { ok: !0, extension, vtt: stored.vtt, converted: stored.converted, sizeBefore, sizeAfter };
4398
- }
4399
-
4400
4568
  // skills/adelin-app-generation/scripts/library-workflow.mjs
4401
4569
  var vocabularyActions = [
4402
4570
  "label.create",
@@ -4587,8 +4755,8 @@ function explainArguments(schema, value, path = "") {
4587
4755
  if (schema.maxItems !== void 0 && value.length > schema.maxItems) return `${where(path)}: expected at most ${schema.maxItems} items`;
4588
4756
  if (schema.uniqueItems && new Set(value.map((v) => JSON.stringify(v))).size !== value.length) return `${where(path)}: expected no repeated items`;
4589
4757
  for (let [index, item] of value.entries()) {
4590
- let problem = explainArguments(schema.items, item, `${where(path)}[${index}]`);
4591
- if (problem) return problem;
4758
+ let problem2 = explainArguments(schema.items, item, `${where(path)}[${index}]`);
4759
+ if (problem2) return problem2;
4592
4760
  }
4593
4761
  }
4594
4762
  if (record3(value)) {
@@ -4599,8 +4767,8 @@ function explainArguments(schema, value, path = "") {
4599
4767
  for (let name of Object.keys(value)) {
4600
4768
  if (schema.propertyNames && explainArguments(schema.propertyNames, name))
4601
4769
  return languages ? `${where(path)}: expected keys that are ${formats[LANGUAGE]}` : `${child(path, fieldName(name))}: expected a field key`;
4602
- let rule = properties[name] ?? values, problem = rule && explainArguments(rule, value[name], child(path, name));
4603
- if (problem) return problem;
4770
+ let rule = properties[name] ?? values, problem2 = rule && explainArguments(rule, value[name], child(path, name));
4771
+ if (problem2) return problem2;
4604
4772
  }
4605
4773
  let size = Object.keys(value).length;
4606
4774
  if (values && (size < (schema.minProperties ?? 0) || size > (schema.maxProperties ?? 1 / 0)))
@@ -4637,14 +4805,14 @@ function explainMutation(args) {
4637
4805
  }, missing = accepted.slice(0, action === "operation.inspect" ? 3 : action === "preview.page" ? 4 : 5).find((name) => args[name] === void 0);
4638
4806
  if (missing) return `${missing} is required for ${action}${hints[missing] ?? ""}`;
4639
4807
  for (let name of accepted.filter((name2) => name2 !== "action" && name2 !== "payload")) {
4640
- let problem2 = args[name] !== void 0 && explainArguments(mutationFields[name], args[name], name);
4641
- if (problem2) return problem2;
4808
+ let problem3 = args[name] !== void 0 && explainArguments(mutationFields[name], args[name], name);
4809
+ if (problem3) return problem3;
4642
4810
  }
4643
4811
  if (args.mode === "preview" && args.confirmation !== void 0) return 'confirmation is not accepted with mode "preview"; send it on the next request without mode';
4644
4812
  let detail = explainFilePayload(action, args.payload, args.mode !== void 0 || args.confirmation !== void 0);
4645
4813
  if (detail && detail !== DETACH_ONLY) return detail;
4646
- let schema = payloadSchema(action), problem = schema && explainArguments(schema, args.payload, "payload");
4647
- if (problem) return problem;
4814
+ let schema = payloadSchema(action), problem2 = schema && explainArguments(schema, args.payload, "payload");
4815
+ if (problem2) return problem2;
4648
4816
  if (detail) return detail;
4649
4817
  try {
4650
4818
  return normalizeMutation(args), null;
@@ -4670,12 +4838,12 @@ function explainLiveMutation(args) {
4670
4838
  let hints = { operation_id: " (a new UUID for each change)", payload: `: ${shapeOf(livePayloadSchema(action))}` }, missing = accepted.slice(0, 4).find((name) => args[name] === void 0);
4671
4839
  if (missing) return `${missing} is required for ${action}${hints[missing] ?? ""}`;
4672
4840
  for (let name of accepted.filter((name2) => name2 !== "action" && name2 !== "payload")) {
4673
- let problem2 = args[name] !== void 0 && explainArguments(mutationFields[name], args[name], name);
4674
- if (problem2) return problem2;
4841
+ let problem3 = args[name] !== void 0 && explainArguments(mutationFields[name], args[name], name);
4842
+ if (problem3) return problem3;
4675
4843
  }
4676
4844
  if (args.mode === "preview" && args.confirmation !== void 0) return 'confirmation is not accepted with mode "preview"; send it on the next request without mode';
4677
- let problem = explainArguments(livePayloadSchema(action), args.payload, "payload");
4678
- return problem ? withToken(liveBranchProblem(action, args.payload) || problem) : null;
4845
+ let problem2 = explainArguments(livePayloadSchema(action), args.payload, "payload");
4846
+ return problem2 ? withToken(liveBranchProblem(action, args.payload) || problem2) : null;
4679
4847
  }
4680
4848
  function liveBranchProblem(action, payload) {
4681
4849
  if (action === "stream.delete" && record3(payload?.recordings)) return explainArguments(recordingList, payload.recordings, "payload.recordings");
@@ -4687,8 +4855,8 @@ function normalizeSampleImport(operation, args) {
4687
4855
  if (!record3(args)) throw invalid("arguments: expected an object");
4688
4856
  let input = { ...args };
4689
4857
  for (let name of ["app_id", "import_id"]) typeof input[name] == "string" && (input[name] = input[name].toLowerCase());
4690
- let problem = explainArguments(sampleImportPayloads[operation], input);
4691
- if (problem) throw invalid(problem);
4858
+ let problem2 = explainArguments(sampleImportPayloads[operation], input);
4859
+ if (problem2) throw invalid(problem2);
4692
4860
  return operation === "status" ? { app_id: input.app_id } : { app_id: input.app_id, import_id: input.import_id, max_steps: input.max_steps ?? 20, wait_seconds: input.wait_seconds ?? 60 };
4693
4861
  }
4694
4862
  var localFailure = (error) => error?.message === "SCHEDULE_ZONE_REQUIRED" ? libraryFailure("SCHEDULE_ZONE_REQUIRED") : libraryFailure("INVALID_ARGUMENT", error?.detail);
@@ -4725,28 +4893,28 @@ function normalizeLibraryArgs(operation, args) {
4725
4893
  return result;
4726
4894
  }
4727
4895
  async function advanceSampleImportLoop({ call, now = Date.now, sleep: sleep2 = (ms) => new Promise((done) => setTimeout(done, ms)) }, args) {
4728
- let { app_id, import_id, max_steps, wait_seconds } = normalizeSampleImport("advance", args), deadline = now() + wait_seconds * 1e3, refresh = { operation: "library tree" }, current = null, steps = 0, mediaFailures = 0, finish = (stopReason, failure) => ({ import: current, steps, ...stopReason ? { stopReason } : {}, refresh, ...failure ? { error: failure.error } : {} }), wait3 = async (ms) => steps >= max_steps || !Number.isFinite(ms) || ms < 0 || now() + ms > deadline ? !1 : (await sleep2(ms), now() <= deadline);
4896
+ let { app_id, import_id, max_steps, wait_seconds } = normalizeSampleImport("advance", args), deadline = now() + wait_seconds * 1e3, refresh = { operation: "library tree" }, current = null, steps = 0, mediaFailures = 0, finish = (stopReason, failure2) => ({ import: current, steps, ...stopReason ? { stopReason } : {}, refresh, ...failure2 ? { error: failure2.error } : {} }), wait3 = async (ms) => steps >= max_steps || !Number.isFinite(ms) || ms < 0 || now() + ms > deadline ? !1 : (await sleep2(ms), now() <= deadline);
4729
4897
  for (; steps < max_steps; ) {
4730
4898
  steps++;
4731
- let reply, hint = 1e3;
4899
+ let reply2, hint = 1e3;
4732
4900
  try {
4733
- reply = decodeSampleImport(await call("mutate_library_sample_import", { app_id, import_id }), app_id, "advance", { import_id });
4901
+ reply2 = decodeSampleImport(await call("mutate_library_sample_import", { app_id, import_id }), app_id, "advance", { import_id });
4734
4902
  } catch (error) {
4735
4903
  let code = error?.rateLimited ? "MUTATION_UNAVAILABLE" : error?.code;
4736
- reply = libraryFailure(code), hint = Math.max(1e3, Number(error?.retryAfterMs) || 0);
4904
+ reply2 = libraryFailure(code), hint = Math.max(1e3, Number(error?.retryAfterMs) || 0);
4737
4905
  }
4738
- if (!reply.ok) {
4739
- let code = reply.error.code;
4740
- if (code === "SAMPLE_IMPORT_BLOCKED") return finish("blocked", reply);
4906
+ if (!reply2.ok) {
4907
+ let code = reply2.error.code;
4908
+ if (code === "SAMPLE_IMPORT_BLOCKED") return finish("blocked", reply2);
4741
4909
  if (code === "SAMPLE_MEDIA_UNAVAILABLE") {
4742
- if (++mediaFailures >= 2) return finish("media_unavailable", reply);
4743
- if (steps >= max_steps) return finish("budget", reply);
4910
+ if (++mediaFailures >= 2) return finish("media_unavailable", reply2);
4911
+ if (steps >= max_steps) return finish("budget", reply2);
4744
4912
  continue;
4745
4913
  }
4746
4914
  if (mediaFailures = 0, ["RETRYABLE_CONFLICT", "MUTATION_UNAVAILABLE"].includes(code) && await wait3(hint)) continue;
4747
- return finish(null, reply);
4915
+ return finish(null, reply2);
4748
4916
  }
4749
- if (mediaFailures = 0, current = reply.data, current.next === "none") return finish("complete");
4917
+ if (mediaFailures = 0, current = reply2.data, current.next === "none") return finish("complete");
4750
4918
  if (current.next === "blocked") return finish("blocked", libraryFailure("SAMPLE_IMPORT_BLOCKED"));
4751
4919
  if (!current.progressed && current.busyUntil) {
4752
4920
  if (await wait3(Math.max(0, Date.parse(current.busyUntil) - now()))) continue;
@@ -4970,8 +5138,8 @@ function collectionPayload(action, p) {
4970
5138
  function filePayload({ action, payload: p, mode, confirmation }) {
4971
5139
  let detail = explainFilePayload(action, p, mode !== void 0 || confirmation !== void 0);
4972
5140
  if (detail && detail !== DETACH_ONLY) throw invalid(detail);
4973
- let problem = explainArguments(payloadSchema(action), p, "payload");
4974
- if (problem) throw invalid(problem);
5141
+ let problem2 = explainArguments(payloadSchema(action), p, "payload");
5142
+ if (problem2) throw invalid(problem2);
4975
5143
  if (detail) throw invalid(detail);
4976
5144
  if (closed(p, payloadSchema(action).required, Object.keys(payloadSchema(action).properties)), action === "entry.assets") return { entry_id: lowerId(p.entry_id), ...Object.fromEntries(roles.filter((role) => p[role] !== void 0).map((role) => [role, p[role] === null ? null : lowerId(p[role])])) };
4977
5145
  if (action === "entry.artwork.remove") return { entry_id: lowerId(p.entry_id), slot: p.slot, ...typeof p.language == "string" ? { language: p.language } : {} };
@@ -5000,80 +5168,6 @@ function liveScheduleAt(schedule3) {
5000
5168
  return { ...schedule3, at: { ...at } };
5001
5169
  }
5002
5170
 
5003
- // skills/adelin-app-generation/scripts/library-files.mjs
5004
- import { createHash as createHash2, generateKeyPairSync, randomBytes, sign } from "node:crypto";
5005
- 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";
5006
- import { basename as basename2, dirname as dirname3, join as join4, resolve as resolve5 } from "node:path";
5007
-
5008
- // skills/adelin-app-generation/scripts/__generated__/library-artwork-rules.mjs
5009
- var ARTWORK_SHAPES = {
5010
- poster: { ratio: [2, 3], min: { width: 400, height: 600 }, plural: "Posters", example: "1000\xD71500" },
5011
- backdrop: { ratio: [16, 9], min: { width: 1280, height: 720 }, plural: "Backdrops", example: "1920\xD71080" }
5012
- }, ARTWORK_RATIO_TOLERANCE = 0.02, LOGO_MAX_SIDE = 4096, gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
5013
- function ratioName({ width, height }) {
5014
- let divisor2 = gcd(width, height), w = width / divisor2, h = height / divisor2;
5015
- return w <= 32 && h <= 32 ? ` (${w}:${h})` : "";
5016
- }
5017
- function artworkShapeError(slot, size) {
5018
- let actual = `${size.width}\xD7${size.height}`;
5019
- if (slot === "logo" && Math.max(size.width, size.height) > LOGO_MAX_SIDE)
5020
- return `Logos can be up to ${LOGO_MAX_SIDE}\xD7${LOGO_MAX_SIDE}. This one is ${actual}.`;
5021
- let rule = ARTWORK_SHAPES[slot];
5022
- if (!rule) return null;
5023
- let [w, h] = rule.ratio;
5024
- return Math.abs(size.width / size.height / (w / h) - 1) > ARTWORK_RATIO_TOLERANCE ? `${rule.plural} need a ${w}:${h} image, like ${rule.example}. This one is ${actual}${ratioName(size)}.` : size.width < rule.min.width || size.height < rule.min.height ? `${rule.plural} need to be at least ${rule.min.width}\xD7${rule.min.height}. This one is ${actual}.` : null;
5025
- }
5026
- var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10], JPEG_SIGNATURE = [255, 216, 255], ARTWORK_MAX_BYTES = 10 * 1024 * 1024, ARTWORK_EXTENSIONS = ["png", "jpg", "jpeg"], startsWith = (bytes2, signature) => signature.every((byte, index) => bytes2[index] === byte);
5027
- function artworkFileType(file) {
5028
- let dot = file.fileName.lastIndexOf("."), extension = dot < 0 ? "" : file.fileName.slice(dot + 1).toLowerCase();
5029
- return ARTWORK_EXTENSIONS.includes(extension) ? file.bytes.byteLength > ARTWORK_MAX_BYTES ? { ok: !1, code: "LIBRARY_ARTWORK_TOO_LARGE" } : startsWith(file.bytes, PNG_SIGNATURE) ? { ok: !0, type: "png" } : startsWith(file.bytes, JPEG_SIGNATURE) ? { ok: !0, type: "jpg" } : { ok: !1, code: "LIBRARY_ARTWORK_NOT_IMAGE" } : { ok: !1, code: "LIBRARY_ARTWORK_TYPE" };
5030
- }
5031
- function pngSize(bytes2) {
5032
- if (bytes2.length < 24 || !startsWith(bytes2, PNG_SIGNATURE)) return null;
5033
- let view = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength);
5034
- return { width: view.getUint32(16), height: view.getUint32(20) };
5035
- }
5036
- function exifTurnsSideways(view, start, end) {
5037
- let tiff = start + 6;
5038
- if (end - start < 14 || view.getUint32(start) !== 1165519206) return !1;
5039
- let little = view.getUint16(tiff) === 18761, ifd = tiff + view.getUint32(tiff + 4, little);
5040
- if (ifd + 2 > end) return !1;
5041
- let count4 = view.getUint16(ifd, little);
5042
- for (let index = 0; index < count4; index += 1) {
5043
- let entry = ifd + 2 + index * 12;
5044
- if (entry + 12 > end) return !1;
5045
- if (view.getUint16(entry, little) === 274) return view.getUint16(entry + 8, little) >= 5;
5046
- }
5047
- return !1;
5048
- }
5049
- function jpegSize(bytes2) {
5050
- if (bytes2.length < 4 || bytes2[0] !== 255 || bytes2[1] !== 216) return null;
5051
- let view = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength), sideways = !1, offset = 2;
5052
- for (; offset + 4 <= bytes2.length; ) {
5053
- if (bytes2[offset] !== 255) return null;
5054
- let marker = bytes2[offset + 1];
5055
- if (marker === 255) {
5056
- offset += 1;
5057
- continue;
5058
- }
5059
- if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
5060
- offset += 2;
5061
- continue;
5062
- }
5063
- let length = view.getUint16(offset + 2), segment = offset + 4;
5064
- if (marker === 225 && (sideways = sideways || exifTurnsSideways(view, segment, Math.min(segment + length - 2, bytes2.length))), marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204 && segment + 5 <= bytes2.length) {
5065
- let height = view.getUint16(segment + 1), width = view.getUint16(segment + 3);
5066
- return sideways ? { width: height, height: width } : { width, height };
5067
- }
5068
- if (marker === 218 || marker === 217) return null;
5069
- offset += 2 + length;
5070
- }
5071
- return null;
5072
- }
5073
- function imageSize(bytes2) {
5074
- return pngSize(bytes2) ?? jpegSize(bytes2);
5075
- }
5076
-
5077
5171
  // skills/adelin-app-generation/scripts/library-files-output.mjs
5078
5172
  var KEPT = [
5079
5173
  "INVALID_ARGUMENT",
@@ -5265,8 +5359,8 @@ function normalizeFilesArgs(operation, args) {
5265
5359
  let schema = Object.hasOwn(INPUTS, operation ?? "") ? INPUTS[operation] : null;
5266
5360
  if (!schema) throw invalid2(`operation: expected one of ${filesOperations.join(", ")}`);
5267
5361
  if (!plain2(args)) throw invalid2("arguments: expected an object");
5268
- let input = Object.fromEntries(Object.entries(args).filter(([, value]) => value !== void 0).map(([key4, value]) => [key4, ["app_id", "entry_id", "operation_id", "file_id"].includes(key4) && uuid2.test(value) ? value.toLowerCase() : value])), problem = explainArguments(schema, input);
5269
- if (problem) throw invalid2(problem);
5362
+ let input = Object.fromEntries(Object.entries(args).filter(([, value]) => value !== void 0).map(([key4, value]) => [key4, ["app_id", "entry_id", "operation_id", "file_id"].includes(key4) && uuid2.test(value) ? value.toLowerCase() : value])), problem2 = explainArguments(schema, input);
5363
+ if (problem2) throw invalid2(problem2);
5270
5364
  if (operation === "put-artwork" && input.language === null && delete input.language, operation === "add-subtitle" && !subtitleLanguageValid(input.language)) throw invalid2("language: expected a tag such as en or pt-BR, at most 35 characters");
5271
5365
  if (operation === "check" && input.kind === "artwork" != (input.slot !== void 0))
5272
5366
  throw invalid2(input.kind === "artwork" ? "slot is required for kind artwork: poster, backdrop or logo" : "slot is accepted only for kind artwork");
@@ -5307,8 +5401,8 @@ function verdictOf(kind2, slot, fileName2, bytes2) {
5307
5401
  if (!type.ok) return { verdict: "refuse", code: type.code, message: FILES_MESSAGES[type.code] };
5308
5402
  let size = imageSize(bytes2);
5309
5403
  if (!size) return { verdict: "refuse", code: "LIBRARY_ARTWORK_NOT_IMAGE", message: FILES_MESSAGES.LIBRARY_ARTWORK_NOT_IMAGE };
5310
- let problem = artworkShapeError(slot, size);
5311
- return problem ? { verdict: "refuse", code: "LIBRARY_ARTWORK_SHAPE", message: problem } : slot === "logo" && type.type === "png" ? { verdict: "deferred", code: null, message: "Logo transparency is checked on the server." } : { verdict: "pass", code: null, message: null };
5404
+ let problem2 = artworkShapeError(slot, size);
5405
+ return problem2 ? { verdict: "refuse", code: "LIBRARY_ARTWORK_SHAPE", message: problem2 } : slot === "logo" && type.type === "png" ? { verdict: "deferred", code: null, message: "Logo transparency is checked on the server." } : { verdict: "pass", code: null, message: null };
5312
5406
  }
5313
5407
  function localFile(kind2, slot, path) {
5314
5408
  let bytes2 = readLocal(path, kind2 === "artwork" ? ARTWORK_MAX_BYTES : 2097152, kind2 === "artwork" ? "LIBRARY_ARTWORK_TOO_LARGE" : "LIBRARY_SUBTITLE_TOO_LARGE"), name = basename2(path);
@@ -5524,14 +5618,345 @@ var URL_HELP = "", WRITE_HELP = "--file PATH --operation-id <UUID> --expected-re
5524
5618
  check: "--kind artwork --slot poster|backdrop|logo --file PATH | --kind subtitle --file PATH"
5525
5619
  };
5526
5620
 
5621
+ // 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";
5623
+ var ACTION = Object.freeze({
5624
+ heartbeat_edit_session: "heartbeat",
5625
+ save_app_changes: "build",
5626
+ prepare_build: "prepare",
5627
+ reconcile_save: "reconcile",
5628
+ close_edit_session: "close",
5629
+ tell_builder: "note",
5630
+ ask_builder: "ask",
5631
+ choice_status: "choice",
5632
+ record_choice: "choose",
5633
+ request_device: "device_request",
5634
+ device_status: "device_status",
5635
+ device_operation: "device",
5636
+ preview_pass: "preview_pass",
5637
+ agent_view: "agent_view",
5638
+ handover_edit_session: "handover"
5639
+ }), MAX_DEVICE_BYTES = 3 * 1024 * 1024;
5640
+ function sameTuple(a, b) {
5641
+ return a.app === b.appId && a.lease === b.leaseId && a.chat === b.chatSessionId && a.epoch === b.epoch;
5642
+ }
5643
+ var UUID6 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/, STAGING_PATH = /^\/adelin-(prod|dev)-compiler-staging\/[A-Za-z0-9-]{1,64}\/([a-f0-9-]{36})\/source\.json$/, R2_HOST = /^[a-f0-9]{32}\.r2\.cloudflarestorage\.com$/;
5644
+ var TICKET_HEADERS = "content-length,if-none-match,x-amz-checksum-sha256";
5645
+ function stagingTarget(ticket, body) {
5646
+ let target2;
5647
+ try {
5648
+ target2 = new URL(ticket.url);
5649
+ } catch {
5650
+ throw new Error("Invalid staging upload.");
5651
+ }
5652
+ let r2 = target2.protocol === "https:" && !target2.port && R2_HOST.test(target2.hostname), local = !1, headers = ticket.headers !== null && typeof ticket.headers == "object" ? ticket.headers : {}, [, bucketEnv, pathJobId] = STAGING_PATH.exec(target2.pathname) ?? [];
5653
+ if (!(r2 || local) || target2.username || target2.password || target2.hash || bucketEnv !== "prod" || !UUID6.test(ticket.jobId) || pathJobId !== ticket.jobId || Object.keys(headers).sort().join() !== TICKET_HEADERS || headers["content-length"] !== String(Buffer.byteLength(body)) || headers["if-none-match"] !== "*" || headers["x-amz-checksum-sha256"] !== createHash3("sha256").update(body).digest("base64") || !Number.isSafeInteger(ticket.expiresAt) || ticket.expiresAt <= Date.now()) throw new Error("Invalid staging upload.");
5654
+ return target2;
5655
+ }
5656
+ var SERVER_CODE = /^[A-Z][A-Z0-9_]{2,63}$/;
5657
+ function cleanServerMessage(value) {
5658
+ return typeof value == "string" ? value.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, 500) : "";
5659
+ }
5660
+ async function rejection(response2, action) {
5661
+ let serverCode, serverMessage = "";
5662
+ try {
5663
+ let parsed = JSON.parse((await response2.text()).slice(0, 4096));
5664
+ typeof parsed?.error == "string" && SERVER_CODE.test(parsed.error) && (serverCode = parsed.error, serverMessage = cleanServerMessage(parsed.message));
5665
+ } catch {
5666
+ }
5667
+ return Object.assign(
5668
+ new Error(`Adelin rejected the local ${action} request (${response2.status}).`),
5669
+ { status: response2.status, action, ...serverCode && { serverCode }, ...serverMessage && { serverMessage } }
5670
+ );
5671
+ }
5672
+ var LocalBuildTransport = class {
5673
+ constructor(mcpUrl, fetcher = fetch, { release: release2 = null } = {}) {
5674
+ this.url = new URL(validateMcpUrl(mcpUrl)), this.fetcher = fetcher, this.privateKey = null, this.publicKey = null, this.token = null, this.tuple = null, this.expiresAt = 0, this.release = release2, this.continuation = null;
5675
+ }
5676
+ prepare(appId) {
5677
+ if (this.privateKey) throw new Error("A local build is already prepared.");
5678
+ let keys3 = generateKeyPairSync2("ed25519");
5679
+ return this.privateKey = keys3.privateKey, this.publicKey = keys3.publicKey.export({ format: "der", type: "spki" }).toString("base64url"), this.appId = appId, this.publicKey;
5680
+ }
5681
+ attach(token2, tuple) {
5682
+ if (!this.privateKey || typeof token2 != "string" || token2.length > 8192 || !/^[A-Za-z0-9_.-]+$/.test(token2) || tuple.appId !== this.appId)
5683
+ throw new Error("Invalid local build authorization.");
5684
+ let claims;
5685
+ try {
5686
+ claims = JSON.parse(Buffer.from(token2.split(".")[1], "base64url").toString("utf8"));
5687
+ } catch {
5688
+ throw new Error("Invalid local build authorization.");
5689
+ }
5690
+ if (token2.split(".").length !== 3 || claims.key !== this.publicKey || !sameTuple(claims, tuple) || !Number.isSafeInteger(claims.exp) || claims.exp * 1e3 <= Date.now()) throw new Error("Local build authorization does not match this app.");
5691
+ this.token = token2, this.tuple = tuple, this.expiresAt = claims.exp * 1e3;
5692
+ }
5693
+ detach() {
5694
+ this.privateKey = null, this.publicKey = null, this.token = null, this.tuple = null, this.appId = null, this.expiresAt = 0, this.continuation = null;
5695
+ }
5696
+ async handover(release2) {
5697
+ if (!this.tuple) {
5698
+ this.release = release2;
5699
+ return;
5700
+ }
5701
+ let result = await this.request("handover_edit_session", { version: release2.version, contractId: release2.contractId }, { release: release2 }), value = JSON.parse(result.content[0].text);
5702
+ this.attach(value.token, this.tuple), this.release = release2;
5703
+ }
5704
+ async call(name, args) {
5705
+ if (name === "save_app_changes") {
5706
+ let body = JSON.stringify({ files: args.files }), files = args.files.map((file) => ({
5707
+ path: file.path,
5708
+ baseVersion: file.baseVersion,
5709
+ hash: createHash3("sha256").update(file.content, "utf8").digest("hex"),
5710
+ bytes: Buffer.byteLength(file.content)
5711
+ })), upload = { digest: createHash3("sha256").update(body).digest("hex"), bytes: Buffer.byteLength(body) }, prepared = await this.request("prepare_build", { ...args, files, upload }), ticket = JSON.parse(prepared.content[0].text);
5712
+ if (ticket?.error) return prepared;
5713
+ let target2 = stagingTarget(ticket, body), uploaded = await this.fetcher(target2, {
5714
+ method: "PUT",
5715
+ redirect: "error",
5716
+ headers: ticket.headers,
5717
+ body,
5718
+ signal: AbortSignal.timeout(3e4)
5719
+ });
5720
+ if (await uploaded.body?.cancel(), !uploaded.ok) throw new Error("Source upload failed. No build was saved.");
5721
+ return this.request(name, { ...args, files, jobId: ticket.jobId, upload });
5722
+ }
5723
+ return this.request(name, args);
5724
+ }
5725
+ async request(name, args, { release: release2 = this.release } = {}) {
5726
+ if (!this.privateKey || !this.token || !this.tuple || !(name in ACTION))
5727
+ throw new Error("No authorized local build session.");
5728
+ let action = ACTION[name], path = `/v1/local-builder/${action}`, tuple = {
5729
+ app_id: this.tuple.appId,
5730
+ lease_id: this.tuple.leaseId,
5731
+ chat_session_id: this.tuple.chatSessionId,
5732
+ 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
5734
+ ${path}
5735
+ ${timestamp2}
5736
+ ${nonce}
5737
+ ${digest4}`), signature = sign2(null, bytes2, this.privateKey).toString("base64url"), url = new URL(path, this.url), response2 = await this.fetcher(url, {
5738
+ method: "POST",
5739
+ redirect: "error",
5740
+ headers: {
5741
+ "Content-Type": "application/json",
5742
+ Authorization: `Bearer ${this.token}`,
5743
+ ...release2 && { "X-Adelin-Cli-Version": release2.version, "X-Adelin-Authoring-Contract": release2.contractId },
5744
+ ...this.continuation && { "X-Adelin-Continuation": this.continuation },
5745
+ "X-Adelin-Timestamp": timestamp2,
5746
+ "X-Adelin-Nonce": nonce,
5747
+ "X-Adelin-Signature": signature
5748
+ },
5749
+ body,
5750
+ signal: AbortSignal.timeout(["build", "prepare"].includes(action) ? 12e4 : action === "device" ? 45e3 : 15e3)
5751
+ }), refusal3 = response2.status === 400 && (action === "ask" || action === "choose");
5752
+ if (response2.status === 426)
5753
+ throw await response2.body?.cancel(), Object.assign(new Error("Adelin authoring needs an update. Run adelin setup."), { code: "UPDATE_REQUIRED" });
5754
+ if (!response2.ok && !refusal3) throw await rejection(response2, action);
5755
+ let continuation = response2.headers?.get("x-adelin-continuation");
5756
+ if (continuation) {
5757
+ if (continuation.length > 16384 || !/^[A-Za-z0-9_.-]+$/.test(continuation)) throw new Error("Invalid build continuation.");
5758
+ this.continuation = continuation;
5759
+ }
5760
+ let text4 = await response2.text();
5761
+ if (Buffer.byteLength(text4, "utf8") > (action === "device" ? MAX_DEVICE_BYTES : 2 * 1024 * 1024)) throw new Error("Adelin build response is too large.");
5762
+ return { content: [{ type: "text", text: text4 }] };
5763
+ }
5764
+ async close() {
5765
+ this.detach();
5766
+ }
5767
+ };
5768
+
5769
+ // skills/adelin-app-generation/scripts/local-assets.mjs
5770
+ import { writeAtomic } from "./local-save.mjs";
5771
+ import {
5772
+ ASSET_STATE,
5773
+ UUID as UUID7,
5774
+ assertNoSymlinkAncestors as assertNoSymlinkAncestors3,
5775
+ lstatIfPresent as lstatIfPresent3,
5776
+ readSafeFile as readSafeFile4,
5777
+ sha256 as sha2564,
5778
+ withWorkspaceMutation as withWorkspaceMutation2
5779
+ } from "./workspace-state.mjs";
5780
+ var ASSETS_FOLDER = "assets", MAX_ASSET_SAVES = 10, MAX_ASSET_FILES = 200, MAX_STATE_BYTES = 256 * 1024, MAX_REPLY_BYTES = 1024 * 1024, TYPES2 = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" }, LABELS = { "image/png": ["PNG", ".png"], "image/jpeg": ["JPEG", ".jpg or .jpeg"], "image/webp": ["WebP", ".webp"] }, CODED = /^([A-Z][A-Z0-9_]{2,63}): ([\s\S]*)$/, SERVER_CODE2 = /^[A-Z][A-Z0-9_]{2,63}$/;
5781
+ var NAME_RULE = "Asset names use lowercase letters, digits, _ or - (at most 64 characters before the extension) and end in .png, .jpg, .jpeg or .webp.", plain3 = (value) => !!value && typeof value == "object" && !Array.isArray(value), coded = (code, message) => Object.assign(new Error(message), { code, expose: !0 }), problem = (path, error, message) => ({ path, error, message });
5782
+ function sniff(bytes2) {
5783
+ return bytes2.length >= 8 && bytes2.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? "image/png" : bytes2.length >= 3 && bytes2[0] === 255 && bytes2[1] === 216 && bytes2[2] === 255 ? "image/jpeg" : bytes2.length >= 12 && bytes2.toString("latin1", 0, 4) === "RIFF" && bytes2.toString("latin1", 8, 12) === "WEBP" ? "image/webp" : null;
5784
+ }
5785
+ function scanAssets(workspace) {
5786
+ let root = resolve6(workspace), folder = join5(root, ASSETS_FOLDER);
5787
+ assertNoSymlinkAncestors3(root);
5788
+ let stat2 = lstatIfPresent3(folder);
5789
+ if (!stat2) return { files: [], problems: [] };
5790
+ if (!stat2.isDirectory()) return { files: [], problems: [problem(ASSETS_FOLDER, "ASSET_PATH_INVALID", "assets must be a folder, not a link or a file.")] };
5791
+ let names = readdirSync2(folder).filter((name) => !name.startsWith(".")).sort();
5792
+ if (names.length > MAX_ASSET_FILES)
5793
+ return { files: [], problems: [problem(ASSETS_FOLDER, "ASSET_LIMIT", `assets/ can hold at most ${MAX_ASSET_FILES} files.`)] };
5794
+ let files = [], problems = [];
5795
+ for (let name of names) {
5796
+ let path = `${ASSETS_FOLDER}/${name}`, entry = lstatIfPresent3(join5(folder, name));
5797
+ if (!entry?.isFile()) {
5798
+ problems.push(problem(path, "ASSET_PATH_INVALID", "Put image files directly in assets/; folders and links are not saved."));
5799
+ continue;
5800
+ }
5801
+ if (name.length > 69 || !ASSET_NAME.test(name)) {
5802
+ problems.push(problem(path, "ASSET_NAME_INVALID", NAME_RULE));
5803
+ continue;
5804
+ }
5805
+ if (entry.size > 10485760) {
5806
+ problems.push(problem(path, "ASSET_TOO_LARGE", "Image files can be up to 10 MB."));
5807
+ continue;
5808
+ }
5809
+ let bytes2 = readSafeFile4(join5(folder, name), 10485760), contentType = sniff(bytes2);
5810
+ if (!contentType) {
5811
+ problems.push(problem(path, "ATTACHMENT_NOT_IMAGE", "That file is not a PNG, JPEG or WebP image."));
5812
+ continue;
5813
+ }
5814
+ if (TYPES2[name.slice(name.lastIndexOf(".") + 1)] !== contentType) {
5815
+ let [label, endings] = LABELS[contentType];
5816
+ problems.push(problem(path, "ASSET_NAME_INVALID", `This image is ${label}, so the name must end in ${endings}.`));
5817
+ continue;
5818
+ }
5819
+ files.push({ name, path, contentType, size: bytes2.length, sha256: sha2564(bytes2) });
5820
+ }
5821
+ return { files, problems };
5822
+ }
5823
+ function readState(root, appId) {
5824
+ let path = join5(root, ASSET_STATE);
5825
+ if (assertNoSymlinkAncestors3(path), !lstatIfPresent3(path)) return {};
5826
+ try {
5827
+ let value = JSON.parse(readSafeFile4(path, MAX_STATE_BYTES).toString("utf8"));
5828
+ return value?.schema !== 1 || value.appId !== appId || !plain3(value.assets) ? {} : Object.fromEntries(Object.entries(value.assets).filter(([name, stamp]) => ASSET_NAME.test(name) && /^[a-f0-9]{64}$/.test(stamp?.sha256 ?? "")));
5829
+ } catch {
5830
+ return {};
5831
+ }
5832
+ }
5833
+ function writeState(root, appId, assets) {
5834
+ withWorkspaceMutation2(root, () => writeAtomic(root, ASSET_STATE, JSON.stringify({ schema: 1, appId, assets }) + `
5835
+ `));
5836
+ }
5837
+ function assetStatus(workspace, appId) {
5838
+ let root = resolve6(workspace);
5839
+ if (!lstatIfPresent3(join5(root, ASSETS_FOLDER))) return null;
5840
+ let { files, problems } = scanAssets(root), stamps = readState(root, appId);
5841
+ return { files: files.length, pending: files.filter((file) => stamps[file.name]?.sha256 !== file.sha256).map((file) => file.path), problems };
5842
+ }
5843
+ function reply(result) {
5844
+ let text4 = result?.content?.length === 1 && result.content[0].type === "text" ? result.content[0].text : null;
5845
+ if (typeof text4 != "string" || Buffer.byteLength(text4, "utf8") > MAX_REPLY_BYTES) throw coded("ADELIN_TOOL_FAILED", "Adelin returned an invalid asset reply.");
5846
+ if (result.isError) {
5847
+ let match = CODED.exec(text4);
5848
+ throw coded(match ? match[1] : "ADELIN_TOOL_FAILED", match ? cleanServerMessage(match[2]) : "Adelin refused the asset request.");
5849
+ }
5850
+ let value;
5851
+ try {
5852
+ value = JSON.parse(text4);
5853
+ } catch {
5854
+ }
5855
+ if (!plain3(value)) throw coded("ADELIN_TOOL_FAILED", "Adelin returned an invalid asset reply.");
5856
+ return value;
5857
+ }
5858
+ function uploadTarget(ticket, file) {
5859
+ let target2;
5860
+ try {
5861
+ target2 = new URL(ticket.uploadUrl);
5862
+ } catch {
5863
+ target2 = null;
5864
+ }
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))
5866
+ throw coded("ADELIN_TOOL_FAILED", "Adelin returned an invalid asset upload.");
5867
+ return target2;
5868
+ }
5869
+ async function saveOne({ root, appId, edit, call, fetcher, timeout }, file) {
5870
+ let bytes2 = readSafeFile4(join5(root, file.path), 10485760);
5871
+ if (bytes2.length !== file.size || sha2564(bytes2) !== file.sha256) throw coded("ASSET_SOURCE_CHANGED", `${file.path} changed while it was being saved. Build again.`);
5872
+ let session = { app_id: appId, lease_id: edit.leaseId, chat_session_id: edit.chatSessionId, epoch: edit.epoch }, ticket = reply(await call("create_asset_upload", { ...session, fileName: file.name, contentType: file.contentType, byteLength: file.size })), target2 = uploadTarget(ticket, file), uploaded;
5873
+ try {
5874
+ uploaded = await fetcher(target2, {
5875
+ method: "PUT",
5876
+ redirect: "error",
5877
+ body: bytes2,
5878
+ signal: timeout(transferDeadlineMs(file.size)),
5879
+ headers: { "content-type": file.contentType, "content-length": String(file.size) }
5880
+ }), await uploaded.body?.cancel();
5881
+ } catch {
5882
+ throw coded("ASSET_UPLOAD_FAILED", `Uploading ${file.path} did not finish. Build again.`);
5883
+ }
5884
+ if (!uploaded.ok) throw coded("ASSET_UPLOAD_FAILED", `Uploading ${file.path} was refused (HTTP ${uploaded.status}). Build again.`);
5885
+ let saved = reply(await call("save_attachment_as_asset", { ...session, attachmentId: ticket.attachmentId, name: file.name, replace: file.replace }));
5886
+ if (saved.name !== file.name || typeof saved.assetPath != "string" || typeof saved.replaced != "boolean")
5887
+ throw coded("ADELIN_TOOL_FAILED", "Adelin returned an invalid asset reply.");
5888
+ return { name: saved.name, assetPath: saved.assetPath, width: saved.width, height: saved.height, replaced: saved.replaced };
5889
+ }
5890
+ var notSaved = (appId, assets, nextAction, state = "assets_not_saved") => ({ ok: !1, result: { state, appId, assets, sourceSent: !1, nextAction } });
5891
+ async function saveWorkspaceAssets({
5892
+ workspace,
5893
+ appId,
5894
+ leaseId,
5895
+ chatSessionId,
5896
+ epoch,
5897
+ call,
5898
+ replace = [],
5899
+ fetcher = fetch,
5900
+ timeout = (ms) => AbortSignal.timeout(ms)
5901
+ }) {
5902
+ let root = resolve6(workspace), { files, problems } = scanAssets(root), local = new Set(files.map((file) => file.name));
5903
+ for (let name of replace) local.has(name) || problems.push(problem(`${ASSETS_FOLDER}/${name}`, "ASSET_NOT_FOUND", "replace_assets names an image that is not in assets/."));
5904
+ if (problems.length) return notSaved(appId, { problems }, "Fix or remove these files in assets/, then build again. No source was sent.");
5905
+ if (!files.length) return null;
5906
+ let stamps = readState(root, appId), saved = /* @__PURE__ */ new Set();
5907
+ try {
5908
+ for (let asset of reply(await call("list_assets", { app_id: appId })).assets ?? []) typeof asset?.name == "string" && saved.add(asset.name);
5909
+ } catch (error) {
5910
+ return notSaved(appId, { failed: failure(ASSETS_FOLDER, error) }, "Build again shortly. No source was sent.");
5911
+ }
5912
+ let work = [];
5913
+ for (let file of files) {
5914
+ let stamp = stamps[file.name];
5915
+ if (!(saved.has(file.name) && stamp?.sha256 === file.sha256)) {
5916
+ if (saved.has(file.name) && !stamp && !replace.includes(file.name)) {
5917
+ problems.push(problem(file.path, "ASSET_NAME_TAKEN", `The app already has an image named ${file.name} that this workspace did not save. Rename the local file, or build with replace_assets ["${file.name}"] only if the builder asked to replace that image.`));
5918
+ continue;
5919
+ }
5920
+ work.push({ ...file, replace: saved.has(file.name) });
5921
+ }
5922
+ }
5923
+ if (problems.length) return notSaved(appId, { problems }, "Rename these files or confirm the replacement, then build again. No source was sent.");
5924
+ let context = { root, appId, edit: { leaseId, chatSessionId, epoch }, call, fetcher, timeout }, done = [];
5925
+ for (let file of work.slice(0, MAX_ASSET_SAVES)) {
5926
+ try {
5927
+ done.push(await saveOne(context, file));
5928
+ } catch (error) {
5929
+ return notSaved(
5930
+ appId,
5931
+ { saved: done, failed: failure(file.path, error) },
5932
+ "Fix the cause, then build again; images already saved are not sent again. No source was sent."
5933
+ );
5934
+ }
5935
+ stamps[file.name] = { sha256: file.sha256 }, writeState(root, appId, stamps);
5936
+ }
5937
+ return work.length > MAX_ASSET_SAVES ? notSaved(
5938
+ appId,
5939
+ { saved: done, remaining: work.slice(MAX_ASSET_SAVES).map((file) => file.path) },
5940
+ "Call build_app again to save the remaining images. No source was sent.",
5941
+ "assets_pending"
5942
+ ) : { ok: !0, report: { saved: done, unchanged: files.length - work.length } };
5943
+ }
5944
+ function failure(path, error) {
5945
+ let shown2 = error?.expose === !0 && typeof error.code == "string" && SERVER_CODE2.test(error.code);
5946
+ return { path, error: shown2 ? error.code : "ADELIN_TOOL_FAILED", message: shown2 ? error.message.slice(0, 500) : "Adelin could not save this image. Try again." };
5947
+ }
5948
+
5949
+ // skills/adelin-app-generation/scripts/local-builder.mjs
5950
+ import { typecheck } from "./typecheck.mjs";
5951
+
5527
5952
  // skills/adelin-app-generation/scripts/media-workflow.mjs
5528
- import { resolve as resolve10 } from "node:path";
5953
+ import { resolve as resolve11 } from "node:path";
5529
5954
 
5530
5955
  // skills/adelin-app-generation/scripts/media-jobs.mjs
5531
5956
  import { spawn } from "node:child_process";
5532
5957
  import { randomUUID as randomUUID5 } from "node:crypto";
5533
- import { existsSync as existsSync3, readFileSync as readFileSync5, readdirSync as readdirSync4, realpathSync as realpathSync5, statSync } from "node:fs";
5534
- import { basename as basename5, dirname as dirname6, join as join9, resolve as resolve9 } from "node:path";
5958
+ import { existsSync as existsSync3, readFileSync as readFileSync5, readdirSync as readdirSync5, realpathSync as realpathSync5, statSync } from "node:fs";
5959
+ import { basename as basename5, dirname as dirname6, join as join10, resolve as resolve10 } from "node:path";
5535
5960
  import { fileURLToPath as fileURLToPath2 } from "node:url";
5536
5961
 
5537
5962
  // skills/adelin-app-generation/scripts/media-output.mjs
@@ -5763,8 +6188,8 @@ function deletionPlan(value) {
5763
6188
  return uploads.some((row) => row.effect === "original_only" && !row.restorable) && fail3(), count2(value.totalFreesBytes) !== uploads.reduce((sum, row) => sum + row.freesBytes, 0) && fail3(), { uploads, skipped: skippedRows(value.skipped), totalFreesBytes: value.totalFreesBytes, previewId: id5(value.previewId), expiresAt: iso(value.expiresAt) };
5764
6189
  }
5765
6190
  function mutationFailure(code, extra = {}) {
5766
- let failure = mediaFailure(code);
5767
- return BILLING2.test(failure.error.code) && (failure.error.message = "Billing refused this transcode."), { ok: !1, error: { ...failure.error, ...extra } };
6191
+ let failure2 = mediaFailure(code);
6192
+ return BILLING2.test(failure2.error.code) && (failure2.error.message = "Billing refused this transcode."), { ok: !1, error: { ...failure2.error, ...extra } };
5768
6193
  }
5769
6194
  function mutationRefusal(value, request) {
5770
6195
  let code = value.error;
@@ -5887,7 +6312,7 @@ function decodeMediaMutation(result, request) {
5887
6312
  import { spawn as spawnChild } from "node:child_process";
5888
6313
  import { constants as constants3 } from "node:fs";
5889
6314
  import { access, realpath, stat } from "node:fs/promises";
5890
- import { basename as basename3, delimiter, isAbsolute as isAbsolute3, join as join5 } from "node:path";
6315
+ import { basename as basename3, delimiter, isAbsolute as isAbsolute3, join as join6 } from "node:path";
5891
6316
 
5892
6317
  // skills/adelin-app-generation/scripts/__generated__/media-probe-rules.mjs
5893
6318
  import { posix } from "node:path";
@@ -6323,7 +6748,7 @@ async function findFfprobe(env) {
6323
6748
  for (let dir of String(env.PATH ?? env.Path ?? "").split(delimiter))
6324
6749
  if (!(!dir || !isAbsolute3(dir)))
6325
6750
  for (let name of names) {
6326
- let candidate2 = join5(dir, name);
6751
+ let candidate2 = join6(dir, name);
6327
6752
  try {
6328
6753
  if ((await stat(candidate2)).isFile())
6329
6754
  return await access(candidate2, constants3.X_OK), candidate2;
@@ -6333,9 +6758,9 @@ async function findFfprobe(env) {
6333
6758
  return null;
6334
6759
  }
6335
6760
  function runFfprobe(program, file, { env, spawn: spawn4, setTimer, clearTimer }) {
6336
- return new Promise((resolve12) => {
6761
+ return new Promise((resolve13) => {
6337
6762
  let stdout = [], stderr = [], sizes = { stdout: 0, stderr: 0 }, timedOut2 = !1, launchFailed = !1, settled = !1, timer, child2, finish = (exitCode) => {
6338
- settled || (settled = !0, clearTimer(timer), resolve12({ exitCode, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr), timedOut: timedOut2, launchFailed }));
6763
+ settled || (settled = !0, clearTimer(timer), resolve13({ exitCode, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr), timedOut: timedOut2, launchFailed }));
6339
6764
  };
6340
6765
  try {
6341
6766
  child2 = spawn4(
@@ -6398,7 +6823,7 @@ import {
6398
6823
  readFileSync as readFileSync4,
6399
6824
  readlinkSync as readlinkSync2,
6400
6825
  realpathSync as realpathSync4,
6401
- readdirSync as readdirSync3,
6826
+ readdirSync as readdirSync4,
6402
6827
  renameSync as renameSync4,
6403
6828
  rmSync,
6404
6829
  symlinkSync,
@@ -6406,20 +6831,20 @@ import {
6406
6831
  writeFileSync as writeFileSync5
6407
6832
  } from "node:fs";
6408
6833
  import { homedir as homedir2 } from "node:os";
6409
- import { join as join8, resolve as resolve8, sep as sep2 } from "node:path";
6834
+ import { join as join9, resolve as resolve9, sep as sep2 } from "node:path";
6410
6835
  import { promisify } from "node:util";
6411
6836
  import { randomUUID as randomUUID4 } from "node:crypto";
6412
6837
 
6413
6838
  // skills/adelin-app-generation/scripts/cli-release.mjs
6414
- import { dirname as dirname4, join as join6, relative as relative2, resolve as resolve6 } from "node:path";
6839
+ import { dirname as dirname4, join as join7, relative as relative2, resolve as resolve7 } from "node:path";
6415
6840
  import { fileURLToPath } from "node:url";
6416
- var import_authoring_release = __toESM(require_authoring_release(), 1), CLI_ROOT = resolve6(dirname4(fileURLToPath(import.meta.url)), "..");
6841
+ var import_authoring_release = __toESM(require_authoring_release(), 1), CLI_ROOT = resolve7(dirname4(fileURLToPath(import.meta.url)), "..");
6417
6842
 
6418
6843
  // skills/adelin-app-generation/scripts/media-transfer-runner.mjs
6419
- import { createDecipheriv, createHash as createHash3, createPublicKey, diffieHellman, generateKeyPairSync as generateKeyPairSync2, hkdfSync, randomBytes as randomBytes2, randomUUID as randomUUID3 } from "node:crypto";
6420
- 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 readdirSync2, renameSync as renameSync3, unlinkSync as unlinkSync5, writeFileSync as writeFileSync4 } from "node:fs";
6844
+ import { createDecipheriv, createHash as createHash4, createPublicKey, diffieHellman, generateKeyPairSync as generateKeyPairSync3, hkdfSync, randomBytes as randomBytes3, randomUUID as randomUUID3 } from "node:crypto";
6845
+ 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";
6421
6846
  import { homedir } from "node:os";
6422
- import { basename as basename4, dirname as dirname5, join as join7, resolve as resolve7 } from "node:path";
6847
+ import { basename as basename4, dirname as dirname5, join as join8, resolve as resolve8 } from "node:path";
6423
6848
 
6424
6849
  // skills/adelin-app-generation/scripts/__generated__/media-scheduler.mjs
6425
6850
  var hostClock = {
@@ -6457,11 +6882,11 @@ function createUploadScheduler(clock = hostClock) {
6457
6882
  }
6458
6883
  }
6459
6884
  function acquire(bytes2, signal) {
6460
- return signal.aborted ? Promise.reject(new Error("Upload was aborted.")) : (active === 0 && waiting.length === 0 && (limit3 = 1, fastSamples = 0, generation += 1), new Promise((resolve12, reject) => {
6885
+ return signal.aborted ? Promise.reject(new Error("Upload was aborted.")) : (active === 0 && waiting.length === 0 && (limit3 = 1, fastSamples = 0, generation += 1), new Promise((resolve13, reject) => {
6461
6886
  let entry = {
6462
6887
  bytes: bytes2,
6463
6888
  signal,
6464
- resolve: resolve12,
6889
+ resolve: resolve13,
6465
6890
  cancel: () => {
6466
6891
  waiting = waiting.filter((item) => item !== entry), signal.removeEventListener("abort", entry.cancel), reject(new Error("Upload was aborted."));
6467
6892
  }
@@ -6474,7 +6899,7 @@ function createUploadScheduler(clock = hostClock) {
6474
6899
  var sharedUploadScheduler = createUploadScheduler();
6475
6900
 
6476
6901
  // skills/adelin-app-generation/scripts/media-transfer-runner.mjs
6477
- var TRANSFER = Object.freeze({ signBatch: 50, rateFirstMs: 2e3, rateMaxMs: 3e4, rateTries: 6, resumeMarginMs: 10 * 6e4, privateBytes: 2 * 1024 * 1024 }), POST_UPLOAD = Object.freeze(["probing", "awaiting_options", "queued", "processing", "ready", "failed"]), UUID6 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, SEAL_INFO = Buffer.from("adelin-media-transfer-v1"), TRANSPORT = /* @__PURE__ */ new Set(["AUTH_REQUIRED", "APP_SELECTION_CHANGED", "REMOTE_UNAVAILABLE", "REQUEST_TIMEOUT", "RESPONSE_TOO_LARGE", "RECONSENT_REQUIRED", "UPDATE_REQUIRED"]), REMOTE_CODES2 = /* @__PURE__ */ new Set([
6902
+ var TRANSFER = Object.freeze({ signBatch: 50, rateFirstMs: 2e3, rateMaxMs: 3e4, rateTries: 6, resumeMarginMs: 10 * 6e4, privateBytes: 2 * 1024 * 1024 }), POST_UPLOAD = Object.freeze(["probing", "awaiting_options", "queued", "processing", "ready", "failed"]), UUID8 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, SEAL_INFO = Buffer.from("adelin-media-transfer-v1"), TRANSPORT = /* @__PURE__ */ new Set(["AUTH_REQUIRED", "APP_SELECTION_CHANGED", "REMOTE_UNAVAILABLE", "REQUEST_TIMEOUT", "RESPONSE_TOO_LARGE", "RECONSENT_REQUIRED", "UPDATE_REQUIRED"]), REMOTE_CODES2 = /* @__PURE__ */ new Set([
6478
6903
  "INVALID_ARGUMENT",
6479
6904
  "ACCESS_DENIED",
6480
6905
  "NOT_FOUND",
@@ -6507,8 +6932,8 @@ var TRANSFER = Object.freeze({ signBatch: 50, rateFirstMs: 2e3, rateMaxMs: 3e4,
6507
6932
  throw new TransferError(code, extra);
6508
6933
  }, hostSleep = (ms) => new Promise((done) => setTimeout(done, ms));
6509
6934
  function adelinConfigDir(env = process.env) {
6510
- let base = process.platform === "win32" ? env.APPDATA || join7(homedir(), "AppData", "Roaming") : env.XDG_CONFIG_HOME || join7(homedir(), ".config");
6511
- return join7(resolve7(base), "adelin");
6935
+ let base = process.platform === "win32" ? env.APPDATA || join8(homedir(), "AppData", "Roaming") : env.XDG_CONFIG_HOME || join8(homedir(), ".config");
6936
+ return join8(resolve8(base), "adelin");
6512
6937
  }
6513
6938
  function privateDirectory(path) {
6514
6939
  mkdirSync3(path, { recursive: !0, mode: 448 });
@@ -6517,7 +6942,7 @@ function privateDirectory(path) {
6517
6942
  }
6518
6943
  function writePrivateJson(path, value) {
6519
6944
  privateDirectory(dirname5(path));
6520
- let stage = `${path}.${randomBytes2(12).toString("hex")}.tmp`, fd = openSync3(stage, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384);
6945
+ let stage = `${path}.${randomBytes3(12).toString("hex")}.tmp`, fd = openSync3(stage, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384);
6521
6946
  try {
6522
6947
  writeFileSync4(fd, JSON.stringify(value) + `
6523
6948
  `), fsyncSync2(fd);
@@ -6557,7 +6982,7 @@ function processAlive2(pid) {
6557
6982
  }
6558
6983
  function acquireLock(path, busyCode, isAlive = processAlive2) {
6559
6984
  privateDirectory(dirname5(path));
6560
- let stage = `${path}.${randomBytes2(12).toString("hex")}.tmp`;
6985
+ let stage = `${path}.${randomBytes3(12).toString("hex")}.tmp`;
6561
6986
  writeFileSync4(stage, String(process.pid), { flag: "wx", mode: 384 });
6562
6987
  try {
6563
6988
  for (let attempt = 0; attempt < 2; attempt++)
@@ -6574,27 +6999,27 @@ function acquireLock(path, busyCode, isAlive = processAlive2) {
6574
6999
  }
6575
7000
  var JOURNAL_KEYS = ["schema", "mcpUrl", "appId", "assetId", "uploadId", "startOperationId", "file", "partSize", "partCount", "createdAt", "abandonAt", "parts"], isRecord = (value) => !!value && typeof value == "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype, exactKeys = (value, keys3) => isRecord(value) && Object.keys(value).length === keys3.length && keys3.every((key4) => Object.hasOwn(value, key4)), positive = (value) => Number.isSafeInteger(value) && value > 0, nullable2 = (value, check2) => value === null || check2(value);
6576
7001
  function validJournal(value) {
6577
- return !exactKeys(value, JOURNAL_KEYS) || value.schema !== 1 || typeof value.mcpUrl != "string" || !UUID6.test(value.appId) || !UUID6.test(value.startOperationId) || !nullable2(value.assetId, (v) => UUID6.test(v)) || !nullable2(value.uploadId, (v) => typeof v == "string" && v.length <= 1024) || !exactKeys(value.file, ["size", "sha256", "name"]) || !positive(value.file.size) || !/^[0-9a-f]{64}$/.test(value.file.sha256) || typeof value.file.name != "string" || !nullable2(value.partSize, positive) || !nullable2(value.partCount, positive) || !nullable2(value.createdAt, (v) => typeof v == "string") || !nullable2(value.abandonAt, (v) => typeof v == "string") ? !1 : isRecord(value.parts) && Object.entries(value.parts).every(([n, etag]) => /^[1-9][0-9]{0,4}$/.test(n) && Number(n) <= (value.partCount ?? 0) && typeof etag == "string" && etag.length <= 256);
7002
+ return !exactKeys(value, JOURNAL_KEYS) || value.schema !== 1 || typeof value.mcpUrl != "string" || !UUID8.test(value.appId) || !UUID8.test(value.startOperationId) || !nullable2(value.assetId, (v) => UUID8.test(v)) || !nullable2(value.uploadId, (v) => typeof v == "string" && v.length <= 1024) || !exactKeys(value.file, ["size", "sha256", "name"]) || !positive(value.file.size) || !/^[0-9a-f]{64}$/.test(value.file.sha256) || typeof value.file.name != "string" || !nullable2(value.partSize, positive) || !nullable2(value.partCount, positive) || !nullable2(value.createdAt, (v) => typeof v == "string") || !nullable2(value.abandonAt, (v) => typeof v == "string") ? !1 : isRecord(value.parts) && Object.entries(value.parts).every(([n, etag]) => /^[1-9][0-9]{0,4}$/.test(n) && Number(n) <= (value.partCount ?? 0) && typeof etag == "string" && etag.length <= 256);
6578
7003
  }
6579
7004
  function readJournal2(path) {
6580
7005
  let value = readPrivateJson(path);
6581
7006
  return value !== null && !validJournal(value) && refuse2("MEDIA_JOURNAL_INVALID"), value;
6582
7007
  }
6583
7008
  function findJournals(dir, match) {
6584
- let folder = join7(dir, "uploads");
7009
+ let folder = join8(dir, "uploads");
6585
7010
  if (!existsSync(folder)) return [];
6586
7011
  let found = [];
6587
- for (let name of readdirSync2(folder))
7012
+ for (let name of readdirSync3(folder))
6588
7013
  if (/^[0-9a-f]{64}\.json$/.test(name))
6589
7014
  try {
6590
- let journal = readJournal2(join7(folder, name));
6591
- journal && match(journal) && found.push({ path: join7(folder, name), journal });
7015
+ let journal = readJournal2(join8(folder, name));
7016
+ journal && match(journal) && found.push({ path: join8(folder, name), journal });
6592
7017
  } catch {
6593
7018
  }
6594
7019
  return found;
6595
7020
  }
6596
7021
  async function fileIdentity(blob, signal) {
6597
- let hash = createHash3("sha256");
7022
+ let hash = createHash4("sha256");
6598
7023
  try {
6599
7024
  for await (let chunk of blob.stream())
6600
7025
  signal?.aborted && refuse2("INTERRUPTED"), hash.update(chunk);
@@ -6605,7 +7030,7 @@ async function fileIdentity(blob, signal) {
6605
7030
  return { size: blob.size, sha256: hash.digest("hex") };
6606
7031
  }
6607
7032
  function replyKeys() {
6608
- let pair = generateKeyPairSync2("x25519");
7033
+ let pair = generateKeyPairSync3("x25519");
6609
7034
  return { privateKey: pair.privateKey, publicKey: pair.publicKey.export({ format: "jwk" }).x };
6610
7035
  }
6611
7036
  function openSealed(privateKey, assetId, sealed) {
@@ -6643,7 +7068,7 @@ function decode(result, args, privateKey) {
6643
7068
  let sealed = isRecord(value) && Object.hasOwn(value, "sealed");
6644
7069
  (result.isError || !exactKeys(value, ["ok", "action", "appId", "data", ...sealed ? ["sealed"] : []]) || value.ok !== !0 || value.action !== args.action || value.appId !== args.app_id || !exactKeys(value.data, DATA_KEYS[args.action])) && refuse2("INVALID_RESPONSE"), leaksAuthority(value.data) && refuse2("MEDIA_UNAVAILABLE");
6645
7070
  let { data } = value;
6646
- return (!UUID6.test(data.assetId) || args.payload.asset_id && data.assetId !== args.payload.asset_id) && refuse2("INVALID_RESPONSE"), { data, secret: sealed ? openSealed(privateKey, data.assetId, value.sealed) : void 0 };
7071
+ return (!UUID8.test(data.assetId) || args.payload.asset_id && data.assetId !== args.payload.asset_id) && refuse2("INVALID_RESPONSE"), { data, secret: sealed ? openSealed(privateKey, data.assetId, value.sealed) : void 0 };
6647
7072
  }
6648
7073
  function transferClient(remote2, { sleep: sleep2 = hostSleep, keys: keys3 = replyKeys } = {}) {
6649
7074
  return async function(action, appId, payload, operationId) {
@@ -6686,8 +7111,8 @@ function notResumable(status2, now, marginMs = TRANSFER.resumeMarginMs) {
6686
7111
  return status2.status === "uploading" && status2.uploadIdMatches === !0 && now < abandonAt - marginMs ? null : status2.abandoned === !0 || status2.status === "uploading" && now >= abandonAt ? "abandoned" : status2.status === "failed" ? "failed" : ["removing", "removed"].includes(status2.status) ? "cancelled" : status2.status !== "uploading" ? "state" : status2.uploadIdMatches !== !0 ? "upload_id" : "expired_window";
6687
7112
  }
6688
7113
  var sortedParts = (journal) => Object.entries(journal.parts).map(([n, etag]) => ({ partNumber: Number(n), etag })).sort((a, b) => a.partNumber - b.partNumber), PROBE = { enqueued: "queued", not_needed: "queued", deferred: "deferred" };
6689
- function outcome(reply, journal, resumedParts) {
6690
- let { data } = reply;
7114
+ function outcome(reply2, journal, resumedParts) {
7115
+ let { data } = reply2;
6691
7116
  return (!["completed", "already_completed"].includes(data.state) || !Object.hasOwn(PROBE, data.probe) || typeof data.status != "string") && refuse2("INVALID_RESPONSE"), data.status === "failed" && refuse2("UPLOAD_NOT_RESUMABLE", { reason: "failed", assetId: data.assetId }), {
6692
7117
  outcome: "uploaded",
6693
7118
  assetId: data.assetId,
@@ -6781,23 +7206,23 @@ var fail4 = (message) => {
6781
7206
  throw new Error(message);
6782
7207
  };
6783
7208
  function cliInstallHome(env = process.env) {
6784
- let base = process.platform === "win32" ? env.LOCALAPPDATA || join8(homedir2(), "AppData", "Local") : env.XDG_DATA_HOME || join8(homedir2(), ".local/share");
6785
- return join8(resolve8(base), "adelin", "cli", "production");
7209
+ let base = process.platform === "win32" ? env.LOCALAPPDATA || join9(homedir2(), "AppData", "Local") : env.XDG_DATA_HOME || join9(homedir2(), ".local/share");
7210
+ return join9(resolve9(base), "adelin", "cli", "production");
6786
7211
  }
6787
7212
  function holdCliReleaseForProcess(release2, pid, home = cliInstallHome()) {
6788
- if (!release2.root.startsWith(resolve8(home, "releases") + sep2)) return () => {
7213
+ if (!release2.root.startsWith(resolve9(home, "releases") + sep2)) return () => {
6789
7214
  };
6790
7215
  (!Number.isSafeInteger(pid) || pid < 1) && fail4("Invalid CLI release owner.");
6791
- let refs = join8(home, "references");
7216
+ let refs = join9(home, "references");
6792
7217
  privateDirectory(refs);
6793
- let path = join8(refs, `${pid}-${randomUUID4()}.json`);
7218
+ let path = join9(refs, `${pid}-${randomUUID4()}.json`);
6794
7219
  return writePrivateJson(path, { pid, root: release2.root }), () => {
6795
7220
  existsSync2(path) && unlinkSync6(path);
6796
7221
  };
6797
7222
  }
6798
7223
 
6799
7224
  // skills/adelin-app-generation/scripts/media-jobs.mjs
6800
- var JOB_STATES = Object.freeze(["queued", "hashing", "starting", "transferring", "finalizing", "uploaded", "failed", "cancelled", "interrupted"]), TERMINAL = ["uploaded", "failed", "cancelled", "interrupted"], JOB_POLL_MS = 1e3, CLI = realpathSync5(fileURLToPath2(new URL("./adelin.mjs", import.meta.url))), UUID7 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, JOB_KEYS = [
7225
+ var JOB_STATES = Object.freeze(["queued", "hashing", "starting", "transferring", "finalizing", "uploaded", "failed", "cancelled", "interrupted"]), TERMINAL = ["uploaded", "failed", "cancelled", "interrupted"], JOB_POLL_MS = 1e3, CLI = realpathSync5(fileURLToPath2(new URL("./adelin.mjs", import.meta.url))), UUID9 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, JOB_KEYS = [
6801
7226
  "schema",
6802
7227
  "jobId",
6803
7228
  "appId",
@@ -6824,12 +7249,12 @@ var TRANSCODE_NEXT = {
6824
7249
  inspect: "The job stopped. Check media inspect with this operationId, or media status; start it with media transcode if it never started.",
6825
7250
  status: "The job stopped following this transcode. Follow it with media status."
6826
7251
  }, transcoding = (job) => !!job.transcode && !TRANSCODE_DONE.includes(job.transcode.state);
6827
- var jobFile = (dir, jobId) => join9(dir, "media-jobs", `${jobId}.json`), lockFile = (dir, jobId) => join9(dir, "media-jobs", `${jobId}.lock`);
7252
+ var jobFile = (dir, jobId) => join10(dir, "media-jobs", `${jobId}.json`), lockFile = (dir, jobId) => join10(dir, "media-jobs", `${jobId}.lock`);
6828
7253
  function readJob(dir, jobId) {
6829
- if (!UUID7.test(jobId)) return null;
7254
+ if (!UUID9.test(jobId)) return null;
6830
7255
  let job = readPrivateJson(jobFile(dir, jobId));
6831
7256
  if (job === null) return null;
6832
- if (!job || Object.keys(job).length !== JOB_KEYS.length || !JOB_KEYS.every((key4) => Object.hasOwn(job, key4)) || job.jobId !== jobId || !JOB_STATES.includes(job.state) || job.transcode !== null && (typeof job.transcode != "object" || !UUID7.test(job.transcode.operationId ?? "")))
7257
+ if (!job || Object.keys(job).length !== JOB_KEYS.length || !JOB_KEYS.every((key4) => Object.hasOwn(job, key4)) || job.jobId !== jobId || !JOB_STATES.includes(job.state) || job.transcode !== null && (typeof job.transcode != "object" || !UUID9.test(job.transcode.operationId ?? "")))
6833
7258
  throw new TransferError("MEDIA_JOURNAL_INVALID");
6834
7259
  return job;
6835
7260
  }
@@ -6851,7 +7276,7 @@ function jobStatus(dir, jobId, isAlive = processAlive2) {
6851
7276
  if (!job) throw new TransferError("MEDIA_JOB_NOT_FOUND");
6852
7277
  let { state, error } = job;
6853
7278
  !TERMINAL.includes(state) && !isAlive(runnerPid(dir, job)) && (state = "interrupted", error = { code: "INTERRUPTED", next: "resume" });
6854
- let failure = error ? mediaFailure(error.code, void 0, { ...error, assetId: job.assetId }).error : null;
7279
+ let failure2 = error ? mediaFailure(error.code, void 0, { ...error, assetId: job.assetId }).error : null;
6855
7280
  return {
6856
7281
  jobId,
6857
7282
  state,
@@ -6862,7 +7287,7 @@ function jobStatus(dir, jobId, isAlive = processAlive2) {
6862
7287
  partCount: job.partCount,
6863
7288
  resumedParts: job.resumedParts,
6864
7289
  concurrency: TERMINAL.includes(state) ? 0 : job.concurrency,
6865
- error: failure && { code: failure.code, message: failure.message, ...failure.reason ? { reason: failure.reason } : {}, ...failure.status ? { status: failure.status } : {} },
7290
+ error: failure2 && { code: failure2.code, message: failure2.message, ...failure2.reason ? { reason: failure2.reason } : {}, ...failure2.status ? { status: failure2.status } : {} },
6866
7291
  next: error ? nextStep(error.next) : null,
6867
7292
  outcome: job.outcome,
6868
7293
  transcode: publicTranscode(job, state === "uploaded" && transcoding(job) && !isAlive(runnerPid(dir, job)))
@@ -6904,7 +7329,7 @@ function spawnRunner({ jobId, mcpUrl }) {
6904
7329
  }), child2.pid && holdCliReleaseForProcess({ root: dirname6(dirname6(CLI)) }, child2.pid), child2.unref(), child2.pid;
6905
7330
  }
6906
7331
  async function startUploadJob({ appId, path, name, transcode, mcpUrl, dir = adelinConfigDir(), check: check2 = checkMediaFile, spawn: start = spawnRunner, newId = randomUUID5 }) {
6907
- let absolute = resolve9(path), verdict = await check2(absolute);
7332
+ let absolute = resolve10(path), verdict = await check2(absolute);
6908
7333
  if (verdict.verdict === "refuse") throw new TransferError(verdict.code);
6909
7334
  let size;
6910
7335
  try {
@@ -6961,8 +7386,8 @@ async function startUploadJob({ appId, path, name, transcode, mcpUrl, dir = adel
6961
7386
  };
6962
7387
  }
6963
7388
  function jobsForAsset(dir, appId, assetId) {
6964
- let folder = join9(dir, "media-jobs");
6965
- return existsSync3(folder) ? readdirSync4(folder).filter((name) => /^[0-9a-f-]{36}\.json$/.test(name)).map((name) => {
7389
+ let folder = join10(dir, "media-jobs");
7390
+ return existsSync3(folder) ? readdirSync5(folder).filter((name) => /^[0-9a-f-]{36}\.json$/.test(name)).map((name) => {
6966
7391
  try {
6967
7392
  return readJob(dir, name.slice(0, -5));
6968
7393
  } catch {
@@ -6999,7 +7424,7 @@ var mediaOperations = Object.freeze({
6999
7424
  status: "get_media_asset",
7000
7425
  profiles: "get_transcode_profiles",
7001
7426
  "recently-deleted": "get_media_recently_deleted"
7002
- }), MEDIA_WAIT = Object.freeze({ firstPollMs: 5e3, maxPollMs: 15e3, growth: 1.5, mcpMaxSeconds: 25, cliDefaultSeconds: 120, cliMaxSeconds: 3600, transcodeDefaultSeconds: 900 }), MEDIA_STATUSES2 = Object.freeze(["uploading", "probing", "awaiting_options", "queued", "processing", "ready", "failed"]), UUID8 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", uuid3 = new RegExp(UUID8, "i"), closed3 = (properties, required) => ({ type: "object", properties, required, additionalProperties: !1 }), id6 = { type: "string", pattern: UUID8 }, limit = { type: "integer", minimum: 1, maximum: 100 }, cursor2 = { type: "string", minLength: 1, maxLength: 2048 }, waitSeconds = (max) => ({ type: "integer", minimum: 0, maximum: max }), inputs = (max) => ({
7427
+ }), MEDIA_WAIT = Object.freeze({ firstPollMs: 5e3, maxPollMs: 15e3, growth: 1.5, mcpMaxSeconds: 25, cliDefaultSeconds: 120, cliMaxSeconds: 3600, transcodeDefaultSeconds: 900 }), MEDIA_STATUSES2 = Object.freeze(["uploading", "probing", "awaiting_options", "queued", "processing", "ready", "failed"]), UUID10 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", uuid3 = new RegExp(UUID10, "i"), closed3 = (properties, required) => ({ type: "object", properties, required, additionalProperties: !1 }), id6 = { type: "string", pattern: UUID10 }, limit = { type: "integer", minimum: 1, maximum: 100 }, cursor2 = { type: "string", minLength: 1, maxLength: 2048 }, waitSeconds = (max) => ({ type: "integer", minimum: 0, maximum: max }), inputs = (max) => ({
7003
7428
  list: closed3({
7004
7429
  app_id: id6,
7005
7430
  kind: { enum: ["video", "audio"] },
@@ -7033,8 +7458,8 @@ function normalizeMediaArgs(operation, args, { maxWaitSeconds = MEDIA_WAIT.mcpMa
7033
7458
  if (!schema) throw invalid4(`operation: expected one of ${Object.keys(mediaOperations).join(", ")}`);
7034
7459
  if (!args || typeof args != "object" || Array.isArray(args) || Object.getPrototypeOf(args) !== Object.prototype) throw invalid4("arguments: expected an object");
7035
7460
  args = Object.fromEntries(Object.entries(args).map(([key4, value]) => [key4, ["app_id", "asset_id"].includes(key4) && uuid3.test(value) ? value.toLowerCase() : value]));
7036
- let problem = explainArguments(schema, args) ?? (args.cursor !== void 0 && !args.cursor.trim() ? "cursor: expected non-empty text" : null);
7037
- if (problem) throw invalid4(problem);
7461
+ let problem2 = explainArguments(schema, args) ?? (args.cursor !== void 0 && !args.cursor.trim() ? "cursor: expected non-empty text" : null);
7462
+ if (problem2) throw invalid4(problem2);
7038
7463
  let result = { ...args };
7039
7464
  return args.q !== void 0 && (result.q = args.q.trim()), operation === "status" && (result.wait_seconds = args.wait_seconds ?? 0), result;
7040
7465
  }
@@ -7137,10 +7562,10 @@ function normalizeTransferArgs(operation, args, { maxWaitSeconds = MEDIA_WAIT.mc
7137
7562
  if (!schema) throw invalid4(`operation: expected one of ${mediaTransferOperations.join(", ")}`);
7138
7563
  if (!args || typeof args != "object" || Array.isArray(args) || Object.getPrototypeOf(args) !== Object.prototype) throw invalid4("arguments: expected an object");
7139
7564
  args = Object.fromEntries(Object.entries(args).map(([key4, value]) => [key4, ["app_id", "asset_id", "job_id", "transcode"].includes(key4) && uuid3.test(value) ? value.toLowerCase() : value]));
7140
- let problem = explainArguments(schema, args) ?? (typeof args.name == "string" && !args.name.trim() ? "name: expected non-empty text" : null);
7141
- if (problem) throw invalid4(problem);
7565
+ let problem2 = explainArguments(schema, args) ?? (typeof args.name == "string" && !args.name.trim() ? "name: expected non-empty text" : null);
7566
+ if (problem2) throw invalid4(problem2);
7142
7567
  let result = { ...args };
7143
- return args.path !== void 0 && (result.path = resolve10(args.path)), args.name !== void 0 && (result.name = args.name.trim()), operation === "upload-status" && (result.wait_seconds = args.wait_seconds ?? 0), result;
7568
+ return args.path !== void 0 && (result.path = resolve11(args.path)), args.name !== void 0 && (result.name = args.name.trim()), operation === "upload-status" && (result.wait_seconds = args.wait_seconds ?? 0), result;
7144
7569
  }
7145
7570
  var URL_FLAG = [];
7146
7571
  var ALLOWED = {
@@ -7247,14 +7672,14 @@ var HEX642 = "^[a-f0-9]{64}$", hexToken = { type: "string", pattern: HEX642 }, t
7247
7672
  "operation.inspect takes only {app_id, action, target_operation_id}; preview.page takes only {app_id, action, preview_id, cursor}.",
7248
7673
  "Invalid arguments return INVALID_ARGUMENT naming the field; nothing changes."
7249
7674
  ].join(`
7250
- `), plain3 = (value) => !!value && typeof value == "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype, fieldName2 = (name) => /^[A-Za-z_][\w.-]{0,40}$/.test(name) ? name : "an unrecognised field", ID_PATHS = [["app_id"], ["operation_id"], ["target_operation_id"], ["preview_id"], ["payload", "asset_id"], ["payload", "profile_id"], ["payload", "preview_id"], ["confirmation", "preview_id"]], lowerIds = (args) => {
7675
+ `), plain4 = (value) => !!value && typeof value == "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype, fieldName2 = (name) => /^[A-Za-z_][\w.-]{0,40}$/.test(name) ? name : "an unrecognised field", ID_PATHS = [["app_id"], ["operation_id"], ["target_operation_id"], ["preview_id"], ["payload", "asset_id"], ["payload", "profile_id"], ["payload", "preview_id"], ["confirmation", "preview_id"]], lowerIds = (args) => {
7251
7676
  let copy = { ...args };
7252
7677
  for (let [first, second] of ID_PATHS)
7253
- second ? plain3(copy[first]) && uuid3.test(copy[first][second] ?? "") && (copy[first] = { ...copy[first], [second]: copy[first][second].toLowerCase() }) : uuid3.test(copy[first] ?? "") && (copy[first] = copy[first].toLowerCase());
7254
- return plain3(copy.payload) && Array.isArray(copy.payload.asset_ids) && (copy.payload = { ...copy.payload, asset_ids: copy.payload.asset_ids.map((value) => uuid3.test(value ?? "") ? value.toLowerCase() : value) }), copy;
7678
+ second ? plain4(copy[first]) && uuid3.test(copy[first][second] ?? "") && (copy[first] = { ...copy[first], [second]: copy[first][second].toLowerCase() }) : uuid3.test(copy[first] ?? "") && (copy[first] = copy[first].toLowerCase());
7679
+ return plain4(copy.payload) && Array.isArray(copy.payload.asset_ids) && (copy.payload = { ...copy.payload, asset_ids: copy.payload.asset_ids.map((value) => uuid3.test(value ?? "") ? value.toLowerCase() : value) }), copy;
7255
7680
  };
7256
7681
  function explainMediaMutation(args) {
7257
- if (!plain3(args)) return "arguments: expected an object";
7682
+ if (!plain4(args)) return "arguments: expected an object";
7258
7683
  let { action } = args, list2 = mediaMutationActions.join(", ");
7259
7684
  if (action === void 0) return `action is required: one of ${list2}`;
7260
7685
  if (!mediaMutationActions.includes(action)) return `action: expected one of ${list2}`;
@@ -7267,18 +7692,18 @@ function explainMediaMutation(args) {
7267
7692
  }, missing = required.find((name) => args[name] === void 0);
7268
7693
  if (missing) return `${missing} is required for ${action}${hints[missing] ?? ""}`;
7269
7694
  for (let name of accepted.filter((name2) => !["action", "payload"].includes(name2))) {
7270
- let problem2 = args[name] !== void 0 && explainArguments(mediaMutationFields[name], args[name], name);
7271
- if (problem2) return problem2;
7695
+ let problem3 = args[name] !== void 0 && explainArguments(mediaMutationFields[name], args[name], name);
7696
+ if (problem3) return problem3;
7272
7697
  }
7273
7698
  if (args.mode === "preview" && args.confirmation !== void 0) return 'confirmation is not accepted with mode "preview"; send it on the commit request without mode';
7274
- if (action === "profile.update" && plain3(args.payload) && Object.keys(args.payload).join() === "profile_id")
7699
+ if (action === "profile.update" && plain4(args.payload) && Object.keys(args.payload).join() === "profile_id")
7275
7700
  return `payload: profile.update changes at least one of ${PROFILE_SETTINGS.join(", ")}`;
7276
- let schema = mediaPayloadSchema(action), problem = schema && explainArguments(schema, args.payload, "payload");
7277
- return problem || (action === "asset.rename" && [...args.payload.name.trim()].length > 200 ? "payload.name: expected 1 to 200 characters after trimming" : action.startsWith("profile.") && typeof args.payload.name == "string" && args.payload.name.trim().length > 80 ? "payload.name: expected 1 to 80 characters after trimming" : null);
7701
+ let schema = mediaPayloadSchema(action), problem2 = schema && explainArguments(schema, args.payload, "payload");
7702
+ return problem2 || (action === "asset.rename" && [...args.payload.name.trim()].length > 200 ? "payload.name: expected 1 to 200 characters after trimming" : action.startsWith("profile.") && typeof args.payload.name == "string" && args.payload.name.trim().length > 80 ? "payload.name: expected 1 to 80 characters after trimming" : null);
7278
7703
  }
7279
7704
  function normalizeMediaMutation(args) {
7280
- let input = plain3(args) ? lowerIds(args) : args, problem = explainMediaMutation(input);
7281
- if (problem) throw invalid4(problem);
7705
+ let input = plain4(args) ? lowerIds(args) : args, problem2 = explainMediaMutation(input);
7706
+ if (problem2) throw invalid4(problem2);
7282
7707
  return typeof input.payload?.name == "string" ? { ...input, payload: { ...input.payload, name: input.payload.name.trim() } } : input.action === "asset.delete" ? { ...input, mode: input.mode ?? "commit" } : input;
7283
7708
  }
7284
7709
  var SETTING_FLAGS = ["--name", "--max-height", "--scrub-previews", "--no-scrub-previews", "--segment-seconds"];
@@ -7698,13 +8123,13 @@ var liveOperations = Object.freeze({
7698
8123
  recordings: "get_live_recordings",
7699
8124
  "saved-recordings": "get_live_saved_recordings",
7700
8125
  preview: "create_live_preview"
7701
- }), UUID9 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", uuid4 = new RegExp(UUID9, "i"), closed4 = (properties, required) => ({ type: "object", properties, required, additionalProperties: !1 }), id8 = { type: "string", pattern: UUID9 }, limit2 = { type: "integer", minimum: 1, maximum: 100 }, cursor4 = { type: "string", minLength: 1, maxLength: 2048 }, READS = {
8126
+ }), UUID11 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", uuid4 = new RegExp(UUID11, "i"), closed4 = (properties, required) => ({ type: "object", properties, required, additionalProperties: !1 }), id8 = { type: "string", pattern: UUID11 }, limit2 = { type: "integer", minimum: 1, maximum: 100 }, cursor4 = { type: "string", minLength: 1, maxLength: 2048 }, READS = {
7702
8127
  list: closed4({ app_id: id8, status: { enum: ["live", "offline", "disabled"] }, limit: limit2, cursor: cursor4 }, ["app_id"]),
7703
8128
  get: closed4({ app_id: id8, entry_id: id8 }, ["app_id", "entry_id"]),
7704
8129
  viewers: closed4({ app_id: id8, entry_id: id8 }, ["app_id", "entry_id"]),
7705
8130
  recordings: closed4({ app_id: id8, limit: limit2, cursor: cursor4 }, ["app_id"]),
7706
8131
  "saved-recordings": closed4({ app_id: id8, entry_id: id8, limit: limit2, cursor: cursor4 }, ["app_id", "entry_id"]),
7707
- preview: closed4({ app_id: id8, entry_id: id8, operation_id: { type: "string", pattern: UUID9.replace("[1-8]", "[1-5]") } }, ["app_id", "entry_id", "operation_id"])
8132
+ preview: closed4({ app_id: id8, entry_id: id8, operation_id: { type: "string", pattern: UUID11.replace("[1-8]", "[1-5]") } }, ["app_id", "entry_id", "operation_id"])
7708
8133
  }, READ_TOOLS = {
7709
8134
  list: "List the app's live streams with their status (live, offline or disabled), latency, DVR and viewer-count settings; filter by status and page with cursor. Never returns stream keys or provider ids.",
7710
8135
  get: "Read one live record: provisioning state, the stream with its pending changes, streamRevision and recording settings, and the schedule with its revision and next announcement.",
@@ -7757,34 +8182,34 @@ var liveOperations = Object.freeze({
7757
8182
  annotations: { readOnlyHint: !1, destructiveHint: !0, idempotentHint: !0 },
7758
8183
  inputSchema: mutateSchema
7759
8184
  })
7760
- ]), invalid5 = (detail) => Object.assign(Error("INVALID_ARGUMENT"), { detail }), plain4 = (value) => !!value && typeof value == "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype, lower = (value) => typeof value == "string" && uuid4.test(value) ? value.toLowerCase() : value, lowerIn = (value, names) => plain4(value) ? { ...value, ...Object.fromEntries(names.filter((name) => Object.hasOwn(value, name)).map((name) => [name, lower(value[name])])) } : value;
8185
+ ]), invalid5 = (detail) => Object.assign(Error("INVALID_ARGUMENT"), { detail }), plain5 = (value) => !!value && typeof value == "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype, lower = (value) => typeof value == "string" && uuid4.test(value) ? value.toLowerCase() : value, lowerIn = (value, names) => plain5(value) ? { ...value, ...Object.fromEntries(names.filter((name) => Object.hasOwn(value, name)).map((name) => [name, lower(value[name])])) } : value;
7761
8186
  function normalizeLiveRead(operation, args) {
7762
8187
  if (!Object.hasOwn(READS, operation ?? "")) throw invalid5(`operation: expected one of ${Object.keys(READS).join(", ")}`);
7763
- if (!plain4(args)) throw invalid5("arguments: expected an object");
7764
- let input = lowerIn(args, ["app_id", "entry_id"]), problem = explainArguments(READS[operation], input) ?? (typeof input.cursor == "string" && !input.cursor.trim() ? "cursor: expected non-empty text" : null);
7765
- if (problem) throw invalid5(problem);
8188
+ if (!plain5(args)) throw invalid5("arguments: expected an object");
8189
+ let input = lowerIn(args, ["app_id", "entry_id"]), problem2 = explainArguments(READS[operation], input) ?? (typeof input.cursor == "string" && !input.cursor.trim() ? "cursor: expected non-empty text" : null);
8190
+ if (problem2) throw invalid5(problem2);
7766
8191
  return input;
7767
8192
  }
7768
8193
  function lowerIds2(args) {
7769
8194
  let payload = lowerIn(args.payload, ["entry_id", "recording_id", "target_operation_id", "preview_id"]);
7770
- return plain4(payload?.settings) && (payload.settings = lowerIn(payload.settings, ["folder_id"])), plain4(payload?.recordings) && Array.isArray(payload.recordings.entry_ids) && (payload.recordings = { ...payload.recordings, entry_ids: payload.recordings.entry_ids.map(lower) }), {
8195
+ return plain5(payload?.settings) && (payload.settings = lowerIn(payload.settings, ["folder_id"])), plain5(payload?.recordings) && Array.isArray(payload.recordings.entry_ids) && (payload.recordings = { ...payload.recordings, entry_ids: payload.recordings.entry_ids.map(lower) }), {
7771
8196
  ...lowerIn(args, ["app_id", "operation_id"]),
7772
8197
  ...Object.hasOwn(args, "payload") ? { payload } : {},
7773
8198
  ...Object.hasOwn(args, "confirmation") ? { confirmation: lowerIn(args.confirmation, ["preview_id"]) } : {}
7774
8199
  };
7775
8200
  }
7776
8201
  function normalizeLiveMutation(args) {
7777
- if (!plain4(args)) throw invalid5("arguments: expected an object");
7778
- let input = lowerIds2(args.operation_id === void 0 ? { ...args, operation_id: randomUUID6() } : args), problem = explainLiveMutation(input), schedule3 = input.payload?.schedule;
7779
- if (input.action === "schedule.set" && plain4(schedule3) && (!problem || problem.startsWith("payload.schedule")))
8202
+ if (!plain5(args)) throw invalid5("arguments: expected an object");
8203
+ let input = lowerIds2(args.operation_id === void 0 ? { ...args, operation_id: randomUUID6() } : args), problem2 = explainLiveMutation(input), schedule3 = input.payload?.schedule;
8204
+ if (input.action === "schedule.set" && plain5(schedule3) && (!problem2 || problem2.startsWith("payload.schedule")))
7780
8205
  try {
7781
8206
  liveScheduleAt(schedule3);
7782
8207
  } catch (error) {
7783
8208
  if (error.message === "SCHEDULE_ZONE_REQUIRED") throw error;
7784
8209
  }
7785
- let listed = input.action === "stream.delete" && plain4(input.payload?.recordings) && Object.keys(input.payload.recordings).join() === "entry_ids" ? input.payload.recordings.entry_ids : null;
7786
- if (problem?.startsWith("payload.recordings.entry_ids") && Array.isArray(listed) && listed.length > 100) throw Error("LIVE_DELETE_SELECTION_TOO_LARGE");
7787
- if (problem) throw invalid5(problem);
8210
+ let listed = input.action === "stream.delete" && plain5(input.payload?.recordings) && Object.keys(input.payload.recordings).join() === "entry_ids" ? input.payload.recordings.entry_ids : null;
8211
+ if (problem2?.startsWith("payload.recordings.entry_ids") && Array.isArray(listed) && listed.length > 100) throw Error("LIVE_DELETE_SELECTION_TOO_LARGE");
8212
+ if (problem2) throw invalid5(problem2);
7788
8213
  return input;
7789
8214
  }
7790
8215
  var localRefusal = (error) => error?.message === "SCHEDULE_ZONE_REQUIRED" ? liveFailure("SCHEDULE_ZONE_REQUIRED") : error?.message === "LIVE_DELETE_SELECTION_TOO_LARGE" ? liveFailure("LIVE_DELETE_SELECTION_TOO_LARGE", void 0, { field: "payload.recordings.entry_ids" }) : liveFailure("INVALID_ARGUMENT", error?.detail);
@@ -7806,7 +8231,7 @@ async function liveMutate(remote2, args) {
7806
8231
  try {
7807
8232
  request = normalizeLiveMutation(args);
7808
8233
  } catch (error) {
7809
- return { ...localRefusal(error), ...plain4(args) && uuid4.test(args.operation_id ?? "") ? { operationId: args.operation_id.toLowerCase() } : {} };
8234
+ return { ...localRefusal(error), ...plain5(args) && uuid4.test(args.operation_id ?? "") ? { operationId: args.operation_id.toLowerCase() } : {} };
7810
8235
  }
7811
8236
  let operationId = request.operation_id;
7812
8237
  if (request.action === "stream.reset" && request.mode !== "preview")
@@ -7851,7 +8276,7 @@ adelin live <command> --help shows one command.
7851
8276
  `;
7852
8277
 
7853
8278
  // skills/adelin-app-generation/scripts/live-credentials.mjs
7854
- var UUID10 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
8279
+ var UUID12 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
7855
8280
  var READ_CODES2 = ["INVALID_ARGUMENT", "ACCESS_DENIED", "NOT_FOUND", "RETRYABLE_CONFLICT", "LIVE_ENTRY_UNAVAILABLE", "MUTATION_UNAVAILABLE", ...LIVE_FUNDED_CODES], RESET_CODES = [
7856
8281
  ...READ_CODES2,
7857
8282
  "OPERATION_PAYLOAD_CONFLICT",
@@ -7867,12 +8292,12 @@ var URL_HELP3 = "", SYNTAX4 = {
7867
8292
  credentials: `--app <UUID> --entry <UUID> --out DIR${URL_HELP3}`,
7868
8293
  reset: `--app <UUID> --entry <UUID> --out DIR --operation-id <UUID> --confirmation-file FILE${URL_HELP3} (preview first: adelin live mutate --action stream.reset --mode preview)`
7869
8294
  };
7870
- var placeholder = (value, name) => typeof value == "string" && UUID10.test(value) ? value.toLowerCase() : name;
8295
+ var placeholder = (value, name) => typeof value == "string" && UUID12.test(value) ? value.toLowerCase() : name;
7871
8296
  function credentialsCliOnlyRefusal(args) {
7872
8297
  let app = placeholder(args?.app_id, "APP"), entry = placeholder(args?.entry_id, "ENTRY");
7873
8298
  return { ok: !1, error: { code: "LIVE_CREDENTIALS_CLI_ONLY", message: `Broadcast credentials never reach an agent; the Adelin CLI writes them to a private file. Read them with: adelin live credentials --app ${app} --entry ${entry} --out DIR. To reset the key, preview stream.reset with mode "preview" (live_mutate or adelin live mutate --action stream.reset --mode preview), then run: adelin live reset --app ${app} --entry ${entry} --out DIR --operation-id OP --confirmation-file FILE` } };
7874
8299
  }
7875
- var id9 = { type: "string", pattern: UUID10.source }, liveCredentialsTool = Object.freeze({
8300
+ var id9 = { type: "string", pattern: UUID12.source }, liveCredentialsTool = Object.freeze({
7876
8301
  name: "live_credentials",
7877
8302
  description: "Broadcast credentials (stream key, SRT stream id and passphrase) are never returned to agents. This tool always refuses with LIVE_CREDENTIALS_CLI_ONLY and names the Adelin CLI commands that write them to a private file for the user.",
7878
8303
  annotations: { readOnlyHint: !0, destructiveHint: !1 },
@@ -7900,8 +8325,8 @@ var previewTools = PREVIEW_TOOL_NAMES.map((name) => {
7900
8325
  429: "Too many device actions. Wait about a minute, then continue.",
7901
8326
  502: "The device did not respond. Wait a moment and try again."
7902
8327
  };
7903
- function deviceContent(reply) {
7904
- let { status: status2, result } = reply ?? {};
8328
+ function deviceContent(reply2) {
8329
+ let { status: status2, result } = reply2 ?? {};
7905
8330
  if (status2 === 200 && result?.kind === "image" && typeof result.dataUrl == "string")
7906
8331
  return { content: [{ type: "image", mimeType: result.mediaType ?? "image/jpeg", data: result.dataUrl.split(",")[1] ?? "" }] };
7907
8332
  if (status2 === 200) return { content: [{ type: "text", text: JSON.stringify(result ?? {}) }] };
@@ -7920,7 +8345,7 @@ var INSTALLING_REASON = "Downloading the preview browser (about 130 MB) once. Ca
7920
8345
  function createLocalPreviewBrowser({ previewPass, env = process.env, load = () => Promise.resolve().then(() => (init_src(), src_exports)) }) {
7921
8346
  let shared = null, page2 = null, pageStarting = null, pageShown = !1, generation = 0, viewers = 0, releaseHold = null, browserState = "down", browserListeners = /* @__PURE__ */ new Set(), renewGrant = async (target2) => {
7922
8347
  try {
7923
- let reply = await previewPass({ target: target2, pass: !0 }), route = reply?.status === 200 ? reply.result : null;
8348
+ let reply2 = await previewPass({ target: target2, pass: !0 }), route = reply2?.status === 200 ? reply2.result : null;
7924
8349
  return route?.route === "browser" && typeof route.grant == "string" ? route.grant : null;
7925
8350
  } catch {
7926
8351
  return null;
@@ -8024,154 +8449,6 @@ function createLocalPreviewBrowser({ previewPass, env = process.env, load = () =
8024
8449
  };
8025
8450
  }
8026
8451
 
8027
- // skills/adelin-app-generation/scripts/local-build-transport.mjs
8028
- import { createHash as createHash5, generateKeyPairSync as generateKeyPairSync3, randomBytes as randomBytes6, sign as sign2 } from "node:crypto";
8029
- var ACTION = Object.freeze({
8030
- heartbeat_edit_session: "heartbeat",
8031
- save_app_changes: "build",
8032
- prepare_build: "prepare",
8033
- reconcile_save: "reconcile",
8034
- close_edit_session: "close",
8035
- tell_builder: "note",
8036
- ask_builder: "ask",
8037
- choice_status: "choice",
8038
- record_choice: "choose",
8039
- request_device: "device_request",
8040
- device_status: "device_status",
8041
- device_operation: "device",
8042
- preview_pass: "preview_pass",
8043
- agent_view: "agent_view",
8044
- handover_edit_session: "handover"
8045
- }), MAX_DEVICE_BYTES = 3 * 1024 * 1024;
8046
- function sameTuple(a, b) {
8047
- return a.app === b.appId && a.lease === b.leaseId && a.chat === b.chatSessionId && a.epoch === b.epoch;
8048
- }
8049
- var UUID11 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/, STAGING_PATH = /^\/adelin-(prod|dev)-compiler-staging\/[A-Za-z0-9-]{1,64}\/([a-f0-9-]{36})\/source\.json$/, R2_HOST = /^[a-f0-9]{32}\.r2\.cloudflarestorage\.com$/;
8050
- var TICKET_HEADERS = "content-length,if-none-match,x-amz-checksum-sha256";
8051
- function stagingTarget(ticket, body) {
8052
- let target2;
8053
- try {
8054
- target2 = new URL(ticket.url);
8055
- } catch {
8056
- throw new Error("Invalid staging upload.");
8057
- }
8058
- let r2 = target2.protocol === "https:" && !target2.port && R2_HOST.test(target2.hostname), local = !1, headers = ticket.headers !== null && typeof ticket.headers == "object" ? ticket.headers : {}, [, bucketEnv, pathJobId] = STAGING_PATH.exec(target2.pathname) ?? [];
8059
- if (!(r2 || local) || target2.username || target2.password || target2.hash || bucketEnv !== "prod" || !UUID11.test(ticket.jobId) || pathJobId !== ticket.jobId || Object.keys(headers).sort().join() !== TICKET_HEADERS || headers["content-length"] !== String(Buffer.byteLength(body)) || headers["if-none-match"] !== "*" || headers["x-amz-checksum-sha256"] !== createHash5("sha256").update(body).digest("base64") || !Number.isSafeInteger(ticket.expiresAt) || ticket.expiresAt <= Date.now()) throw new Error("Invalid staging upload.");
8060
- return target2;
8061
- }
8062
- var SERVER_CODE = /^[A-Z][A-Z0-9_]{2,63}$/;
8063
- function cleanServerMessage(value) {
8064
- return typeof value == "string" ? value.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, 500) : "";
8065
- }
8066
- async function rejection(response2, action) {
8067
- let serverCode, serverMessage = "";
8068
- try {
8069
- let parsed = JSON.parse((await response2.text()).slice(0, 4096));
8070
- typeof parsed?.error == "string" && SERVER_CODE.test(parsed.error) && (serverCode = parsed.error, serverMessage = cleanServerMessage(parsed.message));
8071
- } catch {
8072
- }
8073
- return Object.assign(
8074
- new Error(`Adelin rejected the local ${action} request (${response2.status}).`),
8075
- { status: response2.status, action, ...serverCode && { serverCode }, ...serverMessage && { serverMessage } }
8076
- );
8077
- }
8078
- var LocalBuildTransport = class {
8079
- constructor(mcpUrl, fetcher = fetch, { release: release2 = null } = {}) {
8080
- this.url = new URL(validateMcpUrl(mcpUrl)), this.fetcher = fetcher, this.privateKey = null, this.publicKey = null, this.token = null, this.tuple = null, this.expiresAt = 0, this.release = release2, this.continuation = null;
8081
- }
8082
- prepare(appId) {
8083
- if (this.privateKey) throw new Error("A local build is already prepared.");
8084
- let keys3 = generateKeyPairSync3("ed25519");
8085
- return this.privateKey = keys3.privateKey, this.publicKey = keys3.publicKey.export({ format: "der", type: "spki" }).toString("base64url"), this.appId = appId, this.publicKey;
8086
- }
8087
- attach(token2, tuple) {
8088
- if (!this.privateKey || typeof token2 != "string" || token2.length > 8192 || !/^[A-Za-z0-9_.-]+$/.test(token2) || tuple.appId !== this.appId)
8089
- throw new Error("Invalid local build authorization.");
8090
- let claims;
8091
- try {
8092
- claims = JSON.parse(Buffer.from(token2.split(".")[1], "base64url").toString("utf8"));
8093
- } catch {
8094
- throw new Error("Invalid local build authorization.");
8095
- }
8096
- if (token2.split(".").length !== 3 || claims.key !== this.publicKey || !sameTuple(claims, tuple) || !Number.isSafeInteger(claims.exp) || claims.exp * 1e3 <= Date.now()) throw new Error("Local build authorization does not match this app.");
8097
- this.token = token2, this.tuple = tuple, this.expiresAt = claims.exp * 1e3;
8098
- }
8099
- detach() {
8100
- this.privateKey = null, this.publicKey = null, this.token = null, this.tuple = null, this.appId = null, this.expiresAt = 0, this.continuation = null;
8101
- }
8102
- async handover(release2) {
8103
- if (!this.tuple) {
8104
- this.release = release2;
8105
- return;
8106
- }
8107
- let result = await this.request("handover_edit_session", { version: release2.version, contractId: release2.contractId }, { release: release2 }), value = JSON.parse(result.content[0].text);
8108
- this.attach(value.token, this.tuple), this.release = release2;
8109
- }
8110
- async call(name, args) {
8111
- if (name === "save_app_changes") {
8112
- let body = JSON.stringify({ files: args.files }), files = args.files.map((file) => ({
8113
- path: file.path,
8114
- baseVersion: file.baseVersion,
8115
- hash: createHash5("sha256").update(file.content, "utf8").digest("hex"),
8116
- bytes: Buffer.byteLength(file.content)
8117
- })), upload = { digest: createHash5("sha256").update(body).digest("hex"), bytes: Buffer.byteLength(body) }, prepared = await this.request("prepare_build", { ...args, files, upload }), ticket = JSON.parse(prepared.content[0].text);
8118
- if (ticket?.error) return prepared;
8119
- let target2 = stagingTarget(ticket, body), uploaded = await this.fetcher(target2, {
8120
- method: "PUT",
8121
- redirect: "error",
8122
- headers: ticket.headers,
8123
- body,
8124
- signal: AbortSignal.timeout(3e4)
8125
- });
8126
- if (await uploaded.body?.cancel(), !uploaded.ok) throw new Error("Source upload failed. No build was saved.");
8127
- return this.request(name, { ...args, files, jobId: ticket.jobId, upload });
8128
- }
8129
- return this.request(name, args);
8130
- }
8131
- async request(name, args, { release: release2 = this.release } = {}) {
8132
- if (!this.privateKey || !this.token || !this.tuple || !(name in ACTION))
8133
- throw new Error("No authorized local build session.");
8134
- let action = ACTION[name], path = `/v1/local-builder/${action}`, tuple = {
8135
- app_id: this.tuple.appId,
8136
- lease_id: this.tuple.leaseId,
8137
- chat_session_id: this.tuple.chatSessionId,
8138
- epoch: this.tuple.epoch
8139
- }, body = Buffer.from(JSON.stringify({ ...tuple, ...args }), "utf8"), timestamp2 = String(Date.now()), nonce = randomBytes6(24).toString("base64url"), digest4 = createHash5("sha256").update(body).digest("hex"), bytes2 = Buffer.from(`POST
8140
- ${path}
8141
- ${timestamp2}
8142
- ${nonce}
8143
- ${digest4}`), signature = sign2(null, bytes2, this.privateKey).toString("base64url"), url = new URL(path, this.url), response2 = await this.fetcher(url, {
8144
- method: "POST",
8145
- redirect: "error",
8146
- headers: {
8147
- "Content-Type": "application/json",
8148
- Authorization: `Bearer ${this.token}`,
8149
- ...release2 && { "X-Adelin-Cli-Version": release2.version, "X-Adelin-Authoring-Contract": release2.contractId },
8150
- ...this.continuation && { "X-Adelin-Continuation": this.continuation },
8151
- "X-Adelin-Timestamp": timestamp2,
8152
- "X-Adelin-Nonce": nonce,
8153
- "X-Adelin-Signature": signature
8154
- },
8155
- body,
8156
- signal: AbortSignal.timeout(["build", "prepare"].includes(action) ? 12e4 : action === "device" ? 45e3 : 15e3)
8157
- }), refusal3 = response2.status === 400 && (action === "ask" || action === "choose");
8158
- if (response2.status === 426)
8159
- throw await response2.body?.cancel(), Object.assign(new Error("Adelin authoring needs an update. Run adelin setup."), { code: "UPDATE_REQUIRED" });
8160
- if (!response2.ok && !refusal3) throw await rejection(response2, action);
8161
- let continuation = response2.headers?.get("x-adelin-continuation");
8162
- if (continuation) {
8163
- if (continuation.length > 16384 || !/^[A-Za-z0-9_.-]+$/.test(continuation)) throw new Error("Invalid build continuation.");
8164
- this.continuation = continuation;
8165
- }
8166
- let text4 = await response2.text();
8167
- if (Buffer.byteLength(text4, "utf8") > (action === "device" ? MAX_DEVICE_BYTES : 2 * 1024 * 1024)) throw new Error("Adelin build response is too large.");
8168
- return { content: [{ type: "text", text: text4 }] };
8169
- }
8170
- async close() {
8171
- this.detach();
8172
- }
8173
- };
8174
-
8175
8452
  // skills/adelin-app-generation/scripts/cli-auth.mjs
8176
8453
  import { spawn as spawn3 } from "node:child_process";
8177
8454
  var MAX_AUTH_BYTES = 16 * 1024, MAX_FILE_BYTES = 64 * 1024, LOGIN_TIMEOUT_MS = 5 * 6e4;
@@ -8262,21 +8539,31 @@ var AppMemoryDocumentSchema = z3.strictObject(documentShape).refine(currentDocum
8262
8539
  };
8263
8540
 
8264
8541
  // skills/adelin-app-generation/scripts/local-builder.mjs
8265
- var UUID12 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", ARTIFACT_TOOLS = ["create_artifact", "update_artifact", "read_artifact", "list_artifacts", "share_artifact", "delete_artifact"], exposed = /* @__PURE__ */ new Set([
8542
+ var UUID13 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", ARTIFACT_TOOLS = ["create_artifact", "update_artifact", "read_artifact", "list_artifacts", "share_artifact", "delete_artifact"], ACCESS_TOOLS = [
8543
+ "read_access",
8544
+ "explain_access",
8545
+ "check_access_change",
8546
+ "save_access_offer",
8547
+ "set_access_coverage",
8548
+ "set_access_level",
8549
+ "archive_access_offer"
8550
+ ], TEXT_REPLY_TOOLS = /* @__PURE__ */ new Set([...ACCESS_TOOLS, "search_icons"]), CODED_REFUSAL_TOOLS = /* @__PURE__ */ new Set([...ARTIFACT_TOOLS, "list_assets"]), MAX_TEXT_REPLY_BYTES = 512 * 1024, exposed = /* @__PURE__ */ new Set([
8266
8551
  "connection_status",
8267
8552
  "select_app",
8268
8553
  "list_editable_apps",
8269
8554
  "list_app_templates",
8270
8555
  "list_app_organizations",
8271
8556
  "get_content_schema",
8557
+ "list_assets",
8272
8558
  ...Object.keys(APP_REQUIREMENTS_TOOLS),
8273
8559
  ...Object.keys(APP_MEMORY_TOOLS),
8274
- ...ARTIFACT_TOOLS
8275
- ]), metadataTools = { ...APP_REQUIREMENTS_TOOLS, ...APP_MEMORY_TOOLS }, metadataWrites = /* @__PURE__ */ new Set(["update_app_requirements", "mutate_app_memory"]), privateMetadataFields = ["lease_id", "chat_session_id", "epoch", "resume_proof"], CREATION_POLL_MS = 250, CREATION_WAIT_MS = 25e3, appDenied = "This connection can't access this app. Open Settings \u2192 Connected code agents \u2192 Manage apps to review its access.", saveDenied = "App access was removed or this connection ended. Your local files are unchanged. Review access in Settings before trying again.", VIEW_RETRY_MS = 500, VIEW_RETRY_MAX_MS = 3e4, remoteFailed = "Adelin request failed. Try again.", CREATION_TOOLS = /* @__PURE__ */ new Set(["list_app_templates", "list_app_organizations", "create_app", "advance_app_creation"]), creationUnavailable = "App creation isn't available for this connection. Run adelin login and allow private file transfers when you sign in.", toolUnavailable = "This Adelin tool isn't available for this connection. Run adelin login to sign in again.", saveFailed = "Adelin request failed. Your local files are unchanged. Try again.", NO_APPS_HINT = "No apps are available to this connection. Call list_app_organizations and create_app to make one, or approve apps in Settings \u2192 Connected code agents \u2192 Manage apps.", SERVER_CODE2 = /^[A-Z][A-Z0-9_]{2,63}$/, REJECTED = /^Adelin rejected the local (\w+) request \((\d{3})\)\.$/, SAVE_ACTIONS = ["heartbeat", "prepare", "build", "reconcile", "close", "agent_view"], choiceRefusals = {
8560
+ ...ARTIFACT_TOOLS,
8561
+ ...TEXT_REPLY_TOOLS
8562
+ ]), metadataTools = { ...APP_REQUIREMENTS_TOOLS, ...APP_MEMORY_TOOLS }, metadataWrites = /* @__PURE__ */ new Set(["update_app_requirements", "mutate_app_memory"]), privateMetadataFields = ["lease_id", "chat_session_id", "epoch", "resume_proof"], CREATION_POLL_MS = 250, CREATION_WAIT_MS = 25e3, appDenied = "This connection can't access this app. Open Settings \u2192 Connected code agents \u2192 Manage apps to review its access.", saveDenied = "App access was removed or this connection ended. Your local files are unchanged. Review access in Settings before trying again.", VIEW_RETRY_MS = 500, VIEW_RETRY_MAX_MS = 3e4, remoteFailed = "Adelin request failed. Try again.", CREATION_TOOLS = /* @__PURE__ */ new Set(["list_app_templates", "list_app_organizations", "create_app", "advance_app_creation"]), creationUnavailable = "App creation isn't available for this connection. Run adelin login --force and allow private file transfers when you sign in.", toolUnavailable = "This Adelin tool isn't available for this connection. Run adelin login --force to sign in again.", saveFailed = "Adelin request failed. Your local files are unchanged. Try again.", NO_APPS_HINT = "No apps are available to this connection. Call list_app_organizations and create_app to make one, or approve apps in Settings \u2192 Connected code agents \u2192 Manage apps.", SERVER_CODE3 = /^[A-Z][A-Z0-9_]{2,63}$/, REJECTED = /^Adelin rejected the local (\w+) request \((\d{3})\)\.$/, SAVE_ACTIONS = ["heartbeat", "prepare", "build", "reconcile", "close", "agent_view"], choiceRefusals = {
8276
8563
  DESIGNS_NOT_IN_SESSION: "Offer 1\u20134 designs you created or revised with create_artifact or update_artifact while this app was open.",
8277
8564
  CHOICE_REFUSED: "That design is not one of the options, or the session has ended."
8278
8565
  }, fields = {
8279
- app_id: { type: "string", pattern: UUID12 },
8566
+ app_id: { type: "string", pattern: UUID13 },
8280
8567
  workspace: { type: "string", minLength: 1 }
8281
8568
  }, noArgs = { type: "object", properties: {}, additionalProperties: !1 }, id10 = fields.app_id, closed5 = (properties, required = [], extra = {}) => ({ type: "object", properties, required, additionalProperties: !1, ...extra }), unless = (keys3) => ({ not: { anyOf: keys3.map((key4) => ({ required: [key4] })) } }), actionRules = [
8282
8569
  ...mutationPayloads.map(([actions, payload]) => ({ if: { properties: { action: { enum: actions } } }, then: { properties: { payload } } })),
@@ -8390,7 +8677,7 @@ var UUID12 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-
8390
8677
  description: "Create a new Adelin app, from a template (template_id and template_digest from list_app_templates) or from scratch (languages, the first is primary, and sample_content, possibly empty). Waits until the app is ready, up to about 45 seconds. After state ready, call open_app with the returned app_id to start editing. If state is waiting, call resume_app_creation. Every result after the app exists carries app_id, creation_id and idempotency_key; never create another app for a creation you can resume. Errors such as APP_PLAN_LIMIT are returned as they are; show upgradeUrl to the user.",
8391
8678
  annotations: { readOnlyHint: !1, destructiveHint: !1, idempotentHint: !0 },
8392
8679
  inputSchema: closed5({
8393
- organization_id: { type: "string", pattern: UUID12 },
8680
+ organization_id: { type: "string", pattern: UUID13 },
8394
8681
  name: { type: "string", minLength: 3, maxLength: 256 },
8395
8682
  devices: { type: "array", minItems: 1, maxItems: 3, uniqueItems: !0, items: { enum: ["mobile", "web", "tv"] } },
8396
8683
  start: { oneOf: [
@@ -8419,8 +8706,12 @@ var UUID12 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-
8419
8706
  additionalProperties: !1
8420
8707
  }
8421
8708
  },
8422
- { name: "build_app", description: "Compile and save changed local app files.", inputSchema: noArgs },
8423
- { name: "check_app", description: "Run the advisory local TypeScript check.", inputSchema: noArgs },
8709
+ {
8710
+ name: "build_app",
8711
+ description: `Save new or changed images in the workspace's root ${ASSETS_FOLDER}/ folder as app assets, then compile and save changed local app files. List in replace_assets only the images the builder asked to replace that the app already has from elsewhere.`,
8712
+ inputSchema: closed5({ replace_assets: { type: "array", maxItems: 50, uniqueItems: !0, items: { type: "string", minLength: 5, maxLength: 69 } } })
8713
+ },
8714
+ { name: "check_app", description: `Run the advisory local TypeScript check and check the images in ${ASSETS_FOLDER}/ that the next build will save.`, inputSchema: noArgs },
8424
8715
  { name: "reconcile_build", description: "Reconcile an interrupted build.", inputSchema: noArgs },
8425
8716
  { name: "retry_build", description: "Retry an exact pending build after reconciliation.", inputSchema: noArgs },
8426
8717
  { name: "build_status", description: "Read the current local edit session.", inputSchema: noArgs },
@@ -8436,21 +8727,21 @@ var UUID12 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-
8436
8727
  description: "Ask the builder to choose between 1\u20134 design artifacts you created or revised while this app was open. Adelin shows them in the live session; waits up to 45 seconds and returns the pick, or state waiting with a request_id.",
8437
8728
  annotations: { readOnlyHint: !1, destructiveHint: !1 },
8438
8729
  inputSchema: closed5({
8439
- artifact_ids: { type: "array", minItems: 1, maxItems: 4, uniqueItems: !0, items: { type: "string", pattern: UUID12 } },
8730
+ artifact_ids: { type: "array", minItems: 1, maxItems: 4, uniqueItems: !0, items: { type: "string", pattern: UUID13 } },
8440
8731
  question: { type: "string", minLength: 1, maxLength: 140, pattern: "^[^\\u0000-\\u001f\\u007f]+$" }
8441
8732
  }, ["artifact_ids"])
8442
8733
  },
8443
8734
  {
8444
8735
  name: "request_device",
8445
- description: "After a build that saved files, ask the builder to start a cloud TV or phone so you can check your work. Waits for the answer and for the device to finish starting; returns ready, declined, ended, or waiting or starting with a request_id.",
8736
+ description: "Ask the builder to start a cloud TV or phone, at any time in the session, to check or debug the app. platform tv or phone lets the builder pick the kind; tvos (Apple TV), android-tv, ios (iPhone) or android asks for that exact platform. Waits for the answer and for the device to finish starting; returns ready with the started platform, declined, ended, or waiting or starting with a request_id.",
8446
8737
  annotations: { readOnlyHint: !1, destructiveHint: !1 },
8447
- inputSchema: closed5({ platform: { enum: ["tv", "phone"] }, reason: { type: "string", minLength: 1, maxLength: 140, pattern: "^[^\\u0000-\\u001f\\u007f]+$" } }, ["platform"])
8738
+ inputSchema: closed5({ platform: { enum: ["tv", "phone", "tvos", "android-tv", "ios", "android"] }, reason: { type: "string", minLength: 1, maxLength: 140, pattern: "^[^\\u0000-\\u001f\\u007f]+$" } }, ["platform"])
8448
8739
  },
8449
8740
  {
8450
8741
  name: "wait_for_device",
8451
8742
  description: "Keep waiting for the builder to answer a request_device call, or for the started device to respond.",
8452
8743
  annotations: { readOnlyHint: !0 },
8453
- inputSchema: closed5({ request_id: { type: "string", pattern: UUID12 } }, ["request_id"])
8744
+ inputSchema: closed5({ request_id: { type: "string", pattern: UUID13 } }, ["request_id"])
8454
8745
  },
8455
8746
  ...previewTools.map(({ name, description: description2, annotations, inputSchema }) => ({ name, description: description2, annotations, inputSchema })),
8456
8747
  {
@@ -8463,15 +8754,15 @@ var UUID12 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-
8463
8754
  name: "wait_for_choice",
8464
8755
  description: "Keep waiting up to 45 seconds for the builder to answer an ask_builder_to_choose request.",
8465
8756
  annotations: { readOnlyHint: !0 },
8466
- inputSchema: closed5({ request_id: { type: "string", pattern: UUID12 } }, ["request_id"])
8757
+ inputSchema: closed5({ request_id: { type: "string", pattern: UUID13 } }, ["request_id"])
8467
8758
  },
8468
8759
  {
8469
8760
  name: "record_choice",
8470
8761
  description: "Record the design the builder picked in the terminal, so the dashboard shows it. If they already picked in the dashboard, returns that earlier pick instead.",
8471
8762
  annotations: { readOnlyHint: !1, destructiveHint: !1, idempotentHint: !0 },
8472
8763
  inputSchema: closed5({
8473
- request_id: { type: "string", pattern: UUID12 },
8474
- artifact_id: { type: "string", pattern: UUID12 },
8764
+ request_id: { type: "string", pattern: UUID13 },
8765
+ artifact_id: { type: "string", pattern: UUID13 },
8475
8766
  note: { type: "string", minLength: 1, maxLength: 300 }
8476
8767
  }, ["request_id", "artifact_id"])
8477
8768
  }
@@ -8507,7 +8798,7 @@ function valueOf(result, saving = !1, limit3 = 2 * 1024 * 1024) {
8507
8798
  if (!value || typeof value != "object" || Array.isArray(value))
8508
8799
  throw new Error("Adelin returned an invalid tool result.");
8509
8800
  if (result.isError || "error" in value)
8510
- throw value.error === "UPDATE_REQUIRED" ? updateRequired() : value.error === "INVALID_ARGUMENT" ? invalidArgument() : Object.hasOwn(choiceRefusals, value.error) ? new Error(choiceRefusals[value.error]) : value.error === "APP_NOT_EDITABLE" || value.error === "UNAUTHORIZED" ? new Error(saving ? saveDenied : appDenied) : typeof value.error == "string" && SERVER_CODE2.test(value.error) ? reported(value.error, cleanServerMessage(value.message) || `Adelin refused the request (${value.error}).`) : new Error(saving ? saveFailed : remoteFailed);
8801
+ throw value.error === "UPDATE_REQUIRED" ? updateRequired() : value.error === "INVALID_ARGUMENT" ? invalidArgument() : Object.hasOwn(choiceRefusals, value.error) ? new Error(choiceRefusals[value.error]) : value.error === "APP_NOT_EDITABLE" || value.error === "UNAUTHORIZED" ? new Error(saving ? saveDenied : appDenied) : typeof value.error == "string" && SERVER_CODE3.test(value.error) ? reported(value.error, cleanServerMessage(value.message) || `Adelin refused the request (${value.error}).`) : new Error(saving ? saveFailed : remoteFailed);
8511
8802
  return value;
8512
8803
  }
8513
8804
  var reported = (code, message, extra = {}) => Object.assign(new Error(message), { code, expose: !0, ...extra }), transient = (error) => error?.expose === !0 && (error.code === "REQUEST_TIMEOUT" || error.code === "REMOTE_UNAVAILABLE" && !(error.status < 500));
@@ -8518,7 +8809,7 @@ function remoteError(error, saving = !1, name = "") {
8518
8809
  if (code === "UPDATE_REQUIRED") return updateRequired();
8519
8810
  if (code === "AUTH_REQUIRED") return reported("SIGN_IN_REQUIRED", "Run adelin login.");
8520
8811
  let rejected = REJECTED.exec(error instanceof Error ? error.message : ""), status2 = Number.isSafeInteger(error?.status) ? error.status : rejected ? Number(rejected[2]) : void 0, action = error?.action ?? rejected?.[1];
8521
- return saving && (status2 === 401 || status2 === 403) && SAVE_ACTIONS.includes(action) ? new Error(saveDenied) : code === "ACCESS_DENIED" ? reported(code, appDenied, { status: status2 }) : code === "APP_SELECTION_CHANGED" ? reported(code, "App access changed while this request ran. Retry it, and run adelin login if it happens again.", { status: status2 }) : code === "REQUEST_TIMEOUT" ? reported(code, "Adelin did not answer in time. Try again.") : typeof error?.serverCode == "string" ? reported(error.serverCode, error.serverMessage || `Adelin refused the ${action ?? "request"} (${error.serverCode}, HTTP ${status2}).`, { status: status2 }) : status2 !== void 0 ? reported("REMOTE_UNAVAILABLE", `Adelin answered HTTP ${status2}${action ? ` to the ${action} request` : ""}.`, { status: status2 }) : code === "REMOTE_UNAVAILABLE" ? reported(code, "Adelin could not be reached. Try again shortly.") : new Error(saving ? saveFailed : remoteFailed);
8812
+ return saving && (status2 === 401 || status2 === 403) && SAVE_ACTIONS.includes(action) ? new Error(saveDenied) : code === "ACCESS_DENIED" ? reported(code, appDenied, { status: status2 }) : code === "APP_SELECTION_CHANGED" ? reported(code, "App access changed while this request ran. Retry it, and run adelin login --force if it happens again.", { status: status2 }) : code === "REQUEST_TIMEOUT" ? reported(code, "Adelin did not answer in time. Try again.") : typeof error?.serverCode == "string" ? reported(error.serverCode, error.serverMessage || `Adelin refused the ${action ?? "request"} (${error.serverCode}, HTTP ${status2}).`, { status: status2 }) : status2 !== void 0 ? reported("REMOTE_UNAVAILABLE", `Adelin answered HTTP ${status2}${action ? ` to the ${action} request` : ""}.`, { status: status2 }) : code === "REMOTE_UNAVAILABLE" ? reported(code, "Adelin could not be reached. Try again shortly.") : new Error(saving ? saveFailed : remoteFailed);
8522
8813
  }
8523
8814
  var CONFLICT_MESSAGES = {
8524
8815
  chat_reply: "The builder's App Creator chat is replying right now. Call open_app again after retryAt; Adelin hands the app over once the reply ends.",
@@ -8537,6 +8828,12 @@ function editConflict(result) {
8537
8828
  let message = CONFLICT_MESSAGES[value.holder] ?? CONFLICT_MESSAGES.default;
8538
8829
  return { state: "conflict", ...typeof value.retryAt == "string" ? { retryAt: value.retryAt } : {}, message };
8539
8830
  }
8831
+ function textReply(result) {
8832
+ let text4 = result?.content?.length === 1 && result.content[0].type === "text" ? result.content[0].text : null;
8833
+ if (typeof text4 != "string" || Buffer.byteLength(text4, "utf8") > MAX_TEXT_REPLY_BYTES)
8834
+ throw new Error("Adelin returned an invalid tool result.");
8835
+ return { ...result.isError ? { isError: !0 } : {}, content: [{ type: "text", text: text4 }] };
8836
+ }
8540
8837
  async function safeCall(remote2, name, args, saving = !1) {
8541
8838
  let result;
8542
8839
  try {
@@ -8544,9 +8841,10 @@ async function safeCall(remote2, name, args, saving = !1) {
8544
8841
  } catch (error) {
8545
8842
  throw remoteError(error, saving, name);
8546
8843
  }
8844
+ if (TEXT_REPLY_TOOLS.has(name)) return textReply(result);
8547
8845
  let conflict = name === "open_edit_session" ? editConflict(result) : null;
8548
8846
  if (conflict) return { content: [{ type: "text", text: JSON.stringify(conflict) }] };
8549
- let text4 = ARTIFACT_TOOLS.includes(name) && result?.isError && result.content?.length === 1 ? result.content[0].text : null;
8847
+ let text4 = CODED_REFUSAL_TOOLS.has(name) && result?.isError && result.content?.length === 1 ? result.content[0].text : null;
8550
8848
  return typeof text4 == "string" && text4.length <= 4096 && /^[A-Z][A-Z_]{2,63}: /.test(text4) ? { isError: !0, content: [{ type: "text", text: text4 }] } : (valueOf(result, saving, name === "device_operation" ? MAX_DEVICE_BYTES : void 0), result);
8551
8849
  }
8552
8850
  async function creationCall(remote2, name, args) {
@@ -8597,13 +8895,13 @@ function previewFailure(error) {
8597
8895
  async function routeAndRun(session, browser, tool2, args) {
8598
8896
  if (!session.session || session.state !== "active") return previewRefusalContent("Open an app first.");
8599
8897
  let ask = async (pass) => {
8600
- let reply;
8898
+ let reply2;
8601
8899
  try {
8602
- reply = await session.previewPass({ ...args.target ? { target: args.target } : {}, pass });
8900
+ reply2 = await session.previewPass({ ...args.target ? { target: args.target } : {}, pass });
8603
8901
  } catch (error) {
8604
8902
  return previewRefusalContent(previewFailure(error));
8605
8903
  }
8606
- return reply?.status === 429 ? previewRateLimitedContent(Number.isSafeInteger(reply.result?.refillPerMinute) ? reply.result.refillPerMinute : 60) : reply?.status === 403 ? previewRefusalContent(PREVIEW_REFUSED) : reply?.status === 200 && parsePreviewRoute(reply.result) || previewRefusalContent(PREVIEW_DOWN);
8904
+ return reply2?.status === 429 ? previewRateLimitedContent(Number.isSafeInteger(reply2.result?.refillPerMinute) ? reply2.result.refillPerMinute : 60) : reply2?.status === 403 ? previewRefusalContent(PREVIEW_REFUSED) : reply2?.status === 200 && parsePreviewRoute(reply2.result) || previewRefusalContent(PREVIEW_DOWN);
8607
8905
  }, run = async (route2) => {
8608
8906
  if (route2.content) return route2;
8609
8907
  if (route2.route === "device") return deviceContent(await session.device(tool2.operation, deviceArguments(args)));
@@ -8629,14 +8927,14 @@ async function routeAndRun(session, browser, tool2, args) {
8629
8927
  async function showAgentView(session, browser, openPage) {
8630
8928
  if (!session.session || session.state !== "active") return previewRefusalContent("Open an app first.");
8631
8929
  let openRoute = async () => {
8632
- let reply;
8930
+ let reply2;
8633
8931
  try {
8634
- reply = await session.previewPass({ pass: !0 });
8932
+ reply2 = await session.previewPass({ pass: !0 });
8635
8933
  } catch (error) {
8636
8934
  return { kind: "unavailable", reason: previewFailure(error) };
8637
8935
  }
8638
- if (reply?.status === 403) return { kind: "unavailable", reason: PREVIEW_REFUSED };
8639
- let route = reply?.status === 200 ? parsePreviewRoute(reply.result) : null;
8936
+ if (reply2?.status === 403) return { kind: "unavailable", reason: PREVIEW_REFUSED };
8937
+ let route = reply2?.status === 200 ? parsePreviewRoute(reply2.result) : null;
8640
8938
  return route?.route === "device" ? { kind: "unavailable", reason: DEVICE_ROUTE } : route?.route === "browser" ? route : { kind: "unavailable", reason: PREVIEW_DOWN };
8641
8939
  }, shown2;
8642
8940
  try {
@@ -8648,7 +8946,7 @@ async function showAgentView(session, browser, openPage) {
8648
8946
  return shown2.kind === "page" && shown2.opened !== !1 && openPage(shown2.url), { content: [{ type: "text", text: shown2.kind === "app-creator" ? APP_CREATOR_WATCHING : shown2.kind === "page" && shown2.opened === !1 ? "The agent's browser is already open as a page in the builder's default browser on this computer; no new page was opened. If the builder closed it, the link is in this MCP server's log." : shown2.kind === "page" ? "The agent's browser is now open as a page in the builder's default browser on this computer, where they can watch and control it. If no page opened, the link is in this MCP server's log." : shown2.reason }] };
8649
8947
  }
8650
8948
  function checkCheckoutSupport(bundlePath, release2) {
8651
- let { typeDeclarations, tsconfig } = JSON.parse(readSafeFile4(bundlePath).toString("utf8")), entries2 = Array.isArray(typeDeclarations) ? typeDeclarations.map((file) => [file?.path, file?.content]) : [], expected = release2.support;
8949
+ let { typeDeclarations, tsconfig } = JSON.parse(readSafeFile5(bundlePath).toString("utf8")), entries2 = Array.isArray(typeDeclarations) ? typeDeclarations.map((file) => [file?.path, file?.content]) : [], expected = release2.support;
8652
8950
  if (entries2.length !== Object.keys(expected).length - 1 || tsconfig !== expected["tsconfig.json"] || new Set(entries2.map(([path]) => path)).size !== entries2.length || entries2.some(([path, bytes2]) => typeof bytes2 != "string" || path === "tsconfig.json" || !Object.hasOwn(expected, path) || bytes2 !== expected[path])) throw updateRequired();
8653
8951
  }
8654
8952
  function recordCheckout(project, workspace, appId) {
@@ -8656,33 +8954,33 @@ function recordCheckout(project, workspace, appId) {
8656
8954
  !isAbsolute4(path) && path !== ".." && !path.startsWith(".." + sep3) && registerWorkspace(root, destination, appId);
8657
8955
  }
8658
8956
  function guardCheckoutWorktree(project, workspace) {
8659
- let root = realpathSync6(project), destination = resolve11(workspace), path = relative3(root, destination);
8957
+ let root = realpathSync6(project), destination = resolve12(workspace), path = relative3(root, destination);
8660
8958
  if (isAbsolute4(path) || path === ".." || path.startsWith(".." + sep3)) return;
8661
8959
  let ancestor = destination;
8662
- for (; !lstatIfPresent3(ancestor); ) ancestor = dirname8(ancestor);
8960
+ for (; !lstatIfPresent4(ancestor); ) ancestor = dirname8(ancestor);
8663
8961
  assertWorkspaceWorktree(root, ancestor);
8664
8962
  }
8665
8963
  async function checkout(remote2, appId, workspace, release2) {
8666
- if (lstatIfPresent3(assertSafeTarget2(resolve11(workspace), MANIFEST4))) {
8964
+ if (lstatIfPresent4(assertSafeTarget2(resolve12(workspace), MANIFEST4))) {
8667
8965
  workspaceFingerprint(workspace, appId);
8668
8966
  let pending = readPendingSave2(workspace, appId);
8669
8967
  return release2 && !pending && syncWorkspaceSupport(workspace, appId, release2), { state: "existing", appId, ...pending ? { pendingOperationId: pending.operationId } : {} };
8670
8968
  }
8671
8969
  let metadata2 = valueOf(await remote2.call("checkout_app", { app_id: appId, delivery: "chunked" }));
8672
8970
  if (!Number.isSafeInteger(metadata2.chunkCount) || metadata2.chunkCount < 1 || metadata2.chunkCount > 86) throw new Error("Adelin checkout is too large.");
8673
- let temp = mkdtempSync2(join11(realpathSync6(tmpdir()), "adelin-checkout-"));
8971
+ let temp = mkdtempSync2(join12(realpathSync6(tmpdir()), "adelin-checkout-"));
8674
8972
  try {
8675
- let folder = join11(temp, "chunks");
8973
+ let folder = join12(temp, "chunks");
8676
8974
  mkdirSync5(folder, { mode: 448 });
8677
8975
  let chunks = [];
8678
8976
  for (let index = 0; index < metadata2.chunkCount; index++) {
8679
8977
  let chunk = valueOf(await remote2.call("read_checkout_chunk", {
8680
8978
  bundle_id: metadata2.bundleId,
8681
8979
  index
8682
- })), path = join11(folder, `${index}.json`);
8980
+ })), path = join12(folder, `${index}.json`);
8683
8981
  writeFileSync6(path, JSON.stringify(chunk), { flag: "wx", mode: 384 }), chunks.push(path);
8684
8982
  }
8685
- let bundle = join11(temp, "bundle.json");
8983
+ let bundle = join12(temp, "bundle.json");
8686
8984
  assembleCheckout(metadata2, chunks, bundle, appId), release2 && checkCheckoutSupport(bundle, release2);
8687
8985
  let installed = materialize(bundle, workspace, appId);
8688
8986
  return release2 && syncWorkspaceSupport(workspace, appId, release2), installed;
@@ -8713,19 +9011,19 @@ function createPreviewOwner(session, previewBrowser, viewRetryMs) {
8713
9011
  ).unref?.(), run = async () => {
8714
9012
  if (paused || view !== current || !current) return;
8715
9013
  if (session.state !== "active") return void (session.state === "disconnected" && retry());
8716
- let reply = null;
9014
+ let reply2 = null;
8717
9015
  try {
8718
- reply = await session.registerView({ port: current.port, view_id: current.viewId, browser: browserState });
9016
+ reply2 = await session.registerView({ port: current.port, view_id: current.viewId, browser: browserState });
8719
9017
  } catch (error) {
8720
9018
  if (error?.message !== saveDenied) return void retry();
8721
9019
  }
8722
9020
  if (view !== current) return;
8723
- let key4 = reply?.registered === !0 ? reply.ticketKey : null, binding = key4 && typeof key4.kid == "string" && typeof key4.publicKey == "string" && typeof reply.userId == "string" && Array.isArray(reply.dashboardOrigins) ? JSON.stringify([current.viewId, key4.kid, key4.publicKey, reply.userId, reply.dashboardOrigins]) : null;
9021
+ let key4 = reply2?.registered === !0 ? reply2.ticketKey : null, binding = key4 && typeof key4.kid == "string" && typeof key4.publicKey == "string" && typeof reply2.userId == "string" && Array.isArray(reply2.dashboardOrigins) ? JSON.stringify([current.viewId, key4.kid, key4.publicKey, reply2.userId, reply2.dashboardOrigins]) : null;
8724
9022
  if (binding !== applied && (shutDashboard(), !!binding))
8725
9023
  try {
8726
- let { createLocalTicketVerifier: createLocalTicketVerifier2 } = await Promise.resolve().then(() => (init_src(), src_exports)), verify2 = createLocalTicketVerifier2({ ...key4, appId: current.appId, viewId: current.viewId, userId: reply.userId });
9024
+ let { createLocalTicketVerifier: createLocalTicketVerifier2 } = await Promise.resolve().then(() => (init_src(), src_exports)), verify2 = createLocalTicketVerifier2({ ...key4, appId: current.appId, viewId: current.viewId, userId: reply2.userId });
8727
9025
  if (view !== current) return;
8728
- previewBrowser.allowDashboard({ origins: reply.dashboardOrigins, verify: verify2 }), applied = binding;
9026
+ previewBrowser.allowDashboard({ origins: reply2.dashboardOrigins, verify: verify2 }), applied = binding;
8729
9027
  } catch {
8730
9028
  }
8731
9029
  };
@@ -8779,7 +9077,13 @@ function createLocalBuilder(remote2, transport, {
8779
9077
  onToolsChanged,
8780
9078
  ...options2
8781
9079
  } = {}) {
8782
- let safeRemote = { call: (name, args) => safeCall(remote2, name, args) }, sessionRemote = {
9080
+ let safeRemote = { call: (name, args) => safeCall(remote2, name, args) }, assetCall = async (name, args) => {
9081
+ try {
9082
+ return await remote2.call(name, args);
9083
+ } catch (error) {
9084
+ throw remoteError(error, !1, name);
9085
+ }
9086
+ }, sessionRemote = {
8783
9087
  prepare: (...args) => transport.prepare(...args),
8784
9088
  attach: (...args) => transport.attach(...args),
8785
9089
  detach: () => transport.detach(),
@@ -8853,7 +9157,7 @@ function createLocalBuilder(remote2, transport, {
8853
9157
  try {
8854
9158
  if (name === "open_app") {
8855
9159
  let { app_id: appId, workspace } = args;
8856
- if (typeof appId != "string" || !new RegExp(UUID12).test(appId) || typeof workspace != "string" || !workspace) throw new Error("Expected app_id and workspace.");
9160
+ if (typeof appId != "string" || !new RegExp(UUID13).test(appId) || typeof workspace != "string" || !workspace) throw new Error("Expected app_id and workspace.");
8857
9161
  if (session.pending || session.busy || session.session && session.state !== "disconnected")
8858
9162
  throw new Error("Close the current app first.");
8859
9163
  release2 && guardCheckoutWorktree(project, workspace), await closeBrowser();
@@ -8896,10 +9200,12 @@ function createLocalBuilder(remote2, transport, {
8896
9200
  }
8897
9201
  }
8898
9202
  if (name === "build_app")
8899
- return syncActiveSupport(), response(await session.build());
9203
+ return syncActiveSupport(), response(await session.build({ assets: (edit) => saveWorkspaceAssets({ ...edit, call: assetCall, replace: args.replace_assets ?? [] }) }));
8900
9204
  if (name === "check_app") {
8901
9205
  if (!session.session) throw new Error("Open an app first.");
8902
- return syncActiveSupport(), response(typecheck(session.session.workspace, session.session.appId));
9206
+ syncActiveSupport();
9207
+ let { workspace, appId } = session.session, checked = typecheck(workspace, appId), assets = assetStatus(workspace, appId);
9208
+ return response(assets ? { ...checked, assets } : checked);
8903
9209
  }
8904
9210
  if (name === "reconcile_build") return response(await session.reconcile());
8905
9211
  if (name === "retry_build") return response(await session.retry());
@@ -8916,13 +9222,13 @@ function createLocalBuilder(remote2, transport, {
8916
9222
  if (name === "show_agent_view") return await showAgentView(session, previewBrowser, openPage);
8917
9223
  if (name === "record_choice") return response(await session.recordChoice(args.request_id, args.artifact_id, args.note));
8918
9224
  if (name === "create_app") {
8919
- let startedAt = Date.now(), input = { ...args, idempotency_key: args.idempotency_key ?? randomUUID7() }, created = null, failure = null;
9225
+ let startedAt = Date.now(), input = { ...args, idempotency_key: args.idempotency_key ?? randomUUID7() }, created = null, failure2 = null;
8920
9226
  for (let attempt = 0; attempt < 3 && !created; attempt++)
8921
9227
  try {
8922
9228
  created = await creationCall(remote2, "create_app", input);
8923
9229
  } catch (error) {
8924
9230
  if (!transient(error)) return response({ ...failureBody(error), idempotency_key: input.idempotency_key }, !0);
8925
- failure = error;
9231
+ failure2 = error;
8926
9232
  }
8927
9233
  return created ? created.isError || "error" in created.value ? response({ ...created.value, idempotency_key: input.idempotency_key }, !0) : created.value.state === "ready" ? response({ state: "ready", app_id: created.value.app_id, next: "open_app" }) : await finishCreation(
8928
9234
  remote2,
@@ -8930,7 +9236,7 @@ function createLocalBuilder(remote2, transport, {
8930
9236
  created.value.creation_id,
8931
9237
  creationTiming,
8932
9238
  { startedAt, idempotencyKey: input.idempotency_key }
8933
- ) : response({ ...failureBody(failure ?? new Error(remoteFailed)), idempotency_key: input.idempotency_key }, !0);
9239
+ ) : response({ ...failureBody(failure2 ?? new Error(remoteFailed)), idempotency_key: input.idempotency_key }, !0);
8934
9240
  }
8935
9241
  if (name === "connection_status") {
8936
9242
  let setupState = "setup_required";
@@ -8963,10 +9269,10 @@ function createLocalBuilder(remote2, transport, {
8963
9269
  let result = await safeRemote.call(name, payload);
8964
9270
  return result.isError ? result : response(metadataTools[name].result.parse(valueOf(result)));
8965
9271
  }
8966
- let reply = await safeRemote.call(name, args);
8967
- if (name !== "list_editable_apps") return reply;
8968
- let listed = valueOf(reply);
8969
- return Array.isArray(listed.apps) && !listed.apps.length ? response({ ...listed, hint: NO_APPS_HINT }) : reply;
9272
+ let reply2 = await safeRemote.call(name, args);
9273
+ if (name !== "list_editable_apps") return reply2;
9274
+ let listed = valueOf(reply2);
9275
+ return Array.isArray(listed.apps) && !listed.apps.length ? response({ ...listed, hint: NO_APPS_HINT }) : reply2;
8970
9276
  } catch (error) {
8971
9277
  return error?.code === "INVALID_ARGUMENT" ? response(refused(), !0) : response(failureBody(error), !0);
8972
9278
  }
@@ -9075,11 +9381,11 @@ var CliRemote = class {
9075
9381
  },
9076
9382
  body: payload,
9077
9383
  signal
9078
- }), token2;
9384
+ }), token2, authFailure = (error) => libraryError(["AUTH_EXPIRED", "AUTH_REQUIRED"].includes(error?.code) || !this.auth.status().signedIn || /expired or was revoked/.test(error?.message ?? "") ? "AUTH_REQUIRED" : "REMOTE_UNAVAILABLE");
9079
9385
  try {
9080
9386
  token2 = await this.auth.accessToken();
9081
- } catch {
9082
- throw libraryError("AUTH_REQUIRED");
9387
+ } catch (error) {
9388
+ throw authFailure(error);
9083
9389
  }
9084
9390
  let response2 = await send(token2);
9085
9391
  if (response2.status === 401) {
@@ -9087,8 +9393,8 @@ var CliRemote = class {
9087
9393
  try {
9088
9394
  if (!this.auth.status().signedIn) throw libraryError("AUTH_REQUIRED");
9089
9395
  token2 = await this.auth.refreshNow();
9090
- } catch {
9091
- throw libraryError("AUTH_REQUIRED");
9396
+ } catch (error) {
9397
+ throw authFailure(error);
9092
9398
  }
9093
9399
  response2 = await send(token2);
9094
9400
  }