@adelin-io/cli 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -85,7 +85,7 @@ var require_authoring_release = __commonJS({
85
85
  });
86
86
 
87
87
  // packages/tool-activity/src/previewTools.ts
88
- import { z } from "zod";
88
+ import { z as z3 } from "zod";
89
89
  function tool(name, observe2, title2, description2, deviceShape) {
90
90
  let operation = name.slice(8);
91
91
  return Object.freeze({ name, operation, observe: observe2, title: title2, description: description2, deviceShape });
@@ -94,10 +94,10 @@ function previewToolShape(name) {
94
94
  return { ...PREVIEW_TOOLS[name].deviceShape, target: previewTargetSchema.optional() };
95
95
  }
96
96
  function previewToolSchema(name) {
97
- return z.strictObject(previewToolShape(name));
97
+ return z3.strictObject(previewToolShape(name));
98
98
  }
99
99
  function previewToolJsonSchema(name) {
100
- return z.toJSONSchema(previewToolSchema(name));
100
+ return z3.toJSONSchema(previewToolSchema(name));
101
101
  }
102
102
  function deviceArguments(args) {
103
103
  let { target: _target, ...rest } = args;
@@ -160,8 +160,8 @@ function pickNote(ref) {
160
160
  ref.screen && parts.push(`screen ${oneLine(ref.screen)}`), ref.component && parts.push(`component ${oneLine(ref.component)}`);
161
161
  let role = oneLine(ref.role, 40), name = oneLine(ref.name);
162
162
  (role || name) && parts.push([role, name && `"${name}"`].filter(Boolean).join(" "));
163
- let text4 = oneLine(ref.text);
164
- return text4 && parts.push(`"${text4}"`), parts.push(`on ${ref.target}`), `The builder pointed at: ${parts.join(", ")}`;
163
+ let text5 = oneLine(ref.text);
164
+ return text5 && parts.push(`"${text5}"`), parts.push(`on ${ref.target}`), `The builder pointed at: ${parts.join(", ")}`;
165
165
  }
166
166
  var PREVIEW_TOOL_NAMES, AGENT_PREVIEW_TARGETS, previewTargetSchema, utf8, boundedText, coordinate, direction, emptyShape, refShape, logsShape, tapCoordinatesShape, longPressShape, dragShape, swipeShape, scrollUntilVisibleShape, gesturePresetShape, typeTextShape, alertShape, pressButtonShape, findElementShape, waitShape, PREVIEW_TOOLS, observationOutput, json3, previewRouteInputSchema, isHttpUrl, isHttpOrigin, previewRouteSchema, AGENT_VIEW_OPEN_REASONS, agentViewOpenReplySchema, PREVIEW_VIEW_ONLY_TEXT, PREVIEW_USER_CHANGED_NOTE, oneLine, init_previewTools = __esm({
167
167
  "packages/tool-activity/src/previewTools.ts"() {
@@ -184,27 +184,27 @@ var PREVIEW_TOOL_NAMES, AGENT_PREVIEW_TARGETS, previewTargetSchema, utf8, bounde
184
184
  "preview_wait",
185
185
  "preview_tap_focused_tv",
186
186
  "preview_focus_element_tv"
187
- ], AGENT_PREVIEW_TARGETS = ["web_desktop", "web_phone", "webos", "tizen", "vidaa", "titanos", "vega"], previewTargetSchema = z.enum(AGENT_PREVIEW_TARGETS).describe(
187
+ ], AGENT_PREVIEW_TARGETS = ["web_desktop", "web_phone", "webos", "tizen", "vidaa", "titanos", "vega"], previewTargetSchema = z3.enum(AGENT_PREVIEW_TARGETS).describe(
188
188
  "Which instant preview to drive: web_desktop, web_phone, webos, tizen, vidaa, titanos or vega. Defaults to the target the builder selected."
189
- ), utf8 = new TextEncoder(), boundedText = (maxBytes) => z.string().min(1).refine(
189
+ ), utf8 = new TextEncoder(), boundedText = (maxBytes) => z3.string().min(1).refine(
190
190
  (value) => utf8.encode(value).length <= maxBytes && !new RegExp("(?![\\u0080-\\u009f])\\p{Cc}", "u").test(value),
191
191
  "value is outside the preview text boundary"
192
- ), coordinate = () => z.number().finite().min(0).max(1e4), direction = () => z.enum(["up", "down", "left", "right"]), emptyShape = {}, refShape = { ref: boundedText(128) }, logsShape = {
193
- since: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),
194
- tail: z.number().int().min(1).max(500).optional()
195
- }, tapCoordinatesShape = { x: coordinate(), y: coordinate() }, longPressShape = { ref: boundedText(128), duration_ms: z.number().int().min(1).max(1e4).optional() }, dragShape = {
192
+ ), coordinate = () => z3.number().finite().min(0).max(1e4), direction = () => z3.enum(["up", "down", "left", "right"]), emptyShape = {}, refShape = { ref: boundedText(128) }, logsShape = {
193
+ since: z3.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),
194
+ tail: z3.number().int().min(1).max(500).optional()
195
+ }, tapCoordinatesShape = { x: coordinate(), y: coordinate() }, longPressShape = { ref: boundedText(128), duration_ms: z3.number().int().min(1).max(1e4).optional() }, dragShape = {
196
196
  from_ref: boundedText(128).optional(),
197
197
  to_ref: boundedText(128).optional(),
198
198
  x: coordinate().optional(),
199
199
  y: coordinate().optional(),
200
200
  x2: coordinate().optional(),
201
201
  y2: coordinate().optional(),
202
- velocity: z.number().finite().min(1).max(1e4).optional(),
203
- press_duration: z.number().int().min(0).max(1e4).optional(),
204
- hold_duration: z.number().int().min(0).max(1e4).optional()
205
- }, swipeShape = { direction: direction(), distance: z.enum(["short", "medium", "long"]).optional() }, scrollUntilVisibleShape = {
202
+ velocity: z3.number().finite().min(1).max(1e4).optional(),
203
+ press_duration: z3.number().int().min(0).max(1e4).optional(),
204
+ hold_duration: z3.number().int().min(0).max(1e4).optional()
205
+ }, swipeShape = { direction: direction(), distance: z3.enum(["short", "medium", "long"]).optional() }, scrollUntilVisibleShape = {
206
206
  text: boundedText(4096),
207
- element_type: z.enum([
207
+ element_type: z3.enum([
208
208
  "Button",
209
209
  "StaticText",
210
210
  "TextField",
@@ -217,17 +217,17 @@ var PREVIEW_TOOL_NAMES, AGENT_PREVIEW_TARGETS, previewTargetSchema, utf8, bounde
217
217
  "SearchField"
218
218
  ]).optional(),
219
219
  direction: direction().optional(),
220
- max_scrolls: z.number().int().min(1).max(30).optional()
220
+ max_scrolls: z3.number().int().min(1).max(30).optional()
221
221
  }, gesturePresetShape = {
222
- name: z.enum(["scroll_up", "scroll_down", "scroll_left", "scroll_right", "back_swipe", "pull_to_refresh"])
223
- }, typeTextShape = { text: boundedText(4096) }, alertShape = { action: z.enum(["get", "accept", "dismiss"]), button: boundedText(4096).optional() }, pressButtonShape = {
224
- button: z.enum(["back", "dpad_up", "dpad_down", "dpad_left", "dpad_right", "dpad_center"])
222
+ name: z3.enum(["scroll_up", "scroll_down", "scroll_left", "scroll_right", "back_swipe", "pull_to_refresh"])
223
+ }, typeTextShape = { text: boundedText(4096) }, alertShape = { action: z3.enum(["get", "accept", "dismiss"]), button: boundedText(4096).optional() }, pressButtonShape = {
224
+ button: z3.enum(["back", "dpad_up", "dpad_down", "dpad_left", "dpad_right", "dpad_center"])
225
225
  }, findElementShape = {
226
226
  text: boundedText(4096),
227
227
  below: boundedText(4096).optional(),
228
228
  above: boundedText(4096).optional(),
229
229
  near: boundedText(4096).optional()
230
- }, waitShape = { seconds: z.number().finite().min(0).max(30).optional() };
230
+ }, waitShape = { seconds: z3.number().finite().min(0).max(30).optional() };
231
231
  PREVIEW_TOOLS = Object.freeze({
232
232
  preview_ui_tree: tool(
233
233
  "preview_ui_tree",
@@ -357,9 +357,9 @@ var PREVIEW_TOOL_NAMES, AGENT_PREVIEW_TARGETS, previewTargetSchema, utf8, bounde
357
357
  )
358
358
  });
359
359
  observationOutput = (observation) => ({ kind: observation.kind, text: observation.text }), json3 = (value) => ({ content: [{ type: "text", text: JSON.stringify(value) }] });
360
- previewRouteInputSchema = z.strictObject({
360
+ previewRouteInputSchema = z3.strictObject({
361
361
  target: previewTargetSchema.optional(),
362
- pass: z.boolean()
362
+ pass: z3.boolean()
363
363
  }), isHttpUrl = (value) => {
364
364
  try {
365
365
  let { protocol } = new URL(value);
@@ -367,27 +367,27 @@ var PREVIEW_TOOL_NAMES, AGENT_PREVIEW_TARGETS, previewTargetSchema, utf8, bounde
367
367
  } catch {
368
368
  return !1;
369
369
  }
370
- }, isHttpOrigin = (value) => isHttpUrl(value) && new URL(value).origin === value, previewRouteSchema = z.discriminatedUnion("route", [
371
- z.strictObject({ route: z.literal("device") }),
372
- z.strictObject({
373
- route: z.literal("browser"),
374
- target: z.enum(AGENT_PREVIEW_TARGETS),
375
- url: z.string().max(2048).refine(isHttpUrl),
376
- allowedOrigins: z.array(z.string().max(2048).refine(isHttpOrigin)).min(1).max(12),
377
- grant: z.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),
378
- targetNote: z.string().max(200).optional(),
370
+ }, isHttpOrigin = (value) => isHttpUrl(value) && new URL(value).origin === value, previewRouteSchema = z3.discriminatedUnion("route", [
371
+ z3.strictObject({ route: z3.literal("device") }),
372
+ z3.strictObject({
373
+ route: z3.literal("browser"),
374
+ target: z3.enum(AGENT_PREVIEW_TARGETS),
375
+ url: z3.string().max(2048).refine(isHttpUrl),
376
+ allowedOrigins: z3.array(z3.string().max(2048).refine(isHttpOrigin)).min(1).max(12),
377
+ grant: z3.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),
378
+ targetNote: z3.string().max(200).optional(),
379
379
  /** The pass may drive the page; anything but `true` leaves only the observe tools. */
380
- mutate: z.boolean().optional()
380
+ mutate: z3.boolean().optional()
381
381
  })
382
382
  ]);
383
- AGENT_VIEW_OPEN_REASONS = ["not_live", "not_authorized", "unavailable"], agentViewOpenReplySchema = z.discriminatedUnion("state", [
384
- z.strictObject({
385
- state: z.literal("ok"),
386
- viewId: z.string().regex(/^[A-Za-z0-9_-]{22,64}$/),
387
- token: z.string().min(1).max(4096).regex(/^[A-Za-z0-9._-]+$/),
388
- expiresAt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
383
+ AGENT_VIEW_OPEN_REASONS = ["not_live", "not_authorized", "unavailable"], agentViewOpenReplySchema = z3.discriminatedUnion("state", [
384
+ z3.strictObject({
385
+ state: z3.literal("ok"),
386
+ viewId: z3.string().regex(/^[A-Za-z0-9_-]{22,64}$/),
387
+ token: z3.string().min(1).max(4096).regex(/^[A-Za-z0-9._-]+$/),
388
+ expiresAt: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER)
389
389
  }),
390
- z.strictObject({ state: z.literal("unavailable"), reason: z.enum(AGENT_VIEW_OPEN_REASONS) })
390
+ z3.strictObject({ state: z3.literal("unavailable"), reason: z3.enum(AGENT_VIEW_OPEN_REASONS) })
391
391
  ]), PREVIEW_VIEW_ONLY_TEXT = "This editing session can look at the preview but not control it. Use preview_ui_tree, preview_screenshot, preview_logs, preview_find_element or preview_wait.";
392
392
  PREVIEW_USER_CHANGED_NOTE = "The builder changed the page in Agent View since your last preview call. Read the current state (preview_ui_tree or preview_screenshot) before acting.", oneLine = (value, max = 120) => value.replace(/[\s\p{Cc}]+/gu, " ").trim().slice(0, max);
393
393
  }
@@ -410,24 +410,24 @@ var ESCAPE, TV_VIEWPORT, BROWSER_TARGETS, SYSTEM_CHROME_UA, init_targets = __esm
410
410
  });
411
411
 
412
412
  // packages/preview-browser/src/logs.ts
413
- function truncateBytes(text4, maxBytes) {
414
- if (encoder.encode(text4).length <= maxBytes) return text4;
415
- let end = Math.min(text4.length, maxBytes);
416
- for (; end > 0 && encoder.encode(text4.slice(0, end)).length > maxBytes - 3; ) end -= 1;
417
- return `${text4.slice(0, end)}...`;
413
+ function truncateBytes(text5, maxBytes) {
414
+ if (encoder.encode(text5).length <= maxBytes) return text5;
415
+ let end = Math.min(text5.length, maxBytes);
416
+ for (; end > 0 && encoder.encode(text5.slice(0, end)).length > maxBytes - 3; ) end -= 1;
417
+ return `${text5.slice(0, end)}...`;
418
418
  }
419
419
  function createLogBuffer(limits2 = {}) {
420
420
  let maxLines = limits2.maxLines ?? 500, maxLineBytes = limits2.maxLineBytes ?? 2048, maxBytes = limits2.maxBytes ?? 65536, lines = [], total = 0, seq = 0;
421
421
  return {
422
- push(kind2, text4) {
423
- let clipped = truncateBytes(`${text4}`, maxLineBytes), bytes2 = encoder.encode(clipped).length + encoder.encode(kind2).length;
422
+ push(kind2, text5) {
423
+ let clipped = truncateBytes(`${text5}`, maxLineBytes), bytes2 = encoder.encode(clipped).length + encoder.encode(kind2).length;
424
424
  for (seq += 1, lines.push({ seq, kind: kind2, text: clipped, bytes: bytes2 }), total += bytes2; lines.length > maxLines || total > maxBytes && lines.length > 1; )
425
425
  total -= lines.shift().bytes;
426
426
  },
427
427
  read(options2 = {}) {
428
428
  let selected = options2.since === void 0 ? lines : lines.filter((line) => line.seq > options2.since);
429
429
  return options2.tail !== void 0 && (selected = options2.tail > 0 ? selected.slice(-options2.tail) : []), {
430
- lines: selected.map(({ seq: lineSeq, kind: kind2, text: text4 }) => ({ seq: lineSeq, kind: kind2, text: text4 })),
430
+ lines: selected.map(({ seq: lineSeq, kind: kind2, text: text5 }) => ({ seq: lineSeq, kind: kind2, text: text5 })),
431
431
  cursor: seq,
432
432
  available: lines.length
433
433
  };
@@ -606,7 +606,7 @@ function createDialogQueue() {
606
606
  let dialog = held[0];
607
607
  return dialog ? { type: dialog.type(), message: dialog.message(), defaultValue: dialog.defaultValue() } : null;
608
608
  },
609
- accept: (text4) => settle3((dialog) => dialog.accept(text4)),
609
+ accept: (text5) => settle3((dialog) => dialog.accept(text5)),
610
610
  dismiss: () => settle3((dialog) => dialog.dismiss())
611
611
  };
612
612
  }
@@ -631,8 +631,8 @@ function createPreviewBrowserHost(options2) {
631
631
  }
632
632
  }, secrets = /* @__PURE__ */ new Set(), longestFirst = [], keep = (secret) => {
633
633
  secrets.has(secret) || (secrets.add(secret), longestFirst = [...secrets].sort((a, b) => b.length - a.length));
634
- }, scrub = (text4) => {
635
- let out = text4.replace(GRANT_PARAM, "$1[redacted]").replace(JWT, "[redacted]");
634
+ }, scrub = (text5) => {
635
+ let out = text5.replace(GRANT_PARAM, "$1[redacted]").replace(JWT, "[redacted]");
636
636
  for (let secret of longestFirst)
637
637
  if (secret.length >= 4) out = out.split(secret).join("[redacted]");
638
638
  else {
@@ -704,7 +704,7 @@ function createPreviewBrowserHost(options2) {
704
704
  }
705
705
  }
706
706
  async function setUpSession(context, route, grant) {
707
- let target2 = route.target, previewOrigin = new URL(route.url).origin, allowed = /* @__PURE__ */ new Set([previewOrigin, ...route.allowedOrigins]), logs2 = createLogBuffer(), log = (kind2, text4) => logs2.push(kind2, scrub(text4)), dialogs = createDialogQueue(), blockedRequests = /* @__PURE__ */ new WeakSet(), guardBlocked = /* @__PURE__ */ new Set(), cdpSession = null;
707
+ let target2 = route.target, previewOrigin = new URL(route.url).origin, allowed = /* @__PURE__ */ new Set([previewOrigin, ...route.allowedOrigins]), logs2 = createLogBuffer(), log = (kind2, text5) => logs2.push(kind2, scrub(text5)), dialogs = createDialogQueue(), blockedRequests = /* @__PURE__ */ new WeakSet(), guardBlocked = /* @__PURE__ */ new Set(), cdpSession = null;
708
708
  await context.exposeBinding("adelinAgentPreviewGrant", async (source) => {
709
709
  if (source.frame !== source.page.mainFrame() || originOf(source.frame.url()) !== live.previewOrigin)
710
710
  return log("blocked", "blocked: preview pass request from another frame"), emit("preview.browser.renew_refused", { target: target2 }), null;
@@ -939,8 +939,8 @@ function flatten(nodes, parent, ancestors, scrub, secrets, out) {
939
939
  }
940
940
  let box = isBox(node.box) ? node.box : null, own = node.ref ? { ref: node.ref, box } : parent, secret = isSecret(node, secrets);
941
941
  if (node.ref) {
942
- let text4 = !secret && typeof node.text == "string" ? node.text : "";
943
- out.push({ ref: node.ref, role: node.role, label: scrub(oneLine2(`${node.name || text4}`)), box, ancestors });
942
+ let text5 = !secret && typeof node.text == "string" ? node.text : "";
943
+ out.push({ ref: node.ref, role: node.role, label: scrub(oneLine2(`${node.name || text5}`)), box, ancestors });
944
944
  }
945
945
  secret || flatten(asNodes(node.children), own, node.ref ? [...ancestors, node.ref] : ancestors, scrub, secrets, out);
946
946
  }
@@ -1048,8 +1048,8 @@ function centre(box) {
1048
1048
  function inViewport(box, viewport) {
1049
1049
  return !box || box.width <= 0 || box.height <= 0 ? !1 : box.x < viewport.width && box.y < viewport.height && box.x + box.width > 0 && box.y + box.height > 0;
1050
1050
  }
1051
- function matchNodes(nodes, text4, roles2) {
1052
- let needle = oneLine2(text4).toLowerCase(), seen = /* @__PURE__ */ new Set(), matches = nodes.filter((node) => {
1051
+ function matchNodes(nodes, text5, roles2) {
1052
+ let needle = oneLine2(text5).toLowerCase(), seen = /* @__PURE__ */ new Set(), matches = nodes.filter((node) => {
1053
1053
  if (!node.label.toLowerCase().includes(needle) || roles2 && !roles2.includes(node.role)) return !1;
1054
1054
  let key4 = `${node.ref}:${node.label}`;
1055
1055
  return seen.has(key4) ? !1 : (seen.add(key4), !0);
@@ -1072,7 +1072,7 @@ var TREE_LIMIT_BYTES, SNAPSHOT_TIMEOUT_MS, TRUNCATED, FLAG_KEYS, VALUE_KEYS, SEC
1072
1072
  Switch: ["switch", "checkbox"],
1073
1073
  TextView: ["textbox"]
1074
1074
  }), REF_PATTERN = /^(?:f\d+)?e\d+$/;
1075
- oneLine2 = (text4) => text4.replace(new RegExp("\\p{Cc}+", "gu"), " ").trim(), isSecret = (node, secrets) => secrets === null ? FIELD_ROLES.has(node.role) : !!(node.ref && secrets.has(node.ref));
1075
+ oneLine2 = (text5) => text5.replace(new RegExp("\\p{Cc}+", "gu"), " ").trim(), isSecret = (node, secrets) => secrets === null ? FIELD_ROLES.has(node.role) : !!(node.ref && secrets.has(node.ref));
1076
1076
  }
1077
1077
  });
1078
1078
 
@@ -1275,10 +1275,10 @@ async function logs(session, args) {
1275
1275
  tail: typeof args.tail == "number" ? args.tail : 500
1276
1276
  }), lines = [], total = 0;
1277
1277
  for (let line of [...read.lines].reverse()) {
1278
- let text4 = session.redact(`[${line.kind}] ${line.text}`).replace(new RegExp("\\p{Cc}+", "gu"), " ");
1279
- for (; encoder3.encode(text4).length > LOG_LINE_BYTES; ) text4 = `${text4.slice(0, text4.length - 64)}...`;
1280
- if (total += encoder3.encode(text4).length, total > LOG_TOTAL_BYTES) break;
1281
- lines.unshift(text4);
1278
+ let text5 = session.redact(`[${line.kind}] ${line.text}`).replace(new RegExp("\\p{Cc}+", "gu"), " ");
1279
+ for (; encoder3.encode(text5).length > LOG_LINE_BYTES; ) text5 = `${text5.slice(0, text5.length - 64)}...`;
1280
+ if (total += encoder3.encode(text5).length, total > LOG_TOTAL_BYTES) break;
1281
+ lines.unshift(text5);
1282
1282
  }
1283
1283
  return { kind: "logs", lines, cursor: read.cursor, available: !0 };
1284
1284
  }
@@ -1304,8 +1304,8 @@ function spatial(candidates, anchor, relation) {
1304
1304
  let distance = (node) => Math.hypot(centre(node.box).x - centre(a).x, centre(node.box).y - centre(a).y);
1305
1305
  return [...boxed].sort((x, y) => distance(x) - distance(y));
1306
1306
  }
1307
- function scrollArea(snapshot, text4, roles2, session) {
1308
- let viewport = viewportOf(session), target2 = matchNodes(snapshot.nodes, text4, roles2)[0];
1307
+ function scrollArea(snapshot, text5, roles2, session) {
1308
+ let viewport = viewportOf(session), target2 = matchNodes(snapshot.nodes, text5, roles2)[0];
1309
1309
  if (target2)
1310
1310
  for (let ref of [...target2.ancestors].reverse()) {
1311
1311
  let box = boxOf(snapshot, ref);
@@ -1333,22 +1333,22 @@ async function firstShown(session, nodes) {
1333
1333
  async function scrollUntilVisible(session, args) {
1334
1334
  let dialog = session.dialogs.current();
1335
1335
  if (dialog) return acknowledged(dialogObservation(session, dialog));
1336
- let text4 = String(args.text), roles2 = typeof args.element_type == "string" ? ELEMENT_ROLES[args.element_type] : void 0, direction2 = args.direction ?? "down", maxScrolls = typeof args.max_scrolls == "number" ? args.max_scrolls : 10, tv = BROWSER_TARGETS[session.target].tv, scrolls = 0;
1336
+ let text5 = String(args.text), roles2 = typeof args.element_type == "string" ? ELEMENT_ROLES[args.element_type] : void 0, direction2 = args.direction ?? "down", maxScrolls = typeof args.max_scrolls == "number" ? args.max_scrolls : 10, tv = BROWSER_TARGETS[session.target].tv, scrolls = 0;
1337
1337
  try {
1338
1338
  for (; ; ) {
1339
1339
  let snapshot = await takeSnapshot(session);
1340
1340
  if (!snapshot) return acknowledged(await treeObservation(session));
1341
- let visible = await firstShown(session, matchNodes(snapshot.nodes, text4, roles2));
1341
+ let visible = await firstShown(session, matchNodes(snapshot.nodes, text5, roles2));
1342
1342
  if (visible) {
1343
1343
  let note2 = `${JSON.stringify(visible.label)} is visible as ${visible.ref} after ${scrolls} scroll(s).`;
1344
1344
  return acknowledged({ kind: "full", text: `${note2}
1345
1345
  ${snapshot.text}` });
1346
1346
  }
1347
1347
  if (scrolls >= maxScrolls)
1348
- return acknowledged(unavailable(`${JSON.stringify(session.redact(text4))} did not become visible after ${scrolls} scroll(s).
1348
+ return acknowledged(unavailable(`${JSON.stringify(session.redact(text5))} did not become visible after ${scrolls} scroll(s).
1349
1349
  ${snapshot.text}`));
1350
- if (tv ? await sendKey(session, ARROW[direction2]) : await wheel(session, direction2, DISTANCE.medium, scrollArea(snapshot, text4, roles2, session)), scrolls += 1, await settle2(session, 1e3), await snapshotText(session) === snapshot.text && !tv)
1351
- return acknowledged(unavailable(`Scrolling ${direction2} no longer moves the screen; ${JSON.stringify(session.redact(text4))} is not visible.
1350
+ if (tv ? await sendKey(session, ARROW[direction2]) : await wheel(session, direction2, DISTANCE.medium, scrollArea(snapshot, text5, roles2, session)), scrolls += 1, await settle2(session, 1e3), await snapshotText(session) === snapshot.text && !tv)
1351
+ return acknowledged(unavailable(`Scrolling ${direction2} no longer moves the screen; ${JSON.stringify(session.redact(text5))} is not visible.
1352
1352
  ${snapshot.text}`));
1353
1353
  }
1354
1354
  } catch {
@@ -1469,13 +1469,13 @@ var SETTLE_MS, ACTION_TIMEOUT_MS, WIND_DOWN_MS, SCREENSHOT_TIMEOUT_MS, SCREENSHO
1469
1469
  down: DPAD.dpad_down,
1470
1470
  left: DPAD.dpad_left,
1471
1471
  right: DPAD.dpad_right
1472
- }, unavailable = (text4) => ({ kind: "unavailable", text: text4 }), acknowledged = (observation) => ({ kind: "acknowledged", observation }), staleRef = (ref) => unavailable(`The element ${ref} is not on the screen any more; read a new tree with preview_ui_tree.`);
1472
+ }, unavailable = (text5) => ({ kind: "unavailable", text: text5 }), acknowledged = (observation) => ({ kind: "acknowledged", observation }), staleRef = (ref) => unavailable(`The element ${ref} is not on the screen any more; read a new tree with preview_ui_tree.`);
1473
1473
  }
1474
1474
  });
1475
1475
 
1476
1476
  // packages/preview-browser/src/browser.ts
1477
- function unavailableResult(tool2, text4) {
1478
- return PREVIEW_TOOLS[tool2].observe ? { kind: "unavailable", reason: text4 } : { kind: "acknowledged", observation: { kind: "unavailable", text: text4 } };
1477
+ function unavailableResult(tool2, text5) {
1478
+ return PREVIEW_TOOLS[tool2].observe ? { kind: "unavailable", reason: text5 } : { kind: "acknowledged", observation: { kind: "unavailable", text: text5 } };
1479
1479
  }
1480
1480
  function withNotes(result, gate, notes) {
1481
1481
  if (!(result.kind === "unavailable" || "observation" in result)) return result;
@@ -1487,7 +1487,7 @@ function withNotes(result, gate, notes) {
1487
1487
  lines.push(pickNote(pick2));
1488
1488
  }
1489
1489
  if (!lines.length) return result;
1490
- let append = (text4) => [text4, ...lines].filter(Boolean).join(`
1490
+ let append = (text5) => [text5, ...lines].filter(Boolean).join(`
1491
1491
  `);
1492
1492
  return result.kind === "unavailable" ? { ...result, reason: append(result.reason) } : "observation" in result ? { ...result, observation: { ...result.observation, text: append(result.observation.text) } } : result;
1493
1493
  }
@@ -1599,14 +1599,14 @@ var init_turnGate = __esm({
1599
1599
  });
1600
1600
 
1601
1601
  // packages/tool-activity/src/agentView.ts
1602
- import { z as z2 } from "zod";
1602
+ import { z as z4 } from "zod";
1603
1603
  function encodeFrame(header, jpeg) {
1604
1604
  let json4 = new TextEncoder().encode(JSON.stringify(frameHeader.parse(header)));
1605
1605
  if (json4.length > MAX_FRAME_HEADER_BYTES) throw new RangeError("frame header too large");
1606
1606
  let bytes2 = new Uint8Array(4 + json4.length + jpeg.length);
1607
1607
  return new DataView(bytes2.buffer).setUint32(0, json4.length, !1), bytes2.set(json4, 4), bytes2.set(jpeg, 4 + json4.length), bytes2;
1608
1608
  }
1609
- var AGENT_VIEW_KEYS, AGENT_VIEW_CAPS, AGENT_VIEW_CLOSE, AGENT_VIEW_REFUSAL_KEYS, MAX_FRAME_HEADER_BYTES, urlSafe, token, coordinate2, delta, inputText, viewerId, target, bounded, agentViewRights, elementReference, pointer, wheel2, key3, text3, remote, dialogAction, pick, controlInput, viewerInput, viewerMessage, agentViewState, gatewayToViewer, producerMessage, gatewayToProducer, agentViewClaims, dimension, frameHeader, init_agentView = __esm({
1609
+ var AGENT_VIEW_KEYS, AGENT_VIEW_CAPS, AGENT_VIEW_CLOSE, AGENT_VIEW_REFUSAL_KEYS, MAX_FRAME_HEADER_BYTES, urlSafe, token, coordinate2, delta, inputText, viewerId, target, bounded, agentViewRights, elementReference, pointer, wheel2, key3, text4, remote, dialogAction, pick, controlInput, viewerInput, viewerMessage, agentViewState, gatewayToViewer, producerMessage, gatewayToProducer, agentViewClaims, dimension, frameHeader, init_agentView = __esm({
1610
1610
  "packages/tool-activity/src/agentView.ts"() {
1611
1611
  init_previewTools();
1612
1612
  AGENT_VIEW_KEYS = [
@@ -1649,93 +1649,93 @@ var AGENT_VIEW_KEYS, AGENT_VIEW_CAPS, AGENT_VIEW_CLOSE, AGENT_VIEW_REFUSAL_KEYS,
1649
1649
  limit: 4429
1650
1650
  }), AGENT_VIEW_REFUSAL_KEYS = Object.freeze(Object.fromEntries(
1651
1651
  Object.entries(AGENT_VIEW_CLOSE).map(([name, code]) => [code, `agentView.refused.${name}`])
1652
- )), MAX_FRAME_HEADER_BYTES = 1024, urlSafe = (min, max) => z2.string().regex(new RegExp(`^[A-Za-z0-9_-]{${min},${max}}$`)), token = z2.string().min(1).max(4096).regex(/^[A-Za-z0-9._-]+$/), coordinate2 = z2.number().finite().min(0).max(1e4), delta = z2.number().finite().min(-1e4).max(1e4), inputText = z2.string().min(1).max(512).refine((value) => !new RegExp("\\p{Cc}", "u").test(value), "control characters"), viewerId = urlSafe(1, 64), target = z2.enum(AGENT_PREVIEW_TARGETS), bounded = (max) => z2.string().max(max), agentViewRights = z2.enum(["watch", "control"]), elementReference = z2.object({
1652
+ )), MAX_FRAME_HEADER_BYTES = 1024, urlSafe = (min, max) => z4.string().regex(new RegExp(`^[A-Za-z0-9_-]{${min},${max}}$`)), token = z4.string().min(1).max(4096).regex(/^[A-Za-z0-9._-]+$/), coordinate2 = z4.number().finite().min(0).max(1e4), delta = z4.number().finite().min(-1e4).max(1e4), inputText = z4.string().min(1).max(512).refine((value) => !new RegExp("\\p{Cc}", "u").test(value), "control characters"), viewerId = urlSafe(1, 64), target = z4.enum(AGENT_PREVIEW_TARGETS), bounded = (max) => z4.string().max(max), agentViewRights = z4.enum(["watch", "control"]), elementReference = z4.object({
1653
1653
  target,
1654
- node: z2.string().min(1).max(200),
1654
+ node: z4.string().min(1).max(200),
1655
1655
  role: bounded(40),
1656
1656
  name: bounded(120),
1657
1657
  text: bounded(120),
1658
- box: z2.object({
1659
- x: z2.number().finite(),
1660
- y: z2.number().finite(),
1661
- width: z2.number().finite().min(0),
1662
- height: z2.number().finite().min(0)
1658
+ box: z4.object({
1659
+ x: z4.number().finite(),
1660
+ y: z4.number().finite(),
1661
+ width: z4.number().finite().min(0),
1662
+ height: z4.number().finite().min(0)
1663
1663
  }).strict(),
1664
1664
  screen: bounded(120).optional(),
1665
1665
  component: bounded(120).optional(),
1666
1666
  file: bounded(200).optional(),
1667
- line: z2.number().int().min(1).optional(),
1668
- column: z2.number().int().min(1).optional()
1669
- }).strict(), pointer = z2.object({
1670
- t: z2.literal("pointer"),
1671
- phase: z2.enum(["move", "down", "up"]),
1667
+ line: z4.number().int().min(1).optional(),
1668
+ column: z4.number().int().min(1).optional()
1669
+ }).strict(), pointer = z4.object({
1670
+ t: z4.literal("pointer"),
1671
+ phase: z4.enum(["move", "down", "up"]),
1672
1672
  x: coordinate2,
1673
1673
  y: coordinate2,
1674
- button: z2.enum(["left", "middle", "right"])
1675
- }).strict(), wheel2 = z2.object({ t: z2.literal("wheel"), x: coordinate2, y: coordinate2, dx: delta, dy: delta }).strict(), key3 = z2.object({
1676
- t: z2.literal("key"),
1677
- phase: z2.enum(["down", "up"]),
1678
- key: z2.enum(AGENT_VIEW_KEYS),
1679
- code: z2.string().regex(/^[A-Za-z0-9]{1,32}$/)
1680
- }).strict(), text3 = z2.object({ t: z2.literal("text"), text: inputText }).strict(), remote = z2.object({ t: z2.literal("remote"), button: z2.enum(["up", "down", "left", "right", "ok", "back"]) }).strict(), dialogAction = z2.object({
1681
- t: z2.literal("dialog"),
1682
- action: z2.enum(["accept", "dismiss"]),
1683
- text: z2.string().max(512).optional()
1684
- }).strict(), pick = z2.object({ t: z2.literal("pick"), x: coordinate2, y: coordinate2 }).strict(), controlInput = z2.discriminatedUnion("t", [pointer, wheel2, key3, text3, remote, dialogAction]), viewerInput = z2.discriminatedUnion("t", [pointer, wheel2, key3, text3, remote, dialogAction, pick]), viewerMessage = z2.discriminatedUnion("t", [
1685
- z2.object({ t: z2.literal("auth"), ticket: token }).strict(),
1686
- z2.object({ t: z2.literal("reauth"), ticket: token }).strict(),
1687
- z2.object({ t: z2.literal("ping") }).strict(),
1674
+ button: z4.enum(["left", "middle", "right"])
1675
+ }).strict(), wheel2 = z4.object({ t: z4.literal("wheel"), x: coordinate2, y: coordinate2, dx: delta, dy: delta }).strict(), key3 = z4.object({
1676
+ t: z4.literal("key"),
1677
+ phase: z4.enum(["down", "up"]),
1678
+ key: z4.enum(AGENT_VIEW_KEYS),
1679
+ code: z4.string().regex(/^[A-Za-z0-9]{1,32}$/)
1680
+ }).strict(), text4 = z4.object({ t: z4.literal("text"), text: inputText }).strict(), remote = z4.object({ t: z4.literal("remote"), button: z4.enum(["up", "down", "left", "right", "ok", "back"]) }).strict(), dialogAction = z4.object({
1681
+ t: z4.literal("dialog"),
1682
+ action: z4.enum(["accept", "dismiss"]),
1683
+ text: z4.string().max(512).optional()
1684
+ }).strict(), pick = z4.object({ t: z4.literal("pick"), x: coordinate2, y: coordinate2 }).strict(), controlInput = z4.discriminatedUnion("t", [pointer, wheel2, key3, text4, remote, dialogAction]), viewerInput = z4.discriminatedUnion("t", [pointer, wheel2, key3, text4, remote, dialogAction, pick]), viewerMessage = z4.discriminatedUnion("t", [
1685
+ z4.object({ t: z4.literal("auth"), ticket: token }).strict(),
1686
+ z4.object({ t: z4.literal("reauth"), ticket: token }).strict(),
1687
+ z4.object({ t: z4.literal("ping") }).strict(),
1688
1688
  pointer,
1689
1689
  wheel2,
1690
1690
  key3,
1691
- text3,
1691
+ text4,
1692
1692
  remote,
1693
1693
  dialogAction,
1694
1694
  pick
1695
- ]), agentViewState = z2.object({
1696
- t: z2.literal("state"),
1695
+ ]), agentViewState = z4.object({
1696
+ t: z4.literal("state"),
1697
1697
  target,
1698
- viewport: z2.object({ width: z2.number().int().min(1).max(1e4), height: z2.number().int().min(1).max(1e4) }).strict(),
1699
- dialog: z2.object({
1700
- type: z2.enum(["alert", "confirm", "prompt", "beforeunload"]),
1698
+ viewport: z4.object({ width: z4.number().int().min(1).max(1e4), height: z4.number().int().min(1).max(1e4) }).strict(),
1699
+ dialog: z4.object({
1700
+ type: z4.enum(["alert", "confirm", "prompt", "beforeunload"]),
1701
1701
  message: bounded(1e3)
1702
1702
  }).strict().optional(),
1703
- agentBusy: z2.boolean(),
1704
- userHasTurn: z2.boolean(),
1705
- agentOnDevice: z2.boolean()
1706
- }).strict(), gatewayToViewer = z2.discriminatedUnion("t", [
1707
- z2.object({ t: z2.literal("ready"), rights: agentViewRights, expiresAt: z2.number().int().min(0) }).strict(),
1703
+ agentBusy: z4.boolean(),
1704
+ userHasTurn: z4.boolean(),
1705
+ agentOnDevice: z4.boolean()
1706
+ }).strict(), gatewayToViewer = z4.discriminatedUnion("t", [
1707
+ z4.object({ t: z4.literal("ready"), rights: agentViewRights, expiresAt: z4.number().int().min(0) }).strict(),
1708
1708
  agentViewState,
1709
- z2.object({ t: z2.literal("picked"), reference: elementReference }).strict(),
1710
- z2.object({ t: z2.literal("ended"), reason: z2.enum(["session_ended", "producer_lost", "replaced"]) }).strict(),
1711
- z2.object({ t: z2.literal("pong") }).strict()
1712
- ]), producerMessage = z2.discriminatedUnion("t", [
1713
- z2.object({ t: z2.literal("hello"), token }).strict(),
1714
- z2.object({ t: z2.literal("reauth"), token }).strict(),
1709
+ z4.object({ t: z4.literal("picked"), reference: elementReference }).strict(),
1710
+ z4.object({ t: z4.literal("ended"), reason: z4.enum(["session_ended", "producer_lost", "replaced"]) }).strict(),
1711
+ z4.object({ t: z4.literal("pong") }).strict()
1712
+ ]), producerMessage = z4.discriminatedUnion("t", [
1713
+ z4.object({ t: z4.literal("hello"), token }).strict(),
1714
+ z4.object({ t: z4.literal("reauth"), token }).strict(),
1715
1715
  agentViewState,
1716
- z2.object({ t: z2.literal("picked"), viewer: viewerId, reference: elementReference }).strict(),
1717
- z2.object({ t: z2.literal("end") }).strict()
1718
- ]), gatewayToProducer = z2.discriminatedUnion("t", [
1719
- z2.object({ t: z2.literal("watch"), count: z2.number().int().min(0) }).strict(),
1720
- z2.object({ t: z2.literal("refresh") }).strict(),
1721
- z2.object({ t: z2.literal("input"), viewer: viewerId, input: controlInput, proof: token.optional() }).strict(),
1722
- z2.object({ t: z2.literal("pick"), viewer: viewerId, x: coordinate2, y: coordinate2 }).strict(),
1723
- z2.object({ t: z2.literal("left"), viewer: viewerId }).strict()
1724
- ]), agentViewClaims = z2.object({
1725
- iss: z2.literal("adelin-api"),
1726
- aud: z2.string().min(1).max(128),
1727
- sub: z2.string().min(1).max(128),
1716
+ z4.object({ t: z4.literal("picked"), viewer: viewerId, reference: elementReference }).strict(),
1717
+ z4.object({ t: z4.literal("end") }).strict()
1718
+ ]), gatewayToProducer = z4.discriminatedUnion("t", [
1719
+ z4.object({ t: z4.literal("watch"), count: z4.number().int().min(0) }).strict(),
1720
+ z4.object({ t: z4.literal("refresh") }).strict(),
1721
+ z4.object({ t: z4.literal("input"), viewer: viewerId, input: controlInput, proof: token.optional() }).strict(),
1722
+ z4.object({ t: z4.literal("pick"), viewer: viewerId, x: coordinate2, y: coordinate2 }).strict(),
1723
+ z4.object({ t: z4.literal("left"), viewer: viewerId }).strict()
1724
+ ]), agentViewClaims = z4.object({
1725
+ iss: z4.literal("adelin-api"),
1726
+ aud: z4.string().min(1).max(128),
1727
+ sub: z4.string().min(1).max(128),
1728
1728
  view: urlSafe(22, 64),
1729
- app: z2.uuid(),
1730
- sid: z2.string().min(1).max(128).optional(),
1729
+ app: z4.uuid(),
1730
+ sid: z4.string().min(1).max(128).optional(),
1731
1731
  rights: agentViewRights,
1732
- typ: z2.enum(["viewer", "producer"]),
1733
- iat: z2.number().int().min(0),
1734
- exp: z2.number().int().min(0),
1732
+ typ: z4.enum(["viewer", "producer"]),
1733
+ iat: z4.number().int().min(0),
1734
+ exp: z4.number().int().min(0),
1735
1735
  jti: urlSafe(22, 128)
1736
- }).strict().refine((claims) => claims.exp > claims.iat, "exp must follow iat"), dimension = z2.number().int().min(1).max(1e4), frameHeader = z2.object({
1737
- seq: z2.number().int().min(0),
1738
- ts: z2.number().int().min(0),
1736
+ }).strict().refine((claims) => claims.exp > claims.iat, "exp must follow iat"), dimension = z4.number().int().min(1).max(1e4), frameHeader = z4.object({
1737
+ seq: z4.number().int().min(0),
1738
+ ts: z4.number().int().min(0),
1739
1739
  width: dimension,
1740
1740
  height: dimension,
1741
1741
  viewportWidth: dimension,
@@ -1795,14 +1795,14 @@ async function resolvePick(session, point2) {
1795
1795
  return { hit: hit2, aria: aria2 };
1796
1796
  })(), PICK_TIMEOUT_MS + 500).catch(() => null);
1797
1797
  if (!found) return null;
1798
- let { hit, aria } = found, ariaRole = typeof aria?.role == "string" ? aria.role : "", ariaName = typeof aria?.name == "string" ? aria.name : "", ref = typeof aria?.ref == "string" ? aria.ref : "", role = capped3(session, ariaRole || hit.role || hit.tag, 40), name = capped3(session, ariaName || hit.label, 120), text4 = capped3(session, hit.text, 120);
1799
- if (!name && !text4 && UNNAMED.has(role)) return null;
1798
+ let { hit, aria } = found, ariaRole = typeof aria?.role == "string" ? aria.role : "", ariaName = typeof aria?.name == "string" ? aria.name : "", ref = typeof aria?.ref == "string" ? aria.ref : "", role = capped3(session, ariaRole || hit.role || hit.tag, 40), name = capped3(session, ariaName || hit.label, 120), text5 = capped3(session, hit.text, 120);
1799
+ if (!name && !text5 && UNNAMED.has(role)) return null;
1800
1800
  let route = routeFromHash(hit.hash), parsed = elementReference.safeParse({
1801
1801
  target: session.target,
1802
1802
  node: ref || NO_REF,
1803
1803
  role,
1804
1804
  name,
1805
- text: text4,
1805
+ text: text5,
1806
1806
  box: {
1807
1807
  x: Math.round(hit.box.x),
1808
1808
  y: Math.round(hit.box.y),
@@ -2901,6 +2901,152 @@ var init_src = __esm({
2901
2901
  }
2902
2902
  });
2903
2903
 
2904
+ // packages/tool-activity/src/appTasks.ts
2905
+ import { z as z2 } from "zod";
2906
+
2907
+ // packages/tool-activity/src/appMetadata.ts
2908
+ import { z } from "zod";
2909
+ var bytes = (value) => Buffer.byteLength(value, "utf8"), validText = (value) => !value.includes("\0") && Buffer.from(value, "utf8").toString("utf8") === value, APP_CONTEXT_PROJECTION_BYTES = 131072, AppContextProjectionSchema = z.strictObject({
2910
+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/),
2911
+ validUntil: z.iso.datetime({ offset: !0 }).nullable(),
2912
+ summaryMd: z.string().refine(validText)
2913
+ }).refine((value) => bytes(JSON.stringify(value)) <= APP_CONTEXT_PROJECTION_BYTES), CANONICAL_CONTINUATION_BYTES = 262144, CanonicalContinuationSchema = z.string().refine((value) => validText(value) && bytes(value) <= CANONICAL_CONTINUATION_BYTES), RuntimeTurnContextSchema = z.strictObject({ summaryMd: CanonicalContinuationSchema, appContext: AppContextProjectionSchema }), requirementsSchema = z.array(z.string().min(1).refine(
2914
+ (value) => value === value.trim() && [...value].length <= 512
2915
+ )).max(32).refine((items) => items.reduce((total, item) => total + bytes(item), 0) <= 16384), requirementsRevisionSchema = z.string().regex(/^(0|[1-9][0-9]{0,18})$/).pipe(z.string().refine((value) => BigInt(value) <= 9223372036854775807n)), AppRequirementsDocumentSchema = z.strictObject({ requirements: requirementsSchema, revision: requirementsRevisionSchema }), AppRequirementsMutationResultSchema = AppRequirementsDocumentSchema.extend({ outcome: z.enum(["updated", "unchanged", "conflict"]) });
2916
+ function defineTool(tool2) {
2917
+ return { ...tool2, input: z.strictObject(tool2.inputShape) };
2918
+ }
2919
+ var APP_REQUIREMENTS_TOOLS = {
2920
+ read_app_requirements: defineTool({
2921
+ name: "read_app_requirements",
2922
+ title: "Read accepted app requirements",
2923
+ description: "Read app-owned accepted intent and its exact revision, including before the first build.",
2924
+ inputShape: {},
2925
+ result: AppRequirementsDocumentSchema
2926
+ }),
2927
+ update_app_requirements: defineTool({
2928
+ name: "update_app_requirements",
2929
+ title: "Update accepted app requirements",
2930
+ description: "Replace accepted intent using its last read revision. Saves requirements metadata only; returns updated, unchanged or conflict.",
2931
+ inputShape: { requirements: requirementsSchema, expectedRevision: requirementsRevisionSchema },
2932
+ result: AppRequirementsMutationResultSchema
2933
+ })
2934
+ }, APP_MEMORY_LIMITS = Object.freeze({ maxEntries: 32, maxEntryBytes: 2048, maxBytes: 24576 }), APP_MEMORY_REQUEST_BYTES = 65536, uuid = z.uuid(), timestamp = z.iso.datetime({ offset: !0 }).max(35), memoryText = z.string().min(1).refine((value) => value === value.trim() && validText(value) && bytes(value) <= APP_MEMORY_LIMITS.maxEntryBytes), status = z.enum(["open", "completed", "abandoned"]), kind = z.enum(["work", "checkpoint"]), AppMemoryEntrySchema = z.strictObject({
2935
+ id: uuid,
2936
+ kind,
2937
+ status,
2938
+ text: memoryText,
2939
+ createdAt: timestamp,
2940
+ progressAt: timestamp,
2941
+ expiresAt: timestamp,
2942
+ renewable: z.boolean()
2943
+ }).refine((entry) => Date.parse(entry.createdAt) <= Date.parse(entry.progressAt) && Date.parse(entry.progressAt) < Date.parse(entry.expiresAt)).refine((entry) => !entry.renewable || entry.kind === "work" && entry.status === "open");
2944
+ function serializeAppMemoryEntries(entries2) {
2945
+ return JSON.stringify(entries2.map(({ id: id11, kind: kind2, status: status2, text: text5, createdAt, progressAt, expiresAt, renewable }) => ({ id: id11, kind: kind2, status: status2, text: text5, createdAt, progressAt, expiresAt, renewable })));
2946
+ }
2947
+ var unique = (ids3) => new Set(ids3).size === ids3.length, ids = z.array(uuid).min(1).max(APP_MEMORY_LIMITS.maxEntries).refine(unique), entries = z.array(AppMemoryEntrySchema).max(APP_MEMORY_LIMITS.maxEntries).refine((items) => unique(items.map((item) => item.id)) && bytes(serializeAppMemoryEntries(items)) <= APP_MEMORY_LIMITS.maxBytes), limits = z.strictObject({ maxEntries: z.literal(32), maxEntryBytes: z.literal(2048), maxBytes: z.literal(24576) }), documentShape = {
2948
+ revision: requirementsRevisionSchema,
2949
+ entries,
2950
+ bytesUsed: z.int().min(2).max(APP_MEMORY_LIMITS.maxBytes),
2951
+ limits,
2952
+ nearestExpiryAt: timestamp.nullable(),
2953
+ serverNow: timestamp
2954
+ };
2955
+ function currentDocument(value) {
2956
+ let nearest = [...value.entries].sort((left, right) => Date.parse(left.expiresAt) - Date.parse(right.expiresAt))[0]?.expiresAt ?? null;
2957
+ return value.bytesUsed === bytes(serializeAppMemoryEntries(value.entries)) && value.nearestExpiryAt === nearest && value.entries.every((entry) => Date.parse(entry.expiresAt) > Date.parse(value.serverNow));
2958
+ }
2959
+ var AppMemoryDocumentSchema = z.strictObject(documentShape).refine(currentDocument), AppMemoryOperationSchema = z.discriminatedUnion("type", [
2960
+ z.strictObject({ type: z.literal("create"), id: uuid, kind, text: memoryText }),
2961
+ z.strictObject({ type: z.literal("update"), id: uuid, text: memoryText, status, progress: z.boolean() }),
2962
+ z.strictObject({ type: z.literal("remove"), ids }),
2963
+ z.strictObject({ type: z.literal("consolidate"), sourceIds: ids.refine((items) => items.length >= 2), id: uuid, text: memoryText }).refine((operation) => !operation.sourceIds.includes(operation.id))
2964
+ ]), mutationShape = { operationId: uuid, expectedRevision: requirementsRevisionSchema, operation: AppMemoryOperationSchema }, AppMemoryMutationInputSchema = z.strictObject(mutationShape).refine((value) => bytes(JSON.stringify(value)) <= APP_MEMORY_REQUEST_BYTES), AppMemoryOutcomeSchema = z.enum(["updated", "unchanged", "conflict", "capacity", "replayed", "operation_conflict", "reconciliation_required", "nonrenewable"]), AppMemoryReceiptSchema = z.strictObject({ operationId: uuid, outcome: AppMemoryOutcomeSchema, revision: requirementsRevisionSchema }), AppMemoryMutationResultSchema = z.strictObject({
2965
+ ...documentShape,
2966
+ outcome: AppMemoryOutcomeSchema,
2967
+ receipt: AppMemoryReceiptSchema.optional(),
2968
+ recoveryActions: z.array(z.enum(["read", "remove", "reduce", "consolidate", "create"])).max(5).optional(),
2969
+ message: z.string().min(1).max(512).refine(validText).optional()
2970
+ }).refine(currentDocument), APP_MEMORY_TOOLS = {
2971
+ read_app_memory: defineTool({
2972
+ name: "read_app_memory",
2973
+ title: "Read app memory",
2974
+ description: "Read bounded current working context. Follow authoring/app-memory.md in the app-generation skill; context is not authority or saved-app proof.",
2975
+ inputShape: {},
2976
+ result: AppMemoryDocumentSchema
2977
+ }),
2978
+ mutate_app_memory: { ...defineTool({
2979
+ name: "mutate_app_memory",
2980
+ title: "Update app memory",
2981
+ description: "Checkpoint, correct, remove or consolidate working context using its last read revision. Follow authoring/app-memory.md in the app-generation skill.",
2982
+ inputShape: mutationShape,
2983
+ result: AppMemoryMutationResultSchema
2984
+ }), input: AppMemoryMutationInputSchema }
2985
+ };
2986
+
2987
+ // packages/tool-activity/src/appTasks.ts
2988
+ var AppTaskError = class extends Error {
2989
+ }, AppTaskSaveReceiptSchema = z2.strictObject({ taskId: z2.uuid(), saveToken: z2.uuid(), settled: z2.boolean() }), uuid2 = z2.uuid().toLowerCase(), AppTaskSaveFenceSchema = z2.strictObject({ taskId: uuid2, saveToken: uuid2, turnToken: uuid2 }), text = z2.string().trim().min(1).max(768).refine((value) => !value.includes("\0") && Buffer.from(value).toString("utf8") === value), intent = { goal: text, why: text, constraints: text, doneWhen: text }, checkpoint = { done: text, reason: text, checks: text, next: text, saveToken: uuid2.nullable() }, AppTaskSaveContextSchema = z2.strictObject({
2990
+ actorId: uuid2,
2991
+ leaseId: uuid2,
2992
+ chatSessionId: uuid2,
2993
+ epoch: z2.number().int().positive().safe(),
2994
+ turnToken: uuid2
2995
+ }), AppTaskSchema = z2.strictObject({
2996
+ type: z2.literal("app-task"),
2997
+ version: z2.literal(1),
2998
+ ...intent,
2999
+ state: z2.enum(["active", "paused", "completed", "abandoned"]),
3000
+ lastSave: uuid2.nullable(),
3001
+ pending: AppTaskSaveContextSchema.nullable(),
3002
+ checkpoint: z2.strictObject(checkpoint).nullable()
3003
+ }), AppTaskOperationSchema = z2.discriminatedUnion("action", [
3004
+ z2.strictObject({ action: z2.literal("start"), id: uuid2, ...intent }),
3005
+ z2.strictObject({ action: z2.literal("checkpoint"), id: uuid2, ...checkpoint }),
3006
+ z2.strictObject({ action: z2.literal("recover"), id: uuid2, ...checkpoint }),
3007
+ z2.strictObject({ action: z2.literal("finish"), id: uuid2, outcome: z2.enum(["completed", "paused", "abandoned"]) }),
3008
+ z2.strictObject({ action: z2.literal("resume"), id: uuid2 }),
3009
+ z2.strictObject({ action: z2.literal("remove"), id: uuid2 })
3010
+ ]), inputShape = { operationId: uuid2, expectedRevision: requirementsRevisionSchema, operation: AppTaskOperationSchema, task: AppTaskSchema.optional() }, taskInput = z2.strictObject(inputShape).refine(
3011
+ (value) => value.operation.action === "start" ? value.task === void 0 : value.task !== void 0,
3012
+ { message: "Include the original task snapshot for checkpoint, finish, resume, recover or remove." }
3013
+ ), APP_TASK_TOOL = {
3014
+ name: "manage_app_task",
3015
+ title: "Record app task",
3016
+ description: "Start a task with goal, why, constraints and doneWhen before app changes; keep intent within 768 UTF-8 bytes. Pass its id as task_id to builds and deletions. Checkpoint cumulative done, reason, checks, next and latest saveToken (null before any save), within 768 UTF-8 bytes. Finish completed/paused/abandoned only with a current checkpoint; resume paused tasks. Read read_app_memory first; use exact revision and include task as the exact parsed snapshot for every action except start. Preserve the entire request on retries. Recover a pending save only after its original turn lost write authority, recording inspected outcome and uncertainty. Remove only closed task history. One active task per app. Stored context does not prove a build succeeded.",
3017
+ inputShape,
3018
+ input: taskInput,
3019
+ result: AppMemoryMutationResultSchema
3020
+ };
3021
+ function parsedTask(value) {
3022
+ try {
3023
+ let parsed = AppTaskSchema.safeParse(JSON.parse(value));
3024
+ return parsed.success ? parsed.data : null;
3025
+ } catch {
3026
+ return null;
3027
+ }
3028
+ }
3029
+ function readTask(entry) {
3030
+ let task = parsedTask(entry.text);
3031
+ return task && entry.kind === "work" && (["active", "paused"].includes(task.state) ? entry.status === "open" : entry.status === task.state) ? task : null;
3032
+ }
3033
+ function assertTaskWritable(document, taskId) {
3034
+ let targetId = uuid2.parse(taskId), row = document.entries.find((entry) => entry.id.toLowerCase() === targetId), task = row && readTask(row);
3035
+ if (!task || task.state !== "active") throw new AppTaskError("Start or resume this app task with manage_app_task before saving changes.");
3036
+ if (task.pending) throw new AppTaskError("The task already has an unsettled save. Wait for its result before another save.");
3037
+ return row;
3038
+ }
3039
+ function assertTaskCheckpoint(document) {
3040
+ for (let entry of document.entries) {
3041
+ let task = readTask(entry);
3042
+ if (task) {
3043
+ if (task.pending) throw new AppTaskError("The task has an unsettled save. Reconcile it and record a checkpoint before ending this turn.");
3044
+ if (!task.checkpoint || task.checkpoint.saveToken !== task.lastSave)
3045
+ throw new AppTaskError("Record a task checkpoint with done, reason, checks and next covering the latest save before ending this turn.");
3046
+ }
3047
+ }
3048
+ }
3049
+
2904
3050
  // skills/adelin-app-generation/scripts/local-builder.mjs
2905
3051
  import { randomBytes as randomBytes8, randomUUID as randomUUID7 } from "node:crypto";
2906
3052
  import { mkdtempSync as mkdtempSync2, mkdirSync as mkdirSync5, realpathSync as realpathSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "node:fs";
@@ -3193,19 +3339,19 @@ var LocalBuildSession = class {
3193
3339
  }
3194
3340
  }
3195
3341
  /** Saves workspace images through `assets` first, unless a save is pending, then sends the changed source. */
3196
- async build({ assets } = {}) {
3342
+ async build({ assets, taskId } = {}) {
3197
3343
  let session = this.session;
3198
3344
  if (!session || this.state !== "active" || this.busy) throw new Error("No active edit session. Open the app first.");
3199
3345
  this.busy = !0, session.lastActivity = this.now();
3200
3346
  try {
3201
3347
  let { workspace, appId, leaseId, chatSessionId, epoch } = session, saved = null;
3202
3348
  if (assets && !readPendingSave(workspace, appId)) {
3203
- let synced = await assets({ workspace, appId, leaseId, chatSessionId, epoch });
3349
+ let synced = await assets({ workspace, appId, leaseId, chatSessionId, epoch, taskId });
3204
3350
  if (synced && !synced.ok) return synced.result;
3205
3351
  saved = synced?.report ?? null;
3206
3352
  }
3207
- let withAssets = (outcome3) => saved ? { ...outcome3, assets: saved } : outcome3, prepared = prepareSave(workspace, appId, { leaseId, chatSessionId, epoch });
3208
- if (prepared.state === "no_changes") return withAssets(prepared);
3353
+ let withAssets = (outcome3) => saved ? { ...outcome3, assets: saved } : outcome3, prepared = prepareSave(workspace, appId, { leaseId, chatSessionId, epoch }, { taskId });
3354
+ if (prepared.state === "no_changes") return withAssets(saved?.saved?.length ? { ...prepared, state: "assets_saved", task: saved.saved.at(-1).task } : prepared);
3209
3355
  let request = JSON.parse(readFileSync(prepared.requestPath, "utf8")), result = await this.call("save_app_changes", request), outcome2 = applySave(workspace, appId, result);
3210
3356
  return session.fingerprint = this.fingerprint(workspace, appId), withAssets(outcome2);
3211
3357
  } finally {
@@ -3301,7 +3447,7 @@ function openBrowser(url) {
3301
3447
  }
3302
3448
 
3303
3449
  // skills/adelin-app-generation/scripts/local-device-approval.mjs
3304
- var labels = { tvos: "Apple TV", "android-tv": "Android TV", ios: "iPhone", android: "Android phone" }, escape = (text4) => String(text4).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]);
3450
+ var labels = { tvos: "Apple TV", "android-tv": "Android TV", ios: "iPhone", android: "Android phone" }, escape = (text5) => String(text5).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]);
3305
3451
  async function approveCloudDevice(server, { platform, reason, signal, requestId }, { open = openBrowser, timeoutMs = 3e5 } = {}) {
3306
3452
  signal?.throwIfAborted();
3307
3453
  let preferred = platform === "tv" ? "tvos" : platform === "phone" ? "ios" : platform, platforms = [preferred, ...Object.keys(labels).filter((value) => value !== preferred)], message = `Start a cloud device to test this app? This uses your organization's preview minutes.${reason ? ` Reason: ${reason}` : ""}`;
@@ -3411,21 +3557,21 @@ function optionalText(path, maxBytes) {
3411
3557
  return lstatIfPresent(path) ? readSafeFile2(path, maxBytes).toString("utf8") : null;
3412
3558
  }
3413
3559
  function manifestAt(root, appId) {
3414
- let path = assertSafeTarget(root, MANIFEST2), text4 = readSafeFile2(path).toString("utf8");
3415
- return { path, text: text4, value: parseManifest2(text4, appId) };
3560
+ let path = assertSafeTarget(root, MANIFEST2), text5 = readSafeFile2(path).toString("utf8");
3561
+ return { path, text: text5, value: parseManifest2(text5, appId) };
3416
3562
  }
3417
3563
  function contractAt(root, appId) {
3418
- let path = stateFile(root, CONTRACT), text4 = optionalText(path), value = null;
3419
- if (text4 !== null) {
3564
+ let path = stateFile(root, CONTRACT), text5 = optionalText(path), value = null;
3565
+ if (text5 !== null) {
3420
3566
  try {
3421
- value = JSON.parse(text4);
3567
+ value = JSON.parse(text5);
3422
3568
  } catch {
3423
3569
  throw new Error("Invalid workspace support contract marker.");
3424
3570
  }
3425
3571
  if (!record(value) || value.schema !== 1 || value.appId !== appId || !HASH.test(value.contractId))
3426
3572
  throw new Error("Invalid workspace support contract marker.");
3427
3573
  }
3428
- return { path, text: text4, value };
3574
+ return { path, text: text5, value };
3429
3575
  }
3430
3576
  function desiredSupport(release2, appId) {
3431
3577
  let { support, manifest } = release2 ?? {};
@@ -3468,18 +3614,18 @@ function overwrite(root, path, content, previous) {
3468
3614
  atomicFile(root, path, content, previous !== null);
3469
3615
  }
3470
3616
  function readJournal(root, appId) {
3471
- let path = stateFile(root, SUPPORT_PENDING), text4 = optionalText(path, MAX_BUNDLE_BYTES * 2);
3472
- if (text4 === null) return null;
3617
+ let path = stateFile(root, SUPPORT_PENDING), text5 = optionalText(path, MAX_BUNDLE_BYTES * 2);
3618
+ if (text5 === null) return null;
3473
3619
  let journal;
3474
3620
  try {
3475
- journal = JSON.parse(text4);
3621
+ journal = JSON.parse(text5);
3476
3622
  } catch {
3477
3623
  throw new Error("Invalid pending workspace support refresh.");
3478
3624
  }
3479
3625
  if (!record(journal) || journal.schema !== 1 || journal.appId !== appId || !UUID.test(journal.id) || !validPid(journal.ownerPid) || !HASH.test(journal.beforeManifest) || !HASH.test(journal.afterManifest) || !record(journal.beforeSupport) || journal.beforeContract !== null && !HASH.test(journal.beforeContract) || Object.entries(journal.beforeSupport).some(([name, stamp]) => !supportPath(name) || !record(stamp) || !HASH.test(stamp.sha256)))
3480
3626
  throw new Error("Invalid pending workspace support refresh.");
3481
3627
  let desired = desiredSupport({ support: journal.support, manifest: { contractId: journal.contractId } }, appId);
3482
- return { path, text: text4, journal, desired };
3628
+ return { path, text: text5, journal, desired };
3483
3629
  }
3484
3630
  function settle(root, appId, pending) {
3485
3631
  guardWorkspace(root);
@@ -3571,7 +3717,7 @@ function syncWorkspaceSupportLocked(workspace, appId, release2) {
3571
3717
  if (blocked.length) throw new Error(`Workspace support conflict at ${blocked.join(", ")}. Inspect these paths and rerun adelin setup.`);
3572
3718
  if (contract.value?.contractId === desired.contractId && same(manifest.value.support, desired.stamps))
3573
3719
  return { status: recovered ? "refreshed" : "current", contractId: desired.contractId };
3574
- let path = stateFile(root, SUPPORT_PENDING), text4 = json({
3720
+ let path = stateFile(root, SUPPORT_PENDING), text5 = json({
3575
3721
  schema: 1,
3576
3722
  id: randomUUID(),
3577
3723
  ownerPid: process.pid,
@@ -3583,7 +3729,7 @@ function syncWorkspaceSupportLocked(workspace, appId, release2) {
3583
3729
  support: desired.support,
3584
3730
  contractId: desired.contractId
3585
3731
  });
3586
- return atomicFile(root, path, text4, !1), settleOwned(root, appId, readJournal(root, appId), 0), { status: "refreshed", contractId: desired.contractId };
3732
+ return atomicFile(root, path, text5, !1), settleOwned(root, appId, readJournal(root, appId), 0), { status: "refreshed", contractId: desired.contractId };
3587
3733
  }
3588
3734
 
3589
3735
  // skills/adelin-app-generation/scripts/cli-project.mjs
@@ -3643,9 +3789,9 @@ function gitProject(root) {
3643
3789
  return null;
3644
3790
  }
3645
3791
  }
3646
- function loadJson(text4, label) {
3792
+ function loadJson(text5, label) {
3647
3793
  try {
3648
- return JSON.parse(text4);
3794
+ return JSON.parse(text5);
3649
3795
  } catch {
3650
3796
  throw new Error(`Invalid ${label}.`);
3651
3797
  }
@@ -3674,10 +3820,10 @@ ${CODEX_END}
3674
3820
  function clientIsCurrent(root, client, registered) {
3675
3821
  let file = clientConfigFile(root, client);
3676
3822
  if (file !== registered?.file || !record2(registered.fields)) return !1;
3677
- let text4 = optionalFile(join3(root, file));
3678
- if (text4 === null) return !1;
3679
- if (client === "codex") return text4.includes(codexBlock(registered.fields));
3680
- let errors = [], config = parse(text4, errors, { allowTrailingComma: !0 });
3823
+ let text5 = optionalFile(join3(root, file));
3824
+ if (text5 === null) return !1;
3825
+ if (client === "codex") return text5.includes(codexBlock(registered.fields));
3826
+ let errors = [], config = parse(text5, errors, { allowTrailingComma: !0 });
3681
3827
  if (errors.length || !record2(config)) return !1;
3682
3828
  let existing = client === "claude" ? config.mcpServers?.adelin : (record2(config.mcp?.servers) ? config.mcp.servers : config.mcp)?.adelin;
3683
3829
  return existing?.type !== (client === "claude" ? "stdio" : "local") ? !1 : same2(existing.command, registered.fields.command) && (client !== "claude" || same2(existing.args, registered.fields.args));
@@ -3849,8 +3995,8 @@ var CONTROL_RE = /[\u0000-\u001f\u007f]/;
3849
3995
  function plainObject(value) {
3850
3996
  return typeof value == "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
3851
3997
  }
3852
- function codePointLength(text4) {
3853
- return Array.from(text4).length;
3998
+ function codePointLength(text5) {
3999
+ return Array.from(text5).length;
3854
4000
  }
3855
4001
  function canonicalSubtag(part) {
3856
4002
  return /^[A-Za-z]{4}$/.test(part) ? part[0].toUpperCase() + part.slice(1).toLowerCase() : /^[A-Za-z]{2}$/.test(part) ? part.toUpperCase() : part;
@@ -3870,16 +4016,16 @@ function parseLocalizedText(value, opts) {
3870
4016
  let out = {};
3871
4017
  for (let key4 of keys3) {
3872
4018
  if (typeof key4 != "string" || canonicalLanguageTag(key4) !== key4) return null;
3873
- let text4 = value[key4];
3874
- if (typeof text4 != "string") return null;
3875
- let trimmed = text4.trim();
4019
+ let text5 = value[key4];
4020
+ if (typeof text5 != "string") return null;
4021
+ let trimmed = text5.trim();
3876
4022
  if (trimmed.length === 0 || codePointLength(trimmed) > opts.maxLength) return null;
3877
4023
  out[key4] = trimmed;
3878
4024
  }
3879
4025
  return out;
3880
4026
  }
3881
4027
  function hasControlCharacters(map) {
3882
- return Object.values(map).some((text4) => CONTROL_RE.test(text4));
4028
+ return Object.values(map).some((text5) => CONTROL_RE.test(text5));
3883
4029
  }
3884
4030
  function parseLocalizedPatch(value, opts) {
3885
4031
  if (!plainObject(value)) return null;
@@ -3888,13 +4034,13 @@ function parseLocalizedPatch(value, opts) {
3888
4034
  let out = {};
3889
4035
  for (let key4 of keys3) {
3890
4036
  if (typeof key4 != "string" || canonicalLanguageTag(key4) !== key4) return null;
3891
- let text4 = value[key4];
3892
- if (text4 === null) {
4037
+ let text5 = value[key4];
4038
+ if (text5 === null) {
3893
4039
  out[key4] = null;
3894
4040
  continue;
3895
4041
  }
3896
- if (typeof text4 != "string") return null;
3897
- let trimmed = text4.trim();
4042
+ if (typeof text5 != "string") return null;
4043
+ let trimmed = text5.trim();
3898
4044
  if (codePointLength(trimmed) > opts.maxLength) return null;
3899
4045
  out[key4] = trimmed;
3900
4046
  }
@@ -3934,24 +4080,24 @@ function normalizeSubtitleLanguages(value) {
3934
4080
  return result;
3935
4081
  }
3936
4082
  function decodeSubtitleText(bytes2) {
3937
- let text4;
4083
+ let text5;
3938
4084
  try {
3939
- text4 = new TextDecoder("utf-8", { fatal: !0, ignoreBOM: !1 }).decode(bytes2);
4085
+ text5 = new TextDecoder("utf-8", { fatal: !0, ignoreBOM: !1 }).decode(bytes2);
3940
4086
  } catch {
3941
4087
  return { ok: !1, code: "LIBRARY_SUBTITLE_ENCODING" };
3942
4088
  }
3943
- return text4.includes("\0") ? { ok: !1, code: "LIBRARY_SUBTITLE_ENCODING" } : { ok: !0, text: text4.replace(/^/, "").replace(/\r\n?/g, `
4089
+ return text5.includes("\0") ? { ok: !1, code: "LIBRARY_SUBTITLE_ENCODING" } : { ok: !0, text: text5.replace(/^/, "").replace(/\r\n?/g, `
3944
4090
  `) };
3945
4091
  }
3946
- function normaliseVttText(text4) {
3947
- let firstLine = text4.split(`
4092
+ function normaliseVttText(text5) {
4093
+ let firstLine = text5.split(`
3948
4094
  `, 1)[0] ?? "";
3949
- return VTT_HEADER.test(firstLine) ? { ok: !0, vtt: text4.endsWith(`
3950
- `) ? text4 : `${text4}
4095
+ return VTT_HEADER.test(firstLine) ? { ok: !0, vtt: text5.endsWith(`
4096
+ `) ? text5 : `${text5}
3951
4097
  ` } : INVALID;
3952
4098
  }
3953
- function convertSrtText(text4) {
3954
- let lines = text4.split(`
4099
+ function convertSrtText(text5) {
4100
+ let lines = text5.split(`
3955
4101
  `);
3956
4102
  if (!lines.some((line) => line.includes("-->"))) return INVALID;
3957
4103
  let body = lines.map((line) => line.includes("-->") ? line.replace(SRT_TIMESTAMP, "$1.$2") : line).join(`
@@ -4099,7 +4245,7 @@ function parsePublicTypeSpec(value) {
4099
4245
  var str = (value) => (typeof value != "string" && fail(), value), tagValue = (value) => ((typeof value != "string" || canonicalLanguageTag(value) !== value) && fail(), value), localized = (max, allowEmpty = !1) => (value) => {
4100
4246
  (!value || typeof value != "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) && fail();
4101
4247
  let entries2 = Object.entries(value);
4102
- return (!allowEmpty && !entries2.length || entries2.length > MAX_LOCALIZED_KEYS || entries2.some(([tag, text4]) => canonicalLanguageTag(tag) !== tag || typeof text4 != "string" || !text4.trim() || [...text4].length > max)) && fail(), value;
4248
+ return (!allowEmpty && !entries2.length || entries2.length > MAX_LOCALIZED_KEYS || entries2.some(([tag, text5]) => canonicalLanguageTag(tag) !== tag || typeof text5 != "string" || !text5.trim() || [...text5].length > max)) && fail(), value;
4103
4249
  }, languageList = (min = 0) => (value) => {
4104
4250
  let tags = array(tagValue, MAX_LOCALIZED_KEYS)(value);
4105
4251
  return (tags.length < min || new Set(tags).size !== tags.length) && fail(), tags;
@@ -4694,7 +4840,7 @@ var vocabularyActions = [
4694
4840
  "field.localized",
4695
4841
  "entry.fields.patch",
4696
4842
  "app.languages.set"
4697
- ], collectionActions = ["collection.create", "collection.update", "collection.delete", "collection.members.replace", "collection.members.add", "collection.members.remove"], fileActions = ["entry.assets", "entry.artwork.remove", "entry.subtitle.remove", "entry.subtitle.language", "entry.subtitle.languages"], mutationActions = Object.freeze(["entry.create", "entry.patch", "entry.move", "folder.replace", "entry.delete", ...vocabularyActions, "entry.save", "entry.publish", "entry.discard", "entry.draft", "entry.schedule", "entry.schedule.cancel", ...fileActions, ...collectionActions, "preview.page", "operation.inspect"]), uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, libraryOperations = Object.freeze({
4843
+ ], collectionActions = ["collection.create", "collection.update", "collection.delete", "collection.members.replace", "collection.members.add", "collection.members.remove"], fileActions = ["entry.assets", "entry.artwork.remove", "entry.subtitle.remove", "entry.subtitle.language", "entry.subtitle.languages"], mutationActions = Object.freeze(["entry.create", "entry.patch", "entry.move", "folder.replace", "entry.delete", ...vocabularyActions, "entry.save", "entry.publish", "entry.discard", "entry.draft", "entry.schedule", "entry.schedule.cancel", ...fileActions, ...collectionActions, "preview.page", "operation.inspect"]), uuid3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, libraryOperations = Object.freeze({
4698
4844
  mutate: "mutate_library",
4699
4845
  schema: "get_content_schema",
4700
4846
  tree: "get_library_tree",
@@ -4708,9 +4854,9 @@ var vocabularyActions = [
4708
4854
  "sample-import": "get_library_sample_import",
4709
4855
  "sample-import-advance": "mutate_library_sample_import"
4710
4856
  }), lowerId = (value) => {
4711
- if (typeof value != "string" || !uuid.test(value)) throw Error("INVALID_ARGUMENT");
4857
+ if (typeof value != "string" || !uuid3.test(value)) throw Error("INVALID_ARGUMENT");
4712
4858
  return value.toLowerCase();
4713
- }, invalid = (detail) => Object.assign(Error("INVALID_ARGUMENT"), { detail }), UUID3 = uuid.source, KEY = "^[a-z][a-z0-9_]{0,62}$", REVISION = "^(0|[1-9][0-9]{0,18})$", HEX64 = "^[a-f0-9]{64}$", TEXT = "\\S", LANGUAGE = LANGUAGE_TAG_PATTERN.source, id2 = { type: "string", pattern: UUID3 }, nullableId = { anyOf: [id2, { type: "null" }] }, key2 = { type: "string", pattern: KEY }, ids = (maxItems, minItems = 0) => ({ type: "array", items: id2, maxItems, minItems, uniqueItems: !0 }), closedSchema = (properties, required = [], extra = {}) => ({ type: "object", properties, required, additionalProperties: !1, ...extra }), language = { type: "string", pattern: LANGUAGE }, languageMap = (text4, min) => ({ type: "object", propertyNames: language, additionalProperties: text4, minProperties: min, maxProperties: MAX_LOCALIZED_KEYS }), localizedText = (max, min = 1) => languageMap({ type: "string", minLength: 1, maxLength: max, pattern: TEXT }, min), localizedPatch = (max, min = 0) => languageMap({ type: ["string", "null"], minLength: 1, maxLength: max, pattern: TEXT }, min), named = { name: localizedText(80), choice: { const: "create-distinct" } }, typeSpec = closedSchema({ k: { type: "string" }, of: {}, props: {}, localized: { const: !0 } }, ["k"]), note = { type: "string", maxLength: 2e3 }, entryOnly = closedSchema({ entry_id: id2 }, ["entry_id"]), members = (minItems) => closedSchema({ collection_id: id2, entry_ids: { type: "array", items: id2, maxItems: 500, minItems } }, ["collection_id", "entry_ids"]), createPayload = closedSchema({
4859
+ }, invalid = (detail) => Object.assign(Error("INVALID_ARGUMENT"), { detail }), UUID3 = uuid3.source, KEY = "^[a-z][a-z0-9_]{0,62}$", REVISION = "^(0|[1-9][0-9]{0,18})$", HEX64 = "^[a-f0-9]{64}$", TEXT = "\\S", LANGUAGE = LANGUAGE_TAG_PATTERN.source, id2 = { type: "string", pattern: UUID3 }, nullableId = { anyOf: [id2, { type: "null" }] }, key2 = { type: "string", pattern: KEY }, ids2 = (maxItems, minItems = 0) => ({ type: "array", items: id2, maxItems, minItems, uniqueItems: !0 }), closedSchema = (properties, required = [], extra = {}) => ({ type: "object", properties, required, additionalProperties: !1, ...extra }), language = { type: "string", pattern: LANGUAGE }, languageMap = (text5, min) => ({ type: "object", propertyNames: language, additionalProperties: text5, minProperties: min, maxProperties: MAX_LOCALIZED_KEYS }), localizedText = (max, min = 1) => languageMap({ type: "string", minLength: 1, maxLength: max, pattern: TEXT }, min), localizedPatch = (max, min = 0) => languageMap({ type: ["string", "null"], minLength: 1, maxLength: max, pattern: TEXT }, min), named = { name: localizedText(80), choice: { const: "create-distinct" } }, typeSpec = closedSchema({ k: { type: "string" }, of: {}, props: {}, localized: { const: !0 } }, ["k"]), note = { type: "string", maxLength: 2e3 }, entryOnly = closedSchema({ entry_id: id2 }, ["entry_id"]), members = (minItems) => closedSchema({ collection_id: id2, entry_ids: { type: "array", items: id2, maxItems: 500, minItems } }, ["collection_id", "entry_ids"]), createPayload = closedSchema({
4714
4860
  kind: { enum: ["item", "folder"] },
4715
4861
  mediaType: { enum: ["video", "audio", "live", null] },
4716
4862
  title: localizedText(300),
@@ -4742,16 +4888,16 @@ var vocabularyActions = [
4742
4888
  label: labelChoice,
4743
4889
  fields: fieldsPatch,
4744
4890
  move: closedSchema({ parent_id: nullableId, position }, ["parent_id", "position"]),
4745
- replace: ids(1e3)
4891
+ replace: ids2(1e3)
4746
4892
  })],
4747
4893
  [["entry.move"], closedSchema({ entry_id: id2, parent_id: nullableId, position }, ["entry_id", "parent_id", "position"])],
4748
- [["folder.replace"], closedSchema({ folder_id: id2, child_ids: ids(1e3) }, ["folder_id", "child_ids"])],
4894
+ [["folder.replace"], closedSchema({ folder_id: id2, child_ids: ids2(1e3) }, ["folder_id", "child_ids"])],
4749
4895
  [["entry.delete", "entry.discard", "entry.draft", "entry.schedule.cancel", "entry.label.clear"], entryOnly],
4750
- [["entry.publish"], closedSchema({ entry_id: id2, child_ids: ids(200) }, ["entry_id"])],
4896
+ [["entry.publish"], closedSchema({ entry_id: id2, child_ids: ids2(200) }, ["entry_id"])],
4751
4897
  [["entry.schedule"], closedSchema({
4752
4898
  entry_id: id2,
4753
4899
  at: { anyOf: [{ type: "string" }, { type: "null" }, closedSchema({ utc: { type: "string" }, wall: { type: "string" }, zone: { type: "string" } })] },
4754
- child_ids: ids(200)
4900
+ child_ids: ids2(200)
4755
4901
  }, ["entry_id"])],
4756
4902
  [["label.create"], closedSchema(named, ["name"])],
4757
4903
  [["label.rename"], closedSchema({ key: key2, name: localizedPatch(80, 1) }, ["key", "name"])],
@@ -4794,7 +4940,7 @@ var vocabularyActions = [
4794
4940
  "recording.reconfigure",
4795
4941
  "operation.inspect",
4796
4942
  "preview.page"
4797
- ]), livePreviewActions = Object.freeze(["stream.reset", "stream.delete"]), hex64 = { type: "string", pattern: HEX64 }, scheduleRevision = { type: "integer", minimum: 0, maximum: 2147483647 }, liveSettings = closedSchema({ policy: { enum: ["manual", "draft", "publish"] }, folder_id: nullableId }, ["policy", "folder_id"]), liveOptions = closedSchema({ dvr_enabled: { type: "boolean" }, show_viewer_count: { type: "boolean" } }, [], { minProperties: 1 }), recordingList = closedSchema({ entry_ids: ids(100, 1) }, ["entry_ids"]), weeklyDay = closedSchema({
4943
+ ]), livePreviewActions = Object.freeze(["stream.reset", "stream.delete"]), hex64 = { type: "string", pattern: HEX64 }, scheduleRevision = { type: "integer", minimum: 0, maximum: 2147483647 }, liveSettings = closedSchema({ policy: { enum: ["manual", "draft", "publish"] }, folder_id: nullableId }, ["policy", "folder_id"]), liveOptions = closedSchema({ dvr_enabled: { type: "boolean" }, show_viewer_count: { type: "boolean" } }, [], { minProperties: 1 }), recordingList = closedSchema({ entry_ids: ids2(100, 1) }, ["entry_ids"]), weeklyDay = closedSchema({
4798
4944
  weekday: { type: "integer", minimum: 1, maximum: 7 },
4799
4945
  times: { type: "array", items: { type: "string", pattern: "^([01]\\d|2[0-3]):[0-5]\\d$" }, minItems: 1, maxItems: 48 }
4800
4946
  }, ["weekday", "times"]), liveSchedule = { anyOf: [
@@ -4860,7 +5006,7 @@ function explainArguments(schema, value, path = "") {
4860
5006
  let length = [...value].length;
4861
5007
  if (schema.minLength && length < schema.minLength) return `${where(path)}: expected non-empty text`;
4862
5008
  if (schema.maxLength !== void 0 && length > schema.maxLength) return `${where(path)}: expected at most ${schema.maxLength} characters`;
4863
- if (schema.format === "uuid" && !uuid.test(value) || schema.pattern && !new RegExp(schema.pattern).test(value))
5009
+ if (schema.format === "uuid" && !uuid3.test(value) || schema.pattern && !new RegExp(schema.pattern).test(value))
4864
5010
  return `${where(path)}: expected ${formats[schema.pattern] ?? (schema.format === "uuid" ? formats[UUID3] : "the documented format")}`;
4865
5011
  }
4866
5012
  if (typeof value == "number") {
@@ -4903,7 +5049,7 @@ function explainFilePayload(action, payload, previewed) {
4903
5049
  return role ? `payload.assets.${role}: detach with entry.assets` : null;
4904
5050
  }
4905
5051
  if (action === "entry.assets") {
4906
- let role = roles.find((name) => payload[name] !== void 0 && payload[name] !== null && !(typeof payload[name] == "string" && uuid.test(payload[name])));
5052
+ let role = roles.find((name) => payload[name] !== void 0 && payload[name] !== null && !(typeof payload[name] == "string" && uuid3.test(payload[name])));
4907
5053
  return role ? `payload.${role}: expected a UUID or null` : roles.every((name) => payload[name] === void 0) ? "payload needs main, trailer or both" : previewed && !detaches2(payload) ? DETACH_ONLY : null;
4908
5054
  }
4909
5055
  return action === "entry.artwork.remove" && payload.slot !== void 0 && !artworkSlots.includes(payload.slot) ? `payload.slot: expected one of ${artworkSlots.join(", ")}` : action === "entry.artwork.remove" && !artworkLanguage(payload.language) ? "payload.language: expected an app language tag such as lt or pt-BR, or nothing for the first language" : action === "entry.subtitle.language" && payload.language !== void 0 && !subtitleLanguageValid(payload.language) ? "payload.language: expected a language tag such as en or pt-BR" : null;
@@ -4986,10 +5132,10 @@ function normalizeLibraryArgs(operation, args) {
4986
5132
  ...operation === "entry" ? ["entry_id"] : ["limit", "cursor"],
4987
5133
  ...operation === "tree" ? ["media", "label", "status", "q", "section"] : operation === "schema" ? ["section"] : operation === "entry-section" ? ["entry_id", "section"] : operation === "publish-candidates" ? ["entry_id"] : operation === "collections" ? ["q", "media"] : operation === "collection" ? ["collection_id", "section"] : []
4988
5134
  ];
4989
- if (Object.keys(args).some((key4) => !allowed.includes(key4)) || !uuid.test(args.app_id ?? "")) throw Error("INVALID_ARGUMENT");
5135
+ if (Object.keys(args).some((key4) => !allowed.includes(key4)) || !uuid3.test(args.app_id ?? "")) throw Error("INVALID_ARGUMENT");
4990
5136
  let result = { ...args, app_id: args.app_id.toLowerCase() };
4991
5137
  if (operation.startsWith("entry") || operation === "publish-candidates") {
4992
- if (!uuid.test(args.entry_id ?? "")) throw Error("INVALID_ARGUMENT");
5138
+ if (!uuid3.test(args.entry_id ?? "")) throw Error("INVALID_ARGUMENT");
4993
5139
  result.entry_id = args.entry_id.toLowerCase();
4994
5140
  }
4995
5141
  if (operation === "collection" && (result.collection_id = lowerId(args.collection_id)), args.limit !== void 0 && (!Number.isInteger(args.limit) || args.limit < 1 || args.limit > 100) || args.cursor !== void 0 && (typeof args.cursor != "string" || !args.cursor || args.cursor.length > 2048)) throw Error("INVALID_ARGUMENT");
@@ -5067,20 +5213,20 @@ function closed(value, required, optional = []) {
5067
5213
  }
5068
5214
  function normalizeMutation(args) {
5069
5215
  if (args?.action === "operation.inspect") {
5070
- if (closed(args, ["app_id", "action", "target_operation_id"]), ![args.app_id, args.target_operation_id].every((v) => typeof v == "string" && uuid.test(v))) throw Error("INVALID_ARGUMENT");
5216
+ if (closed(args, ["app_id", "action", "target_operation_id"]), ![args.app_id, args.target_operation_id].every((v) => typeof v == "string" && uuid3.test(v))) throw Error("INVALID_ARGUMENT");
5071
5217
  return { ...args, app_id: args.app_id.toLowerCase(), target_operation_id: args.target_operation_id.toLowerCase() };
5072
5218
  }
5073
5219
  if (args?.action === "preview.page") {
5074
- if (closed(args, ["app_id", "action", "preview_id", "cursor"]), ![args.app_id, args.preview_id].every((v) => typeof v == "string" && uuid.test(v)) || typeof args.cursor != "string" || !/^[a-f0-9]{64}$/.test(args.cursor)) throw Error("INVALID_ARGUMENT");
5220
+ if (closed(args, ["app_id", "action", "preview_id", "cursor"]), ![args.app_id, args.preview_id].every((v) => typeof v == "string" && uuid3.test(v)) || typeof args.cursor != "string" || !/^[a-f0-9]{64}$/.test(args.cursor)) throw Error("INVALID_ARGUMENT");
5075
5221
  return { ...args, app_id: args.app_id.toLowerCase(), preview_id: args.preview_id.toLowerCase() };
5076
5222
  }
5077
- if (closed(args, ["app_id", "operation_id", "expected_revision", "action", "payload"], ["mode", "confirmation", "resumes_operation_id"]), args.mode !== void 0 && !["preview", "commit"].includes(args.mode) || args.confirmation !== void 0 && (closed(args.confirmation, ["preview_id", "digest", "acknowledgement"]), !uuid.test(args.confirmation.preview_id ?? "") || ![args.confirmation.digest, args.confirmation.acknowledgement].every((v) => typeof v == "string" && /^[a-f0-9]{64}$/.test(v))) || args.mode === "preview" && args.confirmation || !previewActions.includes(args.action) && (args.mode !== void 0 || args.confirmation) || ![args.app_id, args.operation_id].every((value) => typeof value == "string" && uuid.test(value)) || typeof args.expected_revision != "string" || !/^(0|[1-9][0-9]{0,18})$/.test(args.expected_revision) || Buffer.byteLength(JSON.stringify(args)) > 262144) throw Error("INVALID_ARGUMENT");
5223
+ if (closed(args, ["app_id", "operation_id", "expected_revision", "action", "payload"], ["mode", "confirmation", "resumes_operation_id"]), args.mode !== void 0 && !["preview", "commit"].includes(args.mode) || args.confirmation !== void 0 && (closed(args.confirmation, ["preview_id", "digest", "acknowledgement"]), !uuid3.test(args.confirmation.preview_id ?? "") || ![args.confirmation.digest, args.confirmation.acknowledgement].every((v) => typeof v == "string" && /^[a-f0-9]{64}$/.test(v))) || args.mode === "preview" && args.confirmation || !previewActions.includes(args.action) && (args.mode !== void 0 || args.confirmation) || ![args.app_id, args.operation_id].every((value) => typeof value == "string" && uuid3.test(value)) || typeof args.expected_revision != "string" || !/^(0|[1-9][0-9]{0,18})$/.test(args.expected_revision) || Buffer.byteLength(JSON.stringify(args)) > 262144) throw Error("INVALID_ARGUMENT");
5078
5224
  if (args.action === "entry.save") {
5079
5225
  let p = args.payload;
5080
5226
  if (closed(p, [], ["entry_id", "create", "metadata", "assets", "label", "fields", "move", "replace"]), p.entry_id === void 0 == (p.create === void 0)) throw invalid("payload needs exactly one of entry_id or create");
5081
5227
  if (p.create !== void 0 && p.metadata !== void 0) throw invalid("payload.metadata is not accepted with create; put title and description in create");
5082
5228
  let target2 = p.entry_id ?? args.operation_id;
5083
- if (typeof target2 != "string" || !uuid.test(target2)) throw Error("INVALID_ARGUMENT");
5229
+ if (typeof target2 != "string" || !uuid3.test(target2)) throw Error("INVALID_ARGUMENT");
5084
5230
  let parse2 = (action, payload3) => normalizeMutation({ app_id: args.app_id, operation_id: args.operation_id, expected_revision: args.expected_revision, action, payload: payload3 }).payload, payload2 = p.create !== void 0 ? { create: parse2("entry.create", p.create) } : { entry_id: target2.toLowerCase() };
5085
5231
  if (p.metadata !== void 0 && (payload2.metadata = parse2("entry.patch", { entry_id: target2, patch: p.metadata }).patch), p.assets !== void 0) {
5086
5232
  closed(p.assets, [], roles);
@@ -5100,7 +5246,7 @@ function normalizeMutation(args) {
5100
5246
  payload2.move = move;
5101
5247
  }
5102
5248
  if (p.replace !== void 0 && (payload2.replace = parse2("folder.replace", { folder_id: target2, child_ids: p.replace }).child_ids), Object.keys(payload2).every((k) => k === "entry_id")) throw invalid("payload needs at least one of metadata, assets, label, fields, move or replace");
5103
- if (args.resumes_operation_id !== void 0 && (typeof args.resumes_operation_id != "string" || !uuid.test(args.resumes_operation_id) || args.resumes_operation_id.toLowerCase() === args.operation_id.toLowerCase() || p.create)) throw invalid("resumes_operation_id must name an earlier save of an existing entry, not this operation");
5249
+ if (args.resumes_operation_id !== void 0 && (typeof args.resumes_operation_id != "string" || !uuid3.test(args.resumes_operation_id) || args.resumes_operation_id.toLowerCase() === args.operation_id.toLowerCase() || p.create)) throw invalid("resumes_operation_id must name an earlier save of an existing entry, not this operation");
5104
5250
  return {
5105
5251
  ...args,
5106
5252
  app_id: args.app_id.toLowerCase(),
@@ -5155,7 +5301,7 @@ function normalizeMutation(args) {
5155
5301
  throw invalid(`payload.locales: expected 1 to ${MAX_APP_LANGUAGES} distinct canonical language tags such as en or pt-BR`);
5156
5302
  payload2 = { locales: [...tags] };
5157
5303
  } else {
5158
- if (closed(p, args.action === "entry.label.set" ? ["entry_id", "label"] : ["entry_id"], args.action === "entry.fields.patch" ? ["set", "clear"] : []), typeof p.entry_id != "string" || !uuid.test(p.entry_id)) throw Error("INVALID_ARGUMENT");
5304
+ if (closed(p, args.action === "entry.label.set" ? ["entry_id", "label"] : ["entry_id"], args.action === "entry.fields.patch" ? ["set", "clear"] : []), typeof p.entry_id != "string" || !uuid3.test(p.entry_id)) throw Error("INVALID_ARGUMENT");
5159
5305
  if (payload2.entry_id = p.entry_id.toLowerCase(), args.action === "entry.label.set" && p.label !== null && (p.label && Object.hasOwn(p.label, "key") ? (closed(p.label, ["key"]), key4(p.label.key)) : payload2.label = named2(p.label, "payload.label")), args.action === "entry.fields.patch") {
5160
5306
  if (p.set === null || p.clear === null || (closed(p.set ?? {}, [], Object.keys(p.set ?? {})), Object.keys(p.set ?? {}).forEach(key4), !Array.isArray(p.clear ?? []))) throw Error("INVALID_ARGUMENT");
5161
5307
  if ((p.clear ?? []).forEach(key4), new Set(p.clear ?? []).size !== (p.clear ?? []).length) throw invalid("payload.clear: expected no repeated keys");
@@ -5180,7 +5326,7 @@ function normalizeMutation(args) {
5180
5326
  args.action === "entry.publish" ? ["child_ids"] : args.action === "entry.schedule" ? ["at", "child_ids"] : []
5181
5327
  );
5182
5328
  let id11 = (value) => {
5183
- if (typeof value != "string" || !uuid.test(value)) throw Error("INVALID_ARGUMENT");
5329
+ if (typeof value != "string" || !uuid3.test(value)) throw Error("INVALID_ARGUMENT");
5184
5330
  return value.toLowerCase();
5185
5331
  }, ids3 = (value, max) => {
5186
5332
  if (!Array.isArray(value) || value.length > max) throw Error("INVALID_ARGUMENT");
@@ -5209,13 +5355,13 @@ function normalizeMutation(args) {
5209
5355
  closed(args.payload, ["kind", "title"], ["mediaType", "parentId", "description"]);
5210
5356
  let { kind: kind2, mediaType = null, parentId = null } = args.payload;
5211
5357
  if (!(kind2 === "folder" && mediaType === null || kind2 === "item" && ["video", "audio", "live"].includes(mediaType))) throw invalid("mediaType: expected null for a folder, or video, audio or live for an item");
5212
- if (parentId !== null && (typeof parentId != "string" || !uuid.test(parentId))) throw invalid("parentId: expected a UUID or null");
5358
+ if (parentId !== null && (typeof parentId != "string" || !uuid3.test(parentId))) throw invalid("parentId: expected a UUID or null");
5213
5359
  metadata2 = {
5214
5360
  title: textMap(args.payload.title, 300, "payload.title"),
5215
5361
  description: args.payload.description === void 0 ? {} : textMap(args.payload.description, 5e3, "payload.description", { min: 0 })
5216
5362
  }, payload = { kind: kind2, mediaType, parentId: parentId?.toLowerCase() ?? null };
5217
5363
  } else if (args.action === "entry.patch") {
5218
- if (closed(args.payload, ["entry_id", "patch"]), closed(args.payload.patch, [], ["title", "description"]), typeof args.payload.entry_id != "string" || !uuid.test(args.payload.entry_id) || !Object.keys(args.payload.patch).length) throw Error("INVALID_ARGUMENT");
5364
+ if (closed(args.payload, ["entry_id", "patch"]), closed(args.payload.patch, [], ["title", "description"]), typeof args.payload.entry_id != "string" || !uuid3.test(args.payload.entry_id) || !Object.keys(args.payload.patch).length) throw Error("INVALID_ARGUMENT");
5219
5365
  metadata2 = Object.fromEntries(Object.entries(args.payload.patch).map(([name, value]) => [name, textMap(value, name === "title" ? 300 : 5e3, `payload.patch.${name}`, { patch: !0 })])), payload = { entry_id: args.payload.entry_id.toLowerCase() };
5220
5366
  } else throw Error("INVALID_ARGUMENT");
5221
5367
  return {
@@ -5228,7 +5374,7 @@ function normalizeMutation(args) {
5228
5374
  }
5229
5375
  function textMap(value, max, path, { patch = !1, min = patch ? 0 : 1, name = !1 } = {}) {
5230
5376
  let map = parseLocalizedPatch(value, { maxLength: max }), entries2 = map ? Object.entries(map) : [];
5231
- if (!map || entries2.length < min || entries2.some(([, text4]) => text4 === null ? !patch : !text4.trim()) || name && hasControlCharacters(Object.fromEntries(entries2.filter(([, text4]) => text4 !== null))))
5377
+ if (!map || entries2.length < min || entries2.some(([, text5]) => text5 === null ? !patch : !text5.trim()) || name && hasControlCharacters(Object.fromEntries(entries2.filter(([, text5]) => text5 !== null))))
5232
5378
  throw invalid(`${path}: expected a language map such as {"en": "text"} with at most ${max} characters per language${patch ? "; null removes a language" : ""}`);
5233
5379
  return map;
5234
5380
  }
@@ -5327,9 +5473,9 @@ var KEPT = [
5327
5473
  LIBRARY_SUBTITLE_ENCODING: "Save the subtitle file as UTF-8 and try again.",
5328
5474
  LIBRARY_SUBTITLE_INVALID: "That subtitle file could not be read.",
5329
5475
  LIBRARY_SUBTITLE_LANGUAGE: "Pick a language such as en or pt-BR."
5330
- }), BILLING = /^BILLING_[A-Z_]{1,40}$/, SECRET = /[a-z][a-z0-9+.-]*:\/\/|eyJ[\w-]{4,}\.[\w-]{4,}|-----BEGIN|MCowBQYDK2Vw|(^|\/)(media|originals)\/[0-9a-f-]{36}\/|\/library\/[0-9a-f-]{36}\/(artwork|subtitles)\/|test-artwork\//i, leaksPrivate = (v) => typeof v == "string" ? SECRET.test(v) : Array.isArray(v) ? v.some(leaksPrivate) : !!v && typeof v == "object" && Object.entries(v).some(([key4, entry]) => SECRET.test(key4) || leaksPrivate(entry)), shown = (text4) => {
5331
- if (typeof text4 != "string") return "";
5332
- let value = text4.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
5476
+ }), BILLING = /^BILLING_[A-Z_]{1,40}$/, SECRET = /[a-z][a-z0-9+.-]*:\/\/|eyJ[\w-]{4,}\.[\w-]{4,}|-----BEGIN|MCowBQYDK2Vw|(^|\/)(media|originals)\/[0-9a-f-]{36}\/|\/library\/[0-9a-f-]{36}\/(artwork|subtitles)\/|test-artwork\//i, leaksPrivate = (v) => typeof v == "string" ? SECRET.test(v) : Array.isArray(v) ? v.some(leaksPrivate) : !!v && typeof v == "object" && Object.entries(v).some(([key4, entry]) => SECRET.test(key4) || leaksPrivate(entry)), shown = (text5) => {
5477
+ if (typeof text5 != "string") return "";
5478
+ let value = text5.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
5333
5479
  return value && value.length <= 600 && !SECRET.test(value) ? value : "";
5334
5480
  }, FilesError = class extends Error {
5335
5481
  constructor(code, { message, detail, extra, top } = {}) {
@@ -5339,8 +5485,8 @@ var KEPT = [
5339
5485
  function filesFailure(code, { message, detail, extra = {}, top = {} } = {}) {
5340
5486
  let billing = typeof code == "string" && BILLING.test(code);
5341
5487
  !billing && (typeof code != "string" || !Object.hasOwn(FILES_MESSAGES, code)) && (code = "INTERNAL_ERROR");
5342
- let text4 = billing ? "Billing refused this upload." : FILES_MESSAGES[code];
5343
- return code === "INVALID_ARGUMENT" && shown(detail) ? text4 = shown(detail) : /^LIBRARY_/.test(code) && shown(message) && (text4 = shown(message)), { ok: !1, error: { code, message: text4, ...extra }, ...top };
5488
+ let text5 = billing ? "Billing refused this upload." : FILES_MESSAGES[code];
5489
+ return code === "INVALID_ARGUMENT" && shown(detail) ? text5 = shown(detail) : /^LIBRARY_/.test(code) && shown(message) && (text5 = shown(message)), { ok: !1, error: { code, message: text5, ...extra }, ...top };
5344
5490
  }
5345
5491
  var failureOf = (error) => error instanceof FilesError ? filesFailure(error.code, { message: error.shownMessage, detail: error.detail, extra: error.extra, top: error.top }) : filesFailure(error?.code === "INVALID_ARGUMENT" ? "INVALID_ARGUMENT" : error?.code, { detail: error?.detail }), fail2 = () => {
5346
5492
  throw new FilesError("INVALID_RESPONSE");
@@ -5453,7 +5599,7 @@ function decodeReadReceipt(v) {
5453
5599
  }
5454
5600
 
5455
5601
  // skills/adelin-app-generation/scripts/library-files.mjs
5456
- var FILES_OUTPUT_MAX = 10485760, transferDeadlineMs = (size) => Math.min(18e4, 3e4 + Math.ceil(size / 131072 * 1e3)), UUID5 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", uuid2 = new RegExp(UUID5, "i"), SLOTS3 = ["poster", "backdrop", "logo"], closed2 = (properties, required) => ({ type: "object", properties, required, additionalProperties: !1 }), id4 = { type: "string", pattern: UUID5 }, filePath = { type: "string", minLength: 1, maxLength: 4096, pattern: "^[^\\u0000]+$" }, write = { app_id: id4, entry_id: id4, operation_id: id4, expected_revision: { type: "string", pattern: "^(0|[1-9][0-9]{0,18})$" }, path: filePath }, language3 = { type: "string", minLength: 2, maxLength: 35, pattern: "^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$" }, imageLanguage2 = { type: ["string", "null"], pattern: LANGUAGE_TAG_PATTERN.source }, INPUTS = {
5602
+ var FILES_OUTPUT_MAX = 10485760, transferDeadlineMs = (size) => Math.min(18e4, 3e4 + Math.ceil(size / 131072 * 1e3)), UUID5 = "^[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(UUID5, "i"), SLOTS3 = ["poster", "backdrop", "logo"], closed2 = (properties, required) => ({ type: "object", properties, required, additionalProperties: !1 }), id4 = { type: "string", pattern: UUID5 }, filePath = { type: "string", minLength: 1, maxLength: 4096, pattern: "^[^\\u0000]+$" }, write = { app_id: id4, entry_id: id4, operation_id: id4, expected_revision: { type: "string", pattern: "^(0|[1-9][0-9]{0,18})$" }, path: filePath }, language3 = { type: "string", minLength: 2, maxLength: 35, pattern: "^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$" }, imageLanguage2 = { type: ["string", "null"], pattern: LANGUAGE_TAG_PATTERN.source }, INPUTS = {
5457
5603
  "put-artwork": closed2({ ...write, slot: { enum: SLOTS3 }, language: imageLanguage2 }, [...Object.keys(write), "slot"]),
5458
5604
  "add-subtitle": closed2({ ...write, target: { enum: ["main", "trailer"] }, language: language3 }, [...Object.keys(write), "target", "language"]),
5459
5605
  "replace-subtitle": closed2({ ...write, file_id: id4 }, [...Object.keys(write), "file_id"]),
@@ -5476,7 +5622,7 @@ function normalizeFilesArgs(operation, args) {
5476
5622
  let schema = Object.hasOwn(INPUTS, operation ?? "") ? INPUTS[operation] : null;
5477
5623
  if (!schema) throw invalid2(`operation: expected one of ${filesOperations.join(", ")}`);
5478
5624
  if (!plain2(args)) throw invalid2("arguments: expected an object");
5479
- 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);
5625
+ 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) && uuid4.test(value) ? value.toLowerCase() : value])), problem2 = explainArguments(schema, input);
5480
5626
  if (problem2) throw invalid2(problem2);
5481
5627
  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");
5482
5628
  if (operation === "check" && input.kind === "artwork" != (input.slot !== void 0))
@@ -5878,9 +6024,9 @@ ${digest4}`), signature = sign2(null, bytes2, this.privateKey).toString("base64u
5878
6024
  if (continuation.length > 16384 || !/^[A-Za-z0-9_.-]+$/.test(continuation)) throw new Error("Invalid build continuation.");
5879
6025
  this.continuation = continuation;
5880
6026
  }
5881
- let text4 = await response2.text();
5882
- if (Buffer.byteLength(text4, "utf8") > (action === "device" ? MAX_DEVICE_BYTES : 2 * 1024 * 1024)) throw new Error("Adelin build response is too large.");
5883
- return { content: [{ type: "text", text: text4 }] };
6027
+ let text5 = await response2.text();
6028
+ if (Buffer.byteLength(text5, "utf8") > (action === "device" ? MAX_DEVICE_BYTES : 2 * 1024 * 1024)) throw new Error("Adelin build response is too large.");
6029
+ return { content: [{ type: "text", text: text5 }] };
5884
6030
  }
5885
6031
  async close() {
5886
6032
  this.detach();
@@ -5962,15 +6108,15 @@ function assetStatus(workspace, appId) {
5962
6108
  return { files: files.length, pending: files.filter((file) => stamps[file.name]?.sha256 !== file.sha256).map((file) => file.path), problems };
5963
6109
  }
5964
6110
  function reply(result) {
5965
- let text4 = result?.content?.length === 1 && result.content[0].type === "text" ? result.content[0].text : null;
5966
- if (typeof text4 != "string" || Buffer.byteLength(text4, "utf8") > MAX_REPLY_BYTES) throw coded("ADELIN_TOOL_FAILED", "Adelin returned an invalid asset reply.");
6111
+ let text5 = result?.content?.length === 1 && result.content[0].type === "text" ? result.content[0].text : null;
6112
+ if (typeof text5 != "string" || Buffer.byteLength(text5, "utf8") > MAX_REPLY_BYTES) throw coded("ADELIN_TOOL_FAILED", "Adelin returned an invalid asset reply.");
5967
6113
  if (result.isError) {
5968
- let match = CODED.exec(text4);
6114
+ let match = CODED.exec(text5);
5969
6115
  throw coded(match ? match[1] : "ADELIN_TOOL_FAILED", match ? cleanServerMessage(match[2]) : "Adelin refused the asset request.");
5970
6116
  }
5971
6117
  let value;
5972
6118
  try {
5973
- value = JSON.parse(text4);
6119
+ value = JSON.parse(text5);
5974
6120
  } catch {
5975
6121
  }
5976
6122
  if (!plain3(value)) throw coded("ADELIN_TOOL_FAILED", "Adelin returned an invalid asset reply.");
@@ -5990,7 +6136,7 @@ function uploadTarget(ticket, file) {
5990
6136
  async function saveOne({ root, appId, edit, call, fetcher, timeout }, file) {
5991
6137
  let bytes2 = readSafeFile4(join5(root, file.path), 10485760);
5992
6138
  if (bytes2.length !== file.size || sha2564(bytes2) !== file.sha256) throw coded("ASSET_SOURCE_CHANGED", `${file.path} changed while it was being saved. Build again.`);
5993
- 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;
6139
+ let session = { app_id: appId, lease_id: edit.leaseId, chat_session_id: edit.chatSessionId, epoch: edit.epoch, task_id: edit.taskId }, ticket = reply(await call("create_asset_upload", { ...session, fileName: file.name, contentType: file.contentType, byteLength: file.size })), target2 = uploadTarget(ticket, file), uploaded;
5994
6140
  try {
5995
6141
  uploaded = await fetcher(target2, {
5996
6142
  method: "PUT",
@@ -6004,9 +6150,9 @@ async function saveOne({ root, appId, edit, call, fetcher, timeout }, file) {
6004
6150
  }
6005
6151
  if (!uploaded.ok) throw coded("ASSET_UPLOAD_FAILED", `Uploading ${file.path} was refused (HTTP ${uploaded.status}). Build again.`);
6006
6152
  let saved = reply(await call("save_attachment_as_asset", { ...session, attachmentId: ticket.attachmentId, name: file.name, replace: file.replace }));
6007
- if (saved.name !== file.name || typeof saved.assetPath != "string" || typeof saved.replaced != "boolean")
6153
+ if (!AppTaskSaveReceiptSchema.safeParse(saved.task).success || saved.task.taskId !== edit.taskId || saved.name !== file.name || typeof saved.assetPath != "string" || typeof saved.replaced != "boolean")
6008
6154
  throw coded("ADELIN_TOOL_FAILED", "Adelin returned an invalid asset reply.");
6009
- return { name: saved.name, assetPath: saved.assetPath, width: saved.width, height: saved.height, replaced: saved.replaced };
6155
+ return { name: saved.name, assetPath: saved.assetPath, width: saved.width, height: saved.height, replaced: saved.replaced, task: saved.task };
6010
6156
  }
6011
6157
  var notSaved = (appId, assets, nextAction, state = "assets_not_saved") => ({ ok: !1, result: { state, appId, assets, sourceSent: !1, nextAction } });
6012
6158
  async function saveWorkspaceAssets({
@@ -6015,6 +6161,7 @@ async function saveWorkspaceAssets({
6015
6161
  leaseId,
6016
6162
  chatSessionId,
6017
6163
  epoch,
6164
+ taskId,
6018
6165
  call,
6019
6166
  replace = [],
6020
6167
  fetcher = fetch,
@@ -6042,7 +6189,7 @@ async function saveWorkspaceAssets({
6042
6189
  }
6043
6190
  }
6044
6191
  if (problems.length) return notSaved(appId, { problems }, "Rename these files or confirm the replacement, then build again. No source was sent.");
6045
- let context = { root, appId, edit: { leaseId, chatSessionId, epoch }, call, fetcher, timeout }, done = [];
6192
+ let context = { root, appId, edit: { leaseId, chatSessionId, epoch, taskId }, call, fetcher, timeout }, done = [];
6046
6193
  for (let file of work.slice(0, MAX_ASSET_SAVES)) {
6047
6194
  try {
6048
6195
  done.push(await saveOne(context, file));
@@ -6178,7 +6325,7 @@ var nextStep = (token2) => Object.hasOwn(NEXT, token2 ?? "") ? NEXT[token2] : nu
6178
6325
  exact3(value, Object.keys(fields2));
6179
6326
  for (let [key4, check2] of Object.entries(fields2)) check2(value[key4]);
6180
6327
  return value;
6181
- }, array2 = (check2, max) => (value) => ((!Array.isArray(value) || value.length > max) && fail3(), value.forEach(check2), value), unique = (rows, key4) => {
6328
+ }, array2 = (check2, max) => (value) => ((!Array.isArray(value) || value.length > max) && fail3(), value.forEach(check2), value), unique2 = (rows, key4) => {
6182
6329
  new Set(rows.map((row) => row[key4])).size !== rows.length && fail3();
6183
6330
  }, UPLOAD_STATUSES = ["uploading", "probing", "awaiting_options", "queued", "processing", "ready", "failed"], STAGES = ["queued", "validating", "downloading", "transcoding", "uploading", "finalizing", "ready", "failed"], BUSY = ["uploading", "probing", "queued", "processing"], EFFECTS = ["original_only", "whole_upload"], reference = shape({ entryId: id5, title: str2(1e3) }), track = shape({ language: maybe2(str2(64)), channels: count2, codec: str2(64) }), technical2 = (value) => value === null ? null : Object.hasOwn(value ?? {}, "resolution") ? shape({ duration: number2, resolution: (v) => {
6184
6331
  /^\d+x\d+$/.test(str2(32)(v)) || fail3();
@@ -6219,7 +6366,7 @@ var profile = shape({ id: id5, name: str2(80), maxHeight: oneOf2([null, 2160, 10
6219
6366
  counts: shape({ all: count2, video: count2, audio: count2 }),
6220
6367
  totalBytes: count2,
6221
6368
  page: shape({ limit: count2, returned: count2, nextCursor: maybe2(cursor) })
6222
- })(data), (data.page.limit !== (input.limit ?? 50) || data.page.returned !== data.items.length || data.items.length > data.page.limit) && fail3(), unique(data.items, "id");
6369
+ })(data), (data.page.limit !== (input.limit ?? 50) || data.page.returned !== data.items.length || data.items.length > data.page.limit) && fail3(), unique2(data.items, "id");
6223
6370
  for (let row of data.items) (["removing", "removed"].includes(row.status) || input.kind && row.kind !== input.kind || input.status && row.status !== input.status) && fail3();
6224
6371
  },
6225
6372
  get(data, input) {
@@ -6232,16 +6379,16 @@ var profile = shape({ id: id5, name: str2(80), maxHeight: oneOf2([null, 2160, 10
6232
6379
  page: shape({ limit: count2, returned: count2, total: count2, nextCursor: maybe2(cursor) })
6233
6380
  })(data);
6234
6381
  let { page: page2 } = data;
6235
- (data.assetId !== input.asset_id || page2.limit !== (input.limit ?? 50) || page2.returned !== data.items.length || page2.returned > page2.limit || page2.returned > page2.total) && fail3(), unique(data.items, "entryId");
6382
+ (data.assetId !== input.asset_id || page2.limit !== (input.limit ?? 50) || page2.returned !== data.items.length || page2.returned > page2.limit || page2.returned > page2.total) && fail3(), unique2(data.items, "entryId");
6236
6383
  },
6237
6384
  "recently-deleted"(data, input) {
6238
6385
  shape({
6239
6386
  items: array2(shape({ uploadId: id5, name: str2(), kind: maybe2(oneOf2(["video", "audio"])), sizeBytes: count2, effect: oneOf2(EFFECTS), restorableUntil: instant }), 100),
6240
6387
  page: shape({ limit: count2, returned: count2, nextCursor: maybe2(cursor) })
6241
- })(data), (data.page.limit !== (input.limit ?? 50) || data.page.returned !== data.items.length || data.items.length > data.page.limit) && fail3(), unique(data.items, "uploadId");
6388
+ })(data), (data.page.limit !== (input.limit ?? 50) || data.page.returned !== data.items.length || data.items.length > data.page.limit) && fail3(), unique2(data.items, "uploadId");
6242
6389
  },
6243
6390
  profiles(data) {
6244
- shape({ profilesRevision: digest, items: array2(profile, 100) })(data), unique(data.items, "id"), data.items.filter((row) => row.isDefault).length > 1 && fail3();
6391
+ shape({ profilesRevision: digest, items: array2(profile, 100) })(data), unique2(data.items, "id"), data.items.filter((row) => row.isDefault).length > 1 && fail3();
6245
6392
  }
6246
6393
  };
6247
6394
  DATA.status = DATA.get;
@@ -6298,7 +6445,7 @@ var MUTATION_SIMPLE = [
6298
6445
  "profile.default": ["defaulted", "unchanged"]
6299
6446
  }, PROFILE_CODES = ["MEDIA_PROFILE_INVALID", "MEDIA_PROFILE_NAME_TAKEN", "MEDIA_PROFILE_LAST", "MEDIA_PROFILE_NOT_FOUND"], PROFILE_CONFLICT = "The profiles changed since they were read. Use profilesRevision, or read them again.", isProfileAction = (action) => Object.hasOwn(PROFILE_STATES, action), skippedRows = (value) => {
6300
6447
  let rows = array2(shape({ uploadId: id5, error: oneOf2(["NOT_FOUND", "MEDIA_ORIGINAL_BUSY", "MEDIA_ORIGINAL_GONE"]) }), 100)(value);
6301
- return unique(rows, "uploadId"), rows;
6448
+ return unique2(rows, "uploadId"), rows;
6302
6449
  }, ROW_ERRORS = ["MEDIA_ASSET_NOT_FOUND", "MEDIA_ORIGINAL_BUSY", "MEDIA_ORIGINAL_GONE", "MEDIA_ORIGINAL_EFFECT_CHANGED", "MEDIA_ORIGINAL_DELETE_FAILED"], resultRow = (value) => value?.ok === !0 ? (Object.hasOwn(value, "restorableUntil") ? shape({ uploadId: id5, ok: boolean2, effect: oneOf2(EFFECTS), restorableUntil: iso }) : shape({ uploadId: id5, ok: boolean2, effect: (v) => same3(v, "whole_upload") }))(value) : shape({ uploadId: id5, ok: (v) => same3(v, !1), error: oneOf2(ROW_ERRORS) })(value), hasPreviewId = (request) => typeof request.payload?.preview_id == "string";
6303
6450
  function coversRequest(rows, request) {
6304
6451
  let listed = rows.map((row) => row.uploadId), asked = request.payload.asset_ids;
@@ -6329,7 +6476,7 @@ function mutationRefusal(value, request) {
6329
6476
  if (code === "MEDIA_ASSET_IN_USE") {
6330
6477
  keys(value, ["ok", "error", "usedIn", "usedInTotal"]);
6331
6478
  let usedIn = array2(shape({ entryId: id5, title: chars(300) }), 20)(value.usedIn);
6332
- return unique(usedIn, "entryId"), (!usedIn.length || count2(value.usedInTotal) < usedIn.length) && fail3(), mutationFailure(code, { usedIn, usedInTotal: value.usedInTotal });
6479
+ return unique2(usedIn, "entryId"), (!usedIn.length || count2(value.usedInTotal) < usedIn.length) && fail3(), mutationFailure(code, { usedIn, usedInTotal: value.usedInTotal });
6333
6480
  }
6334
6481
  if (code === "MEDIA_ORIGINAL_GONE")
6335
6482
  return keys(value, ["ok", "error", "originalRemovedAt"], ["status", "restorableUntil"]), value.restorableUntil !== void 0 && value.originalRemovedAt !== null && fail3(), mutationFailure(code, {
@@ -6822,7 +6969,7 @@ function isNotMediaStderr(stderr) {
6822
6969
  function byteLength(value) {
6823
6970
  return typeof value == "string" ? Buffer.byteLength(value, "utf8") : value.byteLength;
6824
6971
  }
6825
- function text(value) {
6972
+ function text2(value) {
6826
6973
  return typeof value == "string" ? value : new TextDecoder().decode(value);
6827
6974
  }
6828
6975
  function probeVerdict(run) {
@@ -6830,10 +6977,10 @@ function probeVerdict(run) {
6830
6977
  if (run.launchFailed === !0 || run.timedOut === !0) return deferred;
6831
6978
  if (byteLength(run.stdout) > PROBE_STDOUT_LIMIT_BYTES || byteLength(run.stderr) > PROBE_STDERR_LIMIT_BYTES)
6832
6979
  return unsupported;
6833
- if (run.exitCode !== 0) return isNotMediaStderr(text(run.stderr)) ? unsupported : deferred;
6980
+ if (run.exitCode !== 0) return isNotMediaStderr(text2(run.stderr)) ? unsupported : deferred;
6834
6981
  let inspection;
6835
6982
  try {
6836
- inspection = normalizeProbeDocument(JSON.parse(text(run.stdout)));
6983
+ inspection = normalizeProbeDocument(JSON.parse(text2(run.stdout)));
6837
6984
  } catch {
6838
6985
  return unsupported;
6839
6986
  }
@@ -7545,7 +7692,7 @@ var mediaOperations = Object.freeze({
7545
7692
  status: "get_media_asset",
7546
7693
  profiles: "get_transcode_profiles",
7547
7694
  "recently-deleted": "get_media_recently_deleted"
7548
- }), 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) => ({
7695
+ }), 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}$", uuid5 = 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) => ({
7549
7696
  list: closed3({
7550
7697
  app_id: id6,
7551
7698
  kind: { enum: ["video", "audio"] },
@@ -7578,7 +7725,7 @@ function normalizeMediaArgs(operation, args, { maxWaitSeconds = MEDIA_WAIT.mcpMa
7578
7725
  let schema = Object.hasOwn(mediaOperations, operation) ? inputs(maxWaitSeconds)[operation] : null;
7579
7726
  if (!schema) throw invalid4(`operation: expected one of ${Object.keys(mediaOperations).join(", ")}`);
7580
7727
  if (!args || typeof args != "object" || Array.isArray(args) || Object.getPrototypeOf(args) !== Object.prototype) throw invalid4("arguments: expected an object");
7581
- args = Object.fromEntries(Object.entries(args).map(([key4, value]) => [key4, ["app_id", "asset_id"].includes(key4) && uuid3.test(value) ? value.toLowerCase() : value]));
7728
+ args = Object.fromEntries(Object.entries(args).map(([key4, value]) => [key4, ["app_id", "asset_id"].includes(key4) && uuid5.test(value) ? value.toLowerCase() : value]));
7582
7729
  let problem2 = explainArguments(schema, args) ?? (args.cursor !== void 0 && !args.cursor.trim() ? "cursor: expected non-empty text" : null);
7583
7730
  if (problem2) throw invalid4(problem2);
7584
7731
  let result = { ...args };
@@ -7682,7 +7829,7 @@ function normalizeTransferArgs(operation, args, { maxWaitSeconds = MEDIA_WAIT.mc
7682
7829
  let schema = Object.hasOwn(transferDescriptions, operation) ? transferInputs(maxWaitSeconds)[operation] : null;
7683
7830
  if (!schema) throw invalid4(`operation: expected one of ${mediaTransferOperations.join(", ")}`);
7684
7831
  if (!args || typeof args != "object" || Array.isArray(args) || Object.getPrototypeOf(args) !== Object.prototype) throw invalid4("arguments: expected an object");
7685
- 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]));
7832
+ args = Object.fromEntries(Object.entries(args).map(([key4, value]) => [key4, ["app_id", "asset_id", "job_id", "transcode"].includes(key4) && uuid5.test(value) ? value.toLowerCase() : value]));
7686
7833
  let problem2 = explainArguments(schema, args) ?? (typeof args.name == "string" && !args.name.trim() ? "name: expected non-empty text" : null);
7687
7834
  if (problem2) throw invalid4(problem2);
7688
7835
  let result = { ...args };
@@ -7745,8 +7892,8 @@ async function mediaTransfer(operation, args, {
7745
7892
  return transferFailure(error);
7746
7893
  }
7747
7894
  }
7748
- var HEX642 = "^[a-f0-9]{64}$", hexToken = { type: "string", pattern: HEX642 }, text2 = { type: "string", minLength: 1, pattern: "\\S" }, PROFILE_SETTINGS = ["name", "maxHeight", "scrubPreviews", "segmentSeconds"], profileFields = { name: text2, maxHeight: { enum: [null, 2160, 1080, 720, 480] }, scrubPreviews: { type: "boolean" }, segmentSeconds: { enum: [4, 6] } }, PROFILE_DEFAULTS = Object.freeze({ maxHeight: 1080, scrubPreviews: !1, segmentSeconds: 6 }), mediaMutationPayloads = Object.freeze([
7749
- [["asset.rename"], closed3({ asset_id: id6, name: text2, expected_snapshot: hexToken }, ["asset_id", "name", "expected_snapshot"])],
7895
+ var HEX642 = "^[a-f0-9]{64}$", hexToken = { type: "string", pattern: HEX642 }, text3 = { type: "string", minLength: 1, pattern: "\\S" }, PROFILE_SETTINGS = ["name", "maxHeight", "scrubPreviews", "segmentSeconds"], profileFields = { name: text3, maxHeight: { enum: [null, 2160, 1080, 720, 480] }, scrubPreviews: { type: "boolean" }, segmentSeconds: { enum: [4, 6] } }, PROFILE_DEFAULTS = Object.freeze({ maxHeight: 1080, scrubPreviews: !1, segmentSeconds: 6 }), mediaMutationPayloads = Object.freeze([
7896
+ [["asset.rename"], closed3({ asset_id: id6, name: text3, expected_snapshot: hexToken }, ["asset_id", "name", "expected_snapshot"])],
7750
7897
  [["asset.delete", "asset.restore"], closed3({ asset_id: id6 }, ["asset_id"])],
7751
7898
  [["asset.transcode"], closed3({ asset_id: id6, profile_id: { anyOf: [id6, { const: "default" }] }, expected_snapshot: hexToken }, ["asset_id", "profile_id", "expected_snapshot"])],
7752
7899
  [["original.delete"], closed3({ asset_ids: { type: "array", items: id6, minItems: 1, maxItems: 100, uniqueItems: !0 }, preview_id: id6 }, ["asset_ids"])],
@@ -7796,8 +7943,8 @@ var HEX642 = "^[a-f0-9]{64}$", hexToken = { type: "string", pattern: HEX642 }, t
7796
7943
  `), 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) => {
7797
7944
  let copy = { ...args };
7798
7945
  for (let [first, second] of ID_PATHS)
7799
- 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());
7800
- 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;
7946
+ second ? plain4(copy[first]) && uuid5.test(copy[first][second] ?? "") && (copy[first] = { ...copy[first], [second]: copy[first][second].toLowerCase() }) : uuid5.test(copy[first] ?? "") && (copy[first] = copy[first].toLowerCase());
7947
+ return plain4(copy.payload) && Array.isArray(copy.payload.asset_ids) && (copy.payload = { ...copy.payload, asset_ids: copy.payload.asset_ids.map((value) => uuid5.test(value ?? "") ? value.toLowerCase() : value) }), copy;
7801
7948
  };
7802
7949
  function explainMediaMutation(args) {
7803
7950
  if (!plain4(args)) return "arguments: expected an object";
@@ -8244,7 +8391,7 @@ var liveOperations = Object.freeze({
8244
8391
  recordings: "get_live_recordings",
8245
8392
  "saved-recordings": "get_live_saved_recordings",
8246
8393
  preview: "create_live_preview"
8247
- }), 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 = {
8394
+ }), UUID11 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", uuid6 = 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 = {
8248
8395
  list: closed4({ app_id: id8, status: { enum: ["live", "offline", "disabled"] }, limit: limit2, cursor: cursor4 }, ["app_id"]),
8249
8396
  get: closed4({ app_id: id8, entry_id: id8 }, ["app_id", "entry_id"]),
8250
8397
  viewers: closed4({ app_id: id8, entry_id: id8 }, ["app_id", "entry_id"]),
@@ -8303,7 +8450,7 @@ var liveOperations = Object.freeze({
8303
8450
  annotations: { readOnlyHint: !1, destructiveHint: !0, idempotentHint: !0 },
8304
8451
  inputSchema: mutateSchema
8305
8452
  })
8306
- ]), 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;
8453
+ ]), 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" && uuid6.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;
8307
8454
  function normalizeLiveRead(operation, args) {
8308
8455
  if (!Object.hasOwn(READS, operation ?? "")) throw invalid5(`operation: expected one of ${Object.keys(READS).join(", ")}`);
8309
8456
  if (!plain5(args)) throw invalid5("arguments: expected an object");
@@ -8352,7 +8499,7 @@ async function liveMutate(remote2, args) {
8352
8499
  try {
8353
8500
  request = normalizeLiveMutation(args);
8354
8501
  } catch (error) {
8355
- return { ...localRefusal(error), ...plain5(args) && uuid4.test(args.operation_id ?? "") ? { operationId: args.operation_id.toLowerCase() } : {} };
8502
+ return { ...localRefusal(error), ...plain5(args) && uuid6.test(args.operation_id ?? "") ? { operationId: args.operation_id.toLowerCase() } : {} };
8356
8503
  }
8357
8504
  let operationId = request.operation_id;
8358
8505
  if (request.action === "stream.reset" && request.mode !== "preview")
@@ -8570,86 +8717,6 @@ function createLocalPreviewBrowser({ previewPass, env = process.env, load = () =
8570
8717
  };
8571
8718
  }
8572
8719
 
8573
- // packages/tool-activity/src/appMetadata.ts
8574
- import { z as z3 } from "zod";
8575
- var bytes = (value) => Buffer.byteLength(value, "utf8"), validText = (value) => !value.includes("\0") && Buffer.from(value, "utf8").toString("utf8") === value, APP_CONTEXT_PROJECTION_BYTES = 131072, AppContextProjectionSchema = z3.strictObject({
8576
- fingerprint: z3.string().regex(/^[a-f0-9]{64}$/),
8577
- validUntil: z3.iso.datetime({ offset: !0 }).nullable(),
8578
- summaryMd: z3.string().refine(validText)
8579
- }).refine((value) => bytes(JSON.stringify(value)) <= APP_CONTEXT_PROJECTION_BYTES), CANONICAL_CONTINUATION_BYTES = 262144, CanonicalContinuationSchema = z3.string().refine((value) => validText(value) && bytes(value) <= CANONICAL_CONTINUATION_BYTES), RuntimeTurnContextSchema = z3.strictObject({ summaryMd: CanonicalContinuationSchema, appContext: AppContextProjectionSchema }), requirementsSchema = z3.array(z3.string().min(1).refine(
8580
- (value) => value === value.trim() && [...value].length <= 512
8581
- )).max(32).refine((items) => items.reduce((total, item) => total + bytes(item), 0) <= 16384), requirementsRevisionSchema = z3.string().regex(/^(0|[1-9][0-9]{0,18})$/).pipe(z3.string().refine((value) => BigInt(value) <= 9223372036854775807n)), AppRequirementsDocumentSchema = z3.strictObject({ requirements: requirementsSchema, revision: requirementsRevisionSchema }), AppRequirementsMutationResultSchema = AppRequirementsDocumentSchema.extend({ outcome: z3.enum(["updated", "unchanged", "conflict"]) });
8582
- function defineTool(tool2) {
8583
- return { ...tool2, input: z3.strictObject(tool2.inputShape) };
8584
- }
8585
- var APP_REQUIREMENTS_TOOLS = {
8586
- read_app_requirements: defineTool({
8587
- name: "read_app_requirements",
8588
- title: "Read accepted app requirements",
8589
- description: "Read app-owned accepted intent and its exact revision, including before the first build.",
8590
- inputShape: {},
8591
- result: AppRequirementsDocumentSchema
8592
- }),
8593
- update_app_requirements: defineTool({
8594
- name: "update_app_requirements",
8595
- title: "Update accepted app requirements",
8596
- description: "Replace accepted intent using its last read revision. Saves requirements metadata only; returns updated, unchanged or conflict.",
8597
- inputShape: { requirements: requirementsSchema, expectedRevision: requirementsRevisionSchema },
8598
- result: AppRequirementsMutationResultSchema
8599
- })
8600
- }, APP_MEMORY_LIMITS = Object.freeze({ maxEntries: 32, maxEntryBytes: 2048, maxBytes: 24576 }), APP_MEMORY_REQUEST_BYTES = 65536, uuid5 = z3.uuid(), timestamp = z3.iso.datetime({ offset: !0 }).max(35), memoryText = z3.string().min(1).refine((value) => value === value.trim() && validText(value) && bytes(value) <= APP_MEMORY_LIMITS.maxEntryBytes), status = z3.enum(["open", "completed", "abandoned"]), kind = z3.enum(["work", "checkpoint"]), AppMemoryEntrySchema = z3.strictObject({
8601
- id: uuid5,
8602
- kind,
8603
- status,
8604
- text: memoryText,
8605
- createdAt: timestamp,
8606
- progressAt: timestamp,
8607
- expiresAt: timestamp,
8608
- renewable: z3.boolean()
8609
- }).refine((entry) => Date.parse(entry.createdAt) <= Date.parse(entry.progressAt) && Date.parse(entry.progressAt) < Date.parse(entry.expiresAt)).refine((entry) => !entry.renewable || entry.kind === "work" && entry.status === "open");
8610
- function serializeAppMemoryEntries(entries2) {
8611
- return JSON.stringify(entries2.map(({ id: id11, kind: kind2, status: status2, text: text4, createdAt, progressAt, expiresAt, renewable }) => ({ id: id11, kind: kind2, status: status2, text: text4, createdAt, progressAt, expiresAt, renewable })));
8612
- }
8613
- var unique2 = (ids3) => new Set(ids3).size === ids3.length, ids2 = z3.array(uuid5).min(1).max(APP_MEMORY_LIMITS.maxEntries).refine(unique2), entries = z3.array(AppMemoryEntrySchema).max(APP_MEMORY_LIMITS.maxEntries).refine((items) => unique2(items.map((item) => item.id)) && bytes(serializeAppMemoryEntries(items)) <= APP_MEMORY_LIMITS.maxBytes), limits = z3.strictObject({ maxEntries: z3.literal(32), maxEntryBytes: z3.literal(2048), maxBytes: z3.literal(24576) }), documentShape = {
8614
- revision: requirementsRevisionSchema,
8615
- entries,
8616
- bytesUsed: z3.int().min(2).max(APP_MEMORY_LIMITS.maxBytes),
8617
- limits,
8618
- nearestExpiryAt: timestamp.nullable(),
8619
- serverNow: timestamp
8620
- };
8621
- function currentDocument(value) {
8622
- let nearest = [...value.entries].sort((left, right) => Date.parse(left.expiresAt) - Date.parse(right.expiresAt))[0]?.expiresAt ?? null;
8623
- return value.bytesUsed === bytes(serializeAppMemoryEntries(value.entries)) && value.nearestExpiryAt === nearest && value.entries.every((entry) => Date.parse(entry.expiresAt) > Date.parse(value.serverNow));
8624
- }
8625
- var AppMemoryDocumentSchema = z3.strictObject(documentShape).refine(currentDocument), AppMemoryOperationSchema = z3.discriminatedUnion("type", [
8626
- z3.strictObject({ type: z3.literal("create"), id: uuid5, kind, text: memoryText }),
8627
- z3.strictObject({ type: z3.literal("update"), id: uuid5, text: memoryText, status, progress: z3.boolean() }),
8628
- z3.strictObject({ type: z3.literal("remove"), ids: ids2 }),
8629
- z3.strictObject({ type: z3.literal("consolidate"), sourceIds: ids2.refine((items) => items.length >= 2), id: uuid5, text: memoryText }).refine((operation) => !operation.sourceIds.includes(operation.id))
8630
- ]), mutationShape = { operationId: uuid5, expectedRevision: requirementsRevisionSchema, operation: AppMemoryOperationSchema }, AppMemoryMutationInputSchema = z3.strictObject(mutationShape).refine((value) => bytes(JSON.stringify(value)) <= APP_MEMORY_REQUEST_BYTES), AppMemoryOutcomeSchema = z3.enum(["updated", "unchanged", "conflict", "capacity", "replayed", "operation_conflict", "reconciliation_required", "nonrenewable"]), AppMemoryReceiptSchema = z3.strictObject({ operationId: uuid5, outcome: AppMemoryOutcomeSchema, revision: requirementsRevisionSchema }), AppMemoryMutationResultSchema = z3.strictObject({
8631
- ...documentShape,
8632
- outcome: AppMemoryOutcomeSchema,
8633
- receipt: AppMemoryReceiptSchema.optional(),
8634
- recoveryActions: z3.array(z3.enum(["read", "remove", "reduce", "consolidate", "create"])).max(5).optional(),
8635
- message: z3.string().min(1).max(512).refine(validText).optional()
8636
- }).refine(currentDocument), APP_MEMORY_TOOLS = {
8637
- read_app_memory: defineTool({
8638
- name: "read_app_memory",
8639
- title: "Read app memory",
8640
- description: "Read bounded current working context. Follow authoring/app-memory.md in the app-generation skill; context is not authority or saved-app proof.",
8641
- inputShape: {},
8642
- result: AppMemoryDocumentSchema
8643
- }),
8644
- mutate_app_memory: { ...defineTool({
8645
- name: "mutate_app_memory",
8646
- title: "Update app memory",
8647
- description: "Checkpoint, correct, remove or consolidate working context using its last read revision. Follow authoring/app-memory.md in the app-generation skill.",
8648
- inputShape: mutationShape,
8649
- result: AppMemoryMutationResultSchema
8650
- }), input: AppMemoryMutationInputSchema }
8651
- };
8652
-
8653
8720
  // skills/adelin-app-generation/scripts/local-builder.mjs
8654
8721
  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 = [
8655
8722
  "read_access",
@@ -8669,9 +8736,10 @@ var UUID13 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-
8669
8736
  "list_assets",
8670
8737
  ...Object.keys(APP_REQUIREMENTS_TOOLS),
8671
8738
  ...Object.keys(APP_MEMORY_TOOLS),
8739
+ APP_TASK_TOOL.name,
8672
8740
  ...ARTIFACT_TOOLS,
8673
8741
  ...TEXT_REPLY_TOOLS
8674
- ]), 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 = {
8742
+ ]), metadataTools = { ...APP_REQUIREMENTS_TOOLS, ...APP_MEMORY_TOOLS, [APP_TASK_TOOL.name]: APP_TASK_TOOL }, metadataWrites = /* @__PURE__ */ new Set(["update_app_requirements", "mutate_app_memory", APP_TASK_TOOL.name]), 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 = {
8675
8743
  DESIGNS_NOT_IN_SESSION: "Offer 1\u20134 designs you created or revised with create_artifact or update_artifact while this app was open.",
8676
8744
  CHOICE_REFUSED: "That design is not one of the options, or the session has ended."
8677
8745
  }, fields = {
@@ -8821,7 +8889,7 @@ var UUID13 = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-
8821
8889
  {
8822
8890
  name: "build_app",
8823
8891
  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.`,
8824
- inputSchema: closed5({ replace_assets: { type: "array", maxItems: 50, uniqueItems: !0, items: { type: "string", minLength: 5, maxLength: 69 } } })
8892
+ inputSchema: closed5({ task_id: { type: "string", pattern: UUID13 }, replace_assets: { type: "array", maxItems: 50, uniqueItems: !0, items: { type: "string", minLength: 5, maxLength: 69 } } }, ["task_id"])
8825
8893
  },
8826
8894
  { 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 },
8827
8895
  { name: "reconcile_build", description: "Reconcile an interrupted build.", inputSchema: noArgs },
@@ -8947,10 +9015,10 @@ function editConflict(result) {
8947
9015
  return { state: "conflict", ...typeof value.retryAt == "string" ? { retryAt: value.retryAt } : {}, message };
8948
9016
  }
8949
9017
  function textReply(result) {
8950
- let text4 = result?.content?.length === 1 && result.content[0].type === "text" ? result.content[0].text : null;
8951
- if (typeof text4 != "string" || Buffer.byteLength(text4, "utf8") > MAX_TEXT_REPLY_BYTES)
9018
+ let text5 = result?.content?.length === 1 && result.content[0].type === "text" ? result.content[0].text : null;
9019
+ if (typeof text5 != "string" || Buffer.byteLength(text5, "utf8") > MAX_TEXT_REPLY_BYTES)
8952
9020
  throw new Error("Adelin returned an invalid tool result.");
8953
- return { ...result.isError ? { isError: !0 } : {}, content: [{ type: "text", text: text4 }] };
9021
+ return { ...result.isError ? { isError: !0 } : {}, content: [{ type: "text", text: text5 }] };
8954
9022
  }
8955
9023
  async function safeCall(remote2, name, args, saving = !1) {
8956
9024
  let result;
@@ -8962,8 +9030,8 @@ async function safeCall(remote2, name, args, saving = !1) {
8962
9030
  if (TEXT_REPLY_TOOLS.has(name)) return textReply(result);
8963
9031
  let conflict = name === "open_edit_session" ? editConflict(result) : null;
8964
9032
  if (conflict) return { content: [{ type: "text", text: JSON.stringify(conflict) }] };
8965
- let text4 = CODED_REFUSAL_TOOLS.has(name) && result?.isError && result.content?.length === 1 ? result.content[0].text : null;
8966
- 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);
9033
+ let text5 = CODED_REFUSAL_TOOLS.has(name) && result?.isError && result.content?.length === 1 ? result.content[0].text : null;
9034
+ return typeof text5 == "string" && text5.length <= 4096 && /^[A-Z][A-Z_]{2,63}: /.test(text5) ? { isError: !0, content: [{ type: "text", text: text5 }] } : (valueOf(result, saving, name === "device_operation" ? MAX_DEVICE_BYTES : void 0), result);
8967
9035
  }
8968
9036
  async function creationCall(remote2, name, args) {
8969
9037
  let result;
@@ -9317,8 +9385,10 @@ function createLocalBuilder(remote2, transport, {
9317
9385
  }), await session.close(), error;
9318
9386
  }
9319
9387
  }
9320
- if (name === "build_app")
9321
- return syncActiveSupport(), response(await session.build({ assets: (edit) => saveWorkspaceAssets({ ...edit, call: assetCall, replace: args.replace_assets ?? [] }) }));
9388
+ if (name === "build_app") {
9389
+ if (syncActiveSupport(), !session.session) throw new Error("Open an app first.");
9390
+ return assetStatus(session.session.workspace, session.session.appId)?.pending.length && assertTaskWritable(APP_MEMORY_TOOLS.read_app_memory.result.parse(valueOf(await safeRemote.call("read_app_memory", { app_id: session.session.appId }))), args.task_id), response(await session.build({ taskId: args.task_id, assets: (edit) => saveWorkspaceAssets({ ...edit, call: assetCall, replace: args.replace_assets ?? [] }) }));
9391
+ }
9322
9392
  if (name === "check_app") {
9323
9393
  if (!session.session) throw new Error("Open an app first.");
9324
9394
  syncActiveSupport();
@@ -9329,7 +9399,7 @@ function createLocalBuilder(remote2, transport, {
9329
9399
  if (name === "retry_build") return response(await session.retry());
9330
9400
  if (name === "build_status") return response(session.status());
9331
9401
  if (name === "close_app")
9332
- return await releaseView(), await closeBrowser(), response(await session.close());
9402
+ return session.session && assertTaskCheckpoint(APP_MEMORY_TOOLS.read_app_memory.result.parse(valueOf(await safeRemote.call("read_app_memory", { app_id: session.session.appId })))), await releaseView(), await closeBrowser(), response(await session.close());
9333
9403
  if (name === "tell_builder") return response(await session.tell(args.message));
9334
9404
  if (name === "ask_builder_to_choose") return response(await session.ask(args.artifact_ids, args.question));
9335
9405
  if (name === "wait_for_choice") return response(await session.awaitChoice(args.request_id));