editorbrain 0.41.0 → 0.41.2

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.
@@ -142,6 +142,21 @@ var billing = { label: "Ver plan y cr\xE9ditos", url: "https://editorbrain.com/a
142
142
  var integrations = { label: "Ver mis integraciones", url: "https://editorbrain.com/app/integrations" };
143
143
  var support = { label: "Contactar soporte", url: "mailto:soporte@editorbrain.com" };
144
144
  var guidance = {
145
+ email_verification_required: { status: 403, help: {
146
+ message: "Verifica tu correo para usar las funciones de IA de EditorBrain.",
147
+ nextStep: "Abre la verificaci\xF3n de correo y solicita un enlace si lo necesitas. Completa ese paso antes de repetir la b\xFAsqueda. Mientras tanto puedes trabajar con tu material y los recursos ya disponibles. No hace falta comprar cr\xE9ditos ni cambiar de cuenta para evitar esta comprobaci\xF3n.",
148
+ actions: [{ label: "Verificar mi correo", url: "https://editorbrain.com/verify-email" }]
149
+ } },
150
+ invalid_authored_query: { status: 400, help: {
151
+ message: "La consulta o su cursor de animaciones no es v\xE1lido.",
152
+ nextStep: "Comprueba los par\xE1metros y l\xEDmites de list_authored_scenes. Si cambiaste la consulta, los filtros o la versi\xF3n, descarta after y comienza en la primera p\xE1gina. Para continuar, utiliza nextCursor tal como se recibi\xF3 con los mismos par\xE1metros; no lo construyas ni lo modifiques. No repitas indefinidamente la petici\xF3n que fall\xF3.",
153
+ actions: []
154
+ } },
155
+ sfx_unavailable: { status: 404, help: {
156
+ message: "Este banco o sonido no est\xE1 disponible para esta selecci\xF3n.",
157
+ nextStep: "Consulta search_sfx con el proyecto actual y respeta su banco configurado. Si no hay bancos disponibles, informa de esa limitaci\xF3n y contin\xFAa las partes independientes del montaje. Puedes solicitar un audio propio con permiso de uso o contactar soporte; no inventes un ID, cambies de banco ni generes sonidos de pago autom\xE1ticamente. Recargar cr\xE9ditos no activa esta biblioteca.",
158
+ actions: [support]
159
+ } },
145
160
  resource_plan_required: { status: 403, help: { message: "Este recurso requiere Creator o Studio.", nextStep: "Puedes ver su preview o proponer un recurso con access.canUse=true que encaje con la escena. Una recarga de cr\xE9ditos no desbloquea recursos premium. No sustituyas la elecci\xF3n expl\xEDcita del usuario ni cambies de plan autom\xE1ticamente.", actions: [billing, { label: "Explorar animaciones", url: "https://editorbrain.com/app/animations" }] } },
146
161
  studio_insufficient_credits: { status: 402, help: {
147
162
  message: "No alcanzan tus cr\xE9ditos creativos de EditorBrain para este encargo.",
@@ -2185,7 +2200,7 @@ function numeric(value, name, min, max, integer2 = false) {
2185
2200
  if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max || integer2 && !Number.isInteger(value)) throw new Error(`${name} must be ${integer2 ? "an integer" : "a number"} from ${min} to ${max}.`);
2186
2201
  }
2187
2202
  function rasterDimensions(binary, mime, name) {
2188
- const invalid6 = () => new Error(`${name} has malformed or missing raster dimensions.`);
2203
+ const invalid7 = () => new Error(`${name} has malformed or missing raster dimensions.`);
2189
2204
  const byte = (offset2) => binary.charCodeAt(offset2);
2190
2205
  const u16 = (offset2) => byte(offset2) * 256 + byte(offset2 + 1);
2191
2206
  const u32 = (offset2) => u16(offset2) * 65536 + u16(offset2 + 2);
@@ -2193,50 +2208,50 @@ function rasterDimensions(binary, mime, name) {
2193
2208
  const le24 = (offset2) => le16(offset2) + byte(offset2 + 2) * 65536;
2194
2209
  const le32 = (offset2) => le24(offset2) + byte(offset2 + 3) * 16777216;
2195
2210
  const check = (width, height) => {
2196
- if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw invalid6();
2211
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw invalid7();
2197
2212
  if (width > MOTION_INPUT_LIMITS.maxImageDimension || height > MOTION_INPUT_LIMITS.maxImageDimension || width * height > MOTION_INPUT_LIMITS.maxImagePixels) throw new Error(`${name} raster dimensions exceed ${MOTION_INPUT_LIMITS.maxImageDimension} pixels per side or ${MOTION_INPUT_LIMITS.maxImagePixels} total pixels.`);
2198
2213
  };
2199
2214
  if (mime === "image/png") {
2200
- if (u32(8) !== 13) throw invalid6();
2215
+ if (u32(8) !== 13) throw invalid7();
2201
2216
  check(u32(16), u32(20));
2202
2217
  return;
2203
2218
  }
2204
2219
  if (mime === "image/jpeg") {
2205
2220
  let offset2 = 2, dimensions;
2206
2221
  while (offset2 < binary.length) {
2207
- if (byte(offset2++) !== 255) throw invalid6();
2222
+ if (byte(offset2++) !== 255) throw invalid7();
2208
2223
  while (offset2 < binary.length && byte(offset2) === 255) offset2++;
2209
- if (offset2 >= binary.length) throw invalid6();
2224
+ if (offset2 >= binary.length) throw invalid7();
2210
2225
  const marker = byte(offset2++);
2211
2226
  if (marker === 217 || marker === 218) break;
2212
- if (marker === 216 || marker === 0) throw invalid6();
2227
+ if (marker === 216 || marker === 0) throw invalid7();
2213
2228
  if (marker === 1 || marker >= 208 && marker <= 215) continue;
2214
- if (offset2 + 2 > binary.length) throw invalid6();
2229
+ if (offset2 + 2 > binary.length) throw invalid7();
2215
2230
  const size = u16(offset2);
2216
- if (size < 2 || offset2 + size > binary.length) throw invalid6();
2231
+ if (size < 2 || offset2 + size > binary.length) throw invalid7();
2217
2232
  if ([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker)) {
2218
- if (size < 11 || size !== 8 + byte(offset2 + 7) * 3) throw invalid6();
2233
+ if (size < 11 || size !== 8 + byte(offset2 + 7) * 3) throw invalid7();
2219
2234
  const width = u16(offset2 + 5), height = u16(offset2 + 3);
2220
2235
  check(width, height);
2221
- if (dimensions && (dimensions[0] !== width || dimensions[1] !== height)) throw invalid6();
2236
+ if (dimensions && (dimensions[0] !== width || dimensions[1] !== height)) throw invalid7();
2222
2237
  dimensions = [width, height];
2223
2238
  }
2224
2239
  offset2 += size;
2225
2240
  }
2226
- if (!dimensions) throw invalid6();
2241
+ if (!dimensions) throw invalid7();
2227
2242
  return;
2228
2243
  }
2229
- if (le32(4) !== binary.length - 8) throw invalid6();
2244
+ if (le32(4) !== binary.length - 8) throw invalid7();
2230
2245
  const frameDimensions = (kind, size, data) => {
2231
2246
  if (kind === "VP8L") {
2232
- if (size < 5 || byte(data) !== 47 || byte(data + 4) >> 5 !== 0) throw invalid6();
2247
+ if (size < 5 || byte(data) !== 47 || byte(data + 4) >> 5 !== 0) throw invalid7();
2233
2248
  const width = 1 + (byte(data + 1) | (byte(data + 2) & 63) << 8);
2234
2249
  const height = 1 + (byte(data + 2) >> 6 | byte(data + 3) << 2 | (byte(data + 4) & 15) << 10);
2235
2250
  check(width, height);
2236
2251
  return true;
2237
2252
  }
2238
2253
  if (kind === "VP8 ") {
2239
- if (size < 10 || byte(data) & 1 || binary.slice(data + 3, data + 6) !== "\x9D*") throw invalid6();
2254
+ if (size < 10 || byte(data) & 1 || binary.slice(data + 3, data + 6) !== "\x9D*") throw invalid7();
2240
2255
  check(le16(data + 6) & 16383, le16(data + 8) & 16383);
2241
2256
  return true;
2242
2257
  }
@@ -2245,26 +2260,26 @@ function rasterDimensions(binary, mime, name) {
2245
2260
  let offset = 12, found = false;
2246
2261
  while (offset + 8 <= binary.length) {
2247
2262
  const kind = binary.slice(offset, offset + 4), size = le32(offset + 4), data = offset + 8;
2248
- if (size > binary.length - data) throw invalid6();
2263
+ if (size > binary.length - data) throw invalid7();
2249
2264
  if (kind === "VP8X") {
2250
- if (size !== 10) throw invalid6();
2265
+ if (size !== 10) throw invalid7();
2251
2266
  check(le24(data + 4) + 1, le24(data + 7) + 1);
2252
2267
  found = true;
2253
2268
  } else if (kind === "ANMF") {
2254
- if (size < 16) throw invalid6();
2269
+ if (size < 16) throw invalid7();
2255
2270
  check(le24(data + 6) + 1, le24(data + 9) + 1);
2256
2271
  let nested = data + 16, frame = false;
2257
2272
  while (nested + 8 <= data + size) {
2258
2273
  const frameKind = binary.slice(nested, nested + 4), frameSize = le32(nested + 4), frameData = nested + 8;
2259
- if (frameSize > data + size - frameData) throw invalid6();
2274
+ if (frameSize > data + size - frameData) throw invalid7();
2260
2275
  frame = frameDimensions(frameKind, frameSize, frameData) || frame;
2261
2276
  nested = frameData + frameSize + frameSize % 2;
2262
2277
  }
2263
- if (!frame || nested !== data + size) throw invalid6();
2278
+ if (!frame || nested !== data + size) throw invalid7();
2264
2279
  } else found = frameDimensions(kind, size, data) || found;
2265
2280
  offset = data + size + size % 2;
2266
2281
  }
2267
- if (!found || offset !== binary.length) throw invalid6();
2282
+ if (!found || offset !== binary.length) throw invalid7();
2268
2283
  }
2269
2284
  function dataUrl(value, name, kind) {
2270
2285
  const max = kind === "font" ? MOTION_INPUT_LIMITS.fontBytes : MOTION_INPUT_LIMITS.imageBytes;
@@ -181247,7 +181262,72 @@ var stopwords = new Set("a al algo como con cual de del donde el ella en entre e
181247
181262
  function stems(text11) {
181248
181263
  return new Set((normalized(text11).match(/[a-z0-9]+/g) ?? []).filter((word) => word.length > 2 && !stopwords.has(word)).map((word) => word.slice(0, 5)));
181249
181264
  }
181250
- var buildSearchIndex = (scenes) => scenes.map((scene) => ({ scene, fields: [
181265
+ var discoveryWords = {
181266
+ animated: "",
181267
+ animation: "",
181268
+ animations: "",
181269
+ show: "",
181270
+ showing: "",
181271
+ with: "",
181272
+ the: "",
181273
+ and: "",
181274
+ for: "",
181275
+ of: "",
181276
+ a: "",
181277
+ an: "",
181278
+ number: "numero",
181279
+ numbers: "numeros",
181280
+ counter: "contador",
181281
+ counters: "contadores",
181282
+ money: "dinero",
181283
+ underline: "subrayar",
181284
+ underlined: "subrayado",
181285
+ word: "palabra",
181286
+ words: "palabras",
181287
+ before: "antes",
181288
+ after: "despues",
181289
+ comparison: "comparacion",
181290
+ compare: "comparar",
181291
+ reveal: "revelar",
181292
+ brand: "marca",
181293
+ end: "final",
181294
+ title: "titulo",
181295
+ name: "nombre",
181296
+ job: "cargo",
181297
+ map: "mapa",
181298
+ route: "ruta",
181299
+ journey: "recorrido",
181300
+ steps: "pasos",
181301
+ list: "lista",
181302
+ chart: "grafica",
181303
+ graph: "grafica",
181304
+ bars: "barras",
181305
+ ranking: "ranking",
181306
+ timeline: "cronologia",
181307
+ photo: "foto",
181308
+ photos: "fotos",
181309
+ image: "imagen",
181310
+ images: "imagenes",
181311
+ testimonial: "testimonio",
181312
+ product: "producto",
181313
+ price: "precio",
181314
+ pricing: "precios",
181315
+ discount: "descuento",
181316
+ typewriter: "maquina escribir",
181317
+ handwriting: "escritura mano",
181318
+ handwritten: "escrito mano"
181319
+ };
181320
+ function discoveryTerms(search) {
181321
+ const translated = search.replace(/\blower third\b/g, "nombre cargo").replace(/\bcount up\b/g, "contador").replace(/\b[a-z0-9]+\b/g, (word) => Object.hasOwn(discoveryWords, word) ? discoveryWords[word] : word);
181322
+ const terms = stems(translated);
181323
+ if (/\bcontador(?:es)?\b/.test(translated)) {
181324
+ terms.delete("conta");
181325
+ terms.add("contador");
181326
+ }
181327
+ return terms;
181328
+ }
181329
+ var mechanismTerms = /* @__PURE__ */ new Set([...stems("subrayar odometro"), "contador"]);
181330
+ var buildSearchIndex = (scenes, precise = false) => scenes.map((scene) => ({ scene, fields: [
181251
181331
  [scene.title, 3],
181252
181332
  [scene.universalMechanism ?? "", 3],
181253
181333
  [scene.intent, 2.5],
@@ -181255,21 +181335,28 @@ var buildSearchIndex = (scenes) => scenes.map((scene) => ({ scene, fields: [
181255
181335
  [(scene.crossNicheUses ?? []).join(" "), 2.5],
181256
181336
  [(scene.presets ?? []).map((preset) => `${preset.name.replace(/-/g, " ")} ${preset.summary}`).join(" "), 2],
181257
181337
  [scene.useFor ?? "", 1.5]
181258
- ].map(([text11, weight]) => ({ terms: stems(text11), weight })) }));
181338
+ ].map(([text11, weight]) => {
181339
+ const terms = stems(text11);
181340
+ if (precise && /\bcontador(?:es)?\b/.test(normalized(text11))) terms.add("contador");
181341
+ return { terms, weight };
181342
+ }) }));
181259
181343
  var searchIndexes = { "1.1.0": buildSearchIndex(catalogs["1.1.0"]), "1.2.0": buildSearchIndex(catalogs["1.2.0"]), "1.3.0": buildSearchIndex(catalogs["1.3.0"]), "1.4.0": buildSearchIndex(catalogs["1.4.0"]) };
181260
- var v14TermWeights = (() => {
181261
- const index = searchIndexes["1.4.0"], frequencies = /* @__PURE__ */ new Map();
181344
+ var bilingualIndex = buildSearchIndex(catalogs["1.4.0"], true);
181345
+ function termWeights(index) {
181346
+ const frequencies = /* @__PURE__ */ new Map();
181262
181347
  for (const { fields } of index) for (const term of new Set(fields.flatMap((field) => [...field.terms]))) {
181263
181348
  frequencies.set(term, (frequencies.get(term) ?? 0) + 1);
181264
181349
  }
181265
181350
  return new Map([...frequencies].map(([term, count]) => [term, 1 + Math.log((index.length + 1) / (count + 1))]));
181266
- })();
181267
- function rankedCandidates(search, version) {
181268
- const scenes = catalogs[version], searchIndex = searchIndexes[version];
181351
+ }
181352
+ var v14TermWeights = termWeights(searchIndexes["1.4.0"]);
181353
+ var bilingualTermWeights = termWeights(bilingualIndex);
181354
+ function rankedCandidates(search, version, bilingual = false) {
181355
+ const scenes = catalogs[version], searchIndex = bilingual ? bilingualIndex : searchIndexes[version];
181269
181356
  if (!search) return scenes;
181270
181357
  const exact = scenes.find((scene) => scene.id === search);
181271
181358
  if (exact) return [exact];
181272
- const queryTerms = stems(search);
181359
+ const queryTerms = bilingual ? discoveryTerms(search) : stems(search);
181273
181360
  if (version === "1.4.0") queryTerms.delete("quien");
181274
181361
  return searchIndex.map(({ scene, fields }) => {
181275
181362
  if (version === "1.4.0") {
@@ -181277,8 +181364,9 @@ function rankedCandidates(search, version) {
181277
181364
  for (const term of queryTerms) {
181278
181365
  const fieldWeight = fields.reduce((sum, field) => sum + (field.terms.has(term) ? field.weight : 0), 0);
181279
181366
  if (!fieldWeight) continue;
181280
- const rarity = v14TermWeights.get(term);
181281
- score += rarity * Math.sqrt(fieldWeight);
181367
+ const rarity = (bilingual ? bilingualTermWeights : v14TermWeights).get(term);
181368
+ const mechanismBoost = bilingual && mechanismTerms.has(term) && fields.slice(0, 2).some((field) => field.terms.has(term)) ? 3 : 1;
181369
+ score += rarity * Math.sqrt(fieldWeight) * mechanismBoost;
181282
181370
  coverage += rarity;
181283
181371
  }
181284
181372
  return { scene, score: score * Math.sqrt(coverage) };
@@ -181322,13 +181410,16 @@ function listAuthoredMotionScenes(options = {}) {
181322
181410
  let version = options.version ?? AUTHORED_MOTION_CATALOG_VERSION;
181323
181411
  if (!isAuthoredMotionVersion(version)) throw Error("Unknown authored motion version");
181324
181412
  let cursorId;
181413
+ let bilingual = version === "1.4.0" && Boolean(search);
181325
181414
  if (after !== void 0) {
181326
- const [cursorVersion, encoded, id2, encodedFilters, ...extra] = after.split("|");
181327
- if (!isAuthoredMotionVersion(cursorVersion) || options.version !== void 0 && options.version !== cursorVersion || encoded !== encodeURIComponent(search) || !id2 || encodedFilters !== cursorFilters || extra.length) throw new Error("Cursor does not match this authored motion query, version or filters.");
181415
+ const [cursorVersion, encoded, id2, encodedFilters, ranker, ...extra] = after.split("|");
181416
+ const q2 = ranker === "q2" && cursorVersion === "1.4.0" && Boolean(search);
181417
+ if (!isAuthoredMotionVersion(cursorVersion) || options.version !== void 0 && options.version !== cursorVersion || encoded !== encodeURIComponent(search) || !id2 || (q2 ? encodedFilters !== (cursorFilters ?? "") : encodedFilters !== cursorFilters) || ranker !== void 0 && !q2 || extra.length) throw new Error("Cursor does not match this authored motion query, version or filters.");
181328
181418
  version = cursorVersion;
181329
181419
  cursorId = id2;
181420
+ bilingual = q2;
181330
181421
  }
181331
- const queryCandidates = version === "1.0.0" ? legacyCandidates(search) : rankedCandidates(search, version);
181422
+ const queryCandidates = version === "1.0.0" ? legacyCandidates(search) : rankedCandidates(search, version, bilingual);
181332
181423
  const candidates = queryCandidates.filter((scene) => matchesAuthoredMotionFilters(scene.facets, filters));
181333
181424
  if (!search && filters.funcion) candidates.sort((a, b) => Number(filters.funcion.includes(b.facets.funciones[0])) - Number(filters.funcion.includes(a.facets.funciones[0])));
181334
181425
  let start3 = 0;
@@ -181340,7 +181431,7 @@ function listAuthoredMotionScenes(options = {}) {
181340
181431
  return {
181341
181432
  version,
181342
181433
  items: page.map(summary),
181343
- nextCursor: start3 + page.length < candidates.length ? `${version}|${encodeURIComponent(search)}|${page[page.length - 1].id}${cursorFilters ? `|${cursorFilters}` : ""}` : null,
181434
+ nextCursor: start3 + page.length < candidates.length ? `${version}|${encodeURIComponent(search)}|${page[page.length - 1].id}${bilingual ? `|${cursorFilters ?? ""}|q2` : cursorFilters ? `|${cursorFilters}` : ""}` : null,
181344
181435
  total: candidates.length,
181345
181436
  facetCounts: countAuthoredMotionFacets(queryCandidates, filters),
181346
181437
  availableFacetCounts: structuredClone(availableFacetCounts[version]),
@@ -181372,12 +181463,12 @@ var SOCIAL_SAFE_PROFILES = {
181372
181463
  reels: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 },
181373
181464
  shorts: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 }
181374
181465
  };
181375
- function validateVisualReview(value, hash6, duration, width, height) {
181466
+ function validateVisualReview(value, hash7, duration, width, height) {
181376
181467
  const v = value;
181377
181468
  const fail3 = () => {
181378
181469
  throw new Error("Invalid visual profile: use the exact artifact hash, output-clock seconds and output-pixel boxes.");
181379
181470
  };
181380
- if (!v || typeof v !== "object" || Array.isArray(v) || v.schemaVersion !== 1 || v.artifactSha256 !== hash6 || !/^[a-f0-9]{64}$/.test(v.artifactSha256)) fail3();
181471
+ if (!v || typeof v !== "object" || Array.isArray(v) || v.schemaVersion !== 1 || v.artifactSha256 !== hash7 || !/^[a-f0-9]{64}$/.test(v.artifactSha256)) fail3();
181381
181472
  if (Object.keys(v).some((k) => !["schemaVersion", "artifactSha256", "platform", "holds", "geometry"].includes(k))) fail3();
181382
181473
  if (v.platform !== void 0 && !Object.hasOwn(SOCIAL_SAFE_PROFILES, v.platform)) fail3();
181383
181474
  if (v.holds !== void 0 && (!Array.isArray(v.holds) || v.holds.length > 1e3)) fail3();
@@ -182432,7 +182523,7 @@ async function downloadPinnedSource(client, pin, root, out, kind, fetcher = fetc
182432
182523
  if (!reader) throw new CliError("INVALID_RESPONSE", "Source download body is missing.", "Retry the pinned source.");
182433
182524
  const temporary = join2(dirname2(target), `.eb-motion-${randomUUID2()}.tmp`);
182434
182525
  let handle;
182435
- const hash6 = createHash("sha256");
182526
+ const hash7 = createHash("sha256");
182436
182527
  let size = 0;
182437
182528
  try {
182438
182529
  await mkdir2(dirname2(target), { recursive: true });
@@ -182443,10 +182534,10 @@ async function downloadPinnedSource(client, pin, root, out, kind, fetcher = fetc
182443
182534
  if (done) break;
182444
182535
  size += value.length;
182445
182536
  if (size > pin.bytes) throw new CliError("HASH_MISMATCH", "Source archive exceeds the pinned length.", "Discard the unverified download.");
182446
- hash6.update(value);
182537
+ hash7.update(value);
182447
182538
  await handle.writeFile(value);
182448
182539
  }
182449
- if (size !== pin.bytes || hash6.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Source archive verification failed.", "Do not extract this download.");
182540
+ if (size !== pin.bytes || hash7.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Source archive verification failed.", "Do not extract this download.");
182450
182541
  await handle.sync();
182451
182542
  await handle.close();
182452
182543
  await checkedPath(root, out, false);
@@ -183897,8 +183988,8 @@ async function probeLocalMedia(value) {
183897
183988
  if (!before.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
183898
183989
  const entries = "format=duration,start_time:stream=index,codec_type,codec_name,width,height,avg_frame_rate,sample_rate,channels,duration,color_transfer,sample_aspect_ratio,pix_fmt:stream_disposition=attached_pic:stream_side_data=side_data_type,rotation,displaymatrix:stream_tags=rotate";
183899
183990
  const { stdout } = await runMediaTool("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", ...localInputArgs(path)]);
183900
- const hash6 = createHash3("sha256");
183901
- for await (const chunk of handle.createReadStream({ autoClose: false })) hash6.update(chunk);
183991
+ const hash7 = createHash3("sha256");
183992
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash7.update(chunk);
183902
183993
  const after = await handle.stat();
183903
183994
  await assertNoMediaSymlinks(path);
183904
183995
  const current2 = await lstat3(path);
@@ -183923,7 +184014,7 @@ async function probeLocalMedia(value) {
183923
184014
  ...type === "audio" ? { sampleRate: nonnegative2(stream.sample_rate), channels: positiveInteger(stream.channels) ?? null } : {}
183924
184015
  };
183925
184016
  });
183926
- return { path, sha256: hash6.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
184017
+ return { path, sha256: hash7.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
183927
184018
  } finally {
183928
184019
  await handle.close();
183929
184020
  }
@@ -184189,6 +184280,98 @@ import { fileURLToPath } from "node:url";
184189
184280
 
184190
184281
  // packages/cli/src/agent-guidance-history.ts
184191
184282
  var VERIFIED_GUIDANCE_RELEASES = [
184283
+ {
184284
+ "version": "0.41.1",
184285
+ "archiveSha256": "2ae2cc3ef80c208af65e50db8909dd16781a28d103794565573d51c0efd098be",
184286
+ "files": {
184287
+ "editorbrain-formats/SKILL.md": "65ea59aae091ca9618b5e479befe0c76edf174df7091ed74d4307485a2252fcd",
184288
+ "editorbrain-formats/references/aspirational-list-demo.md": "e884ce44d15f4496812ed18120f7d4c49c4261e148fcefe05c77c110b589771c",
184289
+ "editorbrain-formats/references/cumulative-tier-list.md": "7b7e8208687c6b925443e55d640ced6c1d09824377884244a09d7f3089d60aa5",
184290
+ "editorbrain-formats/references/numbered-tutorial.md": "95754ae7dbfaa678e11ddf1a2b84710dba83a16e2fa4055051bd4f5f4f868a5f",
184291
+ "editorbrain-motion/SKILL.md": "57292f3a48cc8f1fc2d89f2cc054a3ceabeda9422958fa708f273c662867d5ae",
184292
+ "editorbrain-motion/references/authored-scenes.md": "52e97b89b1d8a288c4ce7bd133eafea84e934ef2bf03ffe2dcef8c368b6f977d",
184293
+ "editorbrain-motion/references/code-motion.md": "50382a797adc1e1596086e2408e81ee75ceb6730ca409be9c884646db643a7cd",
184294
+ "editorbrain-motion/references/component-library.md": "e88ed19d2ab9dca8d2ea02abe6c476021c03b9679bce99292cf7da52d65d2236",
184295
+ "editorbrain-motion/references/generated-motion.md": "a8d214b53c15f742658abd84f03b768fa2821f8cde94f50aab82a3759a30b36b",
184296
+ "editorbrain-motion/references/motion-craft.md": "dae520b0e641fc9c3bf937241936588a855bf3453358e239ccc3cc3a2bcf0825",
184297
+ "editorbrain/AGENTS.md": "b240449d452c824415062a2b422bf55a5ae2d868a81083989d10ffaeb5c33a3f",
184298
+ "editorbrain/SKILL.md": "a9482dcd170739fe279bf2c69a154327c5d6a68926c1555b010a1753851bf0bd",
184299
+ "editorbrain/references/audio-production.md": "9800505dcb320b58f35aeaed77303039d8fffb2c29b46c43cedeeba8637d2482",
184300
+ "editorbrain/references/cli-mcp.md": "2c34ed7f896865e71959562bcc61b5a34292d6a9a4c14690f0c28d00875da75c",
184301
+ "editorbrain/references/editorial-evidence.md": "79ed5bd90eb903014313c32a1e337822c5cb454e642bcfa852dcb77d30a9392e",
184302
+ "editorbrain/references/editorial-families.md": "b802ec6f02fd079e99df84d69a3c515d63ad058960b568c0c7b7dec1912495dd",
184303
+ "editorbrain/references/family-animated.md": "54a140d0a64b01147c52ea8cbaab4e4599bfe1af330f5a3ad6ef2a30351ab47d",
184304
+ "editorbrain/references/family-demonstration.md": "737334a8d9230682cde3a6ed11bfc02c4f9795c8f25a3b668be9d7393ec3e53d",
184305
+ "editorbrain/references/family-essay.md": "003f2cd450f33ba6641a9b1114cbc578c04cbb658b992c89c765d43198d1b4c2",
184306
+ "editorbrain/references/family-personal.md": "e93c304d7bc7d3eb31a3c9cb3be83f4f48d41319c2ac2e1e6f53f38576f5e644",
184307
+ "editorbrain/references/family-presenter.md": "76b8140b924930b306ce97772d6a7b683870bd14f19772b5339a490752b7de24",
184308
+ "editorbrain/references/first-edit.md": "483843af6672b70a76ce6d41e98324fbfc2a31d5ac50633f963d1ab0eeba1bc0",
184309
+ "editorbrain/references/integrations.md": "b5e7ba099acd79053cdd09822092eb121add6de39eada2d6911ad5a4f452ce2a",
184310
+ "editorbrain/references/local-production.md": "268a05706a3c1cae4f61248437c00be3e9ee18b2a0f747c8cd054d88f0a33661",
184311
+ "editorbrain/references/media-preferences.md": "87e508a75cdb6f4644db767273bfb230fb79f182ed05ee0f6257c6c05ea4dc7a",
184312
+ "editorbrain/references/memory-and-review.md": "406589a18e9e86ad8ce7d71e0f5bf00f67dab42c05af7721482fdca1c25c7c1b",
184313
+ "editorbrain/references/motion-review.md": "0fb09a2d61ecd13114ced5cca5daa4580a922cf7d7b3f8698077ceb0e96da6f0",
184314
+ "editorbrain/references/onboarding.md": "b842dac368455b670543d9a0defdad91708c10788d1474ddfa6b31ca929e930b",
184315
+ "editorbrain/references/personal-resources.md": "92ce6f32191929bd946c97305452521f6048d6bb8ea371e9083536eff5ce9512",
184316
+ "editorbrain/references/production-and-review.md": "28a64ee6407a1de7dc204776c158408c11b3987020ad1bdd1b79fd19745fbffa",
184317
+ "editorbrain/references/production-continuity.md": "b73a851bff421fa24e364d8848e312e54de1d3d971099a567295c80a5e18d8c6",
184318
+ "editorbrain/references/real-media.md": "cfad1aa15198dfe5ecc1f1b67c96d43a7d2084e7f5119de93d1b360203694938",
184319
+ "editorbrain/references/search-brief.md": "1bd2514f961522675047910f001f33da035382e48e933bc5eadb9d7d01455a0d",
184320
+ "editorbrain/references/sfx-library.md": "d7ee0d2916559ce11a7fd244ccbcb98172413653c3fdbe0545e57b3eda543b16",
184321
+ "editorbrain/references/starting-an-edit.md": "0b83e006edc43307483489060bde999cb0644623eb9550f56b7add52f4082fff",
184322
+ "editorbrain/references/storage-and-previews.md": "9d06a6bb49f13e23f0af7d5ef35444dd553d1ce8af28662a9aba054b4d0081a5",
184323
+ "editorbrain/references/studio.md": "673377f4534d9a5edd15a75f1ba9acb589458904dfc34332c30033e03801b6a8",
184324
+ "editorbrain/references/style-creator.md": "1b1bc289a5bc308cbbf7f4d699de2933b8934733a2b69b3e98fb1b7420d986f2",
184325
+ "editorbrain/references/style-source.md": "983fa21b4606c3cdc41b2fa4386ddc8f77a1b14ae782aad8774c000696c14de1",
184326
+ "editorbrain/references/workspace-files.md": "29bbddc894ed000bddd065bcb660629e64b29a5cf54dd6850e810b25c990558d"
184327
+ }
184328
+ },
184329
+ {
184330
+ "version": "0.41.0",
184331
+ "archiveSha256": "7a5e5c297d0b9dd95cc4f0a7b214666b437953caae4efca53331372da46e63b1",
184332
+ "files": {
184333
+ "editorbrain/AGENTS.md": "b240449d452c824415062a2b422bf55a5ae2d868a81083989d10ffaeb5c33a3f",
184334
+ "editorbrain-formats/references/aspirational-list-demo.md": "e884ce44d15f4496812ed18120f7d4c49c4261e148fcefe05c77c110b589771c",
184335
+ "editorbrain/references/audio-production.md": "9800505dcb320b58f35aeaed77303039d8fffb2c29b46c43cedeeba8637d2482",
184336
+ "editorbrain-motion/references/authored-scenes.md": "52e97b89b1d8a288c4ce7bd133eafea84e934ef2bf03ffe2dcef8c368b6f977d",
184337
+ "editorbrain/references/cli-mcp.md": "2c34ed7f896865e71959562bcc61b5a34292d6a9a4c14690f0c28d00875da75c",
184338
+ "editorbrain-motion/references/code-motion.md": "50382a797adc1e1596086e2408e81ee75ceb6730ca409be9c884646db643a7cd",
184339
+ "editorbrain-motion/references/component-library.md": "e88ed19d2ab9dca8d2ea02abe6c476021c03b9679bce99292cf7da52d65d2236",
184340
+ "editorbrain-formats/references/cumulative-tier-list.md": "7b7e8208687c6b925443e55d640ced6c1d09824377884244a09d7f3089d60aa5",
184341
+ "editorbrain/references/editorial-evidence.md": "79ed5bd90eb903014313c32a1e337822c5cb454e642bcfa852dcb77d30a9392e",
184342
+ "editorbrain/references/editorial-families.md": "b802ec6f02fd079e99df84d69a3c515d63ad058960b568c0c7b7dec1912495dd",
184343
+ "editorbrain/references/family-animated.md": "54a140d0a64b01147c52ea8cbaab4e4599bfe1af330f5a3ad6ef2a30351ab47d",
184344
+ "editorbrain/references/family-demonstration.md": "737334a8d9230682cde3a6ed11bfc02c4f9795c8f25a3b668be9d7393ec3e53d",
184345
+ "editorbrain/references/family-essay.md": "003f2cd450f33ba6641a9b1114cbc578c04cbb658b992c89c765d43198d1b4c2",
184346
+ "editorbrain/references/family-personal.md": "e93c304d7bc7d3eb31a3c9cb3be83f4f48d41319c2ac2e1e6f53f38576f5e644",
184347
+ "editorbrain/references/family-presenter.md": "76b8140b924930b306ce97772d6a7b683870bd14f19772b5339a490752b7de24",
184348
+ "editorbrain/references/first-edit.md": "483843af6672b70a76ce6d41e98324fbfc2a31d5ac50633f963d1ab0eeba1bc0",
184349
+ "editorbrain-motion/references/generated-motion.md": "a8d214b53c15f742658abd84f03b768fa2821f8cde94f50aab82a3759a30b36b",
184350
+ "editorbrain/references/integrations.md": "b5e7ba099acd79053cdd09822092eb121add6de39eada2d6911ad5a4f452ce2a",
184351
+ "editorbrain/references/local-production.md": "268a05706a3c1cae4f61248437c00be3e9ee18b2a0f747c8cd054d88f0a33661",
184352
+ "editorbrain/references/media-preferences.md": "87e508a75cdb6f4644db767273bfb230fb79f182ed05ee0f6257c6c05ea4dc7a",
184353
+ "editorbrain/references/memory-and-review.md": "406589a18e9e86ad8ce7d71e0f5bf00f67dab42c05af7721482fdca1c25c7c1b",
184354
+ "editorbrain-motion/references/motion-craft.md": "dae520b0e641fc9c3bf937241936588a855bf3453358e239ccc3cc3a2bcf0825",
184355
+ "editorbrain/references/motion-review.md": "0fb09a2d61ecd13114ced5cca5daa4580a922cf7d7b3f8698077ceb0e96da6f0",
184356
+ "editorbrain-formats/references/numbered-tutorial.md": "95754ae7dbfaa678e11ddf1a2b84710dba83a16e2fa4055051bd4f5f4f868a5f",
184357
+ "editorbrain/references/onboarding.md": "fbed6ff607859ffaa43d3006e457e40bb170885cde7ce350e496b20d70739e63",
184358
+ "editorbrain/references/personal-resources.md": "92ce6f32191929bd946c97305452521f6048d6bb8ea371e9083536eff5ce9512",
184359
+ "editorbrain/references/production-and-review.md": "28a64ee6407a1de7dc204776c158408c11b3987020ad1bdd1b79fd19745fbffa",
184360
+ "editorbrain/references/production-continuity.md": "b73a851bff421fa24e364d8848e312e54de1d3d971099a567295c80a5e18d8c6",
184361
+ "editorbrain/references/real-media.md": "cfad1aa15198dfe5ecc1f1b67c96d43a7d2084e7f5119de93d1b360203694938",
184362
+ "editorbrain/references/search-brief.md": "ea2a9c2d5a5cf685c1e5918366901ef2589c4d79aaa78a0dd31e97d6fed42b7b",
184363
+ "editorbrain/references/sfx-library.md": "d7ee0d2916559ce11a7fd244ccbcb98172413653c3fdbe0545e57b3eda543b16",
184364
+ "editorbrain-formats/SKILL.md": "65ea59aae091ca9618b5e479befe0c76edf174df7091ed74d4307485a2252fcd",
184365
+ "editorbrain-motion/SKILL.md": "57292f3a48cc8f1fc2d89f2cc054a3ceabeda9422958fa708f273c662867d5ae",
184366
+ "editorbrain/SKILL.md": "a9482dcd170739fe279bf2c69a154327c5d6a68926c1555b010a1753851bf0bd",
184367
+ "editorbrain/references/starting-an-edit.md": "0b83e006edc43307483489060bde999cb0644623eb9550f56b7add52f4082fff",
184368
+ "editorbrain/references/storage-and-previews.md": "9d06a6bb49f13e23f0af7d5ef35444dd553d1ce8af28662a9aba054b4d0081a5",
184369
+ "editorbrain/references/studio.md": "fc85ebfb42b2ce2c86b4d5ee6ad48e83d3d1e959a307d1e8dd52e0d92a4f6c45",
184370
+ "editorbrain/references/style-creator.md": "1b1bc289a5bc308cbbf7f4d699de2933b8934733a2b69b3e98fb1b7420d986f2",
184371
+ "editorbrain/references/style-source.md": "983fa21b4606c3cdc41b2fa4386ddc8f77a1b14ae782aad8774c000696c14de1",
184372
+ "editorbrain/references/workspace-files.md": "29bbddc894ed000bddd065bcb660629e64b29a5cf54dd6850e810b25c990558d"
184373
+ }
184374
+ },
184192
184375
  {
184193
184376
  "version": "0.26.0",
184194
184377
  "archiveSha256": "be469be196a319b4e29f84c9ff204e478818d1163a4fad8fd49270bcc73e83ba",
@@ -185013,6 +185196,7 @@ import { resolve as resolve4 } from "node:path";
185013
185196
  // packages/cli/src/client.ts
185014
185197
  import { setTimeout as delay } from "node:timers/promises";
185015
185198
  var searchErrors = {
185199
+ email_verification_required: { status: 403, code: "EMAIL_VERIFICATION_REQUIRED", hint: "Verifica tu correo en https://editorbrain.com/app/settings y vuelve a intentar. Cambiar de plan o comprar cr\xE9ditos no resuelve la verificaci\xF3n." },
185016
185200
  resource_policy_unavailable: { status: 503, code: "RESOURCE_POLICY_UNAVAILABLE", hint: "La pol\xEDtica de recursos no est\xE1 disponible. Contin\xFAa el trabajo independiente y consulta el estado del servicio; recargar cr\xE9ditos no lo resuelve." },
185017
185201
  resource_plan_required: { status: 403, code: "RESOURCE_PLAN_REQUIRED", hint: "Consulta https://editorbrain.com/app/billing o elige un recurso Gratis. Recargar cr\xE9ditos no desbloquea este recurso." },
185018
185202
  sfx_disabled: { status: 409, code: "SFX_DISABLED", hint: "Current project preferences disable added effects here. Continue without SFX, including motion-component defaults. Do not change preferences or suggest buying credits; honor only an explicit project exception." },
@@ -185060,6 +185244,17 @@ function searchDiagnostic(status, body) {
185060
185244
  if (typeof code !== "string" || !Object.hasOwn(searchErrors, code)) return void 0;
185061
185245
  return searchErrors[code].status === status ? { ...searchErrors[code], serviceCode: code } : void 0;
185062
185246
  }
185247
+ function safeDiagnosticDetails(body) {
185248
+ const e = body?.error;
185249
+ if (!e || typeof e !== "object") return {};
185250
+ const details = {};
185251
+ if (["free", "creator", "studio"].includes(String(e.requiredPlan))) details.requiredPlan = String(e.requiredPlan);
185252
+ if (e.billingUrl === "https://editorbrain.com/app/billing") details.billingUrl = e.billingUrl;
185253
+ for (const key of ["limit", "retryAfter"]) if (Number.isSafeInteger(e[key]) && Number(e[key]) >= 0 && Number(e[key]) <= 86400) details[key] = Number(e[key]);
185254
+ if (["workspace", "service"].includes(String(e.scope))) details.scope = String(e.scope);
185255
+ if (["service_paused", "tool_paused", "configuration_pending", "pricing_pending"].includes(String(e.availabilityCode))) details.availabilityCode = String(e.availabilityCode);
185256
+ return details;
185257
+ }
185063
185258
  var ApiError = class extends CliError {
185064
185259
  constructor(status, body, retryAfterMs, safeToRetry = false) {
185065
185260
  const codes = {
@@ -185071,7 +185266,7 @@ var ApiError = class extends CliError {
185071
185266
  const [code, hint] = codes[status] ?? [status >= 500 ? "SERVICE_UNAVAILABLE" : "API_ERROR", "Check the request and service status."];
185072
185267
  const diagnostic = searchDiagnostic(status, body);
185073
185268
  const recovery = diagnostic ? recoveryGuidance(diagnostic.serviceCode, status) : void 0;
185074
- super(diagnostic?.code ?? code, `API request failed (HTTP ${status}).`, recovery ? recoveryHint(recovery) : diagnostic?.hint ?? hint, !diagnostic && safeToRetry && (status === 429 || status >= 500), { status, ...recovery ? { recovery } : {}, ...diagnostic ? { serviceCode: diagnostic.serviceCode } : {}, ...retryAfterMs === void 0 ? {} : { retryAfterMs } });
185269
+ super(diagnostic?.code ?? code, `API request failed (HTTP ${status}).`, recovery ? recoveryHint(recovery) : diagnostic?.hint ?? hint, !diagnostic && safeToRetry && (status === 429 || status >= 500), { status, ...recovery ? { recovery } : {}, ...diagnostic ? { serviceCode: diagnostic.serviceCode, ...safeDiagnosticDetails(body) } : {}, ...retryAfterMs === void 0 ? {} : { retryAfterMs } });
185075
185270
  this.status = status;
185076
185271
  this.body = body;
185077
185272
  }
@@ -185149,10 +185344,11 @@ var Client = class {
185149
185344
  const retryAfterMs = retryDelay(response.headers.get("Retry-After"), this.runtime.now());
185150
185345
  if (!response.ok) {
185151
185346
  let errorBody;
185152
- if (/^\/v1\/authored-motion(?:\/|\?|$)/.test(path) || /^\/v1\/sfx\//.test(path) || /^\/v1\/team(?:\/|$)/.test(path) || path.startsWith("/v1/studio/") || path.startsWith("/v1/batches") && response.status === 409 || path === "/v1/search/brief" && [400, 422, 503].includes(response.status) || /^\/v1\/projects\/[^/]+\/progress$/.test(path) && response.status === 409) {
185347
+ if ((/^\/v1\/(?:authored-motion|style-sources|sfx|team|studio|batches)(?:\/|\?|$)/.test(path) || path === "/v1/search/brief" || /^\/v1\/projects\/[^/]+\/progress$/.test(path)) && [400, 402, 403, 404, 409, 422, 429, 503].includes(response.status)) {
185153
185348
  try {
185154
- const diagnostic = searchDiagnostic(response.status, await boundedJson(response, 16 * 1024));
185155
- errorBody = diagnostic ? { error: { code: diagnostic.serviceCode } } : void 0;
185349
+ const parsed = await boundedJson(response, 16 * 1024);
185350
+ const diagnostic = searchDiagnostic(response.status, parsed);
185351
+ errorBody = diagnostic ? { error: { code: diagnostic.serviceCode, ...safeDiagnosticDetails(parsed) } } : void 0;
185156
185352
  } catch {
185157
185353
  }
185158
185354
  } else await response.body?.cancel();
@@ -185185,12 +185381,12 @@ var Client = class {
185185
185381
  return this.request(`/v1/documents/${safeDocumentPath(path).split("/").map(encodeURIComponent).join("/")}`, { method: "PUT", body: { content, expectedRevision } });
185186
185382
  }
185187
185383
  async uploadPreview(path, content, mimeType) {
185188
- const hash6 = path.match(/^\/v1\/assets\/([a-f0-9]{64})(?:\?|$)/)?.[1];
185189
- if (!hash6 || new URL(path, this.url).searchParams.get("purpose") !== "preview") throw new Error("Use an exact preview asset endpoint.");
185384
+ const hash7 = path.match(/^\/v1\/assets\/([a-f0-9]{64})(?:\?|$)/)?.[1];
185385
+ if (!hash7 || new URL(path, this.url).searchParams.get("purpose") !== "preview") throw new Error("Use an exact preview asset endpoint.");
185190
185386
  const sourceHash = new URL(path, this.url).searchParams.get("sourceSha256");
185191
- if (sourceHash !== null && (!/^[a-f0-9]{64}$/.test(sourceHash) || sourceHash === hash6)) throw new Error("Use a distinct original SHA-256, or omit it.");
185387
+ if (sourceHash !== null && (!/^[a-f0-9]{64}$/.test(sourceHash) || sourceHash === hash7)) throw new Error("Use a distinct original SHA-256, or omit it.");
185192
185388
  let plan;
185193
- const params = new URLSearchParams({ sha256: hash6, bytes: String(content.byteLength) });
185389
+ const params = new URLSearchParams({ sha256: hash7, bytes: String(content.byteLength) });
185194
185390
  const projectId = new URL(path, "https://local.invalid").searchParams.get("projectId");
185195
185391
  if (projectId) params.set("projectId", projectId);
185196
185392
  try {
@@ -185202,7 +185398,7 @@ var Client = class {
185202
185398
  if (typeof plan.allowed !== "boolean" || !Number.isSafeInteger(plan.additionalBytes)) throw new Error("Invalid preview preflight response.");
185203
185399
  if (plan.existingAsset) {
185204
185400
  const asset = plan.existingAsset;
185205
- if (!plan.allowed || plan.additionalBytes !== 0 || asset.id !== hash6 || asset.sha256 !== hash6 || asset.bytes !== content.byteLength || asset.mimeType !== mimeType || typeof asset.name !== "string") throw new Error("Existing preview metadata does not match this file.");
185401
+ if (!plan.allowed || plan.additionalBytes !== 0 || asset.id !== hash7 || asset.sha256 !== hash7 || asset.bytes !== content.byteLength || asset.mimeType !== mimeType || typeof asset.name !== "string") throw new Error("Existing preview metadata does not match this file.");
185206
185402
  return new Response(JSON.stringify({ ...asset, reused: true }), { headers: { "Content-Type": "application/json" } });
185207
185403
  }
185208
185404
  if (!plan.allowed) throw new CliError("PREVIEW_STORAGE_FULL", "There is not enough cloud storage for this review copy. Your local edit is intact.", "Continue on the computer, prepare a smaller legible preview, or review eligible files at https://editorbrain.com/app/files. Do not delete protected media or upgrade a plan automatically.");
@@ -185230,7 +185426,11 @@ async function loadSyncState(root, endpoint2, workspaceId) {
185230
185426
  const state = JSON.parse(raw);
185231
185427
  if (state.projectId !== void 0) assertIdentifier(state.projectId);
185232
185428
  if (state.schemaVersion !== 1 || typeof state.documents !== "object") throw new Error("Invalid local sync state");
185233
- if (state.endpoint !== endpoint2 || state.workspaceId !== workspaceId) throw new CliError("WORKSPACE_MISMATCH", "This folder is bound to a different endpoint/workspace.", "Use a separate folder; never merge private documents across spaces.");
185429
+ if (state.endpoint !== endpoint2 || state.workspaceId !== workspaceId) {
185430
+ assertIdentifier(state.workspaceId);
185431
+ normalizeUrl(state.endpoint);
185432
+ throw new CliError("WORKSPACE_MISMATCH", `This folder is bound to a different endpoint/workspace. Bound workspace: ${state.workspaceId}; active workspace: ${workspaceId}.`, "Run editorbrain status to inspect the active connection. Run editorbrain login and authorize the workspace shown as boundWorkspaceId, then retry in this folder. For the current workspace, use a separate folder. Do not delete or edit .sync.json to bypass isolation.", false, { boundWorkspaceId: state.workspaceId, currentWorkspaceId: workspaceId, boundEndpoint: state.endpoint });
185433
+ }
185234
185434
  for (const [path, item] of Object.entries(state.documents)) {
185235
185435
  safeDocumentPath(path);
185236
185436
  if (!Number.isInteger(item.revision) || item.revision < 1 || !/^[a-f0-9]{64}$/.test(item.sha256)) throw new Error("Invalid local revision");
@@ -185476,13 +185676,13 @@ var probe = async (tool) => {
185476
185676
  var remoteOptions = { timeoutMs: 3e3, maxAttempts: 1 };
185477
185677
  var links = { credits: "https://editorbrain.com/app/billing", integrations: "https://editorbrain.com/app/integrations" };
185478
185678
  function studioSummary(value) {
185479
- const invalid6 = () => new CliError("INVALID_RESPONSE", "Respuesta de herramientas IA incompleta.", "Consulta editorbrain studio catalog; no inicies una generaci\xF3n con estado desconocido.");
185480
- if (!value || typeof value !== "object") throw invalid6();
185679
+ const invalid7 = () => new CliError("INVALID_RESPONSE", "Respuesta de herramientas IA incompleta.", "Consulta editorbrain studio catalog; no inicies una generaci\xF3n con estado desconocido.");
185680
+ if (!value || typeof value !== "object") throw invalid7();
185481
185681
  const data = value;
185482
- if (typeof data.balance !== "number" || !Number.isFinite(data.balance) || data.balance < 0 || typeof data.checkoutAvailable !== "boolean" || !Array.isArray(data.tools) || data.tools.length > 20) throw invalid6();
185682
+ if (typeof data.balance !== "number" || !Number.isFinite(data.balance) || data.balance < 0 || typeof data.checkoutAvailable !== "boolean" || !Array.isArray(data.tools) || data.tools.length > 20) throw invalid7();
185483
185683
  const names = { scribe: "tempo", tempo: "tempo", prism: "prism", vox: "vox", music: "aura", aura: "aura" };
185484
185684
  const tools = data.tools.map((item) => {
185485
- if (!item || typeof item !== "object" || typeof item.id !== "string" || !Object.hasOwn(names, item.id) || typeof item.available !== "boolean" || typeof item.canSpend !== "boolean") throw invalid6();
185685
+ if (!item || typeof item !== "object" || typeof item.id !== "string" || !Object.hasOwn(names, item.id) || typeof item.available !== "boolean" || typeof item.canSpend !== "boolean") throw invalid7();
185486
185686
  const reasons = [!item.available ? "unavailable" : null, !item.canSpend ? "permission_required" : null, data.balance === 0 ? "no_credits" : null].filter((reason) => reason !== null);
185487
185687
  return {
185488
185688
  id: names[item.id],
@@ -185492,7 +185692,7 @@ function studioSummary(value) {
185492
185692
  reasons
185493
185693
  };
185494
185694
  });
185495
- if (tools.length !== 4 || new Set(tools.map((tool) => tool.id)).size !== 4) throw invalid6();
185695
+ if (tools.length !== 4 || new Set(tools.map((tool) => tool.id)).size !== 4) throw invalid7();
185496
185696
  return {
185497
185697
  balance: data.balance,
185498
185698
  checkoutAvailable: data.checkoutAvailable,
@@ -186286,8 +186486,8 @@ async function prepareProductionContext(root, projectId, client) {
186286
186486
  const remote = async () => {
186287
186487
  const result2 = await client.request("/v1/workflow/check", { method: "POST", body: { projectId } });
186288
186488
  const snapshot = result2.editorialSnapshot;
186289
- if (!snapshot || snapshot.projectId !== projectId || typeof snapshot.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.contextVersion) || !snapshot.sourceHashes || typeof snapshot.sourceHashes !== "object" || Array.isArray(snapshot.sourceHashes) || Object.values(snapshot.sourceHashes).some((hash6) => typeof hash6 !== "string" || !/^[a-f0-9]{64}$/.test(hash6))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service did not return a versioned editorial context.", "Update the service before connected verification, or explicitly use --offline to check local documents only.");
186290
- if (snapshot.effectiveSourceHashes !== void 0 && (!snapshot.effectiveSourceHashes || typeof snapshot.effectiveSourceHashes !== "object" || Array.isArray(snapshot.effectiveSourceHashes) || Object.values(snapshot.effectiveSourceHashes).some((hash6) => typeof hash6 !== "string" || !/^[a-f0-9]{64}$/.test(hash6)))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service returned invalid effective context hashes.", "Retry after updating the service.");
186489
+ if (!snapshot || snapshot.projectId !== projectId || typeof snapshot.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.contextVersion) || !snapshot.sourceHashes || typeof snapshot.sourceHashes !== "object" || Array.isArray(snapshot.sourceHashes) || Object.values(snapshot.sourceHashes).some((hash7) => typeof hash7 !== "string" || !/^[a-f0-9]{64}$/.test(hash7))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service did not return a versioned editorial context.", "Update the service before connected verification, or explicitly use --offline to check local documents only.");
186490
+ if (snapshot.effectiveSourceHashes !== void 0 && (!snapshot.effectiveSourceHashes || typeof snapshot.effectiveSourceHashes !== "object" || Array.isArray(snapshot.effectiveSourceHashes) || Object.values(snapshot.effectiveSourceHashes).some((hash7) => typeof hash7 !== "string" || !/^[a-f0-9]{64}$/.test(hash7)))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service returned invalid effective context hashes.", "Retry after updating the service.");
186291
186491
  const portableHashes = Object.fromEntries(Object.entries(snapshot.effectiveSourceHashes ?? snapshot.sourceHashes).filter(([path]) => path !== "personal-resources:live"));
186292
186492
  if (stableJson(portableHashes) !== (snapshot.effectiveSourceHashes ? sourceKey : stableJson(resolved.lock.sourceHashes))) throw new CliError("PRODUCTION_CONTEXT_CONFLICT", "Local and web project preferences or material differ.", "Use status and pull --project to inspect/reconcile changes. Do not overwrite either side automatically.");
186293
186493
  return snapshot.contextVersion;
@@ -186435,9 +186635,9 @@ async function prepareStudioAudio(root, file, out, streamIndex) {
186435
186635
  const verified = await probeLocalMedia(prepared);
186436
186636
  if (verified.durationSeconds === null || verified.durationSeconds > 1800 || verified.bytes > 90 * 1024 * 1024) throw new CliError("AUDIO_DURATION_LIMIT", "The decoded audio exceeds the supported duration.", "Inspect source timestamps; no file was uploaded.");
186437
186637
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new CliError("SOURCE_CHANGED", "The source changed during extraction.", "Retry only after the source is stable.");
186438
- const bytes = await readFile6(prepared), hash6 = createHash6("sha256").update(bytes).digest("hex");
186638
+ const bytes = await readFile6(prepared), hash7 = createHash6("sha256").update(bytes).digest("hex");
186439
186639
  await link4(prepared, target);
186440
- return { kind: "editorbrain.scribe-input", name: "Tempo", path: target, sha256: hash6, bytes: bytes.length, durationMs: Math.round(verified.durationSeconds * 1e3), mimeType: "audio/wav", sourceSha256: source2.sha256, sourcePath: source2.path, audioStream: selected.index, sourceStartTimeSeconds: source2.startTimeSeconds, timestampBasis: "milliseconds_from_container_start", silenceRemoved: false, uploaded: false, next: "Upload this WAV using assets upload, then quote Tempo with its assetId. Keep this source mapping locally; returned word times refer to this prepared audio." };
186640
+ return { kind: "editorbrain.scribe-input", name: "Tempo", path: target, sha256: hash7, bytes: bytes.length, durationMs: Math.round(verified.durationSeconds * 1e3), mimeType: "audio/wav", sourceSha256: source2.sha256, sourcePath: source2.path, audioStream: selected.index, sourceStartTimeSeconds: source2.startTimeSeconds, timestampBasis: "milliseconds_from_container_start", silenceRemoved: false, uploaded: false, next: "Upload this WAV using assets upload, then quote Tempo with its assetId. Keep this source mapping locally; returned word times refer to this prepared audio." };
186441
186641
  } finally {
186442
186642
  await rm3(temp, { recursive: true, force: true });
186443
186643
  }
@@ -187017,7 +187217,11 @@ var artifactScript = String.raw`
187017
187217
  field(fontFields, 'Fuente de títulos', tokenValue('typography.heading'), v => setToken('typography.heading', v), { placeholder: 'Ej. Manrope', maxLength: 100 });
187018
187218
  field(fontFields, 'Fuente de texto', tokenValue('typography.body'), v => setToken('typography.body', v), { placeholder: 'Ej. Inter', maxLength: 100 });
187019
187219
  strengthControl(fontFields, 'Aplicar estas fuentes', ['typography.heading', 'typography.body']);
187020
- type.append(details('Escribir mis fuentes', fontFields));
187220
+ const customFonts = !!(tokenValue('typography.heading') || tokenValue('typography.body')) && !fonts.some(([, heading, body]) => tokenValue('typography.heading') === heading && tokenValue('typography.body') === body);
187221
+ const fontDetails = details('Escribir mis fuentes', fontFields, customFonts ? 'Tus fuentes seleccionadas' : undefined);
187222
+ fontDetails.open = customFonts;
187223
+ fontDetails.dataset.selected = String(customFonts);
187224
+ type.append(fontDetails);
187021
187225
  panel.append(type);
187022
187226
  const freedom = section('¿Cuánto puede explorar tu agente?', 'Los tokens obligatorios de marca se respetan en ambos casos.', decide(!p().freedom, () => updateProfile('freedom', '')));
187023
187227
  choices(freedom, [[options.freedom[0], 'Una identidad reconocible', 'Mantener criterios visuales; adaptar cada escena.'], [options.freedom[1], 'Explorar composiciones nuevas', 'Variar recursos y animaciones según el video.']], p().freedom, v => updateProfile('freedom', v), { columns: 2 });
@@ -187676,31 +187880,31 @@ function invalidResponse(write) {
187676
187880
  );
187677
187881
  }
187678
187882
  function brainState(value, brand, write = false) {
187679
- const invalid6 = () => {
187883
+ const invalid7 = () => {
187680
187884
  throw invalidResponse(write);
187681
187885
  };
187682
- if (!object8(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text8(value.notice, 2e3) || value.contextVersion !== void 0 && !hash4(value.contextVersion) || value.contextChanged !== void 0 && typeof value.contextChanged !== "boolean") return invalid6();
187886
+ if (!object8(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text8(value.notice, 2e3) || value.contextVersion !== void 0 && !hash4(value.contextVersion) || value.contextChanged !== void 0 && typeof value.contextChanged !== "boolean") return invalid7();
187683
187887
  let run = null;
187684
187888
  if (value.run !== null) {
187685
187889
  const row = value.run;
187686
- if (!object8(row) || !hash4(row.id) || !["queued", "running", "ready", "accepted", "failed"].includes(String(row.status)) || !integer(row.sourceDesignRevision, 1) || !(row.acceptedDesignRevision === null || integer(row.acceptedDesignRevision, 1)) || !(row.errorCode === null || typeof row.errorCode === "string" && /^[a-z][a-z0-9_]{0,119}$/.test(row.errorCode)) || !date(row.createdAt) || !date(row.updatedAt)) return invalid6();
187687
- if (row.status === "accepted" ? row.acceptedDesignRevision !== row.sourceDesignRevision + 1 : row.acceptedDesignRevision !== null) return invalid6();
187890
+ if (!object8(row) || !hash4(row.id) || !["queued", "running", "ready", "accepted", "failed"].includes(String(row.status)) || !integer(row.sourceDesignRevision, 1) || !(row.acceptedDesignRevision === null || integer(row.acceptedDesignRevision, 1)) || !(row.errorCode === null || typeof row.errorCode === "string" && /^[a-z][a-z0-9_]{0,119}$/.test(row.errorCode)) || !date(row.createdAt) || !date(row.updatedAt)) return invalid7();
187891
+ if (row.status === "accepted" ? row.acceptedDesignRevision !== row.sourceDesignRevision + 1 : row.acceptedDesignRevision !== null) return invalid7();
187688
187892
  let proposal = null;
187689
187893
  if (row.proposal !== null) {
187690
187894
  const proposed = row.proposal;
187691
- if (!object8(proposed) || !text8(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return invalid6();
187895
+ if (!object8(proposed) || !text8(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return invalid7();
187692
187896
  const recommendations = [];
187693
187897
  for (const item of proposed.recommendations) {
187694
- if (!object8(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text8(item.text, 500) || !text8(item.reason, 500) || !Array.isArray(item.sourceFields) || item.sourceFields.length < 1 || item.sourceFields.length > 5 || new Set(item.sourceFields).size !== item.sourceFields.length || item.sourceFields.some((field) => !text8(field, 400))) return invalid6();
187898
+ if (!object8(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text8(item.text, 500) || !text8(item.reason, 500) || !Array.isArray(item.sourceFields) || item.sourceFields.length < 1 || item.sourceFields.length > 5 || new Set(item.sourceFields).size !== item.sourceFields.length || item.sourceFields.some((field) => !text8(field, 400))) return invalid7();
187695
187899
  recommendations.push({ area: item.area, text: item.text, reason: item.reason, sourceFields: [...item.sourceFields] });
187696
187900
  }
187697
187901
  proposal = { summary: proposed.summary, recommendations };
187698
187902
  }
187699
- if ((row.status === "ready" || row.status === "accepted") && !proposal) return invalid6();
187903
+ if ((row.status === "ready" || row.status === "accepted") && !proposal) return invalid7();
187700
187904
  let usage = null;
187701
187905
  if (row.usage !== null) {
187702
187906
  const measured = row.usage;
187703
- if (!object8(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return invalid6();
187907
+ if (!object8(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return invalid7();
187704
187908
  usage = { inputTokens: measured.inputTokens, outputTokens: measured.outputTokens, totalTokens: measured.totalTokens, durationMs: measured.durationMs };
187705
187909
  }
187706
187910
  run = { id: row.id, status: row.status, proposal, usage, errorCode: row.errorCode, sourceDesignRevision: row.sourceDesignRevision, acceptedDesignRevision: row.acceptedDesignRevision, createdAt: row.createdAt, updatedAt: row.updatedAt };
@@ -187919,10 +188123,10 @@ async function loginWithDevice(options, overrides = {}) {
187919
188123
  }
187920
188124
 
187921
188125
  // packages/cli/src/index.ts
187922
- import { chmod as chmod2, lstat as lstat12, mkdir as mkdir14, open as open12 } from "node:fs/promises";
188126
+ import { chmod as chmod2, lstat as lstat13, mkdir as mkdir14, open as open12 } from "node:fs/promises";
187923
188127
  import { constants as constants11 } from "node:fs";
187924
188128
  import { homedir as homedir3 } from "node:os";
187925
- import { basename as basename4, dirname as dirname18, extname as extname7, join as join15, resolve as resolve12 } from "node:path";
188129
+ import { basename as basename6, dirname as dirname18, extname as extname7, join as join15, resolve as resolve12 } from "node:path";
187926
188130
 
187927
188131
  // packages/cli/src/direction-context.ts
187928
188132
  async function prepareDirectionContext(root, client, projectId) {
@@ -188092,14 +188296,14 @@ async function checkLocalResource(root, path, expected) {
188092
188296
  const before = await handle.stat();
188093
188297
  if (!before.isFile()) throw new Error("Resource is not a regular file.");
188094
188298
  if (!expected) return {};
188095
- const hash6 = createHash8("sha256");
188096
- for await (const chunk of handle.createReadStream({ autoClose: false })) hash6.update(chunk);
188299
+ const hash7 = createHash8("sha256");
188300
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash7.update(chunk);
188097
188301
  const after = await handle.stat();
188098
188302
  const current2 = await lstat9(await checkedPath(root, path, false));
188099
188303
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current2.dev !== before.dev || current2.ino !== before.ino) {
188100
188304
  throw new Error("Resource changed while its hash was being checked; check it again.");
188101
188305
  }
188102
- return { actualSha256: hash6.digest("hex") };
188306
+ return { actualSha256: hash7.digest("hex") };
188103
188307
  } finally {
188104
188308
  await handle.close();
188105
188309
  }
@@ -191340,10 +191544,33 @@ async function verifyProduction(options) {
191340
191544
  }
191341
191545
 
191342
191546
  // packages/cli/src/review-artifact.ts
191343
- import { open as open11, mkdir as mkdir13 } from "node:fs/promises";
191547
+ import { lstat as lstat12, mkdir as mkdir13 } from "node:fs/promises";
191548
+ import { basename as basename4, dirname as dirname17, extname as extname6, resolve as resolve11 } from "node:path";
191549
+ import { createHash as createHash13, randomUUID as randomUUID7 } from "node:crypto";
191550
+
191551
+ // packages/cli/src/review-files.ts
191344
191552
  import { constants as constants10 } from "node:fs";
191345
- import { dirname as dirname17, extname as extname6, resolve as resolve11 } from "node:path";
191346
- import { createHash as createHash13 } from "node:crypto";
191553
+ import { open as open11 } from "node:fs/promises";
191554
+ var REVIEW_MEDIA_BYTES = 24 * 1024 * 1024;
191555
+ async function readReviewFile(path, maxBytes) {
191556
+ const handle = await open11(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
191557
+ try {
191558
+ const before = await handle.stat();
191559
+ if (!before.isFile() || before.size <= 0 || before.size > maxBytes) throw new CliError("INVALID_REVIEW_FILE", "Review file is empty, not regular or exceeds the preview size limit.", "Use a lightweight review copy under 24 MiB per medium. Keep the master unchanged.");
191560
+ const bytes = Buffer.alloc(before.size + 1);
191561
+ let length = 0;
191562
+ while (length < bytes.length) {
191563
+ const part = await handle.read(bytes, length, bytes.length - length, length);
191564
+ if (!part.bytesRead) break;
191565
+ length += part.bytesRead;
191566
+ }
191567
+ const after = await handle.stat();
191568
+ if (length !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw new CliError("REVIEW_FILE_CHANGED", "Review file changed while reading.", "Finish rendering and regenerate a new review version.");
191569
+ return bytes.subarray(0, length);
191570
+ } finally {
191571
+ await handle.close();
191572
+ }
191573
+ }
191347
191574
 
191348
191575
  // packages/cli/src/review-artifact-html.ts
191349
191576
  import { createHash as createHash12 } from "node:crypto";
@@ -191638,7 +191865,7 @@ ${JSON.stringify({ ...feedback(), kind: "editorbrain.review-access-request", dec
191638
191865
  player.onerror = () => {
191639
191866
  mediaReady = false;
191640
191867
  $("mark").disabled = true;
191641
- status("Este visor no pudo reproducir el video. Abre el HTML descargado en tu navegador. No apruebes una muestra que no pudiste revisar.");
191868
+ status(data.video.uri.startsWith("data:") ? "Este visor no pudo reproducir el video. Pide a tu agente abrir una revisi\xF3n local ligera. No apruebes una muestra que no pudiste revisar." : "No se pudo cargar el video. Pide a tu agente mantener abierto el servidor de revisi\xF3n y comprobar el preview en tu navegador. No apruebes una muestra que no pudiste revisar.");
191642
191869
  update();
191643
191870
  };
191644
191871
  player.ontimeupdate = () => {
@@ -191683,9 +191910,9 @@ ${JSON.stringify({ ...feedback(), kind: "editorbrain.review-access-request", dec
191683
191910
  update();
191684
191911
  }
191685
191912
  function renderReviewArtifact(data, wordmark) {
191686
- const script = `(${reviewApp.toString()})();`, hash6 = createHash12("sha256").update(script).digest("base64");
191913
+ const script = `(${reviewApp.toString()})();`, hash7 = createHash12("sha256").update(script).digest("base64");
191687
191914
  const json = JSON.stringify(data).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
191688
- return `<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${hash6}'; style-src 'unsafe-inline'; img-src data:; media-src data: blob:; connect-src 'none'; font-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"><title>EditorBrain \xB7 Tu edici\xF3n</title><style>
191915
+ return `<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${hash7}'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data: blob:; connect-src 'none'; font-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"><title>EditorBrain \xB7 Tu edici\xF3n</title><style>
191689
191916
  *{box-sizing:border-box} [hidden]{display:none!important} :root{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;color:#f6f6f6;background:#090909}body{margin:0;background:radial-gradient(ellipse at 15% 0%,#252525 0,transparent 50%),#090909}main{max-width:1220px;margin:auto;padding:28px clamp(18px,4vw,50px) 44px}header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #ffffff20;padding-bottom:22px;gap:20px}header svg{width:146px;height:auto;display:block}header span{color:#aaa;font-size:12px}h1{font-size:clamp(28px,4vw,48px);font-weight:550;letter-spacing:-.045em;margin:14px 0}h2{font-size:20px;letter-spacing:-.025em;margin:0 0 12px}.eyebrow{font-size:10px;letter-spacing:.18em;color:#aaa;margin:30px 0 0}.intro{color:#aaa;font-size:15px;line-height:1.6;margin-bottom:24px}button,a{touch-action:manipulation}button{border:1px solid #ffffff30;border-radius:12px;background:#ffffff08;color:#fff;padding:11px 15px;font:inherit;font-size:13px;cursor:pointer}button:hover{background:#ffffff16}button:disabled{opacity:.38;cursor:default}.primary{background:#f5f5f5;color:#111;font-weight:650;border-color:#fff}.primary:hover{background:#ddd}.secondary{background:transparent}button:focus-visible,textarea:focus-visible,summary:focus-visible,a:focus-visible{outline:2px solid #fff;outline-offset:4px}p{line-height:1.6}.workspace{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(280px,1fr);gap:30px;align-items:start}.preview{position:sticky;top:20px;min-width:0}.screen{border:1px solid #ffffff22;border-radius:20px;overflow:hidden;background:radial-gradient(ellipse,#242424,#050505);display:flex;justify-content:center;min-height:260px}.screen video{width:100%;max-height:590px;display:block}.controls{display:flex;justify-content:center;align-items:center;gap:16px;margin:12px 0;font-size:12px;color:#aaa;font-variant-numeric:tabular-nums}.controls button{padding:8px 12px}aside{background:linear-gradient(140deg,#ffffff07,#ffffff02);border:1px solid #ffffff19;border-radius:20px;padding:24px}aside>p{color:#aaa;font-size:13px}label{display:block;font-size:12px;color:#bbb}select{max-width:100%;padding:10px;background:#181818;color:#fff;border:1px solid #ffffff40;border-radius:8px}#learning-options article{padding:16px 0;border-top:1px solid #ffffff20}textarea{width:100%;background:#090909;border:1px solid #ffffff30;border-radius:12px;padding:14px;color:#fff;font:inherit;font-size:14px;line-height:1.5;min-height:108px;resize:vertical;margin:12px 0}textarea::placeholder{color:#818181}.target{display:flex;align-items:center;gap:10px;margin:16px 0 0;font-size:12px;color:#bbb;flex-wrap:wrap}.target button{padding:6px 10px}.save{width:100%;margin-bottom:16px}.muted{color:#aaa;font-size:12px}details{border-top:1px solid #ffffff20;padding-top:16px;margin-top:16px}summary{cursor:pointer;font-size:13px;line-height:1.6}#phrases{max-height:300px;overflow-y:auto;margin:12px 0}#phrases article{padding:12px;margin-bottom:8px;border-radius:10px;background:#ffffff04;border-left:2px solid transparent}#phrases .speaking{background:#ffffff12;border-left-color:#fff}#phrases article>button:first-child{border:0;background:none;text-align:left;padding:0;line-height:1.7;width:100%;margin-bottom:8px}#phrases article>button:last-child{font-size:11px;padding:6px 8px}#phrases .removed{opacity:.7}#show-cuts-label{margin:12px 0}#approve{width:100%;margin-top:18px}#pending{padding:12px 16px;border-left:2px solid #eee;background:#ffffff08;font-size:13px;margin-bottom:20px}#notes{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:12px}#notes article{border:1px solid #ffffff22;border-radius:12px;padding:15px;font-size:13px;overflow-wrap:anywhere}#notes p{margin-bottom:0}.note-head{display:flex;align-items:center;justify-content:space-between;gap:10px}.note-head button{font-size:11px;padding:5px 8px}#markers{display:flex;gap:8px;flex-wrap:wrap}#markers button{font-size:11px;padding:7px 10px}.handoff{margin-top:24px;padding:22px;border:1px solid #ffffff30;border-radius:18px;background:#ffffff05}.handoff-head{display:flex;align-items:center;justify-content:space-between;gap:20px}.handoff p{color:#aaa;font-size:13px;margin:6px 0}.handoff .actions{display:flex;gap:8px;flex-shrink:0;flex-wrap:wrap}#status{color:#fff;margin:14px 0;font-size:13px}#request{font-family:ui-monospace,monospace;font-size:12px;min-height:200px}footer{margin-top:22px;display:flex;justify-content:space-between;gap:16px;color:#888;font-size:11px}#direction-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,250px),1fr));gap:18px}.direction{padding:16px;border:1px solid #ffffff22;border-radius:18px;background:#ffffff05}.direction.chosen{border-color:#fff;box-shadow:0 0 0 1px #fff}.direction img,.direction video{width:100%;height:220px;object-fit:contain;border-radius:10px;background:#030303;margin-bottom:18px}.direction p{color:#bbb;font-size:14px}.direction button{width:100%}.direction details a{display:block;color:#fff;font-size:12px;margin:8px 0}.no-preview{height:160px;display:grid;place-items:center;background:#222;color:#aaa;margin-bottom:16px;border-radius:10px}#future{background:none;border:0;color:#aaa;padding:0;font-size:12px;text-align:left}#future-details{color:#aaa;font-size:13px}#future-details summary{color:#eee}.future-note{max-width:660px}#undo{margin-top:12px}input[type=checkbox]{accent-color:#fff}#intro{max-width:680px}
191690
191917
  @media(max-width:760px){main{padding-top:20px}.workspace{grid-template-columns:1fr;gap:18px}.preview{position:static}.screen video{max-height:52svh}.screen{min-height:180px}aside{padding:20px}.handoff-head{display:block}.actions{margin-top:14px}.actions button{flex:1}.handoff{padding:18px}h1{font-size:32px}#direction-grid{grid-template-columns:1fr}header svg{width:125px}footer{flex-direction:column}#phrases{max-height:260px}}
191691
191918
  @media(prefers-reduced-motion:no-preference){button,.direction{transition:background .15s,border-color .15s}}
@@ -191774,72 +192001,199 @@ function parseReviewArtifact(value) {
191774
192001
  if (result2.stage !== "directions" && (!result2.video || result2.directions)) invalid4("Review/delivery needs one video; keep direction choices in the earlier artifact.");
191775
192002
  return result2;
191776
192003
  }
191777
- async function embed2(root, input, kind) {
192004
+ async function prepareMedia(root, input, kind, mediaDir, entries) {
191778
192005
  const path = resolve11(root, input.file), extension = extname6(path).toLowerCase();
191779
192006
  const mime = { ".mp4": "video/mp4", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
191780
192007
  if (!mime[extension] || kind === "video" && !mime[extension].startsWith("video/")) invalid4("Use MP4/WebM video or PNG/JPEG/WebP proposal previews.");
191781
- const handle = await open11(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
191782
- try {
191783
- const stat = await handle.stat();
191784
- if (!stat.isFile() || stat.size > 24 * 1024 * 1024 || !stat.size) invalid4("Each review preview must be a regular local file under 24 MiB. Make a lightweight review copy; keep your master.");
191785
- const bytes = await handle.readFile();
191786
- if (bytes.length > 24 * 1024 * 1024) invalid4("Preview grew while reading; retry with a stable file.");
191787
- const after = await handle.stat();
191788
- if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) invalid4("Preview changed while reading.");
191789
- const sha2562 = createHash13("sha256").update(bytes).digest("hex");
191790
- if (input.sha256 && input.sha256 !== sha2562) invalid4("Preview hash does not match this version.");
191791
- return { uri: `data:${mime[extension]};base64,${bytes.toString("base64")}`, sha256: sha2562, mimeType: mime[extension] };
191792
- } finally {
191793
- await handle.close();
192008
+ const bytes = await readReviewFile(path, REVIEW_MEDIA_BYTES);
192009
+ const sha2562 = createHash13("sha256").update(bytes).digest("hex");
192010
+ if (input.sha256 && input.sha256 !== sha2562) invalid4("Preview hash does not match this version.");
192011
+ if (!mediaDir) return { uri: `data:${mime[extension]};base64,${bytes.toString("base64")}`, sha256: sha2562, mimeType: mime[extension] };
192012
+ const name = `${sha2562}${extension}`, file = `${mediaDir}/${name}`;
192013
+ const uri = `${encodeURIComponent(basename4(mediaDir))}/${name}`;
192014
+ if (!entries.some((entry) => entry.uri === uri)) {
192015
+ await atomicWrite(root, file, bytes, { document: false, overwrite: false, mode: 384 });
192016
+ entries.push({ uri, file, sha256: sha2562, bytes: bytes.length, mimeType: mime[extension] });
191794
192017
  }
192018
+ return { uri, sha256: sha2562, mimeType: mime[extension] };
191795
192019
  }
191796
- async function createReviewArtifact(root, value, out) {
192020
+ async function createReviewArtifact(root, value, out, mediaMode = "local") {
192021
+ if (!["local", "embedded"].includes(mediaMode)) invalid4("Use --media-mode local or embedded.");
191797
192022
  const input = parseReviewArtifact(value);
191798
192023
  if (!out.endsWith(".html")) invalid4("Output must be a new .html file.");
191799
192024
  const target = await productionOutputPath(root, out);
191800
- const video = input.video ? await embed2(root, input.video, "video") : void 0;
191801
- const directions = input.directions ? await Promise.all(input.directions.map(async ({ preview, ...d }) => ({ ...d, ...preview ? { preview: await embed2(root, preview, "preview") } : {} }))) : void 0;
192025
+ for (const path of [target, `${target}.review.json`]) {
192026
+ try {
192027
+ await lstat12(path);
192028
+ } catch (error) {
192029
+ if (error.code === "ENOENT") continue;
192030
+ throw error;
192031
+ }
192032
+ invalid4("Review output already exists. Use a new filename; previous decisions are preserved.");
192033
+ }
192034
+ const entries = [];
192035
+ const mediaDir = mediaMode === "local" ? `${out}.media-${randomUUID7()}` : void 0;
192036
+ const video = input.video ? await prepareMedia(root, input.video, "video", mediaDir, entries) : void 0;
192037
+ const directions = input.directions ? [] : void 0;
192038
+ for (const { preview, ...direction } of input.directions ?? []) {
192039
+ directions.push({ ...direction, ...preview ? { preview: await prepareMedia(root, preview, "preview", mediaDir, entries) } : {} });
192040
+ }
191802
192041
  const clean = { schemaVersion: 1, projectId: input.projectId, title: input.title, version: input.version, stage: input.stage, ...input.contextVersion ? { contextVersion: input.contextVersion } : {}, ...video ? { video } : {}, ...directions ? { directions } : {}, ...input.transcript ? { transcript: input.transcript } : {}, ...input.learnings ? { learnings: input.learnings } : {}, ...input.learningContext ? { learningContext: input.learningContext } : {} };
191803
192042
  if (JSON.stringify(clean).length > 40 * 1024 * 1024) invalid4("Embedded previews exceed 40 MiB. Use smaller review copies.");
191804
192043
  const artifactId = createHash13("sha256").update(JSON.stringify(clean)).digest("hex");
191805
192044
  const html = renderReviewArtifact({ ...clean, artifactId }, onboardingWordmark);
191806
192045
  await mkdir13(dirname17(target), { recursive: true });
191807
192046
  await atomicWrite(root, out, html, { document: false, overwrite: false, mode: 384 });
191808
- return { kind: "editorbrain.review-artifact", path: target, artifactId, projectId: input.projectId, stage: input.stage, videoSha256: video?.sha256 ?? null, mediaEmbedded: true, mediaUploaded: false, agentTriggered: false, reviewSurface: "computer", cloudStorageBytes: 0, next: "Default: review on the computer. Open/display this HTML with the host artifact tool. If inline HTML/video is unsupported, offer the downloadable HTML opened in a browser. The user copies the prepared request or attaches downloaded feedback JSON to this chat. Phone review is opt-in: the collapsed action prepares a request, not an upload or approval. Never claim a click started the agent." };
192047
+ if (mediaMode === "local") await atomicWrite(root, `${out}.review.json`, JSON.stringify({ schemaVersion: 1, kind: "editorbrain.local-review", artifactId, html: { file: out, sha256: createHash13("sha256").update(html).digest("hex"), bytes: Buffer.byteLength(html) }, media: entries }), { document: false, overwrite: false, mode: 384 });
192048
+ return { kind: "editorbrain.review-artifact", path: target, artifactId, projectId: input.projectId, stage: input.stage, videoSha256: video?.sha256 ?? null, mediaEmbedded: mediaMode === "embedded", htmlBytes: Buffer.byteLength(html), mediaBytes: entries.reduce((sum, item) => sum + item.bytes, 0), ...mediaMode === "local" ? { openCommand: { executable: "editorbrain", args: ["production", "review-open", "--file", out, "--dir", root] } } : {}, mediaUploaded: false, agentTriggered: false, reviewSurface: "computer", cloudStorageBytes: 0, next: mediaMode === "local" ? "Run openCommand as a persistent preview process. Open its verified URL in the Claude Code Desktop Browser pane or the host browser. Keep the process alive; verify video playback, seeking and comments before delivery. Do not attach this HTML alone or publish it as a native Claude artifact: its private media are separate. No upload. Clicks do not wake the agent." : "Standalone embedded export: inspect htmlBytes before attaching. Host size/playback limits vary; if rejected, regenerate with --media-mode local and use production review-open. Never paste the base64 file into model context. No upload or automatic agent wake-up." };
192049
+ }
192050
+
192051
+ // packages/cli/src/review-server.ts
192052
+ import { createServer as createServer2 } from "node:http";
192053
+ import { createHash as createHash14, randomBytes as randomBytes2 } from "node:crypto";
192054
+ import { basename as basename5 } from "node:path";
192055
+ var hash5 = (bytes) => createHash14("sha256").update(bytes).digest("hex");
192056
+ var invalid5 = () => new CliError("INVALID_LOCAL_REVIEW", "The local review or its media is missing, altered or unsupported.", "Regenerate with production review-artifact --media-mode local using a new output path. Keep the HTML, .review.json and media folder together.");
192057
+ var validHash = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
192058
+ async function startReviewArtifact(root, file, port = 0) {
192059
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError("INVALID_ARGUMENT", "Preview port must be 0 through 65535.", "Omit --port for an available loopback port.");
192060
+ if (!file.endsWith(".html")) throw invalid5();
192061
+ const manifestPath = await productionOutputPath(root, `${file}.review.json`);
192062
+ const manifest = JSON.parse((await readReviewFile(manifestPath, 64 * 1024)).toString());
192063
+ if (manifest?.schemaVersion !== 1 || manifest.kind !== "editorbrain.local-review" || !validHash(manifest.artifactId) || manifest.html?.file !== file || !validHash(manifest.html.sha256) || !Array.isArray(manifest.media) || manifest.media.length > 3) throw invalid5();
192064
+ const html = await readReviewFile(await productionOutputPath(root, file), 2 * 1024 * 1024);
192065
+ if (hash5(html) !== manifest.html.sha256 || html.length !== manifest.html.bytes) throw invalid5();
192066
+ const resources = /* @__PURE__ */ new Map();
192067
+ resources.set("index.html", { body: html, mime: "text/html; charset=utf-8" });
192068
+ const mime = { mp4: "video/mp4", webm: "video/webm", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
192069
+ for (const entry of manifest.media) {
192070
+ if (!entry || typeof entry.file !== "string" || !entry.file.startsWith(`${file}.media-`) || !validHash(entry.sha256)) throw invalid5();
192071
+ const suffix = entry.file.slice(`${file}.media-`.length);
192072
+ const match = /^([a-f0-9-]{36})\/([a-f0-9]{64})\.(mp4|webm|png|jpg|jpeg|webp)$/.exec(suffix);
192073
+ if (!match || match[2] !== entry.sha256 || entry.mimeType !== mime[match[3]]) throw invalid5();
192074
+ const uri = `${encodeURIComponent(basename5(file) + ".media-" + match[1])}/${match[2]}.${match[3]}`;
192075
+ if (entry.uri !== uri || resources.has(uri)) throw invalid5();
192076
+ const bytes = await readReviewFile(await productionOutputPath(root, entry.file), REVIEW_MEDIA_BYTES);
192077
+ if (bytes.length !== entry.bytes || hash5(bytes) !== entry.sha256) throw invalid5();
192078
+ resources.set(uri, { body: bytes, mime: entry.mimeType });
192079
+ }
192080
+ const token = randomBytes2(24).toString("hex"), prefix = `/${token}/`;
192081
+ let origin = "";
192082
+ const server = createServer2((req, res) => {
192083
+ res.setHeader("Cache-Control", "no-store");
192084
+ res.setHeader("Referrer-Policy", "no-referrer");
192085
+ res.setHeader("X-Content-Type-Options", "nosniff");
192086
+ if (req.headers.host !== new URL(origin).host || req.headers.origin && req.headers.origin !== origin) {
192087
+ res.writeHead(403).end();
192088
+ return;
192089
+ }
192090
+ if (req.method !== "GET" && req.method !== "HEAD") {
192091
+ res.setHeader("Allow", "GET, HEAD");
192092
+ res.writeHead(405).end();
192093
+ return;
192094
+ }
192095
+ const route = req.url ?? "";
192096
+ const resource = route.startsWith(prefix) ? resources.get(route.slice(prefix.length)) : void 0;
192097
+ if (!resource) {
192098
+ res.writeHead(404).end();
192099
+ return;
192100
+ }
192101
+ res.setHeader("Content-Type", resource.mime);
192102
+ res.setHeader("Accept-Ranges", "bytes");
192103
+ let start3 = 0, end3 = resource.body.length - 1, status = 200;
192104
+ if (req.headers.range) {
192105
+ const range2 = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range);
192106
+ if (range2 && (range2[1] || range2[2])) {
192107
+ if (!range2[1]) start3 = Math.max(0, resource.body.length - Number(range2[2]));
192108
+ else {
192109
+ start3 = Number(range2[1]);
192110
+ if (range2[2]) end3 = Math.min(end3, Number(range2[2]));
192111
+ }
192112
+ }
192113
+ if (!range2 || !(range2[1] || range2[2]) || !Number.isSafeInteger(start3) || !Number.isSafeInteger(end3) || start3 > end3 || start3 >= resource.body.length) {
192114
+ res.setHeader("Content-Range", `bytes */${resource.body.length}`);
192115
+ res.writeHead(416).end();
192116
+ return;
192117
+ }
192118
+ status = 206;
192119
+ res.setHeader("Content-Range", `bytes ${start3}-${end3}/${resource.body.length}`);
192120
+ }
192121
+ res.setHeader("Content-Length", end3 - start3 + 1);
192122
+ res.writeHead(status);
192123
+ res.end(req.method === "HEAD" ? void 0 : resource.body.subarray(start3, end3 + 1));
192124
+ });
192125
+ server.requestTimeout = 15e3;
192126
+ server.headersTimeout = 1e4;
192127
+ server.maxHeadersCount = 32;
192128
+ await new Promise((resolve13, reject) => {
192129
+ server.once("error", reject);
192130
+ server.listen(port, "127.0.0.1", () => {
192131
+ server.removeListener("error", reject);
192132
+ resolve13();
192133
+ });
192134
+ });
192135
+ const address = server.address();
192136
+ if (!address || typeof address === "string") {
192137
+ server.close();
192138
+ throw invalid5();
192139
+ }
192140
+ origin = `http://127.0.0.1:${address.port}`;
192141
+ const url2 = `${origin}${prefix}index.html`;
192142
+ const close = () => new Promise((resolve13, reject) => {
192143
+ server.close((error) => error ? reject(error) : resolve13());
192144
+ server.closeAllConnections();
192145
+ });
192146
+ try {
192147
+ const probe2 = await fetch(url2, { signal: AbortSignal.timeout(5e3) });
192148
+ if (probe2.status !== 200 || hash5(Buffer.from(await probe2.arrayBuffer())) !== manifest.html.sha256) throw invalid5();
192149
+ } catch (error) {
192150
+ await close();
192151
+ throw error;
192152
+ }
192153
+ return { url: url2, artifactId: manifest.artifactId, htmlBytes: html.length, mediaBytes: [...resources.values()].reduce((sum, r) => sum + r.body.length, 0) - html.length, close };
192154
+ }
192155
+ async function serveReviewArtifact(root, file, port = 0) {
192156
+ try {
192157
+ return await startReviewArtifact(root, file, port);
192158
+ } catch (error) {
192159
+ if (error instanceof CliError) throw error;
192160
+ if (error.code === "EADDRINUSE") throw new CliError("REVIEW_PORT_UNAVAILABLE", "That preview port is already in use.", "Omit --port for a free port, or select another port in the host preview runner. Do not stop an unrelated server.");
192161
+ throw invalid5();
192162
+ }
191809
192163
  }
191810
192164
 
191811
192165
  // packages/cli/src/production-review-client.ts
191812
192166
  var productionReviewCommands = ["reviews", "transcript", "sample", "approve", "change", "feedback", "resolve-feedback", "revoke-sample"];
191813
- var invalid5 = (message) => {
192167
+ var invalid6 = (message) => {
191814
192168
  throw new CliError("INVALID_ARGUMENT", message, "Read editorbrain help and references/production-continuity.md.");
191815
192169
  };
191816
192170
  var uuid2 = (value, name) => {
191817
- if (typeof value !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value)) invalid5(`${name} must be a revision or feedback UUID.`);
192171
+ if (typeof value !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value)) invalid6(`${name} must be a revision or feedback UUID.`);
191818
192172
  return value;
191819
192173
  };
191820
- var hash5 = (value, name) => {
191821
- if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) invalid5(`${name} must be an exact SHA-256 hash.`);
192174
+ var hash6 = (value, name) => {
192175
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) invalid6(`${name} must be an exact SHA-256 hash.`);
191822
192176
  return value;
191823
192177
  };
191824
192178
  var text10 = (value, name, max, optional = false) => {
191825
192179
  if (optional && (value === void 0 || value === null)) return "";
191826
- if (typeof value !== "string" || value.length > max || !optional && !value.trim()) invalid5(`${name} must contain ${optional ? "0" : "1"}\u2013${max} characters.`);
192180
+ if (typeof value !== "string" || value.length > max || !optional && !value.trim()) invalid6(`${name} must contain ${optional ? "0" : "1"}\u2013${max} characters.`);
191827
192181
  return value.trim();
191828
192182
  };
191829
192183
  function reviewBody(value, command) {
191830
192184
  const fields = command === "sample" ? ["assetId", "contextVersion", "title", "notes", "parentRevisionId", "revisionId", "transcript"] : ["resultRevisionId", "contextVersion", "resultNote", "preservedElements"];
191831
- if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !fields.includes(key))) invalid5("Use only documented review fields; project and feedback IDs come from command flags, never the JSON body.");
192185
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !fields.includes(key))) invalid6("Use only documented review fields; project and feedback IDs come from command flags, never the JSON body.");
191832
192186
  const body = value;
191833
- hash5(body.contextVersion, "contextVersion");
192187
+ hash6(body.contextVersion, "contextVersion");
191834
192188
  if (command === "sample") {
191835
192189
  if (body.transcript !== void 0) {
191836
192190
  try {
191837
192191
  body.transcript = parseReviewTranscript(body.transcript);
191838
192192
  } catch (e) {
191839
- invalid5(e.message);
192193
+ invalid6(e.message);
191840
192194
  }
191841
192195
  }
191842
- hash5(body.assetId, "assetId");
192196
+ hash6(body.assetId, "assetId");
191843
192197
  text10(body.title, "title", 120);
191844
192198
  text10(body.notes, "notes", 2e3, true);
191845
192199
  for (const key of ["parentRevisionId", "revisionId"]) if (body[key] !== void 0) uuid2(body[key], key);
@@ -191848,11 +192202,11 @@ function reviewBody(value, command) {
191848
192202
  text10(body.resultNote, "resultNote", 1500);
191849
192203
  text10(body.preservedElements, "preservedElements", 2e3);
191850
192204
  }
191851
- if (Buffer.byteLength(JSON.stringify(body)) > (command === "sample" ? REVIEW_SAMPLE_MAX_BYTES : 8192)) invalid5(command === "sample" ? "Review metadata exceeds the 64 KiB service limit." : "Review metadata exceeds the 8 KiB service limit.");
192205
+ if (Buffer.byteLength(JSON.stringify(body)) > (command === "sample" ? REVIEW_SAMPLE_MAX_BYTES : 8192)) invalid6(command === "sample" ? "Review metadata exceeds the 64 KiB service limit." : "Review metadata exceeds the 8 KiB service limit.");
191852
192206
  return body;
191853
192207
  }
191854
192208
  async function productionReviewCommand(client, root, command, flags) {
191855
- if (!productionReviewCommands.includes(command)) invalid5("Unknown production review command.");
192209
+ if (!productionReviewCommands.includes(command)) invalid6("Unknown production review command.");
191856
192210
  const required = (name) => {
191857
192211
  const value = flags[name];
191858
192212
  if (typeof value !== "string" || !value) throw new CliError("INVALID_ARGUMENT", `--${name} is required.`, "Read editorbrain help.");
@@ -191873,7 +192227,7 @@ async function productionReviewCommand(client, root, command, flags) {
191873
192227
  assertIdentifier(projectId);
191874
192228
  const base = `/v1/projects/${encodeURIComponent(projectId)}`;
191875
192229
  const revision2 = () => encodeURIComponent(uuid2(required("revision"), "--revision"));
191876
- const contextVersion = () => hash5(required("context-version"), "--context-version");
192230
+ const contextVersion = () => hash6(required("context-version"), "--context-version");
191877
192231
  const after = flags.after === void 0 ? void 0 : uuid2(required("after"), "--after");
191878
192232
  if (command === "transcript") return client.request(`${base}/production-reviews/${revision2()}/transcript`);
191879
192233
  if (command === "reviews") return client.request(`${base}/production-reviews${after ? "?" + new URLSearchParams({ after }) : ""}`);
@@ -191881,7 +192235,7 @@ async function productionReviewCommand(client, root, command, flags) {
191881
192235
  const query = new URLSearchParams();
191882
192236
  if (flags.status !== void 0) {
191883
192237
  const status = required("status");
191884
- if (!["pending", "resolved"].includes(status)) invalid5("--status must be pending or resolved.");
192238
+ if (!["pending", "resolved"].includes(status)) invalid6("--status must be pending or resolved.");
191885
192239
  query.set("status", status);
191886
192240
  }
191887
192241
  if (flags.revision !== void 0) query.set("revisionId", uuid2(required("revision"), "--revision"));
@@ -191900,7 +192254,7 @@ async function productionReviewCommand(client, root, command, flags) {
191900
192254
  if (command === "revoke-sample") return client.request(`${base}/production-reviews/${revision2()}`, { method: "DELETE" });
191901
192255
  if (command === "change") {
191902
192256
  const segment = flags.segment === void 0 ? void 0 : required("segment");
191903
- if (segment !== void 0 && !/^[a-zA-Z0-9_-]{1,80}$/.test(segment)) invalid5("Use a valid transcript segment ID.");
192257
+ if (segment !== void 0 && !/^[a-zA-Z0-9_-]{1,80}$/.test(segment)) invalid6("Use a valid transcript segment ID.");
191904
192258
  const times = flags.at === void 0 ? [] : required("at").split(",");
191905
192259
  if (times.length > 2 || times.some((t) => !/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(t) || !Number.isFinite(Number(t)) || Number(t) > 36e3) || times.length === 2 && Number(times[1]) < Number(times[0])) throw new CliError("INVALID_ARGUMENT", "--at accepts one second or a start,end range between 0 and 36000 seconds.", "Example: --at 12,15.5. Omit it for the whole sample.");
191906
192260
  return client.request(`${base}/production-reviews/${revision2()}/changes`, { method: "POST", body: { contextVersion: contextVersion(), text: text10(required("text"), "--text", 1500), target: { ...segment ? { segmentId: segment } : {}, ...times.length ? { startMs: Math.round(Number(times[0]) * 1e3), ...times.length === 2 ? { endMs: Math.round(Number(times[1]) * 1e3) } : {} } : {} }, ...flags.id !== void 0 ? { feedbackId: uuid2(required("id"), "--id") } : {} } });
@@ -192033,7 +192387,8 @@ editorbrain production matte --engine apple-vision --file montage.mp4 --out .edi
192033
192387
  editorbrain production matte-plan --file montage.mp4 [--dir folder]
192034
192388
  editorbrain production check --file render [--profile local-profile.json] [--dir folder] [--out .editorbrain-local/report.json] [--details]
192035
192389
  editorbrain production verify --project ID --file final.mp4 [--platform tiktok|reels|shorts] [--profile geometry.json] [--duration seconds] [--at 0,5,12] [--dir folder] [--out .editorbrain-local/new-check] [--offline] [--details]
192036
- editorbrain production review-artifact --file review.json --out .editorbrain-local/review-v1.html [--dir folder]
192390
+ editorbrain production review-artifact --file review.json --out .editorbrain-local/review-v1.html [--media-mode local|embedded] [--dir folder]
192391
+ editorbrain production review-open --file .editorbrain-local/review-v1.html [--port 0] [--dir folder]
192037
192392
  editorbrain production reviews --project ID [--after UUID]
192038
192393
  editorbrain production transcript --project ID --revision UUID
192039
192394
  editorbrain production sample --project ID --file sample.json [--dir folder]
@@ -192135,7 +192490,7 @@ async function configRoot(create = false) {
192135
192490
  let path = process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join15(homedir3(), ".config", "editorbrain");
192136
192491
  if (!create && !process.env.EDITORBRAIN_CONFIG_DIR && !process.env.EDITORHARNESS_CONFIG_DIR) {
192137
192492
  try {
192138
- await lstat12(path);
192493
+ await lstat13(path);
192139
192494
  } catch (error) {
192140
192495
  if (error.code !== "ENOENT") throw error;
192141
192496
  path = join15(homedir3(), ".config", "editorharness");
@@ -192187,7 +192542,7 @@ async function init(args) {
192187
192542
  for (const path of Object.keys(files)) {
192188
192543
  const target = await checkedPath(root, path);
192189
192544
  try {
192190
- await lstat12(target);
192545
+ await lstat13(target);
192191
192546
  throw new Error(`Refusing to replace existing file: ${path}`);
192192
192547
  } catch (error) {
192193
192548
  if (error.code !== "ENOENT") throw error;
@@ -192199,7 +192554,7 @@ async function init(args) {
192199
192554
  for (const path of directories) {
192200
192555
  const target = await checkedPath(root, path, false);
192201
192556
  try {
192202
- if (!(await lstat12(target)).isDirectory()) throw new Error(`Not a directory: ${path}`);
192557
+ if (!(await lstat13(target)).isDirectory()) throw new Error(`Not a directory: ${path}`);
192203
192558
  } catch (error) {
192204
192559
  if (error.code !== "ENOENT") throw error;
192205
192560
  }
@@ -192503,10 +192858,26 @@ async function main() {
192503
192858
  return;
192504
192859
  }
192505
192860
  if (command === "production" && subcommand === "review-artifact") {
192506
- if (argument || Object.keys(args.flags).some((k) => !["file", "out", "dir"].includes(k))) throw new CliError("INVALID_ARGUMENT", "Unsupported review-artifact option.", "Use --file, --out and optional --dir.");
192861
+ if (argument || Object.keys(args.flags).some((k) => !["file", "out", "dir", "media-mode"].includes(k))) throw new CliError("INVALID_ARGUMENT", "Unsupported review-artifact option.", "Use --file, --out, optional --media-mode local|embedded and --dir.");
192507
192862
  const root2 = resolve12(str(args, "dir") ?? process.cwd()), file = str(args, "file"), out = str(args, "out");
192508
192863
  if (!file || !out) throw new CliError("INVALID_ARGUMENT", "review-artifact requires --file and --out.", "Use a new .editorbrain-local/.../review.html output.");
192509
- output(await createReviewArtifact(root2, await readProductionJson(root2, file), out));
192864
+ const mode = str(args, "media-mode") ?? "local";
192865
+ if (!["local", "embedded"].includes(mode)) throw new CliError("INVALID_ARGUMENT", "Unknown media mode.", "Use local or embedded.");
192866
+ output(await createReviewArtifact(root2, await readProductionJson(root2, file), out, mode));
192867
+ return;
192868
+ }
192869
+ if (command === "production" && subcommand === "review-open") {
192870
+ if (argument || Object.keys(args.flags).some((k) => !["file", "dir", "port"].includes(k))) throw new CliError("INVALID_ARGUMENT", "Unsupported review-open option.", "Use --file, optional --port and --dir.");
192871
+ const root2 = await ensureRoot(str(args, "dir") ?? process.cwd()), file = str(args, "file"), port = str(args, "port");
192872
+ if (!file || port !== void 0 && !/^\d+$/.test(port)) throw new CliError("INVALID_ARGUMENT", "Provide a local review HTML and an integer port.", "Use --file .editorbrain-local/review-v1.html; omit --port for an available port.");
192873
+ const review = await serveReviewArtifact(root2, file, port === void 0 ? 0 : Number(port));
192874
+ const stop = () => {
192875
+ void review.close().catch(() => {
192876
+ });
192877
+ };
192878
+ process.once("SIGINT", stop);
192879
+ process.once("SIGTERM", stop);
192880
+ output({ kind: "editorbrain.review-server", url: review.url, artifactId: review.artifactId, htmlBytes: review.htmlBytes, mediaBytes: review.mediaBytes, listening: true, httpVerified: true, playbackVerified: false, mediaUploaded: false, agentTriggered: false, next: "Keep this foreground process alive in the host preview runner. Open url in Claude Code Desktop Browser or the host browser, verify playback and seeking, and test a timestamped comment before delivery. Do not kill this process after showing the link. Ctrl+C stops it. This URL works only on this computer; phone review needs the private web flow. Save/export notes before stopping or changing ports." });
192510
192881
  return;
192511
192882
  }
192512
192883
  if (command === "production" && productionReviewCommands.includes(subcommand)) {
@@ -192744,7 +193115,7 @@ async function main() {
192744
193115
  const outRoot = await ensureRoot(resolve12(str(args, "dir") ?? process.cwd(), destination), true);
192745
193116
  for (const path of Object.keys(result2.files)) {
192746
193117
  try {
192747
- await lstat12(await checkedPath(outRoot, path, false));
193118
+ await lstat13(await checkedPath(outRoot, path, false));
192748
193119
  throw new Error(`Refusing to replace existing proposal: ${path}`);
192749
193120
  } catch (error) {
192750
193121
  if (error.code !== "ENOENT") throw error;
@@ -192913,15 +193284,15 @@ async function main() {
192913
193284
  const types = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/mp4", ".ogg": "audio/ogg" };
192914
193285
  const mimeType = str(args, "mime") ?? types[extname7(target).toLowerCase()];
192915
193286
  if (!mimeType) throw new Error("Unsupported extension; specify --mime for a supported media format");
192916
- const hash6 = await sha256(bytes);
192917
- const params = new URLSearchParams({ name: basename4(target) });
193287
+ const hash7 = await sha256(bytes);
193288
+ const params = new URLSearchParams({ name: basename6(target) });
192918
193289
  if (str(args, "project")) params.set("projectId", str(args, "project"));
192919
193290
  if (str(args, "purpose")) params.set("purpose", str(args, "purpose"));
192920
193291
  if (str(args, "source-sha256")) params.set("sourceSha256", str(args, "source-sha256"));
192921
- const path = `/v1/assets/${hash6}?${params}`;
193292
+ const path = `/v1/assets/${hash7}?${params}`;
192922
193293
  const result2 = str(args, "purpose") === "preview" ? await client.uploadPreview(path, bytes, mimeType) : await client.media(path, { content: bytes, mimeType });
192923
193294
  const body = await result2.json();
192924
- if (body.sha256 !== hash6) throw new Error("Upload response hash mismatch");
193295
+ if (body.sha256 !== hash7) throw new Error("Upload response hash mismatch");
192925
193296
  output(body);
192926
193297
  return;
192927
193298
  }
@@ -192929,11 +193300,11 @@ async function main() {
192929
193300
  if (!/^[a-f0-9]{64}$/.test(argument)) throw new Error("Asset ID must be its SHA-256");
192930
193301
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
192931
193302
  const root2 = await ensureRoot(dirname18(destination), true);
192932
- await checkedPath(root2, basename4(destination), false);
193303
+ await checkedPath(root2, basename6(destination), false);
192933
193304
  const response = await client.media(`/v1/assets/${argument}`);
192934
193305
  const bytes = new Uint8Array(await response.arrayBuffer());
192935
193306
  if (await sha256(bytes) !== argument) throw new Error("Downloaded asset failed SHA-256 verification");
192936
- await atomicWrite(root2, basename4(destination), bytes, { document: false, overwrite: false });
193307
+ await atomicWrite(root2, basename6(destination), bytes, { document: false, overwrite: false });
192937
193308
  output({ path: destination, sha256: argument, bytes: bytes.length });
192938
193309
  return;
192939
193310
  }
@@ -193034,7 +193405,7 @@ async function main() {
193034
193405
  const mimeType = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm" }[extname7(videoPath).toLowerCase()];
193035
193406
  if (!mimeType) throw new Error("Use MP4, MOV or WebM.");
193036
193407
  assetId = await sha256(bytes);
193037
- const uploaded = await client.media(`/v1/assets/${assetId}?name=${encodeURIComponent(basename4(videoPath))}`, { content: bytes, mimeType });
193408
+ const uploaded = await client.media(`/v1/assets/${assetId}?name=${encodeURIComponent(basename6(videoPath))}`, { content: bytes, mimeType });
193038
193409
  if ((await uploaded.json()).sha256 !== assetId) throw new Error("Upload hash mismatch.");
193039
193410
  }
193040
193411
  if (!script && !assetId && !str(args, "project")) throw new Error("Provide --script, --video, --asset or --project with a saved script.");
@@ -193055,7 +193426,7 @@ async function main() {
193055
193426
  const params = new URLSearchParams({ query: args.positional.slice(2).join(" ") });
193056
193427
  const limit = str(args, "limit"), after = str(args, "after");
193057
193428
  if (limit !== void 0) {
193058
- if (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > 20) throw new Error("--limit must be 1 through 20");
193429
+ if (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > 20) throw new Error("--limit must be 1 through 20. Use --limit 20, then --after <nextCursor> from the previous page with the same query.");
193059
193430
  params.set("limit", limit);
193060
193431
  }
193061
193432
  if (after !== void 0) {
@@ -193067,20 +193438,20 @@ async function main() {
193067
193438
  }
193068
193439
  if (subcommand === "get" && argument) {
193069
193440
  const document2 = str(args, "document");
193070
- const hash6 = str(args, "sha256");
193071
- if (hash6 && !document2) throw new Error("--sha256 requires --document for library get.");
193072
- const result2 = await client.request(`/v1/library/${encodeURIComponent(argument)}${document2 ? `/documents?${new URLSearchParams({ path: document2, ...hash6 ? { sha256: hash6 } : {} })}` : ""}`);
193073
- if (document2 && (typeof result2.content !== "string" || await sha256(result2.content) !== result2.sha256 || hash6 && result2.sha256 !== hash6)) throw new CliError("HASH_MISMATCH", "Reference document verification failed.", "Do not use this evidence; retry the pinned version.");
193441
+ const hash7 = str(args, "sha256");
193442
+ if (hash7 && !document2) throw new Error("--sha256 requires --document for library get.");
193443
+ const result2 = await client.request(`/v1/library/${encodeURIComponent(argument)}${document2 ? `/documents?${new URLSearchParams({ path: document2, ...hash7 ? { sha256: hash7 } : {} })}` : ""}`);
193444
+ if (document2 && (typeof result2.content !== "string" || await sha256(result2.content) !== result2.sha256 || hash7 && result2.sha256 !== hash7)) throw new CliError("HASH_MISMATCH", "Reference document verification failed.", "Do not use this evidence; retry the pinned version.");
193074
193445
  output(result2);
193075
193446
  return;
193076
193447
  }
193077
193448
  if (subcommand === "media" && argument && str(args, "out")) {
193078
- const hash6 = str(args, "sha256");
193079
- if (!hash6 || !/^[a-f0-9]{64}$/.test(hash6)) throw new Error("--sha256 must be a media SHA-256 from library get.");
193449
+ const hash7 = str(args, "sha256");
193450
+ if (!hash7 || !/^[a-f0-9]{64}$/.test(hash7)) throw new Error("--sha256 must be a media SHA-256 from library get.");
193080
193451
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
193081
193452
  const root2 = await ensureRoot(dirname18(destination), true);
193082
- await checkedPath(root2, basename4(destination), false);
193083
- const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash6}`);
193453
+ await checkedPath(root2, basename6(destination), false);
193454
+ const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash7}`);
193084
193455
  const reader = response.body?.getReader();
193085
193456
  if (!reader) throw new Error("Media body missing.");
193086
193457
  const chunks = [];
@@ -193096,9 +193467,9 @@ async function main() {
193096
193467
  chunks.push(value);
193097
193468
  }
193098
193469
  const bytes = Buffer.concat(chunks);
193099
- if (await sha256(bytes) !== hash6) throw new CliError("HASH_MISMATCH", "Reference media verification failed.", "Do not use this file as evidence.");
193100
- await atomicWrite(root2, basename4(destination), bytes, { document: false, overwrite: false });
193101
- output({ videoId: argument, path: destination, sha256: hash6, bytes: size, mimeType: response.headers.get("Content-Type"), reviewed: false });
193470
+ if (await sha256(bytes) !== hash7) throw new CliError("HASH_MISMATCH", "Reference media verification failed.", "Do not use this file as evidence.");
193471
+ await atomicWrite(root2, basename6(destination), bytes, { document: false, overwrite: false });
193472
+ output({ videoId: argument, path: destination, sha256: hash7, bytes: size, mimeType: response.headers.get("Content-Type"), reviewed: false });
193102
193473
  return;
193103
193474
  }
193104
193475
  throw new Error("Use library search, library get, or library media <video-id> --sha256 hash --out file.");