editorbrain 0.52.0 → 0.53.0

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.
@@ -733,9 +733,9 @@ function floatSafeRemainder(val, step) {
733
733
  return ratio - roundedRatio;
734
734
  }
735
735
  var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
736
- function defineLazy(object21, key, getter) {
736
+ function defineLazy(object20, key, getter) {
737
737
  let value = void 0;
738
- Object.defineProperty(object21, key, {
738
+ Object.defineProperty(object20, key, {
739
739
  get() {
740
740
  if (value === EVALUATING) {
741
741
  return void 0;
@@ -747,7 +747,7 @@ function defineLazy(object21, key, getter) {
747
747
  return value;
748
748
  },
749
749
  set(v) {
750
- Object.defineProperty(object21, key, {
750
+ Object.defineProperty(object20, key, {
751
751
  value: v
752
752
  // configurable: true,
753
753
  });
@@ -15862,8 +15862,8 @@ function foldObjects(members2) {
15862
15862
  }
15863
15863
  const properties = {};
15864
15864
  const required2 = /* @__PURE__ */ new Set();
15865
- for (const object21 of objects) {
15866
- for (const key in object21.properties) {
15865
+ for (const object20 of objects) {
15866
+ for (const key in object20.properties) {
15867
15867
  if (Object.prototype.hasOwnProperty.call(properties, key))
15868
15868
  continue;
15869
15869
  const parts = [];
@@ -15877,18 +15877,18 @@ function foldObjects(members2) {
15877
15877
  const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts };
15878
15878
  assignProp(properties, key, merged);
15879
15879
  }
15880
- for (const key of object21.required ?? [])
15880
+ for (const key of object20.required ?? [])
15881
15881
  required2.add(key);
15882
15882
  }
15883
15883
  const folded = { type: "object", properties };
15884
15884
  if (required2.size)
15885
15885
  folded.required = [...required2];
15886
- if (objects.every((object21) => object21.additionalProperties === false)) {
15886
+ if (objects.every((object20) => object20.additionalProperties === false)) {
15887
15887
  folded.additionalProperties = false;
15888
15888
  } else {
15889
15889
  const constraints = [];
15890
- for (const object21 of objects) {
15891
- const constraint = undeclaredConstraint(object21);
15890
+ for (const object20 of objects) {
15891
+ const constraint = undeclaredConstraint(object20);
15892
15892
  if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))
15893
15893
  constraints.push(constraint);
15894
15894
  }
@@ -19915,6 +19915,8 @@ var renderRemoteSubmitSchema = external_exports.object({ ...renderCreateSchema.s
19915
19915
  // packages/core/src/audio-production.ts
19916
19916
  var audioProductionOptions = {
19917
19917
  musicIntensity: ["none", "subtle", "present"],
19918
+ musicCharacter: ["warm", "clean", "energetic", "cinematic"],
19919
+ hookTreatment: ["none", "soft", "marked"],
19918
19920
  sfxDensity: ["none", "sparse", "moderate", "dense"],
19919
19921
  sfxCharacter: ["organic", "digital", "cinematic", "mixed"],
19920
19922
  sfxGeneration: ["allowed", "forbidden"]
@@ -19953,16 +19955,20 @@ function validateAudioProductionPreferences(value) {
19953
19955
  }
19954
19956
  if (input2.music === null) result2.music = null;
19955
19957
  else if (input2.music !== void 0) {
19956
- const music = record2(input2.music, "music", ["intensity"]);
19958
+ const music = record2(input2.music, "music", ["intensity", "character"]);
19957
19959
  result2.music = {};
19958
19960
  if (music.intensity !== void 0) {
19959
19961
  if (music.intensity !== null && (typeof music.intensity !== "string" || !audioProductionOptions.musicIntensity.includes(music.intensity))) throw new Error("music.intensity must be none, subtle, present or null.");
19960
19962
  result2.music.intensity = music.intensity;
19961
19963
  }
19964
+ if (music.character !== void 0) {
19965
+ if (music.character !== null && !audioProductionOptions.musicCharacter.includes(music.character)) throw new Error("Invalid music character.");
19966
+ result2.music.character = music.character;
19967
+ }
19962
19968
  }
19963
19969
  if (input2.sfx === null) result2.sfx = null;
19964
19970
  else if (input2.sfx !== void 0) {
19965
- const sfx = record2(input2.sfx, "sfx", ["library", "generation", "density", "hookWithoutEffects", "character"]);
19971
+ const sfx = record2(input2.sfx, "sfx", ["library", "generation", "density", "hookWithoutEffects", "character", "hookTreatment"]);
19966
19972
  result2.sfx = {};
19967
19973
  if (sfx.library === null) result2.sfx.library = null;
19968
19974
  else if (sfx.library !== void 0) {
@@ -19983,6 +19989,10 @@ function validateAudioProductionPreferences(value) {
19983
19989
  if (sfx.character !== null && !audioProductionOptions.sfxCharacter.includes(sfx.character)) throw new Error("Invalid SFX character.");
19984
19990
  result2.sfx.character = sfx.character;
19985
19991
  }
19992
+ if (sfx.hookTreatment !== void 0) {
19993
+ if (sfx.hookTreatment !== null && !audioProductionOptions.hookTreatment.includes(sfx.hookTreatment)) throw new Error("Invalid hook treatment.");
19994
+ result2.sfx.hookTreatment = sfx.hookTreatment;
19995
+ }
19986
19996
  if (sfx.hookWithoutEffects !== void 0) {
19987
19997
  if (sfx.hookWithoutEffects !== null && typeof sfx.hookWithoutEffects !== "boolean") throw new Error("sfx.hookWithoutEffects must be a boolean or null.");
19988
19998
  result2.sfx.hookWithoutEffects = sfx.hookWithoutEffects;
@@ -20009,13 +20019,21 @@ function applyEditorialAudioConstraints(preferences, profile) {
20009
20019
  if (effective?.sfx?.density && effective.sfx.density !== "none") warnings.push("SFX are disabled by the saved editorial restriction; the original audio preferences remain unchanged.");
20010
20020
  effective = { ...effective, schemaVersion: 1, sfx: { ...effective?.sfx, density: "none", generation: "forbidden" } };
20011
20021
  }
20022
+ if (effective?.sfx?.hookWithoutEffects === true && effective.sfx.hookTreatment && effective.sfx.hookTreatment !== "none") {
20023
+ warnings.push("The saved no-effects opening restriction overrides hook treatment; original preferences remain unchanged.");
20024
+ effective = { ...effective, sfx: { ...effective.sfx, hookTreatment: "none" } };
20025
+ }
20026
+ if (profile.avoid?.includes("Sin voz de IA")) {
20027
+ if (effective?.voice?.mode === "catalog" || effective?.voice?.mode === "cloned" || profile.editorialDelivery?.narration === "generated") warnings.push("Generated narration is excluded by this brand. Use only supplied narration or leave missing audio pending; do not generate or clone a voice.");
20028
+ effective = { ...effective, schemaVersion: 1, voice: { mode: profile.editorialDelivery?.narration === "none" ? "none" : "original" } };
20029
+ }
20012
20030
  const narration = profile.editorialDelivery?.narration;
20013
20031
  const voice = effective?.voice;
20014
20032
  if (narration === "original" || narration === "none") {
20015
20033
  if (voice && voice.mode !== narration) warnings.push(`Narration preference ${narration} conflicts with audio voice ${voice.mode}. Do not generate narration; confirm any deliberate project exception with the current request.`);
20016
20034
  effective = { ...effective, schemaVersion: 1, voice: { mode: narration } };
20017
- } else if (narration === "voiceover" && voice && (voice.mode === "original" || voice.mode === "none")) {
20018
- warnings.push(`Voiceover preference conflicts with audio voice ${voice.mode}. Resolve narration with the current request; do not infer a paid provider or voice.`);
20035
+ } else if ((narration === "voiceover" || narration === "generated") && voice && (voice.mode === "original" || voice.mode === "none")) {
20036
+ warnings.push(`Narration preference conflicts with audio voice ${voice.mode}. Resolve narration with the current request; do not infer a paid provider or voice.`);
20019
20037
  }
20020
20038
  return { ...effective ? { preferences: effective } : {}, warnings };
20021
20039
  }
@@ -20973,7 +20991,7 @@ function recoveryHint(help) {
20973
20991
 
20974
20992
  // packages/core/src/tool-preferences.ts
20975
20993
  var toolLanguages = ["project", "es", "en", "pt", "fr", "de", "it"];
20976
- var transcriptionProviders = ["editorbrain", "assemblyai", "whisper-local", "whisper-online"];
20994
+ var transcriptionProviders = ["editorbrain", "assemblyai", "whisper-local", "whisper-online", "personal"];
20977
20995
  function validateToolPreferences(input2) {
20978
20996
  const obj3 = (value2, keys4) => {
20979
20997
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2) || Object.keys(value2).some((k) => !keys4.includes(k))) throw new Error("Invalid AI tool preference fields.");
@@ -20989,7 +21007,7 @@ function validateToolPreferences(input2) {
20989
21007
  const fields3 = { transcription: ["provider", "language"], images: ["provider", "quality", "resolution", "aspectRatio"], narration: ["provider", "language"], music: ["provider", "durationSeconds", "character"] }[key];
20990
21008
  const section2 = obj3(value[key], fields3);
20991
21009
  if (fields3.some((field) => section2[field] === void 0)) throw new Error("Incomplete AI tool preferences.");
20992
- const providers = { transcription: transcriptionProviders, images: ["editorbrain", "higgsfield", "openai-images"], narration: ["editorbrain", "elevenlabs"], music: ["editorbrain", "suno", "elevenlabs"] }[key];
21010
+ const providers = { transcription: transcriptionProviders, images: ["editorbrain", "higgsfield", "openai-images", "personal"], narration: ["editorbrain", "elevenlabs", "personal"], music: ["editorbrain", "suno", "elevenlabs", "personal"] }[key];
20993
21011
  choice(section2.provider, providers);
20994
21012
  if (key === "transcription" || key === "narration") choice(section2.language, toolLanguages);
20995
21013
  if (key === "images") {
@@ -21031,11 +21049,11 @@ function assertCheckpointArtifactPath(path) {
21031
21049
  }
21032
21050
  function fields(value, expected, label) {
21033
21051
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
21034
- const object21 = value;
21035
- if (Object.keys(object21).some((key) => !expected.includes(key)) || expected.some((key) => !Object.prototype.hasOwnProperty.call(object21, key))) {
21052
+ const object20 = value;
21053
+ if (Object.keys(object20).some((key) => !expected.includes(key)) || expected.some((key) => !Object.prototype.hasOwnProperty.call(object20, key))) {
21036
21054
  throw new Error(`${label} has missing or unsupported fields.`);
21037
21055
  }
21038
- return object21;
21056
+ return object20;
21039
21057
  }
21040
21058
  function proseSpanEnd(value, slash) {
21041
21059
  const closingQuotes = { '"': '"', "'": "'", "`": "`", "\u201C": "\u201D", "\u2018": "\u2019", "\xAB": "\xBB" };
@@ -21129,6 +21147,26 @@ function validateProjectCheckpoint(input2, projectId) {
21129
21147
  return structuredClone(value);
21130
21148
  }
21131
21149
 
21150
+ // packages/core/src/content-presence.ts
21151
+ var contentPresenceOptions = [
21152
+ ["face", "Yo, a c\xE1mara"],
21153
+ ["voice", "Sin cara, con mi voz"],
21154
+ ["ai", "Sin cara, con voz de IA"],
21155
+ ["others", "Otras personas"],
21156
+ ["screen", "Grabaci\xF3n de pantalla"],
21157
+ ["product", "Solo producto o manos"]
21158
+ ];
21159
+ function contentPresenceIssues(value) {
21160
+ if (value === void 0) return [];
21161
+ if (!value || typeof value !== "object" || Array.isArray(value)) return ["contentPresence debe ser un objeto."];
21162
+ const input2 = value;
21163
+ const known = (id4) => contentPresenceOptions.some(([key]) => key === id4);
21164
+ if (Object.keys(input2).some((key) => !["primary", "secondary"].includes(key)) || !known(input2.primary)) return ["contentPresence.primary debe indicar una presentaci\xF3n conocida."];
21165
+ if (input2.secondary !== void 0 && (!Array.isArray(input2.secondary) || input2.secondary.length > 5 || new Set(input2.secondary).size !== input2.secondary.length || input2.secondary.some((id4) => !known(id4) || id4 === input2.primary))) return ["contentPresence.secondary admite hasta cinco presentaciones distintas de la principal, sin duplicados."];
21166
+ return [];
21167
+ }
21168
+ var contentPresenceGuidance = "contentPresence describes the usual subjects and presentation of this brand, not the current footage. Inspect each project before adapting the opening, framing or support. Secondary formats remain possible. It does not authorize invented people, avatars, voice synthesis or cloning, enable stock/generated sources, select an audio voice, or change captions, review, tools or spending. Hidden controls retain their saved choices; apply presenter layout only when the actual footage contains a presenter.";
21169
+
21132
21170
  // packages/core/src/question-policy.ts
21133
21171
  var questionModeOptions = [
21134
21172
  { id: "essential", title: "Solo lo esencial", description: "Pregunta solo si falta algo que cambia el resultado. Los detalles los decide tu agente." },
@@ -21169,6 +21207,9 @@ function planEditQuestions(policy, value) {
21169
21207
  }
21170
21208
 
21171
21209
  // packages/core/src/integrations.ts
21210
+ var integrationAccessMethods = ["agent", "api", "browser", "files"];
21211
+ var integrationCapabilities = ["image", "video", "voiceover", "music", "sfx", "transcription", "stock-image", "stock-video", "other"];
21212
+ var maxCustomIntegrations = 20;
21172
21213
  var integrationCatalog = [
21173
21214
  { id: "higgsfield", name: "Higgsfield", description: "Im\xE1genes y clips generados para apoyar tu edici\xF3n.", capabilities: ["image", "video"], accessMethods: ["agent", "api", "browser", "files"], docsUrl: "https://open.higgsfield.ai/quick-start" },
21174
21215
  { id: "kie-ai", name: "Kie AI", description: "Im\xE1genes, video, voz y m\xFAsica con tu propia cuenta de Kie AI.", capabilities: ["image", "video", "voiceover", "music"], accessMethods: ["api", "agent", "files"], docsUrl: "https://docs.kie.ai/" },
@@ -21187,13 +21228,41 @@ function knownFields(value, allowed) {
21187
21228
  if (Object.keys(value).some((key) => !allowed.includes(key))) throw new Error("Unknown integration field. Credentials and user/workspace IDs are not accepted.");
21188
21229
  }
21189
21230
  function containsCredential(value) {
21190
- return /-----BEGIN [A-Z ]*PRIVATE KEY-----|\bBearer\s+\S{12,}|\b(?:sk-(?:proj-)?|AIza|cfat_|apikey_|tlk_)[A-Za-z0-9_-]{15,}|\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|(?:api[_ -]?key|access[_ -]?token|secret|password)\s*[:=]\s*["']?\S{8,}/i.test(value);
21231
+ return /-----BEGIN [A-Z ]*PRIVATE KEY-----|\bBearer\s+\S{8,}|\b(?:sk-(?:proj-)?|AIza|cfat_|apikey_|tlk_|rpa_)[A-Za-z0-9_-]{15,}|\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|(?:api[_ -]?key|access[_ -]?token|secret|password|authorization)\s*[:=]\s*["']?\S{4,}|https?:\/\/[^\s/]+@|[?&](?:key|token|secret|password|signature|X-Amz-Credential|X-Amz-Signature|access_token|api_key)=/i.test(value);
21191
21232
  }
21192
- function validateIntegrationUpdate(providerId, input2) {
21193
- const provider = integrationCatalog.find((entry) => entry.id === providerId);
21194
- if (!provider) throw new Error("Unknown integration provider.");
21233
+ function safeText(value, field, max, required2 = false) {
21234
+ if (value === void 0 && !required2) return void 0;
21235
+ if (typeof value !== "string" || value.length > max || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value) || required2 && !value.trim()) throw new Error(`${field} must be plain text of at most ${max} characters.`);
21236
+ if (containsCredential(value)) throw new Error("Credentials must stay in your provider connection, never in integration preferences.");
21237
+ return value.trim() || void 0;
21238
+ }
21239
+ function capabilities(value, field, required2 = false) {
21240
+ if (value === void 0 && !required2) return void 0;
21241
+ if (!Array.isArray(value) || value.length > integrationCapabilities.length || required2 && !value.length || new Set(value).size !== value.length || value.some((item) => !integrationCapabilities.includes(item))) throw new Error(`Invalid ${field}; use distinct supported integration capabilities.`);
21242
+ return [...value];
21243
+ }
21244
+ function validateIntegrationDefinition(input2) {
21245
+ if (!object6(input2)) throw new Error("Custom integrations require a definition with name, purpose and capabilities.");
21246
+ knownFields(input2, ["name", "purpose", "capabilities"]);
21247
+ return { name: safeText(input2.name, "name", 100, true), purpose: safeText(input2.purpose, "purpose", 600, true), capabilities: capabilities(input2.capabilities, "capabilities", true) };
21248
+ }
21249
+ function integrationProvider(entry) {
21250
+ const known = integrationCatalog.find((provider) => provider.id === entry.providerId);
21251
+ if (known) return known;
21252
+ if (!/^custom-[a-z0-9][a-z0-9-]{0,51}$/.test(entry.providerId) || !entry.definition) return void 0;
21253
+ const definition = validateIntegrationDefinition(entry.definition);
21254
+ return { id: entry.providerId, name: definition.name, description: definition.purpose, capabilities: definition.capabilities, accessMethods: [...integrationAccessMethods], docsUrl: "", custom: true };
21255
+ }
21256
+ function integrationCatalogFor(entries) {
21257
+ return [...integrationCatalog, ...entries.filter((entry) => entry.providerId.startsWith("custom-")).map((entry) => {
21258
+ const provider = integrationProvider(entry);
21259
+ if (!provider) throw new Error("Invalid custom integration definition.");
21260
+ return provider;
21261
+ })];
21262
+ }
21263
+ function validateSettings(provider, input2) {
21195
21264
  if (!object6(input2)) throw new Error("Integration settings must be an object.");
21196
- knownFields(input2, ["enabled", "accessMethod", "preferences", "expectedRevision"]);
21265
+ knownFields(input2, ["enabled", "accessMethod", "preferences", "expectedRevision", "definition", "connection", "preferredFor"]);
21197
21266
  if (typeof input2.enabled !== "boolean") throw new Error("enabled must be a boolean.");
21198
21267
  if (!provider.accessMethods.includes(input2.accessMethod)) throw new Error("Unsupported access method for this provider.");
21199
21268
  if (!Number.isSafeInteger(input2.expectedRevision) || input2.expectedRevision < 0) throw new Error("The current expectedRevision is required.");
@@ -21201,11 +21270,8 @@ function validateIntegrationUpdate(providerId, input2) {
21201
21270
  knownFields(input2.preferences, ["instructions", "model", "voiceId", "language", "musicMode", "spending"]);
21202
21271
  const preferences = {};
21203
21272
  for (const [field, max] of [["instructions", 1e3], ["model", 120], ["voiceId", 120], ["language", 60]]) {
21204
- const value = input2.preferences[field];
21205
- if (value === void 0) continue;
21206
- if (typeof value !== "string" || value.length > max || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(value)) throw new Error(`${field} must be text of at most ${max} characters.`);
21207
- if (containsCredential(value)) throw new Error("Credentials must stay in your provider connection, never in integration preferences.");
21208
- if (value.trim()) preferences[field] = value.trim();
21273
+ const value = safeText(input2.preferences[field], field, max);
21274
+ if (value) preferences[field] = value;
21209
21275
  }
21210
21276
  const musicMode = input2.preferences.musicMode, spending = input2.preferences.spending;
21211
21277
  if (musicMode !== void 0) {
@@ -21215,7 +21281,98 @@ function validateIntegrationUpdate(providerId, input2) {
21215
21281
  if (preferences.voiceId && !provider.capabilities.includes("voiceover")) throw new Error("voiceId is only available for voice integrations.");
21216
21282
  if (spending !== void 0 && !["ask", "use-approved-budget"].includes(spending)) throw new Error("Invalid spending preference.");
21217
21283
  preferences.spending = spending ?? "ask";
21218
- return { enabled: input2.enabled, accessMethod: input2.accessMethod, preferences, expectedRevision: input2.expectedRevision };
21284
+ const result2 = { enabled: input2.enabled, accessMethod: input2.accessMethod, preferences, expectedRevision: input2.expectedRevision };
21285
+ if (provider.custom) result2.definition = validateIntegrationDefinition(input2.definition);
21286
+ else if (input2.definition !== void 0) throw new Error("Catalog integrations keep their official name and capabilities.");
21287
+ if (input2.connection !== void 0) {
21288
+ if (input2.accessMethod !== "agent" || !object6(input2.connection)) throw new Error("Connection metadata is only available for the agent access method.");
21289
+ knownFields(input2.connection, ["method", "host", "name"]);
21290
+ if (!["mcp", "cli", "native"].includes(input2.connection.method) || !["claude", "codex", "other", "any"].includes(input2.connection.host)) throw new Error("Choose a supported connection method and agent host.");
21291
+ const name = safeText(input2.connection.name, "connection name", 80);
21292
+ if (name && !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/.test(name)) throw new Error("Connection name must be a connector or binary identifier, without commands, arguments, paths or URLs.");
21293
+ result2.connection = { method: input2.connection.method, host: input2.connection.host, ...name ? { name } : {} };
21294
+ }
21295
+ const preferredFor = capabilities(input2.preferredFor, "preferredFor");
21296
+ if (preferredFor) {
21297
+ if (preferredFor.some((capability) => !provider.capabilities.includes(capability))) throw new Error("Preferred capabilities must be declared by this integration.");
21298
+ result2.preferredFor = preferredFor;
21299
+ }
21300
+ return result2;
21301
+ }
21302
+ function validateIntegrationUpdate(providerId, input2) {
21303
+ if (typeof providerId !== "string" || providerId.length > 60) throw new Error("Unknown integration provider.");
21304
+ const provider = integrationProvider({ providerId, definition: object6(input2) ? input2.definition : void 0 });
21305
+ if (!provider) throw new Error("Unknown integration provider. Custom IDs need a custom- prefix and a complete definition.");
21306
+ return validateSettings(provider, input2);
21307
+ }
21308
+ function validateIntegrationProfile(input2, options = {}) {
21309
+ if (!object6(input2) || !["member", "connection"].includes(input2.scope) || !Number.isSafeInteger(input2.revision) || input2.revision < 0 || !(input2.updatedAt === null || typeof input2.updatedAt === "string" && input2.updatedAt.length <= 64 && Number.isFinite(Date.parse(input2.updatedAt))) || !Array.isArray(input2.catalog) || input2.catalog.length > integrationCatalog.length + maxCustomIntegrations + 10 || !Array.isArray(input2.entries) || input2.entries.length > integrationCatalog.length + maxCustomIntegrations + 10) throw new Error("Invalid integration profile.");
21310
+ const catalog = [], catalogIds = /* @__PURE__ */ new Set();
21311
+ for (let raw of input2.catalog) {
21312
+ if (options.allowFuture && object6(raw)) {
21313
+ raw = { ...raw, name: raw.name ?? raw.label ?? raw.id, description: raw.description ?? "Provider metadata unavailable.", capabilities: raw.capabilities ?? [], accessMethods: raw.accessMethods ?? [], docsUrl: raw.docsUrl ?? "" };
21314
+ }
21315
+ if (!object6(raw) || typeof raw.id !== "string" || !/^[a-z0-9][a-z0-9-]{0,119}$/.test(raw.id) || catalogIds.has(raw.id) || !Array.isArray(raw.capabilities) || raw.capabilities.length > 16 || !raw.capabilities.every((value) => typeof value === "string" && /^[a-z0-9-]{1,40}$/.test(value)) || !Array.isArray(raw.accessMethods) || !options.allowFuture && !raw.accessMethods.length || raw.accessMethods.length > 16 || !raw.accessMethods.every((value) => typeof value === "string" && /^[a-z0-9-]{1,40}$/.test(value))) throw new Error("Invalid integration catalog.");
21316
+ const name = safeText(raw.name, "name", 100, true), description = safeText(raw.description, "purpose", 600, true);
21317
+ if (typeof raw.docsUrl !== "string" || raw.docsUrl.length > 400 || containsCredential(raw.docsUrl)) throw new Error("Invalid integration documentation URL.");
21318
+ if (raw.docsUrl) {
21319
+ let url3;
21320
+ try {
21321
+ url3 = new URL(raw.docsUrl);
21322
+ } catch {
21323
+ throw new Error("Invalid integration documentation URL.");
21324
+ }
21325
+ if (url3.protocol !== "https:" || url3.username || url3.password || url3.search || url3.hash) throw new Error("Invalid integration documentation URL.");
21326
+ }
21327
+ const provider = { id: raw.id, name, description, capabilities: [...raw.capabilities], accessMethods: [...raw.accessMethods], docsUrl: raw.docsUrl, ...raw.custom === true ? { custom: true } : {} };
21328
+ const official = integrationCatalog.find((value) => value.id === provider.id);
21329
+ if (official && !options.allowFuture && JSON.stringify(provider) !== JSON.stringify(official)) throw new Error("Catalog integration facts do not match the supported provider.");
21330
+ catalog.push(provider);
21331
+ catalogIds.add(provider.id);
21332
+ }
21333
+ const entries = [], entryIds = /* @__PURE__ */ new Set(), preferred = /* @__PURE__ */ new Set();
21334
+ for (const raw of input2.entries) {
21335
+ if (!object6(raw) || typeof raw.providerId !== "string" || !/^[a-z0-9][a-z0-9-]{0,119}$/.test(raw.providerId) || entryIds.has(raw.providerId) || typeof raw.accessMethod !== "string" || !/^[a-z0-9-]{1,40}$/.test(raw.accessMethod)) throw new Error("Invalid or duplicate integration entry.");
21336
+ knownFields(raw, ["providerId", "enabled", "accessMethod", "preferences", "definition", "connection", "preferredFor"]);
21337
+ const suppliedProvider = catalog.find((value) => value.id === raw.providerId);
21338
+ let provider = suppliedProvider;
21339
+ if (options.allowFuture && (!provider || !provider.accessMethods.length)) {
21340
+ const supported = integrationProvider({ providerId: raw.providerId, definition: raw.definition });
21341
+ provider = supported ?? { id: raw.providerId, name: raw.providerId, description: "Provider metadata unavailable.", capabilities: [...integrationCapabilities], accessMethods: [], docsUrl: "" };
21342
+ provider = { ...provider, accessMethods: [raw.accessMethod] };
21343
+ }
21344
+ if (!provider) throw new Error("Integration is missing its catalog definition.");
21345
+ const { providerId, ...settings } = raw;
21346
+ const knownPreferenceFields = ["instructions", "model", "voiceId", "language", "musicMode", "spending"];
21347
+ const futurePreferences = {};
21348
+ if (object6(settings.preferences) && Object.keys(settings.preferences).length > 24) throw new Error("Too many integration preferences.");
21349
+ if (options.allowFuture && object6(settings.preferences)) {
21350
+ for (const [key, value] of Object.entries(settings.preferences)) if (!knownPreferenceFields.includes(key)) {
21351
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,59}$/.test(key) || /(?:credential|password|secret|token|api.?key|authorization)/i.test(key) || !(typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || value === null)) throw new Error("Invalid future integration preference.");
21352
+ if (typeof value === "string") safeText(value, "preference", 1e3);
21353
+ futurePreferences[key] = value;
21354
+ }
21355
+ }
21356
+ const currentPreferences = object6(settings.preferences) ? Object.fromEntries(Object.entries(settings.preferences).filter(([key]) => knownPreferenceFields.includes(key))) : settings.preferences;
21357
+ const normalized2 = validateSettings(provider, { ...settings, preferences: options.allowFuture ? currentPreferences : settings.preferences, expectedRevision: input2.revision });
21358
+ if (options.allowFuture) {
21359
+ normalized2.preferences = { ...futurePreferences, ...normalized2.preferences };
21360
+ if (object6(settings.preferences) && !Object.hasOwn(settings.preferences, "spending")) delete normalized2.preferences.spending;
21361
+ }
21362
+ if (providerId.startsWith("custom-")) {
21363
+ const derived2 = integrationProvider({ providerId, definition: normalized2.definition });
21364
+ if (!derived2 || suppliedProvider && JSON.stringify(derived2) !== JSON.stringify(suppliedProvider)) throw new Error("Custom integration metadata does not match its definition.");
21365
+ } else if (provider.custom) throw new Error("Invalid custom integration identifier.");
21366
+ for (const capability of normalized2.preferredFor ?? []) {
21367
+ if (preferred.has(capability)) throw new Error("Only one preferred integration is allowed per capability.");
21368
+ preferred.add(capability);
21369
+ }
21370
+ const { expectedRevision, ...entry } = normalized2;
21371
+ entries.push({ providerId, ...entry });
21372
+ entryIds.add(providerId);
21373
+ }
21374
+ if (!options.allowFuture && entryIds.size !== catalogIds.size || entries.filter((value) => value.providerId.startsWith("custom-")).length > maxCustomIntegrations) throw new Error("Invalid integration profile size.");
21375
+ return { scope: input2.scope, revision: input2.revision, updatedAt: input2.updatedAt, catalog, entries, executionPolicy: integrationExecutionPolicy, routes: integrationRoutes(entries, catalog), preferredRoutes: preferredIntegrationRoutes(entries, catalog) };
21219
21376
  }
21220
21377
  var integrationExecutionPolicy = {
21221
21378
  version: 1,
@@ -21227,20 +21384,38 @@ var integrationExecutionPolicy = {
21227
21384
  uncertainSubmission: "recover existing provider job before resubmitting or switching",
21228
21385
  unknownBalance: "unknown is not zero; do not claim insufficient credits without evidence"
21229
21386
  };
21230
- function integrationRoutes(entries, catalog = integrationCatalog) {
21387
+ function integrationRoutes(entries, catalog = integrationCatalogFor(entries)) {
21231
21388
  return entries.filter((entry) => entry.enabled).map((entry) => {
21232
21389
  const provider = catalog.find((item) => item.id === entry.providerId);
21233
21390
  return {
21234
21391
  routeId: `integration:${entry.providerId}:${entry.accessMethod}`,
21235
21392
  providerId: entry.providerId,
21393
+ name: provider?.name ?? entry.providerId,
21394
+ ...entry.definition ? { purpose: entry.definition.purpose, capabilitiesDeclared: true } : {},
21236
21395
  accessMethod: entry.accessMethod,
21396
+ ...entry.connection ? { connection: entry.connection } : {},
21237
21397
  capabilities: provider?.capabilities ?? [],
21398
+ ...entry.preferredFor?.length ? { preferredFor: entry.preferredFor } : {},
21399
+ access: "user_declared",
21400
+ verified: false,
21238
21401
  execution: entry.accessMethod === "files" ? "existing-files" : "verify-in-current-session",
21239
21402
  billingScope: entry.accessMethod === "files" ? "no-generation" : entry.providerId === "whisper-local" ? "local-compute" : "host-or-provider",
21240
21403
  requiresEditorBrainCreativeCredits: false
21241
21404
  };
21242
21405
  });
21243
21406
  }
21407
+ function preferredIntegrationRoute(entries, capability, catalog = integrationCatalogFor(entries)) {
21408
+ const entry = entries.find((value) => value.preferredFor?.includes(capability));
21409
+ if (!entry) return { capability, status: "missing", reason: "no_personal_preference", verified: false };
21410
+ const provider = catalog.find((value) => value.id === entry.providerId);
21411
+ if (!provider || !provider.capabilities.includes(capability)) return { capability, status: "missing", reason: "integration_unavailable", providerId: entry.providerId, verified: false };
21412
+ const detail = { capability, providerId: entry.providerId, name: provider.name, ...entry.definition ? { purpose: entry.definition.purpose } : {}, accessMethod: entry.accessMethod, ...entry.connection ? { connection: entry.connection } : {}, verified: false };
21413
+ if (!entry.enabled) return { ...detail, status: "disabled", reason: "preferred_integration_disabled" };
21414
+ return { ...detail, status: "declared", reason: "verify_in_current_session", execution: entry.accessMethod === "files" ? "existing-files" : "verify-in-current-session", requiresEditorBrainCreativeCredits: false };
21415
+ }
21416
+ function preferredIntegrationRoutes(entries, catalog = integrationCatalogFor(entries)) {
21417
+ return integrationCapabilities.filter((capability) => entries.some((entry) => entry.preferredFor?.includes(capability))).map((capability) => preferredIntegrationRoute(entries, capability, catalog));
21418
+ }
21244
21419
 
21245
21420
  // packages/core/src/onboarding-account.ts
21246
21421
  var onboardingReviewOptions = [
@@ -21253,11 +21428,17 @@ function validateOnboardingAccount(value) {
21253
21428
  const input2 = value;
21254
21429
  if (input2.reviewMode !== void 0 && !onboardingReviewOptions.some((v) => v.id === input2.reviewMode)) throw new Error("Modo de revisi\xF3n inv\xE1lido.");
21255
21430
  if (input2.integrations !== void 0) {
21256
- if (!Array.isArray(input2.integrations) || input2.integrations.length > 20 || new Set(input2.integrations.map((v) => v?.providerId)).size !== input2.integrations.length) throw new Error("Integraciones inv\xE1lidas o duplicadas.");
21431
+ if (!Array.isArray(input2.integrations) || input2.integrations.length > integrationCatalog.length + maxCustomIntegrations || new Set(input2.integrations.map((v) => v?.providerId)).size !== input2.integrations.length) throw new Error("Integraciones inv\xE1lidas o duplicadas.");
21432
+ if (input2.integrations.filter((entry) => typeof entry?.providerId === "string" && entry.providerId.startsWith("custom-")).length > maxCustomIntegrations) throw new Error(`Puedes configurar como m\xE1ximo ${maxCustomIntegrations} integraciones personalizadas.`);
21433
+ const preferred = /* @__PURE__ */ new Set();
21257
21434
  for (const entry of input2.integrations) {
21258
- if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some((k) => !["providerId", "enabled", "accessMethod", "preferences"].includes(k))) throw new Error("Integraci\xF3n inv\xE1lida.");
21435
+ if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some((k) => !["providerId", "enabled", "accessMethod", "preferences", "definition", "connection", "preferredFor"].includes(k))) throw new Error("Integraci\xF3n inv\xE1lida.");
21259
21436
  const { providerId, ...settings } = entry;
21260
- validateIntegrationUpdate(providerId, { ...settings, expectedRevision: 0 });
21437
+ const validated = validateIntegrationUpdate(providerId, { ...settings, expectedRevision: 0 });
21438
+ for (const capability of validated.preferredFor ?? []) {
21439
+ if (preferred.has(capability)) throw new Error("Elige una sola integraci\xF3n preferida por capacidad.");
21440
+ preferred.add(capability);
21441
+ }
21261
21442
  }
21262
21443
  }
21263
21444
  return JSON.parse(JSON.stringify(input2));
@@ -21268,7 +21449,7 @@ function onboardingAccountActions(value) {
21268
21449
  status: input2.reviewMode !== void 0 || input2.integrations?.length ? "pending" : "not-requested",
21269
21450
  requested: input2,
21270
21451
  scope: { reviewMode: "workspace", integrations: "authenticated-member-or-connection" },
21271
- instructions: "These are requested account changes, not saved preferences. Authenticate the intended workspace/member. Read workflow get/get_workflow_preferences and integrations list/get_integrations. Compare current values with these choices. Apply only requested differences using workflow set/set_workflow_preferences or integrations set/set_integration with the current expectedRevision; preserve unmentioned providers and merge unmentioned preference fields from the current entry. Stop on a conflict or uncertain write, reread before resuming. Verify persisted values with fresh reads and check_workflow. Never claim account setup complete after document sync alone. Enabling an integration declares access; verify the actual host tool before use and never infer spending authorization.",
21452
+ instructions: "These are requested account changes, not saved preferences. Authenticate the intended workspace/member. Read workflow get/get_workflow_preferences and integrations list/get_integrations. Compare current values with these choices. Apply only requested differences using workflow set/set_workflow_preferences or integrations set/set_integration with the current expectedRevision; preserve unmentioned providers and merge unmentioned preference fields from the current entry. An explicit empty string for model, voiceId, language or instructions clears that text preference; preserve it while merging, then the integration write normalizes it away. Stop on a conflict or uncertain write, reread before resuming. Verify persisted values with fresh reads and check_workflow. Never claim account setup complete after document sync alone. Enabling an integration declares access; verify the actual host tool before use and never infer spending authorization.",
21272
21453
  links: { review: "https://editorbrain.com/app/preferences", integrations: "https://editorbrain.com/app/integrations" }
21273
21454
  };
21274
21455
  }
@@ -21349,16 +21530,17 @@ function resolveCreativeDirection(brand, project, reviewed, questionMode) {
21349
21530
  // packages/core/src/editorial-delivery.ts
21350
21531
  var editorialDeliveryOptions = {
21351
21532
  preferredDuration: ["short", "medium", "long", "extended"],
21352
- narration: ["original", "voiceover", "none"],
21353
- onScreenText: ["minimal", "key-points", "detailed"],
21533
+ narration: ["original", "voiceover", "generated", "none"],
21534
+ preferredOrientation: ["portrait", "landscape", "square"],
21535
+ onScreenText: ["minimal", "key-points", "detailed", "none"],
21354
21536
  broll: ["footage", "stills", "mixed", "none"],
21355
21537
  visualSupport: ["sparse", "balanced", "rich"],
21356
21538
  presenterLayout: ["original", "reframe", "dynamic"],
21357
- captionLanguage: ["source", "brand"],
21539
+ captionLanguage: ["source", "brand", "es", "en", "bilingual"],
21358
21540
  captionTreatment: ["clean", "word-highlight", "karaoke", "boxed"],
21359
- captionPosition: ["lower", "center", "adaptive"],
21360
- ctaGoal: ["adaptive", "follow", "comment", "visit", "contact", "none"],
21361
- ctaTreatment: ["adaptive", "end-card", "overlay", "spoken"]
21541
+ captionPosition: ["lower", "center", "adaptive", "top"],
21542
+ ctaGoal: ["adaptive", "follow", "comment", "visit", "contact", "save", "buy", "none"],
21543
+ ctaTreatment: ["adaptive", "end-card", "overlay", "spoken", "spoken-overlay"]
21362
21544
  };
21363
21545
  function editorialDeliveryIssues(value) {
21364
21546
  if (value === void 0) return [];
@@ -21951,8 +22133,8 @@ function mediaStyleOverrideIssues(value) {
21951
22133
  }
21952
22134
  return issues;
21953
22135
  }
21954
- function resolveMediaPreferences(selections = [], overrides = {}, taste = {}, motionSelection, motionProduction, editorialDelivery, captionsEnabled) {
21955
- const issues = [...mediaStyleSelectionIssues(selections), ...mediaStyleOverrideIssues(overrides), ...visualTasteIssues(taste), ...motionSelectionIssues(motionSelection), ...motionProductionIssues(motionProduction), ...editorialDeliveryIssues(editorialDelivery)];
22136
+ function resolveMediaPreferences(selections = [], overrides = {}, taste = {}, motionSelection, motionProduction, editorialDelivery, captionsEnabled, contentPresence) {
22137
+ const issues = [...mediaStyleSelectionIssues(selections), ...mediaStyleOverrideIssues(overrides), ...visualTasteIssues(taste), ...motionSelectionIssues(motionSelection), ...motionProductionIssues(motionProduction), ...editorialDeliveryIssues(editorialDelivery), ...contentPresenceIssues(contentPresence)];
21956
22138
  if (issues.length) throw new Error(issues.join("\n"));
21957
22139
  const category = (kind3) => {
21958
22140
  const override = overrides[kind3], mode = override?.mode ?? "inherit";
@@ -21964,7 +22146,7 @@ function resolveMediaPreferences(selections = [], overrides = {}, taste = {}, mo
21964
22146
  const motionSelectionSource = motionSelection !== void 0 ? "brand" : effectiveMotionSelection === "guided" && motion2.source !== "unspecified" ? motion2.source : "implicit";
21965
22147
  if (effectiveMotionSelection === "adaptive") motion2.selections = motion2.selections.map((selection) => selection.state === "default" ? { ...selection, state: "favorite" } : selection);
21966
22148
  const delivery = resolveEditorialDelivery(editorialDelivery, captionsEnabled);
21967
- return { schemaVersion: 1, catalog: { id: MEDIA_STYLE_CATALOG.id, version: MEDIA_STYLE_CATALOG.version }, image: category("image"), motion: motion2, motionSelection: effectiveMotionSelection, motionSelectionSource, motionProduction: motionProduction ?? "auto", motionProductionSource: motionProduction === void 0 ? "implicit" : "brand", ...captionsEnabled === void 0 ? {} : { captionsEnabled }, ...Object.keys(delivery).length ? { editorialDelivery: delivery } : {}, taste: { ...taste }, policy: "captionsEnabled is effective when present; false excludes captions even if the stored output profile enables them. Omission is undecided. Current explicit instructions govern. Project overrides define effective choices; disabled categories stay disabled. Required brand tokens govern, never preview palettes/fonts. Favorites are candidates; effective avoid entries always exclude. Adaptive motion chooses per scene or none; saved defaults become candidate favorites. Guided motion starts from saved choices and checks fit. Production auto chooses by scene and verified tools; code prefers complete editable JavaScript scenes, ai prefers generated clips. Keep exact text/data in controlled composition. Production preferences prove neither personal integration access nor model availability, rights or permission to spend. Check the current member\u2019s integrations and session tools; files access alone cannot generate. Taste guides intensity, not tokens or a forced recipe. Soft contrast must retain readable text and visible essential information." + (Object.keys(delivery).length ? " Editorial delivery contains explicit brand preferences only; omitted fields are for the agent to decide. Existing avoid and source restrictions constrain delivery; no-SFX overrides a general preference for effects. Silent music/effects does not silence speech, and no narration does not mute ambience. Text density excludes subtitles; B-roll format does not authorize a source. Disabled captions omit their language, treatment and position from the effective view without erasing saved choices; a chosen appearance cannot enable captions. Presenter layout original keeps position/size; reframe permits gentle full-frame crops; dynamic permits scene-specific panels/masks. Apply only to an existing presenter, never a quota or permission to generate one. Check faces, hands and moving cutout edges. Missing layout leaves the project decision open. Respect framing and safe areas; karaoke needs verified word timing. For enabled captions, explicit output language prevails; otherwise source uses verified speech language and brand uses language.json. CTA goal none excludes every CTA and omits its treatment. Other CTA goals guide each project; confirm final copy, keyword and destination in its brief or direction, never invent them. Spoken CTA grants no new speech or rewriting permission and cannot override no narration. Voiceover authorizes neither cloning nor providers or spending." : "") };
22149
+ return { ...contentPresence ? { contentPresence: structuredClone(contentPresence) } : {}, schemaVersion: 1, catalog: { id: MEDIA_STYLE_CATALOG.id, version: MEDIA_STYLE_CATALOG.version }, image: category("image"), motion: motion2, motionSelection: effectiveMotionSelection, motionSelectionSource, motionProduction: motionProduction ?? "auto", motionProductionSource: motionProduction === void 0 ? "implicit" : "brand", ...captionsEnabled === void 0 ? {} : { captionsEnabled }, ...Object.keys(delivery).length ? { editorialDelivery: delivery } : {}, taste: { ...taste }, policy: "captionsEnabled is effective when present; false excludes captions even if the stored output profile enables them. Omission is undecided. Current explicit instructions govern. Project overrides define effective choices; disabled categories stay disabled. Required brand tokens govern, never preview palettes/fonts. Favorites are candidates; effective avoid entries always exclude. Adaptive motion chooses per scene or none; saved defaults become candidate favorites. Guided motion starts from saved choices and checks fit. Production auto chooses by scene and verified tools; code prefers complete editable JavaScript scenes, ai prefers generated clips. Keep exact text/data in controlled composition. Production preferences prove neither personal integration access nor model availability, rights or permission to spend. Check the current member\u2019s integrations and session tools; files access alone cannot generate. Taste guides intensity, not tokens or a forced recipe. Soft contrast must retain readable text and visible essential information." + (Object.keys(delivery).length ? " Editorial delivery contains explicit brand preferences only; omitted fields are for the agent to decide. Existing avoid and source restrictions constrain delivery; no-SFX overrides a general preference for effects. Silent music/effects does not silence speech, and no narration does not mute ambience. Text density excludes subtitles; B-roll format does not authorize a source. Disabled captions omit their language, treatment and position from the effective view without erasing saved choices; a chosen appearance cannot enable captions. Presenter layout original keeps position/size; reframe permits gentle full-frame crops; dynamic permits scene-specific panels/masks. Apply only to an existing presenter, never a quota or permission to generate one. Check faces, hands and moving cutout edges. Missing layout leaves the project decision open. Respect framing and safe areas; karaoke needs verified word timing. For enabled captions, explicit output language prevails; otherwise source uses verified speech language, brand uses language.json, es/en requests Spanish/English and bilingual requests both Spanish and English subtitles. Verify the transcript and translation separately; requested caption language never changes source-speech metadata or authorizes dubbing. top placement still respects all safe areas. preferredOrientation is only a habit for new projects, never an override of confirmed output dimensions. onScreenText none excludes added graphic text, not captions. CTA goal none excludes every CTA and omits its treatment. Other CTA goals guide each project; confirm final copy, keyword and destination in its brief or direction, never invent them. Spoken CTA grants no new speech or rewriting permission and cannot override no narration. Voiceover and generated narration authorize neither cloning nor providers or spending; generated does not select an available voice. spoken-overlay combines speech and graphic CTA without waiving these limits." : "") + (contentPresence ? " " + contentPresenceGuidance : "") };
21968
22150
  }
21969
22151
 
21970
22152
  // packages/core/src/media-sources.ts
@@ -22004,17 +22186,17 @@ function resolveMediaSources(preferences, legacyAssets, avoid = []) {
22004
22186
 
22005
22187
  // packages/core/src/editorial-profile.ts
22006
22188
  var profileOptions = {
22007
- experience: ["Estoy empezando", "Ya creo videos", "Edito profesionalmente"],
22189
+ experience: ["Estoy empezando", "Ya creo videos", "Edito seguido", "Edito profesionalmente"],
22008
22190
  role: ["Marca personal / creador", "Negocio / equipo de marketing", "Agencia / editor para clientes"],
22009
- platforms: ["Instagram / Reels", "TikTok", "YouTube Shorts", "YouTube", "LinkedIn"],
22191
+ platforms: ["Instagram / Reels", "TikTok", "YouTube Shorts", "YouTube", "LinkedIn", "Facebook", "X"],
22010
22192
  formats: ["A c\xE1mara", "Tutoriales", "Entrevistas", "Vlogs", "Producto / UGC", "Sin aparecer en c\xE1mara", "Grabaci\xF3n de pantalla", "Narrados con im\xE1genes", "Documentales", "Animados"],
22011
22193
  goal: ["Ense\xF1ar", "Generar confianza", "Vender", "Entretener", "Crear comunidad"],
22012
22194
  pace: ["Pausado", "\xC1gil", "Muy din\xE1mico"],
22013
22195
  captions: ["Subt\xEDtulos discretos", "Palabras destacadas", "Sin subt\xEDtulos"],
22014
22196
  sound: ["Voz protagonista", "M\xFAsica discreta", "M\xFAsica y efectos presentes", "Sin m\xFAsica ni efectos"],
22015
- freedom: ["Mantener un estilo consistente", "Explorar seg\xFAn el proyecto"],
22197
+ freedom: ["Mantener un estilo consistente", "Explorar con moderaci\xF3n", "Explorar seg\xFAn el proyecto"],
22016
22198
  assets: ["Solo mi material", "Se puede proponer material de stock", "Se puede proponer material generado"],
22017
- avoid: ["Sin emojis", "Sin transiciones llamativas", "Sin efectos de sonido", "No reescribir mis palabras", "No usar im\xE1genes generadas"],
22199
+ avoid: ["Sin emojis", "Sin transiciones llamativas", "Sin efectos de sonido", "No reescribir mis palabras", "No usar im\xE1genes generadas", "Sin m\xFAsica con letra", "Sin transiciones giratorias", "Sin voz de IA", "Sin stock gen\xE9rico", "Sin texto en may\xFAsculas"],
22018
22200
  aspects: ["Tipograf\xEDa", "Composici\xF3n", "Colores", "Im\xE1genes", "Ritmo", "Animaci\xF3n", "Sonido"]
22019
22201
  };
22020
22202
  var emptyProfile = () => ({ schemaVersion: 1, experience: "", role: "", niche: "", platforms: [], formats: [], goal: "", pace: "", captions: "", sound: "", freedom: "", assets: "", avoid: [], notes: "", references: [] });
@@ -22025,7 +22207,7 @@ function editorialProfileIssues(value) {
22025
22207
  if (!record5(value)) return ["El perfil editorial debe ser un objeto."];
22026
22208
  const issues = [];
22027
22209
  if (value.schemaVersion !== 1) issues.push("schemaVersion del perfil editorial debe ser 1.");
22028
- const fields3 = [...Object.keys(emptyProfile()), "mediaStyles", "visualTaste", "motionSelection", "motionProduction", "editorialDelivery", "mediaSources", "creativeDirection", "creativePreferencesReviewed", "questionMode", "creatorContext", "referenceLinks"];
22210
+ const fields3 = [...Object.keys(emptyProfile()), "mediaStyles", "visualTaste", "motionSelection", "motionProduction", "editorialDelivery", "mediaSources", "creativeDirection", "creativePreferencesReviewed", "questionMode", "creatorContext", "referenceLinks", "contentPresence"];
22029
22211
  if (Object.keys(value).some((key) => !fields3.includes(key))) issues.push("El perfil editorial contiene campos desconocidos.");
22030
22212
  for (const key of ["experience", "role", "goal", "pace", "captions", "sound", "freedom", "assets"]) {
22031
22213
  const selected = value[key];
@@ -22039,7 +22221,7 @@ function editorialProfileIssues(value) {
22039
22221
  else for (const ref of value.references) {
22040
22222
  if (!record5(ref) || !string4(ref.videoId, 1, 150) || !string4(ref.exampleId, 1, 150) || typeof ref.timestampMs !== "number" || !Number.isFinite(ref.timestampMs) || ref.timestampMs < 0 || !["like", "avoid"].includes(String(ref.sentiment)) || !choices(ref.aspects, profileOptions.aspects)) issues.push("Referencia editorial inv\xE1lida.");
22041
22223
  }
22042
- issues.push(...creatorContextIssues(value.creatorContext));
22224
+ issues.push(...creatorContextIssues(value.creatorContext), ...contentPresenceIssues(value.contentPresence));
22043
22225
  if (value.referenceLinks !== void 0 && (!Array.isArray(value.referenceLinks) || value.referenceLinks.length > 5 || new Set(value.referenceLinks).size !== value.referenceLinks.length || value.referenceLinks.some((link9) => {
22044
22226
  try {
22045
22227
  const u = new URL(link9);
@@ -22062,7 +22244,7 @@ function parseEditorialProfile(value) {
22062
22244
  const issues = editorialProfileIssues(value);
22063
22245
  if (issues.length) throw new Error(issues.join("\n"));
22064
22246
  const input2 = value;
22065
- return { ...input2, ...input2.creatorContext ? { creatorContext: { ...input2.creatorContext } } : {}, ...input2.referenceLinks ? { referenceLinks: [...input2.referenceLinks] } : {}, ...input2.creativePreferencesReviewed ? { creativePreferencesReviewed: [...input2.creativePreferencesReviewed] } : {}, experience: input2.experience ?? "", role: input2.role ?? "", platforms: [...input2.platforms], formats: [...input2.formats], avoid: [...input2.avoid], references: input2.references.map((ref) => ({ videoId: ref.videoId, exampleId: ref.exampleId, timestampMs: ref.timestampMs, sentiment: ref.sentiment, aspects: [...ref.aspects] })), ...input2.mediaStyles !== void 0 ? { mediaStyles: input2.mediaStyles.map((selection) => ({ ...selection })) } : {}, ...input2.visualTaste !== void 0 ? { visualTaste: { ...input2.visualTaste } } : {}, ...input2.editorialDelivery !== void 0 ? { editorialDelivery: { ...input2.editorialDelivery } } : {}, ...input2.mediaSources !== void 0 ? { mediaSources: { ...input2.mediaSources, allowed: [...input2.mediaSources.allowed] } } : {} };
22247
+ return { ...input2, ...input2.contentPresence ? { contentPresence: { ...input2.contentPresence, ...input2.contentPresence.secondary ? { secondary: [...input2.contentPresence.secondary] } : {} } } : {}, ...input2.creatorContext ? { creatorContext: { ...input2.creatorContext } } : {}, ...input2.referenceLinks ? { referenceLinks: [...input2.referenceLinks] } : {}, ...input2.creativePreferencesReviewed ? { creativePreferencesReviewed: [...input2.creativePreferencesReviewed] } : {}, experience: input2.experience ?? "", role: input2.role ?? "", platforms: [...input2.platforms], formats: [...input2.formats], avoid: [...input2.avoid], references: input2.references.map((ref) => ({ videoId: ref.videoId, exampleId: ref.exampleId, timestampMs: ref.timestampMs, sentiment: ref.sentiment, aspects: [...ref.aspects] })), ...input2.mediaStyles !== void 0 ? { mediaStyles: input2.mediaStyles.map((selection) => ({ ...selection })) } : {}, ...input2.visualTaste !== void 0 ? { visualTaste: { ...input2.visualTaste } } : {}, ...input2.editorialDelivery !== void 0 ? { editorialDelivery: { ...input2.editorialDelivery } } : {}, ...input2.mediaSources !== void 0 ? { mediaSources: { ...input2.mediaSources, allowed: [...input2.mediaSources.allowed] } } : {} };
22066
22248
  }
22067
22249
  var start = "<!-- editorbrain:editorial-profile:start -->";
22068
22250
  var end = "<!-- editorbrain:editorial-profile:end -->";
@@ -22084,7 +22266,7 @@ function writeProfile(content, input2) {
22084
22266
  const block = `${start}
22085
22267
  ## Perfil editorial confirmado por el usuario
22086
22268
 
22087
- Estas preferencias pertenecen a esta marca. experience regula la explicaci\xF3n y acompa\xF1amiento, nunca la calidad: a principiantes explicar decisiones con ejemplos y lenguaje simple; a profesionales ofrecer control y decisiones precisas sin tutoriales innecesarios. role indica el contexto de trabajo; no mezclar marcas ni preferencias de clientes distintos. creatorContext describe el equipo y su revisi\xF3n editorial; no crea miembros, no autoriza publicar ni comparte preferencias entre clientes. Interpretar solo las respuestas aplicables al rol vigente; las dem\xE1s se conservan para un cambio posterior. Cada cliente tiene su propia marca. referenceLinks son inspiraci\xF3n aportada por el usuario, no evidencia analizada ni permiso para descargar o redistribuir. Comprueba su contenido antes de atribuir t\xE9cnicas. Los campos vac\xEDos est\xE1n por definir; no son autorizaciones. Adapta las preferencias al guion, los recursos y la plataforma del proyecto. Respeta las restricciones de avoid. Los pedidos actuales expl\xEDcitos gobiernan la tarea; conserva las excepciones en el \xE1mbito del proyecto. Los tokens obligatorios de marca siguen en tokens.json y requieren una excepci\xF3n deliberada con motivo para cambiarlos.
22269
+ Estas preferencias pertenecen a esta marca. experience regula la explicaci\xF3n y acompa\xF1amiento, nunca la calidad: a principiantes explicar decisiones con ejemplos y lenguaje simple; a profesionales ofrecer control y decisiones precisas sin tutoriales innecesarios. role indica el contexto de trabajo; no mezclar marcas ni preferencias de clientes distintos. creatorContext describe el equipo y su revisi\xF3n editorial; no crea miembros, no autoriza publicar ni comparte preferencias entre clientes. Interpretar solo las respuestas aplicables al rol vigente; las dem\xE1s se conservan para un cambio posterior. Cada cliente tiene su propia marca. contentPresence describe qui\xE9n suele aparecer (face, voice, ai, others, screen o product) y formatos secundarios; no demuestra qu\xE9 material tiene este proyecto ni autoriza generar personas, avatares, clonar voces, habilitar fuentes o cambiar audio, revisi\xF3n o gasto. Inspeccionar el material actual; ocultar un control no borra sus elecciones. referenceLinks son inspiraci\xF3n aportada por el usuario, no evidencia analizada ni permiso para descargar o redistribuir. Comprueba su contenido antes de atribuir t\xE9cnicas. Los campos vac\xEDos est\xE1n por definir; no son autorizaciones. Adapta las preferencias al guion, los recursos y la plataforma del proyecto. Respeta las restricciones de avoid. Los pedidos actuales expl\xEDcitos gobiernan la tarea; conserva las excepciones en el \xE1mbito del proyecto. Los tokens obligatorios de marca siguen en tokens.json y requieren una excepci\xF3n deliberada con motivo para cambiarlos.
22088
22270
 
22089
22271
  creativeDirection separa qui\xE9n decide del modo de revisi\xF3n: automatic encarga al agente elegir la direcci\xF3n de cada video consultando material y evidencia de la biblioteca de ediciones; guided parte de tus elecciones y resuelve los detalles abiertos. La calidad exigida es la misma. En automatic no exigir un cuestionario de est\xE9tica ni imponer una plantilla; favoritos orientan y las restricciones expl\xEDcitas siguen vigentes. No borrar preferencias ni guardar autom\xE1ticamente las decisiones del proyecto como estilo de marca. Un estilo reutilizable se guarda cuando el usuario lo pide. creativePreferencesReviewed registra \xFAnicamente categor\xEDas revisadas expl\xEDcitamente por el usuario, incluyendo su decisi\xF3n de delegar campos abiertos. No inferir revisiones por valores precargados ni marcarlas al saltar pasos. Con guided expl\xEDcito, completar las categor\xEDas pendientes antes de editar salvo questionMode=autonomous, que delega los detalles abiertos para ese proyecto sin marcar categor\xEDas confirmadas; conservar elecciones previas y no repetir las ya confirmadas. automatic conserva ese registro para un cambio posterior. La ausencia de creativeDirection conserva el comportamiento previo. project.json puede cambiar creativeDirection solo para ese video. No modifica revisi\xF3n, integraciones, gasto ni permisos.
22090
22272
 
@@ -22094,7 +22276,7 @@ Las referencias indican \xFAnicamente los aspectos que gustaron o se quieren evi
22094
22276
 
22095
22277
  mediaStyles guarda selecciones del cat\xE1logo por styleId y version: favorite indica un candidato, default un punto de partida y avoid una exclusi\xF3n. Sin selecci\xF3n no se presupone un estilo. Consulta solo las fichas necesarias por ID y versi\xF3n; las recetas son conceptos adaptables, no calidad probada. El proyecto puede heredar, sustituir o desactivar cada categor\xEDa mediante mediaStyleOverrides. Los colores y fuentes de las muestras no reemplazan tokens.json. motionSelection puede ser adaptive (el agente elige por escena, tambi\xE9n puede no animar) o guided (parte de las elecciones guardadas y comprueba encaje). En adaptive, favoritos y antiguas bases orientan sin obligar; avoid siempre excluye dentro del alcance efectivo. Sin este campo, una base de movimiento previa conserva guided; el resto usa adaptive. Desactivar la categor\xEDa en el proyecto prevalece sobre ambos modos. motionProduction separa la producci\xF3n: auto deja elegir por escena; code prefiere escenas completas editables en JavaScript; ai prefiere clips generados. Su ausencia equivale a auto. El agente verifica herramientas e integraciones del miembro actual; files solo indica material existente. Esta preferencia no acredita acceso a modelos ni autoriza gasto; datos y texto exactos requieren composici\xF3n controlada. visualTaste conserva preferencias opcionales de densidad (minimal/layered), energ\xEDa (calm/lively) y contraste (soft/strong); omitir un campo significa que est\xE1 por decidir. La densidad regula capas simult\xE1neas, no la frecuencia del apoyo visual. Orientan la composici\xF3n e intensidad, sin elegir autom\xE1ticamente una receta ni cambiar la marca. Un contraste suave debe mantener texto legible e informaci\xF3n esencial visible.
22096
22278
 
22097
- editorialDelivery.preferredDuration expresa una duraci\xF3n habitual orientativa: short 15\u201330 s, medium 30\u201360 s, long 1\u20133 min, extended m\xE1s de 3 min. El guion y el encargo prevalecen; no recortar ideas ni palabras para cumplirla. editorialDelivery conserva preferencias opcionales: narration (original conserva la voz aportada; voiceover prefiere narraci\xF3n en off; none omite narraci\xF3n, no el ambiente), onScreenText (minimal/key-points/detailed regula texto gr\xE1fico, no subt\xEDtulos), broll (footage/stills/mixed/none indica formato del apoyo, no su procedencia), visualSupport (sparse/balanced/rich indica la frecuencia del apoyo visual a lo largo del video, no su velocidad ni el n\xFAmero de capas simult\xE1neas; no es una cuota y puede incluir gr\xE1ficos o animaci\xF3n sin B-roll), presenterLayout (original conserva posici\xF3n y tama\xF1o del presentador; reframe permite reencuadres y zooms suaves manteni\xE9ndolo a pantalla completa; dynamic permite alternar pantalla completa, paneles y m\xE1scaras seg\xFAn la escena, sin una cuota de cambios). Solo se aplica si el material contiene una persona: no exige inventar un presentador, eliminar fondos ni generar avatares. Una eliminaci\xF3n de fondo requiere comprobar bordes en movimiento; conservar rostros, manos y zonas seguras. Omitirlo deja decidir por proyecto. No altera la velocidad del habla ni los permisos de medios. captionLanguage (source usa el idioma verificado del habla; brand usa language.json). captionTreatment elige clean (limpios), word-highlight (palabras clave), karaoke (palabra a palabra sincronizada con voz verificada) o boxed (con fondo); captionPosition elige lower, center o adaptive seg\xFAn encuadre y zonas seguras. Sin subt\xEDtulos o captions.enabled=false desactiva idioma, tratamiento y posici\xF3n de subt\xEDtulos en el contexto efectivo, conservando las opciones originales. ctaGoal indica adaptive, follow, comment, visit, contact o none; ctaTreatment indica adaptive, end-card, overlay o spoken. ctaGoal=none desactiva cualquier CTA y su tratamiento efectivo, sin borrar lo guardado. La meta del CTA pertenece a la marca, pero su texto final, palabra clave y destino se confirman para cada proyecto; nunca inventarlos. spoken no autoriza crear voz ni reescribir el habla original y debe respetar narration=none. Omitir un campo deja decidir al agente; adaptive tampoco fija una elecci\xF3n. Los ajustes expl\xEDcitos de salida del proyecto prevalecen, sin habilitar subt\xEDtulos por elegir su apariencia. mediaSources permite combinar own (material propio), web (medios aut\xE9nticos, archivo y capturas encontrados en internet), stock y generated (IA). allowed es la lista completa permitida; preferred prioriza una de ellas. Cuando est\xE1 presente sustituye assets; sin mediaSources, assets conserva su significado previo. avoid sigue excluyendo fuentes prohibidas, incluso si eran preferidas; una lista efectiva vac\xEDa requiere resolver la incompatibilidad, nunca habilitar otras fuentes. web no acredita derechos ni veracidad: comprobar origen, identidad y permisos del recurso. Ninguna fuente autoriza gasto o acceso a proveedores. visualSupport no habilita fuentes excluidas ni cambia broll=none. assets (solo como fallback) y avoid restringen estas preferencias; ante una preferencia general de efectos y Sin efectos de sonido, no a\xF1adir SFX. Sin m\xFAsica ni efectos conserva la voz que corresponda a narration. voiceover no autoriza clonaci\xF3n, proveedores ni gasto. Idioma, dimensiones y duraci\xF3n exacta se consultan en language.json, outputProfile y brief del proyecto. preferredDuration solo orienta el rango habitual.
22279
+ editorialDelivery.preferredDuration expresa una duraci\xF3n habitual orientativa: short 15\u201330 s, medium 30\u201360 s, long 1\u20133 min, extended m\xE1s de 3 min. El guion y el encargo prevalecen; no recortar ideas ni palabras para cumplirla. editorialDelivery conserva preferencias opcionales: narration (original conserva la voz aportada; voiceover prefiere narraci\xF3n en off; generated prefiere voz generada, sin elegir proveedor o voz ni autorizar clonaci\xF3n o gasto; none omite narraci\xF3n, no el ambiente), onScreenText (none excluye texto gr\xE1fico a\xF1adido; minimal/key-points/detailed regula su cantidad, sin cambiar subt\xEDtulos), broll (footage/stills/mixed/none indica formato del apoyo, no su procedencia), visualSupport (sparse/balanced/rich indica la frecuencia del apoyo visual a lo largo del video, no su velocidad ni el n\xFAmero de capas simult\xE1neas; no es una cuota y puede incluir gr\xE1ficos o animaci\xF3n sin B-roll), presenterLayout (original conserva posici\xF3n y tama\xF1o del presentador; reframe permite reencuadres y zooms suaves manteni\xE9ndolo a pantalla completa; dynamic permite alternar pantalla completa, paneles y m\xE1scaras seg\xFAn la escena, sin una cuota de cambios). Solo se aplica si el material contiene una persona: no exige inventar un presentador, eliminar fondos ni generar avatares. Una eliminaci\xF3n de fondo requiere comprobar bordes en movimiento; conservar rostros, manos y zonas seguras. Omitirlo deja decidir por proyecto. No altera la velocidad del habla ni los permisos de medios. preferredOrientation (portrait/landscape/square) orienta nuevos proyectos; nunca modifica outputProfile ni sus dimensiones confirmadas. captionLanguage (source usa el idioma verificado del habla; brand usa language.json; es/en solicita subt\xEDtulos en espa\xF1ol/ingl\xE9s; bilingual solicita espa\xF1ol e ingl\xE9s). El idioma solicitado no cambia el idioma verificado del audio ni autoriza doblaje; traducir requiere texto verificado y conservar su significado. captionTreatment elige clean (limpios), word-highlight (palabras clave), karaoke (palabra a palabra sincronizada con voz verificada) o boxed (con fondo); captionPosition elige top, lower, center o adaptive seg\xFAn encuadre y zonas seguras. Sin subt\xEDtulos o captions.enabled=false desactiva idioma, tratamiento y posici\xF3n de subt\xEDtulos en el contexto efectivo, conservando las opciones originales. ctaGoal indica adaptive, follow, comment, visit, contact, save, buy o none; ctaTreatment indica adaptive, end-card, overlay, spoken o spoken-overlay. ctaGoal=none desactiva cualquier CTA y su tratamiento efectivo, sin borrar lo guardado. La meta del CTA pertenece a la marca, pero su texto final, palabra clave y destino se confirman para cada proyecto; nunca inventarlos. spoken no autoriza crear voz ni reescribir el habla original y debe respetar narration=none. Omitir un campo deja decidir al agente; adaptive tampoco fija una elecci\xF3n. Los ajustes expl\xEDcitos de salida del proyecto prevalecen, sin habilitar subt\xEDtulos por elegir su apariencia. mediaSources permite combinar own (material propio), web (medios aut\xE9nticos, archivo y capturas encontrados en internet), stock y generated (IA). allowed es la lista completa permitida; preferred prioriza una de ellas. Cuando est\xE1 presente sustituye assets; sin mediaSources, assets conserva su significado previo. avoid sigue excluyendo fuentes prohibidas, incluso si eran preferidas; una lista efectiva vac\xEDa requiere resolver la incompatibilidad, nunca habilitar otras fuentes. web no acredita derechos ni veracidad: comprobar origen, identidad y permisos del recurso. Ninguna fuente autoriza gasto o acceso a proveedores. visualSupport no habilita fuentes excluidas ni cambia broll=none. assets (solo como fallback) y avoid restringen estas preferencias; ante una preferencia general de efectos y Sin efectos de sonido, no a\xF1adir SFX. Sin m\xFAsica ni efectos conserva la voz que corresponda a narration. voiceover no autoriza clonaci\xF3n, proveedores ni gasto. Idioma, dimensiones y duraci\xF3n exacta se consultan en language.json, outputProfile y brief del proyecto. preferredDuration solo orienta el rango habitual.
22098
22280
 
22099
22281
  La preferencia de recursos permite proponer, no autoriza gastos ni servicios externos. La modalidad de revisi\xF3n se consulta en las preferencias de trabajo del espacio/proyecto. No inicies renders ni generaciones de pago sin autorizaci\xF3n correspondiente.
22100
22282
 
@@ -22204,19 +22386,32 @@ var localOnboardingSteps = [
22204
22386
  ["Tu cerebro", "As\xED empieza tu cerebro.", "Revisa tus decisiones antes de guardarlas. Puedes modificarlas despu\xE9s."]
22205
22387
  ];
22206
22388
  function getOnboardingGuide(intake) {
22389
+ const consultation = resolveQuestionPolicy(intake?.profile?.questionMode ?? void 0);
22390
+ const direction = intake?.profile?.creativeDirection ?? null;
22391
+ const role2 = intake?.profile?.role;
22392
+ const organizationFields = role2 === "Negocio / equipo de marketing" ? ["teamSize", "approver", "brandManual"] : role2 === "Agencia / editor para clientes" ? ["clientCount", "clientReview", "settingUp"] : [];
22207
22393
  return {
22208
22394
  schemaVersion: 1,
22395
+ journey: {
22396
+ chapters: ["T\xFA", "Tu marca", "C\xF3mo editas", "Listo"],
22397
+ adaptive: true,
22398
+ creativeDirection: direction,
22399
+ aestheticQuestions: consultation.mode === "autonomous" ? "do-not-ask" : direction === "automatic" ? "only-when-requested" : "only-pending-or-requested",
22400
+ organizationFields: organizationFields.map((field) => `profile.creatorContext.${field}`),
22401
+ rule: "Chapters describe presentation, not a mandatory questionnaire or a new workflow state. Use configuration.pending and saved choices to resume. Preserve earlier answers and confirmations; role-specific questions apply only to that role. Automatic direction skips optional aesthetic selection, never identity, limits, review or permissions. Autonomous consultation asks none and does not mark categories reviewed."
22402
+ },
22209
22403
  questions: {
22210
22404
  rule: "Same saved choices across web, local HTML and chat. Do not ask every optional field. Read existing choices first; apply consultation and creative direction. Empty or omitted fields are not confirmations or permission. Account selections stay pending until authenticated writes are verified.",
22211
22405
  groups: [
22212
- { id: "content", title: "Tu contenido", fields: ["profile.creativeDirection", "profile.questionMode", "identity.name", "identity.description", "identity.audience", "identity.tone", "identity.links", "language.defaultLanguage", "profile.niche", "profile.experience", "profile.role", "profile.platforms", "profile.formats", "profile.goal", "profile.creatorContext"] },
22406
+ { id: "content", title: "Tu contenido", fields: ["profile.creativeDirection", "profile.questionMode", "identity.name", "identity.description", "identity.audience", "identity.tone", "identity.links", "language.defaultLanguage", "profile.niche", "profile.experience", "profile.role", "profile.platforms", "profile.formats", "profile.goal", "profile.creatorContext", "profile.contentPresence"] },
22213
22407
  { id: "brand", title: "Tu marca", fields: ["tokens.color.background", "tokens.color.text", "tokens.color.accent", "tokens.typography.heading", "tokens.typography.body", "tokens.*.strength", "profile.freedom"] },
22214
22408
  { id: "taste", title: "Tus gustos", fields: ["taste.favorites", "profile.mediaStyles", "profile.visualTaste", "profile.motionSelection", "profile.motionProduction"] },
22215
22409
  { id: "editing", title: "Tu edici\xF3n", fields: ["taste.hook", "taste.hookIntensity", "taste.noAbruptZooms", "profile.pace", "profile.captions", "profile.editorialDelivery", "profile.mediaSources", "profile.avoid", "profile.notes", "profile.referenceLinks"] },
22216
- { id: "sound", title: "Tu sonido", fields: ["audio.music.intensity", "audio.sfx.density", "audio.sfx.character", "audio.sfx.hookWithoutEffects"] },
22410
+ { id: "sound", title: "Tu sonido", fields: ["audio.music.intensity", "audio.music.character", "audio.sfx.hookTreatment", "audio.sfx.density", "audio.sfx.character", "audio.sfx.hookWithoutEffects"] },
22217
22411
  { id: "account", title: "Tu cuenta", fields: ["accountSetup.reviewMode", "accountSetup.integrations"], scope: "Separate workspace review / personal integrations. Not brand files. Read current account state before applying requested differences with CAS." }
22218
22412
  ],
22219
22413
  options: {
22414
+ contentPresence: contentPresenceOptions,
22220
22415
  creatorContext: creatorContextOptions,
22221
22416
  profile: profileOptions,
22222
22417
  delivery: editorialDeliveryOptions,
@@ -22231,23 +22426,31 @@ function getOnboardingGuide(intake) {
22231
22426
  motionProduction: motionProductionOptions,
22232
22427
  mediaStyles: { state: mediaStyleStateOptions, selection: { styleId: "ID returned by list_media_styles", version: "Exact version returned with that ID", state: "One of the listed states" }, limit: 24, defaultsPerCategory: 1 },
22233
22428
  mediaSources: { allowed: mediaSourceOptions, preferred: mediaSourceOptions, rule: "allowed is a nonempty list of unique sources; preferred must be in allowed. These choices do not authorize spending." },
22234
- audio: { music: { intensity: audioProductionOptions.musicIntensity }, sfx: { density: audioProductionOptions.sfxDensity, character: audioProductionOptions.sfxCharacter, hookWithoutEffects: [true, false] } }
22429
+ audio: { music: { intensity: audioProductionOptions.musicIntensity, character: audioProductionOptions.musicCharacter }, sfx: { hookTreatment: audioProductionOptions.hookTreatment, density: audioProductionOptions.sfxDensity, character: audioProductionOptions.sfxCharacter, hookWithoutEffects: [true, false] } }
22235
22430
  },
22236
22431
  updates: "Omit a field to preserve its value. Use null to clear an optional profile field, an individual visualTaste/editorialDelivery field, a token, defaultLanguage or an audio preference. Use an empty string/list to clear an ordinary profile or identity field; identity.name must remain nonempty. Clearing is not disabling: use audio none, captions Sin subt\xEDtulos or ctaGoal none to exclude them. A new brand requires identity.name and identity.description.",
22237
22432
  visualCatalog: "Use list_media_styles/get_media_style for the same image and animation choices as web. Product demos orient taste; inspect the edited-video library before editing.",
22433
+ contentPresence: contentPresenceGuidance,
22434
+ delivery: "preferredOrientation only guides a new project; confirmed outputProfile dimensions win. captionLanguage es/en/bilingual requests caption translation, never claims source speech language or changes narration. generated narration requests a technique, not a voice/provider, access, cloning consent or spending. CTA text, destination and closing clip remain project decisions. Music character and opening SFX are preferences, never sound evidence or generation authorization. Existing no-effects restrictions take precedence.",
22238
22435
  advanced: "Existing references, pronunciation/glossary, assets and detailed audio/tool settings are preserved. They are not required onboarding questions. Configure with their dedicated editors/tools when requested.",
22436
+ account: {
22437
+ reviewMode: { scope: "workspace", read: "get_workflow_preferences", write: "set_workflow_preferences", rule: "Use the saved mode and expectedRevision. An explicit project exception still takes precedence when editing." },
22438
+ integrations: { scope: "authenticated-member-in-workspace", read: "get_integrations", write: "set_integration", custom: { id: "custom-<slug>", fields: ["definition.name", "definition.purpose", "definition.capabilities", "accessMethod", "connection", "preferredFor", "preferences"], capabilities: integrationCapabilities, limit: maxCustomIntegrations }, rule: "Use the current personal catalog, including custom tools. At most one preferred integration per capability. No credentials or installation; enabled is declared access and the agent verifies the actual session." },
22439
+ persistence: "accountSetup is a requested change, not saved account state. Keep accountActions until authenticated writes and fresh reads confirm them. Do not copy personal integrations into brand documents or infer success from onboarding sync."
22440
+ },
22239
22441
  glossary: { optional: true, blocking: false, fields: ["language.glossary", "language.doNotTranslate"], suggestion: "Optional, never required for readiness: if the content names products, tools or people that speech recognition may misspell, offer once to list their exact spelling. Tempo sends these brand terms as transcription key terms. Skip in autonomous question mode; send the complete list, keeping existing entries." }
22240
22442
  },
22241
22443
  interactionPreview: { ...editingInteraction(intake?.profile?.questionMode ?? void 0, intake?.accountSetup?.reviewMode), basis: "draft-not-saved" },
22242
- consultation: { options: questionModeOptions, field: "profile.questionMode", ...resolveQuestionPolicy(intake?.profile?.questionMode ?? void 0) },
22444
+ consultation: { options: questionModeOptions, field: "profile.questionMode", ...consultation },
22243
22445
  ...intake ? { current: intake, configuration: creativeConfiguration(intake.profile?.creativeDirection ?? void 0, intake.profile?.creativePreferencesReviewed ?? void 0) } : {},
22244
- creativePreferences: { modes: creativeDirectionOptions, sections: creativePreferenceSections, confirmationField: "profile.creativePreferencesReviewed", rule: "Marca una categor\xEDa solo despu\xE9s de que el usuario confirme sus elecciones o decida delegarlas. Los campos precargados y saltar pasos no son confirmaci\xF3n. Al cambiar a guided, completa las categor\xEDas pendientes antes de editar salvo questionMode=autonomous: delega los detalles abiertos por proyecto sin marcar categor\xEDas revisadas; conserva las ya revisadas y todos los valores previos." },
22245
- web: { url: "https://editorbrain.com/app/onboarding", description: "Recorrido visual completo: preferencias, integraciones personales y conexi\xF3n con tu agente. Requiere tu sesi\xF3n web y elegir el espacio correcto." },
22446
+ creativePreferences: { modes: creativeDirectionOptions, sections: creativePreferenceSections, confirmationField: "profile.creativePreferencesReviewed", rule: "Delegar una secci\xF3n elimina solo sus elecciones est\xE9ticas expl\xEDcitamente liberadas (null/cadenas vac\xEDas), conserva l\xEDmites, fuentes, voces, revisi\xF3n y permisos, y confirma la categor\xEDa cuando corresponda. Cambiar a automatic conserva todas las elecciones guardadas. Marca una categor\xEDa solo despu\xE9s de que el usuario confirme sus elecciones o decida delegarlas. Los campos precargados y saltar pasos no son confirmaci\xF3n. Al cambiar a guided, completa las categor\xEDas pendientes antes de editar salvo questionMode=autonomous: delega los detalles abiertos por proyecto sin marcar categor\xEDas revisadas; conserva las ya revisadas y todos los valores previos." },
22447
+ web: { url: "https://editorbrain.com/app/onboarding", description: "Recorrido visual en cuatro cap\xEDtulos con pasos adaptativos: preferencias, integraciones personales y conexi\xF3n con tu agente. Requiere tu sesi\xF3n web y elegir el espacio correcto." },
22246
22448
  local: {
22247
22449
  description: "Edici\xF3n local de preferencias en seis grupos, con el dise\xF1o del estudio. Funciona sin cuenta; recoge las mismas preferencias editoriales y las solicitudes de configuraci\xF3n de cuenta. No simula conexiones ni an\xE1lisis de IA.",
22248
22450
  steps: localOnboardingSteps.map(([label]) => label),
22249
22451
  commands: ["editorbrain onboarding create --brand <brand-id> --project <new-project-id> --dir <folder>", "editorbrain onboarding serve --session <returned-session> --dir <folder>"],
22250
- completion: "Lee las respuestas; valida y aplica con onboarding apply. Sincroniza expl\xEDcitamente con onboarding sync despu\xE9s de autenticarte. Conserva versiones y resuelve conflictos; nunca sobrescribas una marca existente para completar el onboarding."
22452
+ completion: "Lee las respuestas; valida y aplica con onboarding apply. Sincroniza expl\xEDcitamente con onboarding sync despu\xE9s de autenticarte. Conserva versiones y resuelve conflictos; nunca sobrescribas una marca existente para completar el onboarding.",
22453
+ resume: "Conserva la sesi\xF3n original. onboarding serve --session <session> --dir <folder> retoma su borrador local; para importar las respuestas descargadas usa --file <draft-relative-path>. Importar o guardar un borrador no aplica preferencias ni las sincroniza. Si la marca cambi\xF3 mientras tanto, conserva las respuestas y revisa el conflicto antes de aplicar."
22251
22454
  },
22252
22455
  agent: [
22253
22456
  "Ofrece web, artefacto local o configuraci\xF3n conversacional seg\xFAn el entorno del usuario; no le pidas repetir sus respuestas en otra superficie.",
@@ -22465,7 +22668,7 @@ function validDocument(path, content) {
22465
22668
  if (!result2.valid) throw new Error(result2.issues.map((issue3) => `${issue3.path}: ${issue3.message}`).join("\n"));
22466
22669
  }
22467
22670
  var clone2 = (value) => JSON.parse(JSON.stringify(value));
22468
- var optionalProfileKeys = ["mediaStyles", "visualTaste", "motionSelection", "motionProduction", "editorialDelivery", "mediaSources", "creativeDirection", "creativePreferencesReviewed", "questionMode", "creatorContext", "referenceLinks"];
22671
+ var optionalProfileKeys = ["mediaStyles", "visualTaste", "motionSelection", "motionProduction", "editorialDelivery", "mediaSources", "creativeDirection", "creativePreferencesReviewed", "questionMode", "creatorContext", "referenceLinks", "contentPresence"];
22469
22672
  function mergeProfile(base, patch) {
22470
22673
  const result2 = { ...base };
22471
22674
  record6(patch, "profile", [...Object.keys(emptyProfile()).filter((key) => key !== "schemaVersion"), ...optionalProfileKeys]);
@@ -22479,6 +22682,11 @@ function mergeProfile(base, patch) {
22479
22682
  const issues = creativePreferencesReviewedIssues(value);
22480
22683
  if (issues.length) throw new Error(issues.join("\n"));
22481
22684
  result2[key] = [.../* @__PURE__ */ new Set([...base.creativePreferencesReviewed ?? [], ...value])];
22685
+ } else if (key === "contentPresence") {
22686
+ const fields3 = record6(value, key, ["primary", "secondary"]);
22687
+ const next = { ...object8(result2[key]) ? result2[key] : {}, ...fields3 };
22688
+ if (fields3.secondary === void 0 && Array.isArray(next.secondary)) next.secondary = next.secondary.filter((id4) => id4 !== next.primary);
22689
+ result2[key] = next;
22482
22690
  } else if (key === "creatorContext") {
22483
22691
  const fields3 = record6(value, key, Object.keys(creatorContextOptions));
22484
22692
  result2[key] = { ...object8(result2[key]) ? result2[key] : {}, ...fields3 };
@@ -22674,7 +22882,7 @@ function projectNarrationOverrideIssues(value) {
22674
22882
  const input2 = value;
22675
22883
  const issues = [];
22676
22884
  for (const key of Object.keys(input2)) if (!["value", "reason"].includes(key)) issues.push(`narrationOverride.${key} is unsupported; use value and reason only.`);
22677
- if (typeof input2.value !== "string" || !editorialDeliveryOptions.narration.includes(input2.value)) issues.push("narrationOverride.value must be original, voiceover or none.");
22885
+ if (typeof input2.value !== "string" || !editorialDeliveryOptions.narration.includes(input2.value)) issues.push("narrationOverride.value must be original, voiceover, generated or none.");
22678
22886
  if (typeof input2.reason !== "string" || input2.reason.trim().length < 10 || input2.reason.length > 500) issues.push("narrationOverride.reason must explain this project exception in 10\u2013500 characters.");
22679
22887
  return issues;
22680
22888
  }
@@ -202209,7 +202417,7 @@ function parseReviewTranscript(value) {
202209
202417
  const fail4 = () => {
202210
202418
  throw new Error("Invalid review transcript: use schemaVersion 1, durationMs and up to 200 unique timed phrases. Kept phrases use sample times; removed phrases require source times only.");
202211
202419
  };
202212
- const object21 = (v, keys4) => {
202420
+ const object20 = (v, keys4) => {
202213
202421
  if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).some((k) => !keys4.includes(k))) fail4();
202214
202422
  return v;
202215
202423
  };
@@ -202217,13 +202425,13 @@ function parseReviewTranscript(value) {
202217
202425
  if (!Number.isSafeInteger(v) || v < 0 || v > 36e6) fail4();
202218
202426
  return v;
202219
202427
  };
202220
- const root = object21(value, ["schemaVersion", "durationMs", "segments"]);
202428
+ const root = object20(value, ["schemaVersion", "durationMs", "segments"]);
202221
202429
  if (root.schemaVersion !== 1 || !Array.isArray(root.segments) || root.segments.length > 200) fail4();
202222
202430
  const durationMs = ms2(root.durationMs);
202223
202431
  if (!durationMs) fail4();
202224
202432
  const ids2 = /* @__PURE__ */ new Set();
202225
202433
  const segments = root.segments.map((v) => {
202226
- const s = object21(v, ["id", "text", "state", "startMs", "endMs", "source", "words"]);
202434
+ const s = object20(v, ["id", "text", "state", "startMs", "endMs", "source", "words"]);
202227
202435
  if (typeof s.id !== "string" || !/^[a-zA-Z0-9_-]{1,80}$/.test(s.id) || ids2.has(s.id) || typeof s.text !== "string" || !s.text.trim() || s.text.length > 500 || !["kept", "removed"].includes(s.state)) fail4();
202228
202436
  const id4 = s.id;
202229
202437
  ids2.add(id4);
@@ -202234,7 +202442,7 @@ function parseReviewTranscript(value) {
202234
202442
  if (segment2.endMs <= segment2.startMs || segment2.endMs > durationMs) fail4();
202235
202443
  } else if (s.startMs !== void 0 || s.endMs !== void 0 || !s.source) fail4();
202236
202444
  if (s.source !== void 0) {
202237
- const source2 = object21(s.source, ["assetId", "startMs", "endMs"]);
202445
+ const source2 = object20(s.source, ["assetId", "startMs", "endMs"]);
202238
202446
  if (typeof source2.assetId !== "string" || !/^[a-f0-9]{64}$/.test(source2.assetId)) fail4();
202239
202447
  segment2.source = { assetId: source2.assetId, startMs: ms2(source2.startMs), endMs: ms2(source2.endMs) };
202240
202448
  if (segment2.source.endMs <= segment2.source.startMs) fail4();
@@ -202243,7 +202451,7 @@ function parseReviewTranscript(value) {
202243
202451
  if (segment2.state !== "kept" || !Array.isArray(s.words) || s.words.length > 100) fail4();
202244
202452
  let previous = segment2.startMs;
202245
202453
  segment2.words = s.words.map((v2) => {
202246
- const w = object21(v2, ["text", "startMs", "endMs"]);
202454
+ const w = object20(v2, ["text", "startMs", "endMs"]);
202247
202455
  const startMs = ms2(w.startMs), endMs = ms2(w.endMs);
202248
202456
  if (typeof w.text !== "string" || !w.text.trim() || w.text.length > 100 || startMs < previous || endMs <= startMs || endMs > segment2.endMs) fail4();
202249
202457
  previous = endMs;
@@ -202660,8 +202868,8 @@ function pick2(value, keys4) {
202660
202868
  }
202661
202869
  function canonical(value) {
202662
202870
  return JSON.stringify(value, (_key, item) => {
202663
- const object21 = record12(item);
202664
- return object21 ? Object.fromEntries(Object.keys(object21).sort().map((key) => [key, object21[key]])) : item;
202871
+ const object20 = record12(item);
202872
+ return object20 ? Object.fromEntries(Object.keys(object20).sort().map((key) => [key, object20[key]])) : item;
202665
202873
  }) ?? "undefined";
202666
202874
  }
202667
202875
  var sameJson = (first, second) => canonical(first) === canonical(second);
@@ -203626,7 +203834,7 @@ var USER_GUIDES = [
203626
203834
  "id": "creditos",
203627
203835
  "title": "Qu\xE9 gasta cr\xE9ditos y d\xF3nde ves tu saldo",
203628
203836
  "category": "Cuenta y archivos",
203629
- "summary": "Las herramientas IA y EditorBrain Render pueden consumir cr\xE9ditos. Consulta la cotizaci\xF3n vigente; las preferencias de nube y el presupuesto autorizado determinan qu\xE9 puede ejecutar tu agente.",
203837
+ "summary": "Las herramientas IA disponibles pueden consumir cr\xE9ditos. Consulta la cotizaci\xF3n vigente y autoriza el presupuesto antes de ejecutar.",
203630
203838
  "aliases": [
203631
203839
  "cr\xE9ditos",
203632
203840
  "saldo",
@@ -203649,7 +203857,7 @@ var USER_GUIDES = [
203649
203857
  "id": "donde-quedan-tus-archivos",
203650
203858
  "title": "D\xF3nde quedan tus videos y archivos",
203651
203859
  "category": "Cuenta y archivos",
203652
- "summary": "Tus preferencias determinan si los resultados se conservan en tu computadora, en la nube o en ambos destinos. EditorBrain Render y Storage est\xE1n en beta para los planes habilitados.",
203860
+ "summary": "Los documentos del proyecto y sus medios son cosas distintas. Comprueba qu\xE9 archivos siguen en tu computadora y cu\xE1les registraste para revisarlos en la web.",
203653
203861
  "aliases": [
203654
203862
  "d\xF3nde est\xE1 mi video",
203655
203863
  "d\xF3nde se guarda",
@@ -203801,6 +204009,17 @@ function tutorials(...ids2) {
203801
204009
  }
203802
204010
  var PUBLIC_TASK_CATALOG_VERSION = 1;
203803
204011
  var PUBLIC_TASK_ROUTES = [
204012
+ {
204013
+ id: "onboarding",
204014
+ tutorials: tutorials("bienvenida-editorbrain", "configura-tu-marca", "tus-herramientas"),
204015
+ title: "Configurar tu marca y preferencias",
204016
+ summary: "Empezar o retomar la configuraci\xF3n visual o conversacional, conservando las decisiones guardadas.",
204017
+ aliases: ["onboarding", "setup", "configurar", "configuracion-inicial", "configurar-marca"],
204018
+ cli: ["onboarding guide", "onboarding status", "onboarding create", "onboarding serve", "onboarding apply", "onboarding sync"],
204019
+ mcp: ["get_onboarding_guide", "plan_onboarding_update", "write_document", "get_workflow_preferences", "set_workflow_preferences", "get_integrations", "set_integration"],
204020
+ guides: ["references/onboarding.md", "references/integrations.md"],
204021
+ notes: ["Lee lo guardado y configura s\xF3lo lo pendiente o solicitado. La direcci\xF3n autom\xE1tica conserva l\xEDmites, revisi\xF3n, permisos y preferencias existentes.", "La marca se guarda en documentos; revisi\xF3n e integraciones tienen \xE1mbitos y revisiones de cuenta separados. Sincronizar documentos no conecta herramientas ni completa acciones pendientes.", "El artefacto local requiere un host con archivos y navegador. MCP puede configurar por chat o dirigir a la web sin instalar el CLI."]
204022
+ },
203804
204023
  {
203805
204024
  id: "start",
203806
204025
  tutorials: tutorials("bienvenida-editorbrain", "empieza-un-proyecto", "sube-desde-el-telefono"),
@@ -203872,7 +204091,7 @@ var PUBLIC_TASK_ROUTES = [
203872
204091
  tutorials: tutorials("tus-herramientas", "conecta-tu-agente"),
203873
204092
  title: "Usar herramientas propias",
203874
204093
  summary: "Comprobar herramientas declaradas y acceso real del agente para esta tarea.",
203875
- aliases: ["herramientas", "herramientas-propias", "integraciones", "mis-herramientas"],
204094
+ aliases: ["herramientas", "herramientas-propias", "integraciones", "mis-herramientas", "higgsfield", "integracion-personalizada", "mcp-externo", "cli-externo"],
203876
204095
  cli: ["integrations catalog", "integrations list"],
203877
204096
  mcp: ["get_integrations"],
203878
204097
  guides: ["references/integrations.md", "references/studio.md#transcription-route"],
@@ -205503,11 +205722,18 @@ function studioPreferences(snapshot) {
205503
205722
  const labels = { "typography.heading": "Tipograf\xEDa de t\xEDtulos", "typography.body": "Tipograf\xEDa de texto", "color.background": "Color de fondo", "color.text": "Color de texto", "color.accent": "Color de acento", font_family: "Tipograf\xEDa", font_heading: "Tipograf\xEDa de t\xEDtulos", font_body: "Tipograf\xEDa de texto", primary_color: "Color principal", accent_color: "Color de acento", captionTreatment: "Subt\xEDtulos", caption_treatment: "Subt\xEDtulos", editing_pace: "Ritmo" };
205504
205723
  for (const [key, value] of Object.entries(snapshot.tokens).slice(0, 24)) add("tokens." + key, /font|typography|color|palette/.test(key) ? "brand" : "appearance", labels[key] ?? key.replace(/[_\.]/g, " "), value);
205505
205724
  const delivery = snapshot.mediaPreferences.editorialDelivery;
205725
+ add("mediaPreferences.contentPresence.primary", "appearance", "Qui\xE9n aparece", snapshot.mediaPreferences.contentPresence?.primary, [["face", "Yo, a c\xE1mara"], ["voice", "Sin cara, con mi voz"], ["ai", "Sin cara, con voz de IA"], ["others", "Otras personas"], ["screen", "Grabaci\xF3n de pantalla"], ["product", "Producto o manos"]]);
205726
+ add("mediaPreferences.editorialDelivery.preferredOrientation", "appearance", "Formato habitual", delivery?.preferredOrientation, [["portrait", "Vertical"], ["landscape", "Horizontal"], ["square", "Cuadrado"]]);
205727
+ add("mediaPreferences.editorialDelivery.narration", "audio", "Tipo de narraci\xF3n", delivery?.narration, [["original", "Voz grabada"], ["voiceover", "Voz en off"], ["generated", "Preferir voz de IA"], ["none", "Sin narraci\xF3n"]]);
205728
+ add("mediaPreferences.editorialDelivery.captionLanguage", "appearance", "Idioma de subt\xEDtulos", delivery?.captionLanguage, [["source", "El del audio"], ["brand", "El de la marca"], ["es", "Espa\xF1ol"], ["en", "Ingl\xE9s"], ["bilingual", "Espa\xF1ol e ingl\xE9s"]]);
205729
+ add("mediaPreferences.editorialDelivery.ctaTreatment", "appearance", "Presentaci\xF3n del cierre", delivery?.ctaTreatment, [["adaptive", "Que la IA decida"], ["end-card", "Escena final"], ["overlay", "Texto"], ["spoken", "Hablado"], ["spoken-overlay", "Voz y texto"]]);
205730
+ add("audioProduction.music.character", "audio", "Car\xE1cter de m\xFAsica", snapshot.audioProduction?.music?.character, [["warm", "C\xE1lido"], ["clean", "Limpio"], ["energetic", "Con energ\xEDa"], ["cinematic", "Cinematogr\xE1fico"]]);
205731
+ add("audioProduction.sfx.hookTreatment", "audio", "Efecto al abrir", snapshot.audioProduction?.sfx?.hookTreatment, [["none", "Ninguno"], ["soft", "Suave"], ["marked", "Marcado"]]);
205506
205732
  add("mediaPreferences.captionsEnabled", "appearance", "Mostrar subt\xEDtulos", snapshot.mediaPreferences.captionsEnabled, [["true", "S\xED"], ["false", "No"]]);
205507
205733
  add("mediaPreferences.editorialDelivery.captionTreatment", "appearance", "Tipo de subt\xEDtulos", delivery?.captionTreatment, [["clean", "Limpios"], ["word-highlight", "Palabras clave"], ["karaoke", "Palabra a palabra"], ["boxed", "Con fondo"]]);
205508
- add("mediaPreferences.editorialDelivery.captionPosition", "appearance", "Posici\xF3n de subt\xEDtulos", delivery?.captionPosition, [["lower", "Abajo"], ["center", "Centro"], ["adaptive", "Que la IA decida por escena"]]);
205509
- add("mediaPreferences.editorialDelivery.onScreenText", "appearance", "Texto en pantalla", delivery?.onScreenText, [["minimal", "M\xEDnimo"], ["key-points", "Ideas clave"], ["detailed", "Detallado"]]);
205510
- add("mediaPreferences.editorialDelivery.ctaGoal", "appearance", "Objetivo del cierre", delivery?.ctaGoal, [["adaptive", "Que la IA decida"], ["follow", "Seguir"], ["comment", "Comentar"], ["visit", "Visitar"], ["contact", "Contactar"], ["none", "Sin llamada a la acci\xF3n"]]);
205734
+ add("mediaPreferences.editorialDelivery.captionPosition", "appearance", "Posici\xF3n de subt\xEDtulos", delivery?.captionPosition, [["top", "Arriba"], ["lower", "Abajo"], ["center", "Centro"], ["adaptive", "Que la IA decida por escena"]]);
205735
+ add("mediaPreferences.editorialDelivery.onScreenText", "appearance", "Texto en pantalla", delivery?.onScreenText, [["none", "Ninguno"], ["minimal", "M\xEDnimo"], ["key-points", "Ideas clave"], ["detailed", "Detallado"]]);
205736
+ add("mediaPreferences.editorialDelivery.ctaGoal", "appearance", "Objetivo del cierre", delivery?.ctaGoal, [["adaptive", "Que la IA decida"], ["follow", "Seguir"], ["comment", "Comentar"], ["visit", "Visitar"], ["contact", "Contactar"], ["save", "Guardar"], ["buy", "Comprar"], ["none", "Sin llamada a la acci\xF3n"]]);
205511
205737
  add("mediaPreferences.editorialDelivery.presenterLayout", "appearance", "Tu encuadre", delivery?.presenterLayout, [["original", "Conservarlo"], ["reframe", "Reencuadres suaves"], ["dynamic", "Variar por escena"]]);
205512
205738
  add("creativeDirection.mode", "appearance", "Direcci\xF3n creativa", snapshot.creativeDirection.mode, [["automatic", "Que la IA decida"], ["guided", "Usar mis preferencias"]]);
205513
205739
  add("audioProduction.music.intensity", "audio", "M\xFAsica", snapshot.audioProduction?.music?.intensity, [["none", "Sin m\xFAsica"], ["subtle", "Sutil"], ["present", "Presente"]]);
@@ -205855,7 +206081,7 @@ async function resolveProject(files, projectId) {
205855
206081
  warnings.push(...audio.warnings);
205856
206082
  const sources = resolveMediaSources(editorialProfile.mediaSources, editorialProfile.assets, editorialProfile.avoid);
205857
206083
  if (sources?.allowed?.length === 0) warnings.push("No visual media source remains allowed after editorial restrictions. Resolve the conflict before sourcing; do not fall back to another source.");
205858
- const mediaPreferences = { ...resolveMediaPreferences(editorialProfile.mediaStyles, project.mediaStyleOverrides, editorialProfile.visualTaste, editorialProfile.motionSelection, editorialProfile.motionProduction, editorialProfile.editorialDelivery, editorialProfile.captions === "Sin subt\xEDtulos" ? false : output3.captions?.enabled ?? (editorialProfile.captions ? true : void 0)), ...sources ? { sources } : {} };
206084
+ const mediaPreferences = { ...resolveMediaPreferences(editorialProfile.mediaStyles, project.mediaStyleOverrides, editorialProfile.visualTaste, editorialProfile.motionSelection, editorialProfile.motionProduction, editorialProfile.editorialDelivery, editorialProfile.captions === "Sin subt\xEDtulos" ? false : output3.captions?.enabled ?? (editorialProfile.captions ? true : void 0), editorialProfile.contentPresence), ...sources ? { sources } : {} };
205859
206085
  const styleProduction = Object.fromEntries(Object.entries({ captions: "captions.json", mediaRecipe: "media-style.json", techniques: "techniques.json", components: "components.json", rules: "rules.json" }).flatMap(([key, name]) => {
205860
206086
  const path2 = projectStylePath(project, name);
205861
206087
  return files[path2] ? [[key, JSON.parse(files[path2])]] : [];
@@ -205934,7 +206160,7 @@ ${stableJson(resolved.media)}\`\`\``) : "";
205934
206160
 
205935
206161
  \`\`\`json
205936
206162
  ${stableJson(resolved.styleResources)}\`\`\``) : "";
205937
- const mediaStyleSection = resolved.mediaPreferences.sources || resolved.mediaPreferences.editorialDelivery || resolved.mediaPreferences.motionSelectionSource !== "implicit" || resolved.mediaPreferences.motionProductionSource !== "implicit" || Object.keys(resolved.mediaPreferences.taste).length || resolved.mediaPreferences.image.selections.length || resolved.mediaPreferences.motion.selections.length || resolved.mediaPreferences.image.mode !== "inherit" || resolved.mediaPreferences.motion.mode !== "inherit" ? section2("Media style preferences", `Adaptive motion: choose per scene, using favorites as guidance and excluding avoided styles; no animation is also valid. Guided motion: start from saved choices, checking scene fit. Production auto/code/ai is separate: code can build complete JavaScript scenes; ai prefers generated clips only with verified personal tool access and existing authorization. Disabled categories remain disabled. Retrieve only relevant recipes by ID and version. Required brand tokens govern. visualSupport is the frequency of supporting visuals across the video, not a quota, pace or simultaneous-layer density. sources.allowed is exhaustive when present; empty means resolve incompatibility, absent means undecided. Never use excluded sources. web means authentic sources, archives or screenshots; verify provenance and rights. Resource preferences do not authorize generation or spending.
206163
+ const mediaStyleSection = resolved.mediaPreferences.contentPresence || resolved.mediaPreferences.sources || resolved.mediaPreferences.editorialDelivery || resolved.mediaPreferences.motionSelectionSource !== "implicit" || resolved.mediaPreferences.motionProductionSource !== "implicit" || Object.keys(resolved.mediaPreferences.taste).length || resolved.mediaPreferences.image.selections.length || resolved.mediaPreferences.motion.selections.length || resolved.mediaPreferences.image.mode !== "inherit" || resolved.mediaPreferences.motion.mode !== "inherit" ? section2("Media style preferences", `Adaptive motion: choose per scene, using favorites as guidance and excluding avoided styles; no animation is also valid. Guided motion: start from saved choices, checking scene fit. Production auto/code/ai is separate: code can build complete JavaScript scenes; ai prefers generated clips only with verified personal tool access and existing authorization. Disabled categories remain disabled. Retrieve only relevant recipes by ID and version. Required brand tokens govern. visualSupport is the frequency of supporting visuals across the video, not a quota, pace or simultaneous-layer density. sources.allowed is exhaustive when present; empty means resolve incompatibility, absent means undecided. Never use excluded sources. web means authentic sources, archives or screenshots; verify provenance and rights. Resource preferences do not authorize generation or spending.
205938
206164
 
205939
206165
  \`\`\`json
205940
206166
  ${stableJson(resolved.mediaPreferences)}\`\`\``) : "";
@@ -209014,6 +209240,8 @@ var searchErrors = {
209014
209240
  review_unavailable: { status: 409, code: "REVIEW_UNAVAILABLE", hint: "Read production reviews --project ID. Select the available, current, non-superseded revision that was actually presented; preserve comments and do not silently substitute or approve another version." },
209015
209241
  invalid_continuity_cursor: { status: 400, code: "INVALID_CONTINUITY_CURSOR", hint: "Read project continuity with the exact cursors returned for this project. An older API may not support optional review evidence; never change project or workspace to bypass this error." },
209016
209242
  brand_limit_reached: { status: 409, code: "BRAND_LIMIT_REACHED", hint: "Consulta el l\xEDmite de marcas de este espacio en https://editorbrain.com/app/billing. Puedes seguir editando las existentes. Comprar cr\xE9ditos no aumenta este l\xEDmite." },
209243
+ integration_limit_reached: { status: 409, code: "INTEGRATION_LIMIT_REACHED", hint: "Read integrations list and review existing personal declarations. Do not retry or replace another tool automatically." },
209244
+ invalid_integration: { status: 400, code: "INVALID_ARGUMENT", hint: "Read integrations list --details and preserve your draft while checking fields supported by this service version." },
209017
209245
  invalid_project_intake: { status: 400, code: "INVALID_PROJECT_INTAKE", hint: "Use projects create ID --brand ID --style ID --output-profile ID with existing IDs. The workspace comes from your authenticated account; do not send a workspace ID." },
209018
209246
  project_dependency_missing: { status: 404, code: "PROJECT_DEPENDENCY_MISSING", hint: "Read dependencyKind and documentPath. Discover the existing brand with brands list and styles/output profiles with documents list --prefix .editorbrain/styles/ or .editorbrain/output-profiles/. Preserve saved choices; do not invent replacement preferences or select another brand silently." },
209019
209247
  project_exists: { status: 409, code: "PROJECT_EXISTS", hint: "This ID belongs to an existing or edited project. Use projects intake --project ID to resume it, or choose a new ID for a separate edit. Never overwrite or delete the existing project to retry creation." },
@@ -209081,7 +209309,9 @@ var searchErrors = {
209081
209309
  team_permissions_changed: { status: 409, code: "TEAM_PERMISSIONS_CHANGED", hint: "Run editorbrain team members again. Reconcile the latest grants and permissionsRevision with the owner before saving; do not retry the stale permission file automatically." },
209082
209310
  invalid_team_permissions: { status: 400, code: "INVALID_TEAM_PERMISSIONS", hint: "Use a JSON file with expectedRevision and 1\u2013100 grants, each with kind brand_editor|project_reviewer and scopeId. Removing every access uses team remove --confirm." },
209083
209311
  team_scope_denied: { status: 403, code: "TEAM_SCOPE_DENIED", hint: "Run editorbrain team access. Ask the workspace owner to assign this brand/project at https://editorbrain.com/app/team. Never switch credentials automatically." },
209084
- team_spending_disabled: { status: 403, code: "TEAM_SPENDING_DISABLED", hint: "Your editing grant does not permit spending shared credits. Ask the owner for the resource or verify a user-authorized personal integration; buying credits will not fix this permission." },
209312
+ team_spending_disabled: { status: 403, code: "TEAM_SPENDING_DISABLED", hint: "Run editorbrain team access. Reviewers cannot spend shared credits; an invited editor needs a positive monthly allowance set by the owner at https://editorbrain.com/app/team. Ask the owner to assign it or use a user-authorized personal integration. Buying credits does not grant permission." },
209313
+ team_budget_exceeded: { status: 402, code: "TEAM_BUDGET_EXCEEDED", hint: "Read your monthly allowance with editorbrain team access or studio catalog. Ask the owner to increase the limit at https://editorbrain.com/app/team, or wait for the next UTC calendar month. Do not split jobs, switch credentials or charge another provider to bypass the limit; buying credits does not increase it." },
209314
+ team_seat_limit: { status: 409, code: "TEAM_SEAT_LIMIT", hint: "Run editorbrain team members and inspect editorSeats. Ask the owner to review the indicated plan upgrade at https://editorbrain.com/app/billing or explicitly remove an editor or cancel a pending invitation. Existing editors use one seat across brands; reviewers use none. Buying credits does not add editor seats." },
209085
209315
  invitation_email_limit: { status: 429, code: "INVITATION_EMAIL_LIMIT", hint: "Invitation email is rate-limited for 24 hours, independently of credits. Wait; cancelling or recreating invitations does not reset this limit. Check existing invitations with editorbrain team members." },
209086
209316
  invitation_pending: { status: 409, code: "INVITATION_PENDING", hint: "Run editorbrain team members. Review the pending invitation before canceling or creating a replacement." },
209087
209317
  search_allowance_exhausted: { status: 429, code: "SEARCH_ALLOWANCE_EXHAUSTED", hint: "Consult your search allowance in Plan y cr\xE9ditos." },
@@ -209374,7 +209604,7 @@ var Client = class {
209374
209604
  const retryAfterMs = retryDelay(response.headers.get("Retry-After"), this.runtime.now());
209375
209605
  if (!response.ok) {
209376
209606
  let errorBody;
209377
- if ([401, 403].includes(response.status) || (/^\/v1\/(?:authored-motion|style-sources|sfx|team|studio|batches|render-cloud|resources)(?:\/|\?|$)/.test(path) || path.startsWith("/v1/documents/") || path === "/v1/search/brief" || path === "/v1/projects" || /^\/v1\/projects\/[^/]+\/(?:progress|intake|resolve|export|review-evidence(?:\/[a-f0-9-]{36})?|(?:delivery-evidence|checkpoint-readiness|continuity)(?:\?.*)?)$/.test(path)) && [400, 402, 403, 404, 409, 422, 429, 503].includes(response.status)) {
209607
+ if ([401, 403].includes(response.status) || (/^\/v1\/(?:authored-motion|style-sources|sfx|team|studio|batches|render-cloud|resources|integrations)(?:\/|\?|$)/.test(path) || path.startsWith("/v1/documents/") || path === "/v1/search/brief" || path === "/v1/projects" || /^\/v1\/projects\/[^/]+\/(?:progress|intake|resolve|export|review-evidence(?:\/[a-f0-9-]{36})?|(?:delivery-evidence|checkpoint-readiness|continuity)(?:\?.*)?)$/.test(path)) && [400, 402, 403, 404, 409, 422, 429, 503].includes(response.status)) {
209378
209608
  try {
209379
209609
  const parsed = await boundedJson(response, 16 * 1024);
209380
209610
  const knownDiagnostic = searchDiagnostic(response.status, parsed);
@@ -212200,6 +212430,7 @@ Descubrir una opci\xF3n no autoriza ejecutar, subir material, gastar ni aprobar.
212200
212430
  `;
212201
212431
  }
212202
212432
  var introductions = {
212433
+ integrations: "catalog muestra proveedores conocidos; list conserva tus declaraciones personales y --details a\xF1ade el cat\xE1logo. set acepta el mismo JSON para proveedores conocidos y custom-<id>: enabled, accessMethod, preferences, definition, connection y preferredFor. Un proveedor custom requiere definition con name, purpose y capabilities. connection describe MCP, CLI o herramienta nativa dentro de Claude/Codex/otro host y solo se admite con accessMethod agent; su name es un identificador, nunca un comando ni una URL. Lee list antes de escribir y conserva todos los campos de la entrada; --expected-revision protege cambios concurrentes. Esto guarda contexto, no conecta servicios ni almacena credenciales. Verifica acceso, capacidades y presupuesto en la sesi\xF3n antes de usarlo.",
212203
212434
  push: "Sincroniza documentos con control de revisi\xF3n. Una incompatibilidad confirmada conserva el documento local y permite guardar los dem\xE1s: status:partial, synced:false, skipped y salida 2. Actualiza la API y repite push; no bajes el esquema ni borres campos. Conflictos, permisos, datos inv\xE1lidos y fallos de red detienen la operaci\xF3n. --dry-run no comprueba compatibilidad de escritura del servidor.",
212204
212435
  where: "Ubica archivos de un proyecto usando el registro privado de esta computadora. No usa red ni sincroniza rutas absolutas. Ante IDs ambiguos selecciona --dir.",
212205
212436
  resume: "Acepta resume ID o resume --project ID; si usas ambos deben coincidir. Usa projects find para resolver nombre/tema/fecha antes de elegir el ID. --rehash fuerza SHA-256 nuevo; checkpointHash protege el siguiente hito con --expected-checkpoint. Descarga contexto y checkpoint, conserva cambios locales y verifica archivos por SHA-256. Solo lectura remota: no renderiza, sube medios, abre aplicaciones ni gasta.",
@@ -212868,6 +213099,66 @@ import { fileURLToPath } from "node:url";
212868
213099
 
212869
213100
  // packages/cli/src/agent-guidance-history.ts
212870
213101
  var VERIFIED_GUIDANCE_RELEASES = [
213102
+ {
213103
+ "version": "0.52.0",
213104
+ "archiveSha256": "bcd20a982dcab7e575a7d51c2b52e1093519b71e28d233c343c094c02d397070",
213105
+ "files": {
213106
+ "editorbrain-formats/SKILL.md": "65ea59aae091ca9618b5e479befe0c76edf174df7091ed74d4307485a2252fcd",
213107
+ "editorbrain-formats/references/aspirational-list-demo.md": "e884ce44d15f4496812ed18120f7d4c49c4261e148fcefe05c77c110b589771c",
213108
+ "editorbrain-formats/references/cumulative-tier-list.md": "7b7e8208687c6b925443e55d640ced6c1d09824377884244a09d7f3089d60aa5",
213109
+ "editorbrain-formats/references/numbered-tutorial.md": "95754ae7dbfaa678e11ddf1a2b84710dba83a16e2fa4055051bd4f5f4f868a5f",
213110
+ "editorbrain-motion/SKILL.md": "2e75525be4a176c5917d9f36baf328b827705593f7495622a79f29952eb9f8e7",
213111
+ "editorbrain-motion/references/authored-scenes.md": "7778d324f90872eb6f237cc603ba3276dfaa16a8670d478c6791d43d07902482",
213112
+ "editorbrain-motion/references/code-motion.md": "50382a797adc1e1596086e2408e81ee75ceb6730ca409be9c884646db643a7cd",
213113
+ "editorbrain-motion/references/component-library.md": "e88ed19d2ab9dca8d2ea02abe6c476021c03b9679bce99292cf7da52d65d2236",
213114
+ "editorbrain-motion/references/generated-motion.md": "a8d214b53c15f742658abd84f03b768fa2821f8cde94f50aab82a3759a30b36b",
213115
+ "editorbrain-motion/references/motion-craft.md": "dae520b0e641fc9c3bf937241936588a855bf3453358e239ccc3cc3a2bcf0825",
213116
+ "editorbrain/AGENTS.md": "d32baf173950c24d369bd2d82249538b5894734da8a40b9de7e9c9115e3084ad",
213117
+ "editorbrain/SKILL.md": "9751c71cceed70ee5b40a7d944f5503e8d580b3836533e4eafe921eb9acd813b",
213118
+ "editorbrain/references/audio-production.md": "e67fce6d6f827f71fe81d360e4fa514e452cead81a5d00d04e71987511761ea6",
213119
+ "editorbrain/references/captions.md": "61e2db9dca35f2f74699186c158f93f59c2526d9699d69e64975bd7ce0154170",
213120
+ "editorbrain/references/chat-attachments.md": "11d954543a4238b14744aae217226f4a3c413f18fb4c2c2a4559c16bfdbc89c1",
213121
+ "editorbrain/references/cli-mcp.md": "30ebc7ef765535f98f7997ab0a2225307b3e64533c6777839d1faa5988b3c730",
213122
+ "editorbrain/references/cloud-production.md": "60c428fbdc4e19309fdad28b9848995a0fcc91c86890d64242953cd1f1bd5c01",
213123
+ "editorbrain/references/editorial-evidence.md": "79ed5bd90eb903014313c32a1e337822c5cb454e642bcfa852dcb77d30a9392e",
213124
+ "editorbrain/references/editorial-families.md": "b802ec6f02fd079e99df84d69a3c515d63ad058960b568c0c7b7dec1912495dd",
213125
+ "editorbrain/references/family-animated.md": "54a140d0a64b01147c52ea8cbaab4e4599bfe1af330f5a3ad6ef2a30351ab47d",
213126
+ "editorbrain/references/family-demonstration.md": "737334a8d9230682cde3a6ed11bfc02c4f9795c8f25a3b668be9d7393ec3e53d",
213127
+ "editorbrain/references/family-essay.md": "003f2cd450f33ba6641a9b1114cbc578c04cbb658b992c89c765d43198d1b4c2",
213128
+ "editorbrain/references/family-personal.md": "e93c304d7bc7d3eb31a3c9cb3be83f4f48d41319c2ac2e1e6f53f38576f5e644",
213129
+ "editorbrain/references/family-presenter.md": "76b8140b924930b306ce97772d6a7b683870bd14f19772b5339a490752b7de24",
213130
+ "editorbrain/references/first-edit.md": "60a076152150e70331de111067a38265a6aa757b66754a91d993b16cac2207ae",
213131
+ "editorbrain/references/integrations.md": "36f9c424f76435b0461846b96b56ab20ab081a51ba7b995e34d8e588135d0e2d",
213132
+ "editorbrain/references/local-production.md": "0edc34b4a7c7a3c54968e7574eb8e14bdfdb2b2ad2ed7eeaacf17a066e290368",
213133
+ "editorbrain/references/mcp-studio-artifact.md": "25112d8e1f8fe69cf0cbd6d05e46aefe7176f6299818a12cff2fb65da3f8fdce",
213134
+ "editorbrain/references/media-preferences.md": "87e508a75cdb6f4644db767273bfb230fb79f182ed05ee0f6257c6c05ea4dc7a",
213135
+ "editorbrain/references/memory-and-review.md": "ea2fc233f326fbfa2d5354fc2765e8a5b256586b0d45659907131c5fef573a7b",
213136
+ "editorbrain/references/motion-review.md": "0fb09a2d61ecd13114ced5cca5daa4580a922cf7d7b3f8698077ceb0e96da6f0",
213137
+ "editorbrain/references/onboarding.md": "417050d333ad32284ed4a8e2e420f8b7773255a11e2f3be729d1ad6029ab00d1",
213138
+ "editorbrain/references/personal-resources.md": "671ccc9440cacc1844aacc56f13de5ffaf236d6594fe2bdea8059f2c09af7c1a",
213139
+ "editorbrain/references/production-and-review.md": "9c69c058b1f899800fcbe538fa61fea7e397bef4cc092a09e394c2cc6ca2a0ea",
213140
+ "editorbrain/references/production-continuity.md": "7371bf133b7f7266285bf53013c007ef53daf390c0807c8cf35ffcf2225399a6",
213141
+ "editorbrain/references/project-batches.md": "5d5b3429fd638d163c47367b9df45113d345b2414f4687070cc974769768244d",
213142
+ "editorbrain/references/real-media.md": "cfad1aa15198dfe5ecc1f1b67c96d43a7d2084e7f5119de93d1b360203694938",
213143
+ "editorbrain/references/render-delivery.md": "e697f08e4e5162ed845b5e65d0d0358054cf097761c60ee5f19744f304ee5bc5",
213144
+ "editorbrain/references/search-brief.md": "1bd2514f961522675047910f001f33da035382e48e933bc5eadb9d7d01455a0d",
213145
+ "editorbrain/references/sfx-library.md": "af8833278ce74f52f9ddcb8a00fc0b8cb7b6c35066531f3c1ce5465a6dccd3d9",
213146
+ "editorbrain/references/starting-an-edit.md": "746094fc9893bb82aa938256313de5ccb412cb2c78864ea502e8515485ce8a3c",
213147
+ "editorbrain/references/storage-and-previews.md": "095e4d9091774191f95444b4c78e6b12263f1608d8f6cecaa598675223e68405",
213148
+ "editorbrain/references/studio-review.md": "2c685dac929a4c750ac1d60d3597e9197a6852818f6f49465bec7897d54e00c6",
213149
+ "editorbrain/references/studio.md": "c2905eab379e1e0513a6b79fdb7db9d36832d55735effe3b713b1e243f2daa4f",
213150
+ "editorbrain/references/style-creator.md": "9de3b2528da9ce092ef0b16d03d8d6a79597f4ed4bd4901501dc79625122519a",
213151
+ "editorbrain/references/style-rules.md": "bdea1cda112ccf82dd500f21d3aac70e5aad462c89cb253c6896d834de1b6e02",
213152
+ "editorbrain/references/style-sharing.md": "11079572c54222fc708d5a85cadf4064b07ae6febff42d8c5fdf5719f934b3fc",
213153
+ "editorbrain/references/style-source.md": "418458a097287c91e7cda02a096743dfe62c3ad3d78a9f7133ba385b2eedd9e6",
213154
+ "editorbrain/references/task-map.md": "f9c9bf324ff98b6fc89e6318fbb155fd40588570e37a15f47e0eea970bbe6455",
213155
+ "editorbrain/references/user-guides.md": "47b49bff489ccd973badebf1a122d5d0e8acc451424afdb9ef19e1fe4c197f2a",
213156
+ "editorbrain/references/voice-cleanup.md": "75e06cef365306ffb84e550e4c720ddc5eae320b7ea5447d6887187b20691e40",
213157
+ "editorbrain/references/workflow-evidence.md": "a82c73db9fec6df71a66e30d81df299766807aba51503a6259117cdde33120a2",
213158
+ "editorbrain/references/workspace-files.md": "efc34453ac5b7273d6e94587666f00932be079b29b105e348303d5e492f58eb7",
213159
+ "editorbrain/scripts/deepfilter-cleanup.mjs": "e557a31bea16570c7ab16aaf54f883110bad8a42e28fac6282b0a1aa81de635e"
213160
+ }
213161
+ },
212871
213162
  {
212872
213163
  "version": "0.51.0",
212873
213164
  "archiveSha256": "1606eb6e7a0820dfaeb41a2f207e922fd197448008c9bbd66e9c7d321cceb556",
@@ -214396,9 +214687,6 @@ import { resolve as resolve9 } from "node:path";
214396
214687
  // packages/cli/src/integrations.ts
214397
214688
  import { constants as constants15 } from "node:fs";
214398
214689
  import { lstat as lstat19, open as open18 } from "node:fs/promises";
214399
- function object15(value) {
214400
- return value !== null && typeof value === "object" && !Array.isArray(value);
214401
- }
214402
214690
  function invalidState(write) {
214403
214691
  return new CliError(
214404
214692
  "INVALID_RESPONSE",
@@ -214409,20 +214697,11 @@ function invalidState(write) {
214409
214697
  );
214410
214698
  }
214411
214699
  function integrationState(value, write = false) {
214412
- if (!object15(value) || !["member", "connection"].includes(value.scope) || !Number.isSafeInteger(value.revision) || value.revision < 0 || !(value.updatedAt === null || typeof value.updatedAt === "string" && value.updatedAt.length <= 64 && Number.isFinite(Date.parse(value.updatedAt))) || !Array.isArray(value.entries) || !Array.isArray(value.catalog)) throw invalidState(write);
214413
- const providers = /* @__PURE__ */ new Set();
214414
- for (const entry of value.entries) {
214415
- if (!object15(entry) || typeof entry.providerId !== "string" || !entry.providerId || entry.providerId.length > 120 || providers.has(entry.providerId) || typeof entry.enabled !== "boolean" || typeof entry.accessMethod !== "string" || !entry.accessMethod || entry.accessMethod.length > 64 || !object15(entry.preferences)) throw invalidState(write);
214416
- providers.add(entry.providerId);
214700
+ try {
214701
+ return validateIntegrationProfile(value, { allowFuture: true });
214702
+ } catch {
214703
+ throw invalidState(write);
214417
214704
  }
214418
- if (value.catalog.some((provider) => !object15(provider) || typeof provider.id !== "string" || !provider.id)) throw invalidState(write);
214419
- return {
214420
- scope: value.scope,
214421
- revision: value.revision,
214422
- updatedAt: value.updatedAt,
214423
- entries: value.entries,
214424
- catalog: value.catalog
214425
- };
214426
214705
  }
214427
214706
  async function readIntegrationSettings(file2) {
214428
214707
  const invalidFile = () => new CliError("INVALID_ARGUMENT", "Choose a regular integration settings JSON file under 16 KiB.", "Store provider credentials in the provider connection, not this file.");
@@ -214449,7 +214728,7 @@ async function readIntegrationSettings(file2) {
214449
214728
  try {
214450
214729
  return JSON.parse(bytes.subarray(0, length).toString("utf8"));
214451
214730
  } catch {
214452
- throw new CliError("INVALID_ARGUMENT", "Integration settings must be valid JSON.", "The file should contain enabled, accessMethod and preferences only.");
214731
+ throw new CliError("INVALID_ARGUMENT", "Integration settings must be valid JSON.", "Use enabled, accessMethod, preferences and optional definition, connection, preferredFor. Never include credentials.");
214453
214732
  }
214454
214733
  } finally {
214455
214734
  await handle.close();
@@ -214463,7 +214742,7 @@ function integrationRevision(value) {
214463
214742
  }
214464
214743
  async function listIntegrations(client, details = false) {
214465
214744
  const state = integrationState(await client.request("/v1/integrations"));
214466
- const routing = { executionPolicy: integrationExecutionPolicy, routes: integrationRoutes(state.entries, state.catalog) };
214745
+ const routing = { executionPolicy: integrationExecutionPolicy, routes: integrationRoutes(state.entries, state.catalog), preferredRoutes: preferredIntegrationRoutes(state.entries, state.catalog).filter((route) => route.status !== "missing") };
214467
214746
  if (details) return { ...state, ...routing };
214468
214747
  return {
214469
214748
  ...routing,
@@ -214480,13 +214759,29 @@ async function setIntegration(client, providerId, settings, expectedRevision) {
214480
214759
  try {
214481
214760
  if (!settings || typeof settings !== "object" || Array.isArray(settings) || "expectedRevision" in settings) throw new Error();
214482
214761
  update = validateIntegrationUpdate(providerId, { ...settings, expectedRevision });
214483
- } catch {
214484
- throw new CliError("INVALID_ARGUMENT", "Invalid integration preferences, access method or provider.", "Use integrations catalog for supported providers. The JSON accepts enabled, accessMethod, preferences; never credentials.");
214762
+ } catch (error62) {
214763
+ throw new CliError("INVALID_ARGUMENT", error62 instanceof Error && error62.message ? error62.message : "Invalid integration settings.", "Use integrations catalog for known providers or custom-<id> with definition. The JSON accepts enabled, accessMethod, preferences, definition, connection and preferredFor; never credentials. Read integrations list and preserve the complete entry before saving.");
214485
214764
  }
214486
214765
  let response;
214487
214766
  try {
214488
214767
  response = await client.request(`/v1/integrations/${encodeURIComponent(providerId)}`, { method: "PUT", body: update });
214489
214768
  } catch (error62) {
214769
+ const serviceError = error62 instanceof ApiError && error62.body && typeof error62.body === "object" && "error" in error62.body ? error62.body.error : void 0;
214770
+ const serviceCode = serviceError && typeof serviceError === "object" && "code" in serviceError ? serviceError.code : void 0;
214771
+ if (error62 instanceof ApiError && error62.status === 409 && serviceCode === "integration_limit_reached") throw new CliError(
214772
+ "INTEGRATION_LIMIT_REACHED",
214773
+ "The personal custom integration limit has been reached.",
214774
+ "Run editorbrain integrations list and review existing declarations. Do not retry or replace another tool automatically.",
214775
+ false,
214776
+ { status: 409 }
214777
+ );
214778
+ if (error62 instanceof ApiError && error62.status === 400 && serviceCode === "invalid_integration") throw new CliError(
214779
+ "INVALID_ARGUMENT",
214780
+ "The service rejected this integration declaration.",
214781
+ "Read integrations list --details and check the supported fields for this service version. Preserve your draft; do not remove metadata or retry a changed declaration automatically.",
214782
+ false,
214783
+ { status: 400 }
214784
+ );
214490
214785
  if (error62 instanceof ApiError && error62.status === 409) throw new CliError(
214491
214786
  "INTEGRATION_CONFLICT",
214492
214787
  "Integration preferences changed before this save.",
@@ -214499,8 +214794,18 @@ async function setIntegration(client, providerId, settings, expectedRevision) {
214499
214794
  }
214500
214795
  const state = integrationState(response, true);
214501
214796
  const entry = state.entries.find((value) => value.providerId === providerId);
214502
- if (state.revision !== expectedRevision + 1 || !entry || entry.enabled !== update.enabled || entry.accessMethod !== update.accessMethod || stableJson(entry.preferences) !== stableJson(update.preferences)) throw invalidState(true);
214503
- return { scope: state.scope, revision: state.revision, updatedAt: state.updatedAt, entry, access: "user_declared" };
214797
+ const { expectedRevision: _expectedRevision, ...saved } = update;
214798
+ if (state.revision !== expectedRevision + 1 || !entry || stableJson(entry) !== stableJson({ providerId, ...saved })) throw invalidState(true);
214799
+ const confirmedPreferences = preferredIntegrationRoutes(state.entries, state.catalog).filter((route) => route.status !== "missing");
214800
+ return {
214801
+ scope: state.scope,
214802
+ revision: state.revision,
214803
+ updatedAt: state.updatedAt,
214804
+ entry,
214805
+ preferredRoutes: confirmedPreferences,
214806
+ access: "user_declared",
214807
+ notice: "Preferences for the selected capabilities are reassigned atomically. Run integrations list to read complete state. This declaration does not connect tools or authorize charges."
214808
+ };
214504
214809
  }
214505
214810
 
214506
214811
  // packages/cli/src/doctor.ts
@@ -215359,7 +215664,7 @@ import { isAbsolute as isAbsolute3, resolve as resolve11 } from "node:path";
215359
215664
  var CACHE_FILE = "verification-cache.json";
215360
215665
  var MAX_BYTES = 2 * 1024 * 1024;
215361
215666
  var MAX_FILES = 1024;
215362
- var object16 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
215667
+ var object15 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
215363
215668
  var keys3 = (value, names) => Object.keys(value).length === names.length && names.every((name) => Object.hasOwn(value, name));
215364
215669
  var fingerprint = (stat3) => ({ dev: String(stat3.dev), ino: String(stat3.ino), size: String(stat3.size), mtimeNs: String(stat3.mtimeNs), ctimeNs: String(stat3.ctimeNs) });
215365
215670
  var sameStat = (left, right) => Object.keys(left).every((key) => left[key] === right[key]);
@@ -215368,10 +215673,10 @@ var warning = (error62) => ({ code: error62 instanceof CliError ? error62.code :
215368
215673
  function parseCache(raw) {
215369
215674
  try {
215370
215675
  const value = JSON.parse(raw);
215371
- if (!object16(value) || !keys3(value, ["schemaVersion", "files"]) || value.schemaVersion !== 1 || !Array.isArray(value.files) || value.files.length > MAX_FILES) throw invalid6();
215676
+ if (!object15(value) || !keys3(value, ["schemaVersion", "files"]) || value.schemaVersion !== 1 || !Array.isArray(value.files) || value.files.length > MAX_FILES) throw invalid6();
215372
215677
  const seen = /* @__PURE__ */ new Set();
215373
215678
  for (const entry of value.files) {
215374
- if (!object16(entry) || !keys3(entry, ["scope", "path", "stat", "sha256", "hashedAt"]) || typeof entry.scope !== "string" || !/^[a-f0-9]{64}$/.test(entry.scope) || typeof entry.path !== "string" || entry.path.length > 4096 || !isAbsolute3(entry.path) || resolve11(entry.path) !== entry.path || /[\x00-\x1f\x7f]/.test(entry.path) || !object16(entry.stat) || !keys3(entry.stat, ["dev", "ino", "size", "mtimeNs", "ctimeNs"]) || Object.values(entry.stat).some((field) => typeof field !== "string" || !/^-?\d{1,30}$/.test(field)) || BigInt(entry.stat.size) < 0n || BigInt(entry.stat.size) > BigInt(Number.MAX_SAFE_INTEGER) || typeof entry.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(entry.sha256) || typeof entry.hashedAt !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(entry.hashedAt) || !Number.isFinite(Date.parse(entry.hashedAt))) throw invalid6();
215679
+ if (!object15(entry) || !keys3(entry, ["scope", "path", "stat", "sha256", "hashedAt"]) || typeof entry.scope !== "string" || !/^[a-f0-9]{64}$/.test(entry.scope) || typeof entry.path !== "string" || entry.path.length > 4096 || !isAbsolute3(entry.path) || resolve11(entry.path) !== entry.path || /[\x00-\x1f\x7f]/.test(entry.path) || !object15(entry.stat) || !keys3(entry.stat, ["dev", "ino", "size", "mtimeNs", "ctimeNs"]) || Object.values(entry.stat).some((field) => typeof field !== "string" || !/^-?\d{1,30}$/.test(field)) || BigInt(entry.stat.size) < 0n || BigInt(entry.stat.size) > BigInt(Number.MAX_SAFE_INTEGER) || typeof entry.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(entry.sha256) || typeof entry.hashedAt !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(entry.hashedAt) || !Number.isFinite(Date.parse(entry.hashedAt))) throw invalid6();
215375
215680
  const key = JSON.stringify([entry.scope, entry.path]);
215376
215681
  if (seen.has(key)) throw invalid6();
215377
215682
  seen.add(key);
@@ -216438,18 +216743,24 @@ async function setup(options, runner = runHost) {
216438
216743
 
216439
216744
  // packages/cli/src/onboarding.ts
216440
216745
  import { createServer as createServer2 } from "node:http";
216746
+ import { constants as constants18 } from "node:fs";
216441
216747
  import { randomBytes, createHash as createHash21 } from "node:crypto";
216442
216748
  import { join as join21, dirname as dirname21 } from "node:path";
216443
- import { mkdir as mkdir15 } from "node:fs/promises";
216749
+ import { mkdir as mkdir15, open as open21 } from "node:fs/promises";
216444
216750
 
216445
216751
  // packages/cli/src/onboarding-artifact.ts
216446
216752
  function safeJson(value) {
216447
216753
  return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
216448
216754
  }
216449
- function renderOnboardingArtifact({ intake, submission, requiresIdentity = false }) {
216755
+ function renderOnboardingArtifact({ intake, submission, requiresIdentity = false, restoredDraft = false }) {
216450
216756
  if (submission) {
216451
216757
  const url3 = new URL(submission.actionUrl);
216452
216758
  if (url3.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url3.hostname) || url3.username || url3.password || url3.hash) throw new Error("Onboarding submission must target an HTTP loopback address.");
216759
+ if (submission.draftUrl) {
216760
+ const draft = new URL(submission.draftUrl);
216761
+ if (draft.origin !== url3.origin || draft.username || draft.password || draft.hash) throw new Error("Draft submission must use the same local server.");
216762
+ }
216763
+ if (submission.draftVersion !== void 0 && submission.draftVersion !== null && !/^[a-f0-9]{64}$/.test(submission.draftVersion)) throw new Error("Draft version must be a SHA-256 or null.");
216453
216764
  if (!submission.csrfToken || /[\r\n]/.test(submission.csrfToken)) throw new Error("Onboarding submission requires a valid local token.");
216454
216765
  }
216455
216766
  const styles = MEDIA_STYLE_CATALOG.styles.map((style) => ({ id: style.id, version: style.version, category: style.category, name: style.name, description: style.description, examples: (style.preview.examples || []).filter((example) => {
@@ -216460,235 +216771,78 @@ function renderOnboardingArtifact({ intake, submission, requiresIdentity = false
216460
216771
  return false;
216461
216772
  }
216462
216773
  }).map((example) => ({ ratio: example.ratio, url: example.url })) }));
216463
- const data = { creatorContextOptions, requiresIdentity, demos: onboardingDemoExamples, hooks: onboardingHookOptions, hookIntensities: onboardingHookIntensityOptions, reviewModes: onboardingReviewOptions, integrations: integrationCatalog, intake: validateOnboardingIntake(intake), submission: submission || null, options: profileOptions, styles, questionModes: questionModeOptions, creativeDirections: creativeDirectionOptions, creativeSections: creativePreferenceSections, steps: localOnboardingSteps };
216774
+ const validatedIntake = validateOnboardingIntake(intake);
216775
+ const data = { creatorContextOptions, requiresIdentity, restoredDraft, demos: onboardingDemoExamples, hooks: onboardingHookOptions, hookIntensities: onboardingHookIntensityOptions, reviewModes: onboardingReviewOptions, integrations: integrationCatalogFor(validatedIntake.accountSetup?.integrations ?? []), intake: validatedIntake, submission: submission || null, options: profileOptions, styles, questionModes: questionModeOptions, creativeDirections: creativeDirectionOptions, creativeSections: creativePreferenceSections, steps: localOnboardingSteps };
216464
216776
  return `<!doctype html>
216465
216777
  <html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Tu cerebro editorial \xB7 EditorBrain</title><style>${artifactCss}</style></head>
216466
- <body data-theme="paper"><div class="app"><header class="top"><a href="#main" class="product-label" aria-label="EditorBrain, ir a tus preferencias">${onboardingWordmark}</a><span class="local-badge">Tu estudio \xB7 En tu computadora</span></header>
216467
- <nav id="steps" aria-label="Pasos de tus preferencias"></nav><div class="layout"><main id="main" tabindex="-1"><div class="page-top"><span id="step-count" class="eyebrow"></span><button type="button" id="download-top" class="text-button">Descargar respuestas</button></div><h1 id="page-title" tabindex="-1"></h1><p id="page-description" class="intro"></p><form id="preferences" novalidate><div id="panel"></div></form><div id="error" class="notice error" role="alert" hidden></div><div id="status" class="notice" role="status" hidden></div><footer class="actions"><button type="button" id="previous" class="button secondary">\u2190 Atr\xE1s</button><span id="save-hint">Puedes cambiar tus preferencias despu\xE9s.</span><button type="button" id="next" class="button primary">Continuar \u2192</button></footer></main></div><footer class="bottom">EditorBrain \xB7 Tu criterio, en cada edici\xF3n.<span>Preferencias locales. No conecta servicios ni activa compras.</span></footer></div>
216778
+ <body data-theme="light"><div class="app"><header class="top"><a href="#main" class="product-label" aria-label="EditorBrain, ir a tus preferencias">${onboardingWordmark}</a><div class="top-actions"><span class="local-badge">Preferencias locales</span><button type="button" id="theme-toggle" class="theme-toggle" aria-label="Cambiar a modo oscuro" title="Cambiar a modo oscuro"><svg class="moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><path d="M20.9 13a9 9 0 0 1-9.9-9.9A9 9 0 1 0 20.9 13Z"/></svg><svg class="sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5"/></svg></button></div></header>
216779
+ <nav id="steps" aria-label="Pasos de tus preferencias"></nav><div class="layout"><main id="main" tabindex="-1"><div class="page-top"><span id="step-count" class="eyebrow"></span><div class="draft-actions"><button type="button" id="save-draft" class="text-button">Guardar borrador</button><button type="button" id="import-draft" class="text-button" hidden>Importar borrador</button><input type="file" id="draft-file" accept="application/json,.json" hidden><button type="button" id="download-top" class="text-button">Descargar respuestas</button></div></div><h1 id="page-title" tabindex="-1"></h1><p id="page-description" class="intro"></p><p id="draft-help" class="small"></p><form id="preferences" novalidate><div id="panel"></div></form><div id="error" class="notice error" role="alert" hidden></div><div id="status" class="notice" role="status" hidden></div><footer class="actions"><button type="button" id="previous" class="button secondary">\u2190 Atr\xE1s</button><span id="save-hint">Puedes cambiar tus preferencias despu\xE9s.</span><button type="button" id="next" class="button primary">Continuar \u2192</button></footer></main></div><footer class="bottom">EditorBrain \xB7 Tu criterio, en cada edici\xF3n.<span>Preferencias locales. No conecta servicios ni activa compras.</span></footer></div>
216468
216780
  <dialog id="style-dialog" aria-labelledby="dialog-title"><div class="dialog-head"><div><span class="eyebrow">REFERENCIA DE APARIENCIA</span><h2 id="dialog-title"></h2></div><button type="button" id="close-dialog" class="button secondary">Cerrar</button></div><p id="dialog-description"></p><div id="dialog-examples"></div><p class="small">Ejemplos generados con IA. Orientan el tratamiento visual; no sustituyen tu marca ni acreditan hechos reales.</p></dialog>
216469
216781
  <script id="onboarding-data" type="application/json">${safeJson(data)}</script><script>${artifactScript}</script></body></html>`;
216470
216782
  }
216471
216783
  var artifactCss = String.raw`
216472
- :root{color-scheme:light;--paper:#f3ede4;--surface:#fffaf3;--ink:#29241f;--muted:#807368;--line:#ded0c1;--accent:#713348;--brand-bg:#f1e8d8;--brand-text:#282621;--brand-accent:#aa765d}
216784
+ :root{color-scheme:light;--paper:#fafafa;--surface:#ffffff;--surface-2:#f3f3f2;--surface-soft:#f5f0e8;--ink:#1b1b19;--muted:#575651;--line:#d9d8d5;--line-subtle:#eae9e6;--select:#f1e4cf;--select-border:#72706b;--select-ink:#141312;--select-muted:#4f4943;--focus:#4f4943;--accent:#93460c;--action:#e89a4a;--action-hover:#f0ad6a;--action-ink:#141312;--success:#28633a;--success-bg:#e8f4eb;--danger:#b53725;--danger-bg:#fff0ed;--overlay:#0005;--brand-bg:#f1e8d8;--brand-text:#282621;--brand-accent:#aa765d}
216785
+ body[data-theme=dark]{color-scheme:dark;--paper:#0f0e0d;--surface:#1a1918;--surface-2:#282624;--surface-soft:#2c2925;--ink:#f5f3f0;--muted:#bdb8b2;--line:#3d3a36;--line-subtle:#262422;--select-border:#f1e4cf;--focus:#f1e4cf;--accent:#e89a4a;--success:#a9dcb0;--success-bg:#24302a;--danger:#e0705a;--danger-bg:#321f1d;--overlay:#0009}
216473
216786
  *{box-sizing:border-box}
216474
- body{margin:0;background:radial-gradient(ellipse 80% 700px at 95% 0,#e6cdbd75,transparent),var(--paper);color:var(--ink);font:15px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
216787
+ body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;transition:background-color .18s,color .18s}
216475
216788
  button,input,select,textarea{font:inherit}
216476
216789
  button,a,input,select,textarea,summary{-webkit-tap-highlight-color:transparent}
216477
216790
  button{cursor:pointer;color:inherit}
216478
216791
  button:disabled{cursor:default;opacity:.6}
216479
- button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,summary:focus-visible{outline:3px solid #a26a7b;outline-offset:4px}
216480
- a{color:inherit}
216481
- h1,h2,h3,p{margin-top:0}
216792
+ :where(button,a,input,select,textarea,summary):focus-visible{outline:2px solid var(--focus);outline-offset:3px}
216793
+ a{color:var(--accent)}
216794
+ h1,h2,h3,p{margin-top:0}h1,h2,h3{text-wrap:balance}p{text-wrap:pretty}
216482
216795
  .app{max-width:1440px;margin:auto;padding:0 4vw}
216483
- .top{height:88px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;gap:18px}
216484
- .product-label{font-size:17px;font-weight:600;letter-spacing:0;text-decoration:none;color:var(--accent);display:flex;align-items:center;gap:7px}
216485
- .local-badge{padding:6px 11px;border:1px solid #d9c7b8;border-radius:30px;color:#7c645c;font-size:11px}
216486
- .layout{max-width:1120px;margin:auto;padding:44px 0 56px}
216487
- .eyebrow{font-size:11px;letter-spacing:.13em;font-weight:650;text-transform:uppercase}
216488
- #steps{display:flex;gap:8px;max-width:680px;margin:30px auto 0;padding:10px 18px;border:1px solid #85696135;border-radius:99px;background:#ffffff0a}
216489
- #steps button{flex:1;min-width:0;border:0;background:transparent;padding:7px 0;color:inherit;font-size:10px}
216490
- .step-bar{display:block;height:8px;border:1px solid #a78f8055;border-radius:3px;margin-bottom:7px}
216491
- #steps [aria-current=step] .step-bar{background:#e89a4a;box-shadow:0 0 14px #e89a4a35;border-color:#e89a4a}
216492
- #steps [data-done=true] .step-bar{background:#e89a4a65}
216493
- .page-top{display:flex;align-items:center;justify-content:space-between;gap:14px}
216494
- h2{font:400 clamp(30px,3.7vw,45px)/1.12 Georgia,serif;letter-spacing:-1.4px;margin:20px 0 14px}
216495
- h2:focus,#main:focus{outline:none}
216496
- .intro{color:var(--muted);font-size:14px;max-width:650px;margin-bottom:32px}
216497
- h3{font-size:17px;line-height:1.4;letter-spacing:-.3px;margin:0 0 8px}
216498
- .section{margin-bottom:32px;min-width:0}
216499
- .section p{font-size:12px;color:var(--muted);margin-bottom:14px}
216500
- .section-head{display:flex;justify-content:space-between;align-items:flex-start;gap:14px;margin-bottom:16px}
216501
- .section-head p{margin:4px 0 0}
216502
- .fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}
216503
- .fields label,.field{display:grid;gap:7px;font-size:12px;font-weight:550}
216504
- .field.wide{grid-column:1/-1}
216505
- input,select,textarea{width:100%;border:1px solid #d6c5b4;border-radius:8px;padding:12px;background:#fffaf4;color:var(--ink);min-width:0}
216506
- input::placeholder,textarea::placeholder{color:#a89586}
216507
- textarea{resize:vertical}
216508
- input[type=color]{padding:5px;height:46px}
216509
- label small,.small{color:var(--muted);font-size:11px;line-height:1.55;font-weight:400}
216510
- .grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
216511
- .grid.two{grid-template-columns:repeat(2,minmax(0,1fr))}
216512
- .choice{position:relative;text-align:left;border:1px solid var(--line);border-radius:12px;background:var(--surface);padding:17px;display:flex;flex-direction:column;align-items:stretch;gap:7px;min-width:0;transition:border-color .2s,box-shadow .2s}
216513
- .choice:hover{border-color:#b78a82}
216514
- .choice strong{font-size:13px;line-height:1.5;display:block;padding-right:18px}
216515
- .choice small{font-size:11px;color:var(--muted);line-height:1.55;display:block}
216516
- .choice[aria-pressed=true]{border-color:var(--accent);box-shadow:inset 0 0 0 1px var(--accent);background:#f4e8df}
216517
- .choice[aria-pressed=true]:after{content:'✓';position:absolute;top:14px;right:12px;width:17px;height:17px;border-radius:50%;background:var(--accent);color:white;display:grid;place-items:center;font-size:11px}
216518
- .decide{font-size:11px;border:1px solid var(--line);border-radius:30px;background:transparent;padding:8px 11px;white-space:nowrap}
216519
- .decide[aria-pressed=true]{color:var(--accent);border-color:#a8707e;background:#f0e0df55}
216520
- .chips{display:flex;gap:8px;flex-wrap:wrap}
216521
- .chips .choice{padding:9px 12px;border-radius:22px;flex-direction:row;gap:0}
216522
- .chips .choice strong{font-size:12px;font-weight:500;padding-right:0}
216523
- .chips .choice[aria-pressed=true]{padding-right:33px}
216524
- .chips .choice[aria-pressed=true]:after{top:11px;right:10px}
216525
- .button{border:1px solid var(--line);border-radius:9px;padding:12px 19px;font-size:12px;min-height:44px;text-align:center}
216526
- .button.primary{background:var(--accent);color:#fff9f1;border-color:var(--accent)}
216527
- .button.secondary{background:transparent}
216528
- .text-button{background:none;border:none;padding:7px 0;color:var(--accent);font-size:11px;text-decoration:underline;text-underline-offset:4px}
216529
- .actions{display:flex;align-items:center;justify-content:space-between;gap:15px;border-top:1px solid var(--line);padding-top:25px;margin-top:34px}
216530
- .actions>span{font-size:11px;color:var(--muted);text-align:center}
216531
- .bottom{border-top:1px solid var(--line);padding:24px 0;display:flex;justify-content:space-between;gap:20px;font-size:10px;color:var(--muted)}
216532
- details{margin:15px 0;border:1px solid var(--line);border-radius:11px;padding:0 17px}
216533
- summary{font-size:12px;font-weight:600;cursor:pointer;padding:13px 0}
216534
- details>div{padding:5px 0 17px}
216535
- summary small{font-weight:400;color:var(--muted);margin-left:10px}
216536
- .notice{background:#eee2d1;border-left:3px solid #ae7957;padding:13px 17px;font-size:12px;border-radius:0 8px 8px 0;white-space:pre-wrap;margin:18px 0}
216537
- .notice.error{border-color:var(--accent);background:#f0dfe0}
216538
- .brand-preview{position:relative;border-radius:16px;background:var(--brand-bg);color:var(--brand-text);padding:40px;min-height:250px;display:flex;flex-direction:column;justify-content:center;overflow:hidden;margin:20px 0;border:1px solid #d6c5b4}
216539
- .brand-preview:after{content:'';position:absolute;right:-50px;top:-85px;height:240px;width:240px;border:1px solid var(--brand-accent);border-radius:50%;opacity:.24;box-shadow:0 0 0 35px #ffffff0c,0 0 0 36px var(--brand-accent)}
216540
- .brand-preview span{font-size:10px;text-transform:uppercase;letter-spacing:.17em;color:var(--brand-accent);z-index:1}
216541
- .brand-preview strong{font:400 39px/1.15 Georgia,serif;letter-spacing:-1px;z-index:1;margin:15px 0}
216542
- .brand-preview p{font-size:13px;margin:0;z-index:1;color:inherit;max-width:370px}
216543
- .swatches{display:flex;gap:5px;margin-bottom:9px}
216544
- .swatches i{display:block;height:32px;flex:1;border-radius:5px;border:1px solid #291e2410}
216545
- .font-sample{font-size:34px;line-height:1.15;margin:4px 0 8px;letter-spacing:-.7px}
216546
- .media-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:13px}
216547
- .style-card{min-width:0;background:var(--surface);border:1px solid var(--line);border-radius:12px;overflow:hidden;position:relative}
216548
- .style-preview{aspect-ratio:1/1;background:linear-gradient(130deg,#7a5364,#d8b098);display:grid;place-items:center;overflow:hidden;color:#fff3e2;text-align:center;position:relative}
216549
- .style-preview img{width:100%;height:100%;object-fit:cover;position:absolute;inset:0}
216550
- .style-fallback{font:italic 24px Georgia,serif;max-width:150px;padding:15px;position:relative}
216551
- .style-text{padding:15px}
216552
- .style-text strong{font-size:12px;display:block}
216553
- .style-text p{font-size:10px;line-height:1.6;margin:5px 0 12px}
216554
- .style-actions{display:flex;gap:6px;flex-wrap:wrap}
216555
- .style-actions button{font-size:10px;border:1px solid var(--line);background:none;border-radius:20px;padding:6px 9px}
216556
- .style-actions button[aria-pressed=true]{border-color:var(--accent);background:var(--accent);color:#fff}
216557
- .style-actions button[data-sentiment=avoid][aria-pressed=true]{background:#3c3035}
216558
- .style-base{font-size:9px;background:#eee1cf;padding:5px 9px;margin:0;color:#765e48}
216559
- .preview-optin{display:flex;align-items:center;justify-content:space-between;gap:16px;background:#eadecd66;border:1px solid var(--line);padding:15px 18px;border-radius:10px;margin-bottom:20px}
216560
- .preview-optin p{margin:0;font-size:11px;color:var(--muted);max-width:440px}
216561
- .media-tabs{display:flex;gap:8px;margin:0 0 20px}
216562
- .media-tabs button{border:1px solid var(--line);background:none;border-radius:23px;padding:8px 17px;font-size:12px}
216563
- .media-tabs button[aria-pressed=true]{background:var(--accent);color:#fff;border-color:var(--accent)}
216564
- .motion-preview{width:100%;height:100%;display:flex;align-items:center;justify-content:center;position:relative;padding:18px;isolation:isolate;background:var(--brand-bg);color:var(--brand-text)}
216565
- .motion-preview>strong{font:400 28px/1.05 Georgia,serif;z-index:1}
216566
- .motion-preview>strong em{color:var(--brand-accent)}
216567
- .motion-preview>i{position:absolute;width:45px;height:45px;border:2px solid var(--brand-accent);border-radius:14px;opacity:.3;transform:rotate(-15deg)}
216568
- .motion-preview>i:first-child{left:15px;top:20px}
216569
- .motion-preview>i:nth-child(2){right:17px;bottom:20px}
216570
- .motion-preview[data-kind=kinetic-type] strong{animation:kinetic 3.8s cubic-bezier(.2,.8,.2,1) infinite}
216571
- .motion-preview[data-kind=spring-callout] strong{animation:spring 4s cubic-bezier(.18,.9,.25,1.2) infinite}
216572
- .motion-preview[data-kind=quiet-reveal] strong{animation:quiet 4.8s ease infinite}
216573
- .motion-preview[data-kind=diagram-build]>i{animation:quiet 4s ease infinite;opacity:.5}
216574
- .motion-preview[data-kind=diagram-build]>i:nth-child(2){animation-delay:.4s}
216575
- .motion-preview[data-kind=parallax-depth]>i{animation:depth 5s ease-in-out infinite}
216576
- .motion-preview[data-kind=match-cut] strong{animation:match 4.5s steps(1) infinite}
216577
- .motion-preview[data-playing=false] *{animation:none!important}
216578
- .support-preview{display:flex;gap:4px;background:#4f3441;padding:15px 10px;border-radius:8px;margin-bottom:7px}
216579
- .support-preview span{flex:1;aspect-ratio:3/4;border:1px solid #cab3a333;border-radius:4px;color:#e4ccba;display:grid;place-items:center;background:#e4ccba18}
216580
- .support-preview span[data-insert=true]{background:#e4ccba;color:#6e4c45}
216581
- .support-preview svg{width:80%;height:80%}
216582
- .caption-example{min-height:100px;background:var(--brand-bg);color:var(--brand-text);display:flex;align-items:center;justify-content:center;text-align:center;padding:15px;border-radius:8px;margin-bottom:7px;font-size:17px;line-height:1.4}
216583
- .caption-example mark{background:var(--brand-accent);color:var(--brand-bg);padding:1px 5px;border-radius:3px}
216584
- .caption-example.boxed span{background:var(--brand-text);color:var(--brand-bg);padding:7px;border-radius:5px}
216585
- .caption-example.karaoke span{font-weight:700}
216586
- .caption-example.clean span{font-size:15px}
216587
- .review-list{display:grid;gap:11px}
216588
- .review-item{padding:18px;background:#fffaf2;border:1px solid var(--line);border-radius:12px}
216589
- .review-item h3{font-size:13px;margin:0 0 7px}
216590
- .review-item p{font-size:12px;color:var(--muted);margin:0;white-space:pre-line}
216591
- .review-item button{margin-top:8px}
216592
- .summary-banner{padding:27px 30px;background:linear-gradient(120deg,#3b2933,#783f52);border-radius:14px;color:#fff4e3;margin-bottom:25px}
216593
- .summary-banner h3{font:400 27px Georgia,serif;color:inherit}
216594
- .summary-banner p{font-size:12px;color:#dcc4b4;margin:0}
216595
- .summary-actions{display:flex;gap:12px;flex-wrap:wrap;margin-top:24px}
216596
- dialog{width:min(940px,calc(100% - 32px));max-height:90dvh;overflow:auto;border:1px solid var(--line);border-radius:18px;padding:30px;background:var(--paper);color:var(--ink)}
216597
- dialog::backdrop{background:#291922bd;backdrop-filter:blur(5px)}
216598
- .dialog-head{display:flex;align-items:flex-start;justify-content:space-between;gap:18px}
216599
- .dialog-head h2{font-size:30px;margin:7px 0 18px}
216600
- .dialog-head button{flex-shrink:0}
216601
- #dialog-examples{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:15px;align-items:start}
216602
- #dialog-examples figure{margin:0}
216603
- #dialog-examples img{display:block;width:100%;height:auto;border-radius:9px}
216604
- #dialog-examples figcaption{font-size:11px;margin-top:7px;color:var(--muted)}
216605
- [hidden]{display:none!important}
216606
- @keyframes quiet{0%,15%{opacity:0;transform:translateY(12px)}
216607
- 32%,78%{opacity:1;transform:translateY(0)}
216608
- 95%,100%{opacity:0;transform:translateY(-7px)}
216609
- }
216610
- @keyframes kinetic{0%,12%{opacity:0;transform:translateX(-30px) rotate(-3deg)}
216611
- 25%,77%{opacity:1;transform:translateX(0) rotate(0)}
216612
- 88%,100%{opacity:0;transform:translateX(30px) rotate(3deg)}
216613
- }
216614
- @keyframes spring{0%,10%{transform:scale(.6);opacity:0}
216615
- 28%{transform:scale(1.07);opacity:1}
216616
- 36%,79%{transform:scale(1);opacity:1}
216617
- 95%,100%{transform:scale(.8);opacity:0}
216618
- }
216619
- @keyframes depth{50%{transform:translateX(15px) rotate(12deg)}
216620
- }
216621
- @keyframes match{0%,100%{transform:scale(.9)}
216622
- 35%{transform:scale(1.08)}
216623
- 70%{transform:scale(1)}
216624
- }
216625
- @media(max-width:1100px){.layout{grid-template-columns:220px minmax(0,1fr);gap:34px}
216626
- .sidebar h1{font-size:34px}
216627
- .grid{grid-template-columns:repeat(2,minmax(0,1fr))}
216628
- .media-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
216629
- }
216630
- @media(max-width:780px){.app{padding:0 20px}
216631
- .top{height:70px}
216632
- .layout{display:block;padding-top:24px}
216633
- .page-top{align-items:flex-start}
216634
- h2{font-size:34px}
216635
- .section-head{flex-wrap:wrap}
216636
- .fields{gap:14px}
216637
- .brand-preview{padding:27px;min-height:225px}
216638
- .brand-preview strong{font-size:31px}
216639
- .actions>span{display:none}
216640
- .actions{margin-top:25px}
216641
- .bottom{flex-direction:column;gap:5px}
216642
- .preview-optin{align-items:flex-start;flex-direction:column}
216643
- .style-text{padding:12px}
216644
- .style-actions button{font-size:10px}
216645
- .grid.two{grid-template-columns:repeat(2,minmax(0,1fr))}
216646
- }
216647
- @media(max-width:420px){.app{padding:0 15px}
216648
- .product-label{font-size:17px}
216649
- .local-badge{font-size:10px}
216650
- #steps button{font-size:9px;padding:7px 5px;gap:5px}
216651
- .fields,.grid{grid-template-columns:1fr}
216652
- .grid.two{grid-template-columns:repeat(2,minmax(0,1fr))}
216653
- .media-grid{gap:9px}
216654
- .style-preview{aspect-ratio:4/5}
216655
- .style-text p{font-size:10px}
216656
- .style-fallback{font-size:22px}
216657
- .motion-preview>strong{font-size:23px}
216658
- .actions .button{padding:11px 13px}
216659
- .summary-banner{padding:23px}
216660
- .section-head .decide{white-space:normal}
216661
- dialog{padding:20px}
216662
- #dialog-examples{grid-template-columns:1fr}
216663
- .dialog-head h2{font-size:25px}
216664
- }
216665
-
216666
- body{background:radial-gradient(ellipse at 85% 10%,#edb88420,transparent 55%),#f3ede3;transition:background-color .35s}
216667
- body[data-theme=wine]{background-color:#351d29;color:#f3ede3}
216668
- body[data-theme=porcelain]{background-color:#162a24;color:#f3ede3}
216669
- body:not([data-theme=paper]) .intro,body:not([data-theme=paper]) .bottom,body:not([data-theme=paper]) .actions>span{color:#d4c4b5}
216670
- body:not([data-theme=paper]) .eyebrow,body:not([data-theme=paper]) .text-button{color:#efb678}
216671
- body:not([data-theme=paper]) .top,body:not([data-theme=paper]) .bottom,body:not([data-theme=paper]) .actions{border-color:#f3ede32b}
216672
- body:not([data-theme=paper]) .local-badge{border-color:#f3ede32b;color:#f3ede3}
216673
- .product-label svg{width:174px;height:auto}
216674
- body[data-theme=paper] .product-label svg{filter:brightness(0)}
216675
- #page-title{font:400 clamp(40px,5vw,70px)/1.04 Georgia,serif;letter-spacing:-.045em;max-width:850px;margin:22px 0;outline:none}
216676
- .intro{font-size:16px;line-height:1.7;max-width:730px;margin-bottom:32px}
216677
- #preferences{padding:clamp(20px,3vw,36px);border:1px solid #ffffffa6;border-radius:24px;background:#fbf7f0f5;color:var(--ink);box-shadow:0 24px 70px #100a0614,inset 0 1px 0 #ffffffcc}
216678
- #panel{animation:studio-enter .45s ease-out both}
216679
- #panel .section:last-child{margin-bottom:0}
216680
- #panel .text-button{color:var(--accent)}
216681
- .choice{background:#fffdf6b8;box-shadow:inset 0 1px 0 #ffffffcc;transition:transform .25s,border-color .25s,box-shadow .25s}
216682
- .choice:hover{transform:translateY(-2px);box-shadow:0 8px 24px #682e3b10}
216683
- .actions .button{border-radius:99px;padding:14px 24px}
216684
- .actions .button.primary{background:#e89a4a;color:#211914;border-color:#e89a4a;font-weight:650}
216685
- body:not([data-theme=paper]) .actions .secondary{color:#f3ede3;border-color:#f3ede32b}
216686
- @keyframes studio-enter{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
216687
- @media(max-width:600px){.layout{padding-top:30px}.step-label{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}#steps{gap:6px;margin-top:20px}.step-bar{margin-bottom:0}.top{height:72px}.product-label svg{width:142px}.local-badge{font-size:9px}#page-title{font-size:43px}#preferences{padding:18px;border-radius:18px}.intro{font-size:14px}}
216688
- @media(prefers-reduced-transparency:reduce){#preferences,.choice{background:#fbf7f0}}
216689
- @media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}
216690
- }
216691
-
216796
+ .top{min-height:88px;border-bottom:1px solid var(--line-subtle);display:flex;align-items:center;justify-content:space-between;gap:18px}
216797
+ .product-label{text-decoration:none;color:var(--ink);display:flex;align-items:center;flex-shrink:0}
216798
+ .product-label svg{width:174px;height:auto}.product-label svg g{fill:currentColor}
216799
+ .top-actions{display:flex;align-items:center;gap:15px}
216800
+ .local-badge{color:var(--muted);font-size:12px}
216801
+ .theme-toggle{display:grid;place-items:center;width:44px;height:44px;padding:0;border:1px solid var(--line);border-radius:50%;background:transparent;color:var(--muted);flex-shrink:0;transition:background-color .18s,border-color .18s}
216802
+ .theme-toggle:hover{background:var(--surface-2);border-color:var(--muted)}.theme-toggle svg{width:19px;height:19px}.theme-toggle .sun,body[data-theme=dark] .theme-toggle .moon{display:none}body[data-theme=dark] .theme-toggle .sun{display:block}
216803
+ .layout{max-width:980px;margin:auto;padding:38px 0 56px}.eyebrow{font-size:11px;letter-spacing:.12em;font-weight:650;text-transform:uppercase;color:var(--muted);font-variant-numeric:tabular-nums}
216804
+ #steps{display:flex;gap:10px;max-width:980px;margin:28px auto 0;padding:0;border:0}
216805
+ #steps button{flex:1;min-width:0;min-height:52px;border:1px solid transparent;background:transparent;padding:8px 10px;color:var(--muted);font-size:12px;border-radius:10px;transition:background-color .18s}
216806
+ #steps button:hover{background:var(--surface-2)}.step-bar{display:block;height:3px;background:var(--line);border-radius:3px;margin-bottom:8px}
216807
+ #steps [data-done=true] .step-bar{background:var(--success)}#steps [aria-current=step],#steps [aria-current=step]:hover{background:var(--select);color:var(--select-ink)}#steps [aria-current=step] .step-bar{background:var(--select-ink)}
216808
+ .page-top{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px}.draft-actions{display:flex;flex-wrap:wrap;align-items:center;gap:12px}
216809
+ #page-title{font:400 clamp(34px,4vw,48px)/1.12 Georgia,serif;letter-spacing:-.035em;max-width:850px;margin:21px 0 14px}
216810
+ #page-title:focus,#main:focus{outline:none}h2{font:400 clamp(28px,3.4vw,40px)/1.15 Georgia,serif;letter-spacing:-.025em;margin:20px 0 14px}
216811
+ .intro{color:var(--muted);font-size:15px;max-width:730px;margin-bottom:34px}h3{font-size:17px;line-height:1.4;letter-spacing:-.015em;margin:0 0 8px}
216812
+ #preferences{padding:0;border:0;background:transparent;color:var(--ink)}#panel{animation:studio-enter .2s ease-out both}#panel>.section:last-child{margin-bottom:0}
216813
+ .section{margin-bottom:34px;min-width:0}.section p{font-size:13px;color:var(--muted);margin-bottom:14px}.section-head{display:flex;justify-content:space-between;align-items:flex-start;gap:14px;margin-bottom:16px}.section-head p{margin:4px 0 0}
216814
+ .fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.fields label,.field{display:grid;gap:7px;font-size:13px;font-weight:550}.field.wide{grid-column:1/-1}
216815
+ input,select,textarea{width:100%;border:1px solid var(--line);border-radius:10px;padding:12px;background:var(--surface);color:var(--ink);min-width:0;min-height:46px}input::placeholder,textarea::placeholder{color:var(--muted)}textarea{resize:vertical}input[type=color]{padding:5px;height:46px}label small,.small{color:var(--muted);font-size:12px;line-height:1.55;font-weight:400}
216816
+ .grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.grid.two{grid-template-columns:repeat(2,minmax(0,1fr))}
216817
+ .choice{position:relative;text-align:left;border:1px solid var(--line);border-radius:12px;background:var(--surface);padding:17px;display:flex;flex-direction:column;align-items:stretch;gap:7px;min-width:0;min-height:48px;transition:border-color .18s,background-color .18s,box-shadow .18s}
216818
+ .choice:hover{border-color:var(--muted)}.choice strong{font-size:14px;line-height:1.5;display:block;padding-right:23px}.choice small{font-size:12px;color:var(--muted);line-height:1.55;display:block}
216819
+ .choice[aria-pressed=true]{border-color:var(--select-border);box-shadow:inset 0 0 0 .5px var(--select-border);background:var(--surface-soft)}
216820
+ .choice[aria-pressed=true]:after{content:'✓';position:absolute;top:14px;right:12px;width:19px;height:19px;border-radius:50%;background:var(--ink);color:var(--surface);display:grid;place-items:center;font-size:12px}
216821
+ .grid[data-selection=single]>.choice[aria-pressed=true]{background:var(--select);color:var(--select-ink);border-color:transparent;box-shadow:none}.grid[data-selection=single]>.choice[aria-pressed=true] small{color:var(--select-muted)}.grid[data-selection=single]>.choice[aria-pressed=true]:after{color:var(--select);background:var(--select-ink)}
216822
+ .decide{font-size:12px;border:1px solid var(--line);border-radius:24px;background:transparent;padding:10px 12px;min-height:44px;white-space:nowrap}.decide[aria-pressed=true]{color:var(--ink);border-color:var(--select-border);background:var(--surface-soft)}
216823
+ .chips{display:flex;gap:8px;flex-wrap:wrap}.chips .choice{padding:10px 13px;border-radius:24px;flex-direction:row;gap:0}.chips .choice strong{font-size:12px;font-weight:500;padding-right:0}.chips .choice[aria-pressed=true]{padding-right:36px}.chips .choice[aria-pressed=true]:after{top:12px;right:10px}
216824
+ .button{border:1px solid var(--line);border-radius:10px;padding:12px 19px;font-size:13px;min-height:44px;text-align:center;transition:background-color .18s,border-color .18s}.button.primary{background:var(--action);color:var(--action-ink);border-color:var(--action);font-weight:650}.button.primary:hover{background:var(--action-hover);border-color:var(--action-hover)}.button.secondary{background:transparent;color:var(--ink)}.button.secondary:hover{border-color:var(--muted);background:var(--surface-2)}
216825
+ .text-button{background:none;border:0;padding:10px 0;color:var(--accent);font-size:12px;min-height:44px;text-decoration:underline;text-underline-offset:4px}
216826
+ .actions{display:flex;align-items:center;justify-content:space-between;gap:15px;border-top:1px solid var(--line-subtle);padding-top:25px;margin-top:34px}.actions>span{font-size:12px;color:var(--muted);text-align:center;max-width:500px}.actions .button{border-radius:99px;padding:13px 22px;flex-shrink:0}
216827
+ .bottom{border-top:1px solid var(--line-subtle);padding:24px 0 max(24px,env(safe-area-inset-bottom));display:flex;justify-content:space-between;gap:20px;font-size:12px;color:var(--muted)}
216828
+ details{margin:15px 0;border:1px solid var(--line);border-radius:12px;padding:0 17px;background:var(--surface)}summary{font-size:13px;font-weight:600;cursor:pointer;padding:14px 0;min-height:48px}details>div{padding:5px 0 17px}summary small{font-weight:400;color:var(--muted);margin-left:10px}
216829
+ .notice{background:var(--surface-2);border:1px solid var(--line);padding:15px 18px;font-size:13px;border-radius:12px;white-space:pre-wrap;margin:18px 0;color:var(--ink)}.notice.error{border-color:var(--danger);background:var(--danger-bg);color:var(--danger)}#status:not([hidden]){background:var(--success-bg);color:var(--success);border-color:transparent}
216830
+ .brand-preview{position:relative;border-radius:16px;background:var(--brand-bg);color:var(--brand-text);padding:40px;min-height:250px;display:flex;flex-direction:column;justify-content:center;overflow:hidden;margin:20px 0;border:1px solid var(--line)}.brand-preview:after{content:'';position:absolute;right:-50px;top:-85px;height:240px;width:240px;border:1px solid var(--brand-accent);border-radius:50%;opacity:.24;box-shadow:0 0 0 35px #ffffff0c,0 0 0 36px var(--brand-accent)}.brand-preview span{font-size:11px;text-transform:uppercase;letter-spacing:.14em;color:var(--brand-text);z-index:1}.brand-preview strong{font:400 39px/1.15 Georgia,serif;letter-spacing:-1px;z-index:1;margin:15px 0}.brand-preview p{font-size:13px;margin:0;z-index:1;color:inherit;max-width:370px}
216831
+ .swatches{display:flex;gap:5px;margin-bottom:9px}.swatches i{display:block;height:32px;flex:1;border-radius:5px;border:1px solid #0001}.font-sample{font-size:34px;line-height:1.15;margin:4px 0 8px;letter-spacing:-.7px}
216832
+ .media-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:13px}.style-card{min-width:0;background:var(--surface);border:1px solid var(--line);border-radius:12px;overflow:hidden;position:relative}.style-card:has(.style-actions [aria-pressed=true]){border-color:var(--select-border);box-shadow:inset 0 0 0 .5px var(--select-border)}.style-preview{aspect-ratio:1;background:var(--surface-2);display:grid;place-items:center;overflow:hidden;color:var(--muted);text-align:center;position:relative}.style-preview img{width:100%;height:100%;object-fit:cover;position:absolute;inset:0}.style-fallback{font:italic 24px Georgia,serif;max-width:160px;padding:15px;position:relative}.style-text{padding:15px}.style-text strong{font-size:14px;display:block}.style-text p{font-size:12px;line-height:1.6;margin:5px 0 12px}.style-actions{display:flex;gap:7px;flex-wrap:wrap}.style-actions button{font-size:12px;border:1px solid var(--line);background:transparent;border-radius:24px;padding:9px 11px;min-height:44px}.style-actions button[aria-pressed=true]{border-color:var(--select-border);background:var(--surface-soft);color:var(--ink)}.style-base{font-size:11px;background:var(--surface-soft);padding:7px 10px;margin:0;color:var(--muted)}
216833
+ .preview-optin{display:flex;align-items:center;justify-content:space-between;gap:16px;background:var(--surface-2);border:1px solid var(--line);padding:16px 18px;border-radius:12px;margin-bottom:20px}.preview-optin p{margin:0;font-size:13px;color:var(--muted);max-width:440px}.media-tabs{display:flex;gap:8px;margin:0 0 20px}.media-tabs button{border:1px solid var(--line);background:transparent;border-radius:24px;padding:10px 17px;min-height:44px;font-size:13px}.media-tabs button[aria-pressed=true]{background:var(--select);color:var(--select-ink);border-color:transparent}
216834
+ .motion-preview{width:100%;height:100%;display:flex;align-items:center;justify-content:center;position:relative;padding:18px;isolation:isolate;background:var(--brand-bg);color:var(--brand-text)}.motion-preview>strong{font:400 28px/1.05 Georgia,serif;z-index:1}.motion-preview>strong em{color:var(--brand-accent)}.motion-preview>i{position:absolute;width:45px;height:45px;border:2px solid var(--brand-accent);border-radius:14px;opacity:.3;transform:rotate(-15deg)}.motion-preview>i:first-child{left:15px;top:20px}.motion-preview>i:nth-child(2){right:17px;bottom:20px}
216835
+ .motion-preview[data-kind=kinetic-type] strong{animation:kinetic 3.8s cubic-bezier(.2,.8,.2,1) infinite}.motion-preview[data-kind=spring-callout] strong{animation:spring 4s cubic-bezier(.18,.9,.25,1.2) infinite}.motion-preview[data-kind=quiet-reveal] strong{animation:quiet 4.8s ease infinite}.motion-preview[data-kind=diagram-build]>i{animation:quiet 4s ease infinite;opacity:.5}.motion-preview[data-kind=diagram-build]>i:nth-child(2){animation-delay:.4s}.motion-preview[data-kind=parallax-depth]>i{animation:depth 5s ease-in-out infinite}.motion-preview[data-kind=match-cut] strong{animation:match 4.5s steps(1) infinite}.motion-preview[data-playing=false] *{animation:none!important}
216836
+ .support-preview{display:flex;gap:4px;background:var(--surface-2);padding:15px 10px;border-radius:8px;margin-bottom:7px}.support-preview span{flex:1;aspect-ratio:3/4;border:1px solid var(--line);border-radius:4px;color:var(--muted);display:grid;place-items:center;background:var(--surface)}.support-preview span[data-insert=true]{background:var(--select);color:var(--select-ink)}.support-preview svg{width:80%;height:80%}
216837
+ .caption-example{min-height:100px;background:var(--brand-bg);color:var(--brand-text);display:flex;align-items:center;justify-content:center;text-align:center;padding:15px;border-radius:8px;margin-bottom:7px;font-size:17px;line-height:1.4}.caption-example mark{background:var(--brand-accent);color:var(--brand-bg);padding:1px 5px;border-radius:3px}.caption-example.boxed span{background:var(--brand-text);color:var(--brand-bg);padding:7px;border-radius:5px}.caption-example.karaoke span{font-weight:700}.caption-example.clean span{font-size:15px}
216838
+ .review-list{display:grid;gap:12px}.review-item{padding:19px;background:var(--surface);border:1px solid var(--line);border-radius:12px}.review-item h3{font-size:15px;margin:0 0 7px}.review-item p{font-size:13px;color:var(--muted);margin:0;white-space:pre-line}.review-item button{margin-top:8px}.summary-banner{padding:26px 28px;background:var(--surface-2);border:1px solid var(--line);border-radius:14px;color:var(--ink);margin-bottom:25px}.summary-banner h3{font:400 29px Georgia,serif;color:inherit}.summary-banner p{font-size:13px;color:var(--muted);margin:0}.summary-actions{display:flex;gap:12px;flex-wrap:wrap;margin-top:24px}
216839
+ dialog{width:min(940px,calc(100% - 32px));max-height:90dvh;overflow:auto;border:1px solid var(--line);border-radius:18px;padding:30px;background:var(--surface);color:var(--ink)}dialog::backdrop{background:var(--overlay);backdrop-filter:blur(5px)}.dialog-head{display:flex;align-items:flex-start;justify-content:space-between;gap:18px}.dialog-head h2{font-size:30px;margin:7px 0 18px}.dialog-head button{flex-shrink:0}#dialog-examples{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:15px;align-items:start}#dialog-examples figure{margin:0}#dialog-examples img{display:block;width:100%;height:auto;border-radius:9px}#dialog-examples figcaption{font-size:12px;margin-top:7px;color:var(--muted)}[hidden]{display:none!important}
216840
+ @keyframes studio-enter{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}@keyframes quiet{0%,15%{opacity:0;transform:translateY(12px)}32%,78%{opacity:1;transform:translateY(0)}95%,100%{opacity:0;transform:translateY(-7px)}}@keyframes kinetic{0%,12%{opacity:0;transform:translateX(-30px) rotate(-3deg)}25%,77%{opacity:1;transform:translateX(0) rotate(0)}88%,100%{opacity:0;transform:translateX(30px) rotate(3deg)}}@keyframes spring{0%,10%{transform:scale(.6);opacity:0}28%{transform:scale(1.07);opacity:1}36%,79%{transform:scale(1);opacity:1}95%,100%{transform:scale(.8);opacity:0}}@keyframes depth{50%{transform:translateX(15px) rotate(12deg)}}@keyframes match{0%,100%{transform:scale(.9)}35%{transform:scale(1.08)}70%{transform:scale(1)}}
216841
+ @media(max-width:1100px){.grid,.media-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
216842
+ @media(max-width:780px){.app{padding:0 20px}.top{min-height:76px}.layout{padding-top:28px}.local-badge{display:none}.page-top{align-items:flex-start}.section-head{flex-wrap:wrap}.fields{gap:14px}.brand-preview{padding:27px;min-height:225px}.brand-preview strong{font-size:31px}.actions>span{display:none}.actions{margin-top:25px}.bottom{flex-direction:column;gap:5px}.preview-optin{align-items:flex-start;flex-direction:column}.style-text{padding:14px}}
216843
+ @media(max-width:600px){.app{padding:0 16px}.product-label svg{width:154px}.top{min-height:72px}.top-actions{gap:8px}#steps{gap:4px;margin-top:18px}#steps button{font-size:11px;padding:9px 4px}#steps .step-bar{margin-bottom:5px}#page-title{font-size:36px}.intro{font-size:14px}.fields,.grid,.grid.two{grid-template-columns:1fr}.media-grid{gap:10px}.media-tabs button{flex:1}.choice{padding:16px}.style-preview{aspect-ratio:4/5}.style-fallback{font-size:22px}.motion-preview>strong{font-size:23px}.actions{gap:10px}.actions .button{padding:12px 16px}.summary-banner{padding:22px}.section-head .decide{white-space:normal}.summary-actions{flex-direction:column}.summary-actions .button{width:100%}dialog{padding:20px}#dialog-examples{grid-template-columns:1fr}.dialog-head h2{font-size:25px}}
216844
+ @media(prefers-reduced-transparency:reduce){dialog::backdrop{backdrop-filter:none}}
216845
+ @media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}
216692
216846
  `;
216693
216847
  var artifactScript = String.raw`
216694
216848
  (() => {
@@ -216696,7 +216850,7 @@ var artifactScript = String.raw`
216696
216850
  const data = JSON.parse(document.getElementById('onboarding-data').textContent), intake = structuredClone(data.intake), options = data.options, catalog = data.styles;
216697
216851
  const $ = id => document.getElementById(id), panel = $('panel'), error = $('error'), status = $('status');
216698
216852
  let sfxExpanded = false;
216699
- let step = 0, mediaTab = 'image', showImages = false, busy = false, observer, nameEdited = false;
216853
+ let step = 0, mediaTab = 'image', showImages = false, busy = false, observer, nameEdited = false, dirty = false;
216700
216854
  const editedTokens = new Set();
216701
216855
  const steps = data.steps;
216702
216856
  const p = () => intake.profile || {}, delivery = () => p().editorialDelivery && typeof p().editorialDelivery === 'object' ? p().editorialDelivery : {}, audio = () => intake.audio || {};
@@ -216706,13 +216860,13 @@ var artifactScript = String.raw`
216706
216860
  const append = (parent, ...children) => { children.filter(Boolean).forEach(child => parent.append(child)); return parent; };
216707
216861
  const button = (text, handler, cls = 'button secondary') => { const el = node('button', cls, text); el.type = 'button'; el.addEventListener('click', handler); return el; };
216708
216862
  const setStatus = (text, isError = false) => { const target = isError ? error : status; target.textContent = text; target.hidden = !text; };
216709
- const changed = () => { setStatus(''); setStatus('', true); };
216863
+ const changed = () => { dirty = true; setStatus(''); setStatus('', true); };
216710
216864
  function updateProfile(key, value) { intake.profile = { ...p(), [key]: value }; changed(); }
216711
216865
  function updateDelivery(key, value) { updateProfile('editorialDelivery', { ...delivery(), [key]: value }); }
216712
216866
  function section(title, description, decide) { const root = node('section', 'section'), head = node('div', 'section-head'), copy = node('div'); append(copy, node('h3', '', title), description ? node('p', '', description) : null); append(head, copy, decide); root.append(head); return root; }
216713
216867
  function decide(selected, fn, label = 'Que mi agente decida') { const el = button(label, () => { fn(); render(); }, 'decide'); el.setAttribute('aria-pressed', String(selected)); return el; }
216714
216868
  function card(value, title, description, selected, handler, preview) { const el = button('', handler, 'choice'); el.dataset.value = value; el.setAttribute('aria-label', title + (description ? ' · ' + description : '')); el.setAttribute('aria-pressed', String(selected)); append(el, preview, node('strong', '', title), description ? node('small', '', description) : null); return el; }
216715
- function choices(container, list, current, handler, { multiple = false, columns = 3, preview } = {}) { const grid = node('div', columns === 2 ? 'grid two' : 'grid'); list.forEach((item, index) => { const [value, title, description] = Array.isArray(item) ? item : [item, item, '']; const selected = multiple ? (current || []).includes(value) : current === value; grid.append(card(value, title, description, selected, () => { handler(value, selected); render(); }, preview?.(value, index))); }); container.append(grid); return grid; }
216869
+ function choices(container, list, current, handler, { multiple = false, columns = 3, preview } = {}) { const grid = node('div', columns === 2 ? 'grid two' : 'grid'); grid.dataset.selection = multiple ? 'multiple' : 'single'; list.forEach((item, index) => { const [value, title, description] = Array.isArray(item) ? item : [item, item, '']; const selected = multiple ? (current || []).includes(value) : current === value; grid.append(card(value, title, description, selected, () => { handler(value, selected); render(); }, preview?.(value, index))); }); container.append(grid); return grid; }
216716
216870
  function field(container, label, value, handler, { placeholder = '', type = 'text', maxLength = 500, wide = false, help = '', multiline = false } = {}) { const wrap = node('label', 'field' + (wide ? ' wide' : '')), labelText = node('span', '', label), input = node(multiline ? 'textarea' : 'input'); if (!multiline)
216717
216871
  input.type = type;
216718
216872
  else
@@ -216767,6 +216921,11 @@ var artifactScript = String.raw`
216767
216921
  }
216768
216922
  intro.append(fields);
216769
216923
  panel.append(intro);
216924
+ const presence = section('¿Quién suele aparecer en tus videos?', 'Describe el contenido habitual. No elige tu voz ni habilita material o servicios.');
216925
+ const presenceOptions = [['face','Yo, a cámara'],['voice','Sin cara, con mi voz'],['ai','Sin cara, con voz de IA'],['others','Otras personas'],['screen','Grabación de pantalla'],['product','Solo producto o manos']];
216926
+ select(presence, 'Presentación principal', p().contentPresence?.primary, presenceOptions, v => updateProfile('contentPresence', v ? {primary:v,secondary:(p().contentPresence?.secondary||[]).filter(id=>id!==v)} : null));
216927
+ if(p().contentPresence?.primary)choices(presence,presenceOptions.filter(([id])=>id!==p().contentPresence.primary),p().contentPresence.secondary||[],(id,selected)=>updateProfile('contentPresence',{...p().contentPresence,secondary:selected?(p().contentPresence.secondary||[]).filter(v=>v!==id):[...(p().contentPresence.secondary||[]),id]}),{multiple:true});
216928
+ panel.append(presence);
216770
216929
  const formats = section('¿Qué tipo de videos quieres hacer?', 'Puedes combinar varios.', decide(!(p().formats || []).length, () => updateProfile('formats', []), 'Decidir en cada video'));
216771
216930
  const primary = ['A cámara', 'Grabación de pantalla', 'Narrados con imágenes', 'Animados', 'Documentales'];
216772
216931
  choices(formats, primary, p().formats, (v, s) => toggleProfileArray('formats', v, s), { multiple: true });
@@ -216801,7 +216960,7 @@ var artifactScript = String.raw`
216801
216960
  panel.append(preview, node('p', 'small', 'Vista de ejemplo. Los colores y fuentes de demostración no se guardan automáticamente.'));
216802
216961
  const palettes = [['Papel editorial', ['#F1E8D8', '#282621', '#E89A4A']], ['Blanco y negro', ['#FFFFFF', '#161616', '#161616']], ['Bosque', ['#EDF1E8', '#23372C', '#65826C']], ['Azul profundo', ['#EDF2FA', '#172C4B', '#3B6CBA']], ['Tierra', ['#F4EBE2', '#392D29', '#BA6753']], ['Oscuro eléctrico', ['#171A22', '#F7F5EF', '#B5CF62']]];
216803
216962
  const paletteSection = section('Tus colores', 'Úsalos como punto de partida o escribe los tuyos.');
216804
- const grid = node('div', 'grid');
216963
+ const grid = node('div', 'grid');grid.dataset.selection='single';
216805
216964
  palettes.forEach(([name, colors]) => { const swatches = node('span', 'swatches'); colors.forEach(color => { const s = node('i'); s.style.background = color; swatches.append(s); }); grid.append(card(name, name, '', colors.every((color, i) => tokenValue(['color.background', 'color.text', 'color.accent'][i])?.toUpperCase() === color), () => { colors.forEach((color, i) => setToken(['color.background', 'color.text', 'color.accent'][i], color)); render(); }, swatches)); });
216806
216965
  paletteSection.append(grid);
216807
216966
  const custom = node('div', 'fields');
@@ -216811,7 +216970,7 @@ var artifactScript = String.raw`
216811
216970
  panel.append(paletteSection);
216812
216971
  const type = section('Tu tipografía', 'La fuente exacta debe estar disponible para el agente al editar. Las muestras usan fuentes del sistema.');
216813
216972
  const fonts = [['Editorial clásico', 'Georgia', 'Arial', 'Georgia,serif'], ['Claro y moderno', 'Arial', 'Arial', 'Arial,sans-serif'], ['Técnico', 'Courier New', 'Arial', '"Courier New",monospace']];
216814
- const fontGrid = node('div', 'grid');
216973
+ const fontGrid = node('div', 'grid');fontGrid.dataset.selection='single';
216815
216974
  fonts.forEach(([name, heading, body, family]) => { const sample = node('span', 'font-sample', 'Aa · Tu idea'); sample.style.fontFamily = family; fontGrid.append(card(name, name, heading + ' + ' + body, tokenValue('typography.heading') === heading && tokenValue('typography.body') === body, () => { setToken('typography.heading', heading); setToken('typography.body', body); render(); }, sample)); });
216816
216975
  type.append(fontGrid);
216817
216976
  const fontFields = node('div', 'fields');
@@ -216825,7 +216984,7 @@ var artifactScript = String.raw`
216825
216984
  type.append(fontDetails);
216826
216985
  panel.append(type);
216827
216986
  const freedom = section('¿Cuánto puede explorar tu agente?', 'Los tokens obligatorios de marca se respetan en ambos casos.', decide(!p().freedom, () => updateProfile('freedom', '')));
216828
- 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 });
216987
+ choices(freedom, [[options.freedom[0], 'Una identidad reconocible', 'Mantener criterios visuales; adaptar cada escena.'], ['Explorar con moderación', 'Algunas sorpresas', 'Mantener tu estilo y explorar cuando aporte.'], ['Explorar según el proyecto', 'Explorar composiciones nuevas', 'Variar recursos y animaciones según el video.']], p().freedom, v => updateProfile('freedom', v), { columns: 2 });
216829
216988
  panel.append(freedom);
216830
216989
  }
216831
216990
  function getStyleState(id) { return (p().mediaStyles || []).find(item => item.styleId === id)?.state; }
@@ -216836,6 +216995,11 @@ var artifactScript = String.raw`
216836
216995
  }
216837
216996
  next.push({ styleId: style.id, version: style.version, state: sentiment });
216838
216997
  } updateProfile('mediaStyles', next); render(); }
216998
+ function styleBase(category, id) {
216999
+ const current=p().mediaStyles||[], eligible=item=>catalog.some(style=>style.id===item.styleId&&style.version===item.version&&style.category===category);
217000
+ if(id&&!current.some(item=>item.styleId===id&&item.state!=='avoid'&&eligible(item)))return;
217001
+ updateProfile('mediaStyles',current.map(item=>eligible(item)?item.styleId===id?{...item,state:'default'}:item.state==='default'?{...item,state:'favorite'}:item:item));
217002
+ }
216839
217003
  function motionPreview(id) { const el = node('div', 'motion-preview'); el.dataset.kind = id; el.dataset.playing = 'false'; append(el, node('i'), node('i')); const text = node('strong', '', 'Una idea.'); text.append(document.createElement('br'), node('em', '', 'Que se entienda.')); el.append(text); return el; }
216840
217004
  function observeMotion() { observer?.disconnect(); observer = new IntersectionObserver(entries => { const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches; entries.forEach(entry => entry.target.dataset.playing = String(entry.isIntersecting && !reduced)); }, { threshold: .35 }); panel.querySelectorAll('.motion-preview').forEach(el => observer.observe(el)); }
216841
217005
  function openExamples(style) { $('dialog-title').textContent = style.name; $('dialog-description').textContent = style.description; const holder = $('dialog-examples'); holder.replaceChildren(); style.examples.forEach(example => { const figure = node('figure'), img = node('img'); img.src = example.url; img.alt = style.name + ' · ' + example.ratio; img.referrerPolicy = 'no-referrer'; append(figure, img, node('figcaption', '', example.ratio)); holder.append(figure); }); $('style-dialog').showModal(); }
@@ -216869,6 +217033,9 @@ var artifactScript = String.raw`
216869
217033
  [['density', 'Composición', [['minimal', 'Pocas capas a la vez'], ['layered', 'Varias capas en diálogo']]], ['energy', 'Movimiento', [['calm', 'Suave'], ['lively', 'Expresivo']]], ['contrast', 'Contraste', [['soft', 'Suave, siempre legible'], ['strong', 'Marcado']]]].forEach(([key, label, items]) => select(tasteFields, label, taste[key], items, v => updateProfile('visualTaste', { ...(p().visualTaste || {}), [key]: v || null })));
216870
217034
  if (mediaTab === 'motion')
216871
217035
  select(tasteFields, 'Cómo producir las animaciones', p().motionProduction, [['auto', 'Que mi agente elija por escena'], ['code', 'Preferir animaciones editables con código'], ['ai', 'Preferir clips generados con IA']], v => updateProfile('motionProduction', v || null));
217036
+ const selectedStyles=(p().mediaStyles||[]).filter(item=>item.state!=='avoid'&&catalog.some(style=>style.id===item.styleId&&style.version===item.version&&style.category===mediaTab));
217037
+ const motionMode=p().motionSelection||((p().mediaStyles||[]).some(item=>item.state==='default'&&catalog.some(style=>style.id===item.styleId&&style.version===item.version&&style.category==='motion'))?'guided':'adaptive');
217038
+ if(selectedStyles.length&&(mediaTab==='image'||motionMode==='guided'))select(tasteFields,mediaTab==='image'?'Base de imagen':'Base de animación',selectedStyles.find(item=>item.state==='default')?.styleId,selectedStyles.map(item=>[item.styleId,catalog.find(style=>style.id===item.styleId).name]),id=>styleBase(mediaTab,id),'Sin base fija');
216872
217039
  panel.append(details('Afinar la dirección visual', tasteFields, 'Opcional'));
216873
217040
  const grid = node('div', 'media-grid'), extraGrid = node('div', 'media-grid');
216874
217041
  const schematicIds = ['quiet-reveal', 'kinetic-type', 'spring-callout', 'diagram-build', 'match-cut', 'parallax-depth'];
@@ -216888,7 +217055,7 @@ var artifactScript = String.raw`
216888
217055
  else if (mediaTab === 'motion' && schematicIds.includes(style.id))
216889
217056
  preview.replaceChildren(motionPreview(style.id)); if (mediaTab === 'image' || schematicIds.includes(style.id))
216890
217057
  article.append(preview); if (getStyleState(style.id) === 'default')
216891
- article.append(node('p', 'style-base', 'Base guardada anteriormente · se conserva')); const body = node('div', 'style-text'); append(body, node('strong', '', style.name), node('p', '', style.description)); const actions = node('div', 'style-actions'); [['favorite', 'Me gusta'], ['avoid', 'Evitar']].forEach(([sentiment, label]) => { const el = button(label, () => toggleStyle(style, sentiment)); el.dataset.sentiment = sentiment; el.setAttribute('aria-label', label + ' ' + style.name); el.setAttribute('aria-pressed', String(getStyleState(style.id) === sentiment)); actions.append(el); }); if (style.examples.length && showImages)
217058
+ article.append(node('p', 'style-base', 'Tu estilo base')); const body = node('div', 'style-text'); append(body, node('strong', '', style.name), node('p', '', style.description)); const actions = node('div', 'style-actions'); [['favorite', 'Me gusta'], ['avoid', 'Evitar']].forEach(([sentiment, label]) => { const el = button(label, () => toggleStyle(style, sentiment)); el.dataset.sentiment = sentiment; el.setAttribute('aria-label', label + ' ' + style.name); el.setAttribute('aria-pressed', String(getStyleState(style.id) === sentiment)); actions.append(el); }); if (style.examples.length && showImages)
216892
217059
  actions.append(button('Ver formatos', () => openExamples(style))); body.append(actions); article.append(body); (mediaTab === 'motion' && !schematicIds.includes(style.id) ? extraGrid : grid).append(article); });
216893
217060
  panel.append(grid);
216894
217061
  if (extraGrid.childElementCount)
@@ -216897,7 +217064,7 @@ var artifactScript = String.raw`
216897
217064
  }
216898
217065
  function layoutPreview(value) {
216899
217066
  const wrap = node('span'); wrap.setAttribute('aria-hidden', 'true');
216900
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 240 160'); svg.style.cssText = 'width:100%;height:130px;display:block;color:var(--ink)';
217067
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 240 160'); svg.style.cssText = 'width:100%;height:130px;display:block;color:inherit';
216901
217068
  const shape = (tag, attrs) => { const e = document.createElementNS(svg.namespaceURI, tag); for (const [k,v] of Object.entries(attrs)) e.setAttribute(k,String(v)); svg.append(e); };
216902
217069
  shape('rect', {x:60,y:10,width:120,height:140,rx:12,fill:'none',stroke:'currentColor',opacity:.25});
216903
217070
  if(value==='dynamic') { shape('circle',{cx:148,cy:42,r:20,fill:'currentColor',opacity:.15}); shape('circle',{cx:148,cy:37,r:7,fill:'currentColor',opacity:.7}); shape('path',{d:'M137 54a11 11 0 0 1 22 0',stroke:'currentColor','stroke-width':8,fill:'none',opacity:.4}); shape('path',{d:'M77 103h34l12-20 22 36h22',stroke:'currentColor','stroke-width':3,fill:'none'}); }
@@ -216968,14 +217135,15 @@ var artifactScript = String.raw`
216968
217135
  captions.append(captionOptions);
216969
217136
  panel.append(captions);
216970
217137
  const extra = node('div', 'fields');
217138
+ select(extra, 'Formato habitual', d.preferredOrientation, [['portrait','Vertical'],['landscape','Horizontal'],['square','Cuadrado']], v=>updateDelivery('preferredOrientation',v||null));
216971
217139
  select(extra, 'Duración habitual', d.preferredDuration, [['short','15–30 segundos'],['medium','30–60 segundos'],['long','1–3 minutos'],['extended','Más de 3 minutos']], v=>updateDelivery('preferredDuration', v||null));
216972
217140
  field(extra, 'Enlaces de referencia (hasta 5)', (p().referenceLinks||[]).join('\n'), v=>updateProfile('referenceLinks',v.split('\n').map(s=>s.trim()).filter(Boolean)), {multiline:true,wide:true,maxLength:10000});
216973
- select(extra, 'Texto además de subtítulos', d.onScreenText, [['minimal', 'Solo lo esencial'], ['key-points', 'Ideas y datos clave'], ['detailed', 'Explicaciones visuales detalladas']], v => updateDelivery('onScreenText', v || null));
217141
+ select(extra, 'Texto además de subtítulos', d.onScreenText, [['none','Ningún texto gráfico'], ['minimal', 'Solo lo esencial'], ['key-points', 'Ideas y datos clave'], ['detailed', 'Explicaciones visuales detalladas']], v => updateDelivery('onScreenText', v || null));
216974
217142
  select(extra, 'Material de apoyo', d.broll, [['footage', 'Clips de video'], ['stills', 'Fotos e ilustraciones'], ['mixed', 'Combinar fotos y video'], ['none', 'Sin material de apoyo']], v => updateDelivery('broll', v || null));
216975
- select(extra, 'Idioma de los subtítulos', d.captionLanguage, [['source', 'El mismo que el audio'], ['brand', 'El idioma de mi marca']], v => updateDelivery('captionLanguage', v || null));
216976
- select(extra, 'Posición de subtítulos', d.captionPosition, [['lower', 'Abajo'], ['center', 'Al centro'], ['adaptive', 'Según el encuadre']], v => updateDelivery('captionPosition', v || null));
216977
- select(extra, '¿Qué acción quieres invitar a hacer?', d.ctaGoal, [['adaptive', 'Según el video'], ['follow', 'Seguir mi cuenta'], ['comment', 'Comentar'], ['visit', 'Visitar un enlace'], ['contact', 'Contactarme'], ['none', 'Sin llamada a la acción']], v => updateDelivery('ctaGoal', v || null));
216978
- select(extra, 'Cómo mostrar esa invitación', d.ctaTreatment, [['adaptive', 'Según el video'], ['end-card', 'Pantalla final'], ['overlay', 'Sobre la imagen'], ['spoken', 'Solo con la voz']], v => updateDelivery('ctaTreatment', v || null));
217143
+ select(extra, 'Idioma de los subtítulos', d.captionLanguage, [['source', 'El mismo que el audio'], ['brand', 'El idioma de mi marca'], ['es','Español'], ['en','Inglés'], ['bilingual','Español e inglés']], v => updateDelivery('captionLanguage', v || null));
217144
+ select(extra, 'Posición de subtítulos', d.captionPosition, [['top','Arriba'], ['lower', 'Abajo'], ['center', 'Al centro'], ['adaptive', 'Según el encuadre']], v => updateDelivery('captionPosition', v || null));
217145
+ select(extra, '¿Qué acción quieres invitar a hacer?', d.ctaGoal, [['adaptive', 'Según el video'], ['follow', 'Seguir mi cuenta'], ['comment', 'Comentar'], ['visit', 'Visitar un enlace'], ['contact', 'Contactarme'], ['save','Guardar'], ['buy','Comprar'], ['none', 'Sin llamada a la acción']], v => updateDelivery('ctaGoal', v || null));
217146
+ select(extra, 'Cómo mostrar esa invitación', d.ctaTreatment, [['adaptive', 'Según el video'], ['end-card', 'Pantalla final'], ['overlay', 'Sobre la imagen'], ['spoken', 'Solo con la voz'], ['spoken-overlay','Voz y texto']], v => updateDelivery('ctaTreatment', v || null));
216979
217147
  extra.append(node('p', 'small', 'La llamada a la acción puede invitar a seguirte, comentar o contactarte. Su texto y destino se confirman para cada video.'));
216980
217148
  panel.append(details('Texto, cierre y llamada a la acción', extra, 'Opcional'));
216981
217149
  const limits = section('Lo que debemos respetar', 'Las restricciones prevalecen sobre las preferencias generales.');
@@ -217000,10 +217168,11 @@ var artifactScript = String.raw`
217000
217168
  function soundStep() {
217001
217169
  const d = delivery(), current = effectiveAudio();
217002
217170
  const voice = section('¿Cómo quieres contar la historia?', 'La voz puede acompañar cualquier formato.', decide(!d.narration, () => updateDelivery('narration', null)));
217003
- choices(voice, [['original', 'Mi voz grabada', 'Conservar la voz de tus clips o audios.'], ['voiceover', 'Voz en off', 'Narración que acompaña las imágenes.'], ['none', 'Sin narración', 'Contar con imagen, texto y sonido.']], d.narration, v => updateDelivery('narration', v));
217171
+ choices(voice, [['original', 'Mi voz grabada', 'Conservar la voz de tus clips o audios.'], ['voiceover', 'Voz en off', 'Narración que acompaña las imágenes.'], ['generated','Voz de IA','Preferencia; requiere voz, acceso y presupuesto confirmados.'], ['none', 'Sin narración', 'Contar con imagen, texto y sonido.']], d.narration, v => updateDelivery('narration', v));
217004
217172
  panel.append(voice);
217005
217173
  const music = section('Música', 'El ambiente que acompaña el contenido.', decide(!current.music?.intensity, () => setAudio('music', '')));
217006
217174
  choices(music, [['none', 'Sin música', 'La voz y el ambiente bastan.'], ['subtle', 'De fondo', 'Acompaña sin competir.'], ['present', 'Con presencia', 'Parte de la energía del video.']], current.music?.intensity, v => setAudio('music', v));
217175
+ select(music,'Carácter de música',current.music?.character,[['warm','Cálido'],['clean','Limpio'],['energetic','Con energía'],['cinematic','Cinematográfico']], v=>{intake.audio={...effectiveAudio(),music:{...effectiveAudio().music,character:v||null}};changed();});
217007
217176
  panel.append(music);
217008
217177
  const sfx = section('Efectos de sonido', 'Clics, acentos y transiciones cuando ayudan.', decide(!current.sfx?.density, () => setAudio('sfx', '')));
217009
217178
  const blocked = (p().avoid || []).includes('Sin efectos de sonido');
@@ -217020,6 +217189,7 @@ var artifactScript = String.raw`
217020
217189
  const fields = node('fieldset', 'fields'); fields.disabled = blocked || current.sfx?.density === 'none';
217021
217190
  const setSfx = (key, value) => { intake.audio = { ...effectiveAudio(), sfx: { ...effectiveAudio().sfx, [key]: value } }; changed(); };
217022
217191
  select(fields, 'Carácter del sonido', current.sfx?.character, [['organic', 'Natural: papel y objetos'], ['digital', 'Digital: clics e interfaces'], ['cinematic', 'Cinematográfico'], ['mixed', 'Una combinación']], v => setSfx('character', v || null));
217192
+ select(fields, 'Efecto de apertura', current.sfx?.hookTreatment, [['none','Ninguno'],['soft','Suave'],['marked','Marcado']], v=>setSfx('hookTreatment',v||null));
217023
217193
  select(fields, 'Apertura sin efectos añadidos', current.sfx?.hookWithoutEffects === true ? 'yes' : current.sfx?.hookWithoutEffects === false ? 'no' : '', [['yes', 'Sí, dejar el hook limpio'], ['no', 'Puede usar efectos si aportan']], v => setSfx('hookWithoutEffects', v ? v === 'yes' : null));
217024
217194
  fields.append(node('p', 'small', 'La cantidad no es volumen. Conserva voz y ambiente; revisa los acentos en el video final.')); detail.append(fields); sfx.append(detail);
217025
217195
  panel.append(sfx, node('p', 'small', 'Seleccionar una voz en off no clona voces ni autoriza gastos. El agente verificará los archivos, las integraciones y los permisos disponibles.'));
@@ -217030,13 +217200,23 @@ var artifactScript = String.raw`
217030
217200
  const box=node('div');
217031
217201
  data.integrations.forEach(provider=>{
217032
217202
  const entry=intake.accountSetup?.integrations?.find(v=>v.providerId===provider.id);
217033
- const update=(patch,redraw=true)=>{const previous=intake.accountSetup?.integrations||[];const next={providerId:provider.id,enabled:true,accessMethod:provider.accessMethods[0],preferences:{spending:'ask'},...entry,...patch};intake.accountSetup={...intake.accountSetup,integrations:[...previous.filter(v=>v.providerId!==provider.id),next]};changed();if(redraw)render();};
217203
+ const currentEntry=()=>intake.accountSetup?.integrations?.find(v=>v.providerId===provider.id)||entry;
217204
+ const update=(patch,redraw=true)=>{const previous=intake.accountSetup?.integrations||[];const current=previous.find(v=>v.providerId===provider.id);const next={providerId:provider.id,enabled:true,accessMethod:provider.accessMethods[0],preferences:{spending:'ask'},...(provider.custom?{definition:{name:provider.name,purpose:provider.description,capabilities:provider.capabilities}}:{}),...current,...patch};const others=previous.filter(v=>v.providerId!==provider.id).map(v=>patch.preferredFor?{...v,...(v.preferredFor?{preferredFor:v.preferredFor.filter(capability=>!patch.preferredFor.includes(capability))}:{})}:v);intake.accountSetup={...intake.accountSetup,integrations:[...others,next]};changed();if(redraw)render();};
217034
217205
  const row=section(provider.name,provider.description);
217035
217206
  select(row,'Usar '+provider.name,entry?String(entry.enabled):'', [['true','Quiero usar mi acceso'],['false','No usar este servicio']],v=>{if(v===''){intake.accountSetup={...intake.accountSetup,integrations:(intake.accountSetup?.integrations||[]).filter(e=>e.providerId!==provider.id)};changed();render();}else update({enabled:v==='true'});},'Conservar lo existente / configurar después');
217036
217207
  if(entry?.enabled){
217037
- select(row,'Acceso a '+provider.name,entry.accessMethod,provider.accessMethods.map(id=>[id,{agent:'Desde mi agente (MCP o herramienta)',api:'Mi propia API',browser:'Mi sesión del navegador',files:'Solo archivos ya creados'}[id]]),v=>{if(v)update({accessMethod:v});});
217208
+ select(row,'Acceso a '+provider.name,entry.accessMethod,provider.accessMethods.map(id=>[id,{agent:'Desde mi agente (MCP, CLI o herramienta)',api:'Mi propia API',browser:'Mi sesión del navegador',files:'Solo archivos ya creados'}[id]]),v=>{if(v)update({accessMethod:v,...(v!=='agent'?{connection:undefined}:{})});});
217209
+ if(entry.accessMethod==='agent'){
217210
+ select(row,'Método en mi agente · '+provider.name,entry.connection?.method,[['mcp','MCP'],['cli','CLI'],['native','Herramienta nativa']],v=>{const current=currentEntry()?.connection;update({connection:v?{...current,method:v,host:current?.host||'any'}:undefined});},'Verificar en la sesión');
217211
+ if(entry.connection){
217212
+ select(row,'Agente · '+provider.name,entry.connection.host,[['any','Cualquiera'],['claude','Claude'],['codex','Codex'],['other','Otro']],v=>update({connection:{...currentEntry()?.connection,host:v||'any'}}),'Cualquiera');
217213
+ field(row,'Identificador · '+provider.name,entry.connection.name,v=>{const connection={...(intake.accountSetup?.integrations?.find(item=>item.providerId===provider.id)?.connection||entry.connection)};if(v.trim())connection.name=v.trim();else delete connection.name;update({connection},false);},{maxLength:80,help:'Nombre del MCP o ejecutable. Sin argumentos, URLs, claves ni contraseñas.'});
217214
+ }
217215
+ }
217216
+ const preferred=node('div','fields');preferred.append(node('p','small','Preferir '+provider.name+' para:'));
217217
+ choices(preferred,provider.capabilities.map(capability=>[capability,({image:'Imágenes',video:'Video',voiceover:'Narración',music:'Música',sfx:'Efectos de sonido',transcription:'Transcripción','stock-image':'Fotos de stock','stock-video':'Video de stock',other:'Otra tarea'})[capability]||capability]),entry.preferredFor||[],(capability,selected)=>update({preferredFor:selected?(entry.preferredFor||[]).filter(value=>value!==capability):[...(entry.preferredFor||[]),capability]}),{multiple:true});row.append(preferred);
217038
217218
  const prefs=entry.preferences||{},fields=node('div','fields');
217039
- const change=(key,value)=>{const next={...(intake.accountSetup?.integrations?.find(v=>v.providerId===provider.id)?.preferences||prefs)};if(value)next[key]=value;else delete next[key];update({preferences:next},false);};
217219
+ const change=(key,value)=>{const next={...(intake.accountSetup?.integrations?.find(v=>v.providerId===provider.id)?.preferences||prefs)};if(value||['model','language','voiceId','instructions'].includes(key))next[key]=value;else delete next[key];update({preferences:next},false);};
217040
217220
  field(fields,'Modelo preferido · '+provider.name,prefs.model,v=>change('model',v),{maxLength:120});
217041
217221
  field(fields,'Idioma · '+provider.name,prefs.language,v=>change('language',v),{maxLength:60});
217042
217222
  if(provider.capabilities.includes('voiceover'))field(fields,'ID de voz · '+provider.name,prefs.voiceId,v=>change('voiceId',v),{maxLength:120});
@@ -217059,6 +217239,8 @@ var artifactScript = String.raw`
217059
217239
  const list = node('div', 'review-list');
217060
217240
  const selections = (p().mediaStyles || []).map(v => { const item = catalog.find(s => s.id === v.styleId); return (v.state === 'avoid' ? 'Evitar: ' : v.state === 'default' ? 'Base guardada: ' : 'Me gusta: ') + (item?.name || v.styleId); });
217061
217241
  const sourceNames = { own: 'Material propio', web: 'Material auténtico de internet', stock: 'Stock', generated: 'Generado con IA' }, sources = p().mediaSources;
217242
+ const d=delivery(),sound=effectiveAudio();
217243
+ const described=(title,value,labels)=>value===undefined||value===null||value===''?'':title+': '+(labels?.[value]??String(value));
217062
217244
  const rows = [
217063
217245
  ['Consultas', data.questionModes.find(option => option.id === (p().questionMode || 'essential'))?.title, 0],
217064
217246
  ['Dirección creativa', data.creativeDirections.find(option => option.id === p().creativeDirection)?.label || 'Sin cambio: conservar las preferencias existentes.', 0],
@@ -217066,8 +217248,11 @@ var artifactScript = String.raw`
217066
217248
  ['Marca', Object.entries(intake.tokens || {}).filter(([, v]) => v).map(([key, rule]) => key.replace('color.', '').replace('typography.', '') + ': ' + rule.value + ' · ' + ({ required: 'obligatorio', preferred: 'preferencia', example: 'ejemplo' }[rule.strength])).join('\n'), 1],
217067
217249
  ['Gustos visuales', [...taste().favorites.map(id=>data.demos[id]?.name||id),...selections].join('\n'), 2],
217068
217250
  ['Apertura y límites', [data.hooks.find(v=>v[0]===taste().hook)?.[1],data.hookIntensities.find(v=>v[0]===taste().hookIntensity)?.[1],taste().noAbruptZooms&&'Sin acercamientos bruscos'].filter(Boolean).join(' · '), 3],
217069
- ['Edición y recursos', [p().pace, delivery().presenterLayout && 'Encuadre: ' + ({ original: 'mantener', reframe: 'reencuadres suaves', dynamic: 'composiciones variadas' }[delivery().presenterLayout]), delivery().visualSupport && 'Apoyo visual: ' + ({ sparse: 'poco', balanced: 'equilibrado', rich: 'abundante' }[delivery().visualSupport]), p().captions, sources?.allowed?.map(v => sourceNames[v]).join(' · '), sources?.preferred && 'Empezar por: ' + sourceNames[sources.preferred], delivery().ctaGoal && 'Cierre: ' + ({ adaptive: 'según el video', follow: 'seguir mi cuenta', comment: 'comentar', visit: 'visitar un enlace', contact: 'contactarme', none: 'sin llamada a la acción' }[delivery().ctaGoal]), !sources && p().assets, (p().avoid || []).join(' · ')].filter(Boolean).join('\n'), 3],
217070
- ['Narración y sonido', [delivery().narration && 'Narración: ' + ({ original: 'tu voz grabada', voiceover: 'voz en off', none: 'sin narración' }[delivery().narration]), effectiveAudio().music?.intensity && 'Música: ' + ({ none: 'sin música', subtle: 'de fondo', present: 'con presencia' }[effectiveAudio().music.intensity]), (p().avoid || []).includes('Sin efectos de sonido') ? 'Efectos: desactivados por tus límites' : effectiveAudio().sfx?.density && 'Efectos: ' + ({ none: 'sin efectos', sparse: 'sutiles', moderate: 'equilibrados', dense: 'expresivos' }[effectiveAudio().sfx.density]), effectiveAudio().sfx?.character && 'Carácter: ' + ({organic:'natural',digital:'digital',cinematic:'cinematográfico',mixed:'combinado'}[effectiveAudio().sfx.character]), effectiveAudio().sfx?.hookWithoutEffects === true && 'Apertura sin efectos añadidos'].filter(Boolean).join('\n'), 4],
217251
+ ['Edición y recursos', [p().pace,described('Formato',d.preferredOrientation,{portrait:'vertical',landscape:'horizontal',square:'cuadrado'}),described('Duración',d.preferredDuration,{short:'15–30 segundos',medium:'30–60 segundos',long:'1–3 minutos',extended:'más de 3 minutos'}),described('Encuadre',d.presenterLayout,{original:'mantener',reframe:'reencuadres suaves',dynamic:'composiciones variadas'}),described('Apoyo visual',d.visualSupport,{sparse:'poco',balanced:'equilibrado',rich:'abundante'}),described('Material de apoyo',d.broll,{footage:'clips',stills:'imágenes',mixed:'imágenes y clips',none:'sin material de apoyo'}),sources?.allowed?.map(v=>sourceNames[v]??v).join(' · '),described('Empezar por',sources?.preferred,sourceNames),!sources&&p().assets].filter(Boolean).join('\n'),3],
217252
+ ['Textos y subtítulos',[p().captions,described('Apariencia',d.captionTreatment,{clean:'limpios', 'word-highlight':'palabras clave',karaoke:'palabra a palabra',boxed:'con fondo'}),described('Posición',d.captionPosition,{top:'arriba',lower:'abajo',center:'al centro',adaptive:'según el encuadre'}),described('Idioma',d.captionLanguage,{source:'el del audio',brand:'el de mi marca',es:'español',en:'inglés',bilingual:'español e inglés'}),described('Texto gráfico',d.onScreenText,{none:'ninguno',minimal:'solo lo esencial','key-points':'ideas y datos clave',detailed:'explicaciones detalladas'})].filter(Boolean).join('\n'),3],
217253
+ ['Cierre',[described('Cierre',d.ctaGoal,{adaptive:'según el video',follow:'seguir mi cuenta',comment:'comentar',visit:'visitar un enlace',contact:'contactarme',save:'guardar el video',buy:'comprar',none:'sin llamada a la acción'}),described('Presentación',d.ctaTreatment,{adaptive:'según el video','end-card':'pantalla final',overlay:'sobre la imagen',spoken:'solo con la voz','spoken-overlay':'voz y texto'})].filter(Boolean).join('\n'),3],
217254
+ ['Narración y sonido',[described('Narración',d.narration,{original:'tu voz grabada',voiceover:'voz en off',generated:'voz de IA',none:'sin narración'}),described('Música',sound.music?.intensity,{none:'sin música',subtle:'de fondo',present:'con presencia'}),described('Carácter musical',sound.music?.character,{warm:'cálido',clean:'limpio',energetic:'con energía',cinematic:'cinematográfico'}),(p().avoid||[]).includes('Sin efectos de sonido')?'Efectos: desactivados por tus límites':described('Efectos',sound.sfx?.density,{none:'sin efectos',sparse:'sutiles',moderate:'equilibrados',dense:'expresivos'}),described('Carácter',sound.sfx?.character,{organic:'natural',digital:'digital',cinematic:'cinematográfico',mixed:'combinado'}),sound.sfx?.hookWithoutEffects===true?'Apertura sin efectos añadidos':described('Efecto de apertura',sound.sfx?.hookTreatment,{none:'ninguno',soft:'suave',marked:'marcado'})].filter(Boolean).join('\n'),4],
217255
+ ['Límites y referencias',[(p().avoid||[]).join(' · '),p().notes,(p().referenceLinks||[]).join('\n')].filter(Boolean).join('\n'),3],
217071
217256
  ];
217072
217257
  rows.forEach(([title, text, target]) => { const item = node('section', 'review-item'); append(item, node('h3', '', title), node('p', '', text || 'Tu agente lo decidirá según cada video.'), button('Cambiar ' + title.toLowerCase(), () => navigate(target), 'text-button')); list.append(item); });
217073
217258
  panel.append(list);
@@ -217099,7 +217284,6 @@ var artifactScript = String.raw`
217099
217284
  $('page-description').textContent = steps[step][2];
217100
217285
  const route = visibleSteps(); if (!route.includes(step)) route.splice(2, 0, step);
217101
217286
  $('step-count').textContent = 'Paso ' + (route.indexOf(step) + 1) + ' de ' + route.length;
217102
- document.body.dataset.theme = ['paper','paper','wine','wine','wine','porcelain'][step];
217103
217287
  $('previous').hidden = step === 0;
217104
217288
  $('next').hidden = step === steps.length - 1;
217105
217289
  $('next').textContent = step === 0 ? 'Continuar →' : 'Confirmar y continuar →';
@@ -217117,6 +217301,8 @@ var artifactScript = String.raw`
217117
217301
  const match = [...panel.querySelectorAll(activeKey[0])].find(el => JSON.stringify([el.tagName, el.dataset.value || '', el.getAttribute('aria-label') || '', el.textContent, el.closest('section')?.querySelector('h3')?.textContent || '']) === JSON.stringify(activeKey));
217118
217302
  match?.focus({ preventScroll: true });
217119
217303
  }
217304
+ if(busy)document.querySelectorAll('button,input,select,textarea').forEach(control=>control.disabled=true);
217305
+ else ['previous','next','download-top','save-draft','import-draft','draft-file','theme-toggle'].forEach(id=>{const control=$(id);if(control)control.disabled=false;});
217120
217306
  }
217121
217307
  function navigate(next) { if (busy)
217122
217308
  return; step = Math.max(0, Math.min(steps.length - 1, next)); render(); $('page-title').focus({ preventScroll: true }); $('main').scrollIntoView({ block: 'start', behavior: 'instant' }); }
@@ -217133,20 +217319,54 @@ var artifactScript = String.raw`
217133
217319
  if (!intake.brandId)
217134
217320
  throw new Error('Falta el identificador de marca. Genera de nuevo el formulario desde EditorBrain.');
217135
217321
  }
217136
- function download() { try {
217137
- validate();
217138
- const file = new Blob([JSON.stringify(cleanIntake(), null, 2) + '\n'], { type: 'application/json' }), url = URL.createObjectURL(file), a = node('a');
217322
+ function downloadIntake(draft=false) {
217323
+ const file = new Blob([JSON.stringify(cleanIntake(), null, 2) + '\n'], { type: 'application/json' });
217324
+ if(file.size>128*1024)throw new Error('El archivo supera 128 KiB. Reduce las notas o referencias antes de guardarlo.');
217325
+ const url = URL.createObjectURL(file), a = node('a');
217139
217326
  a.href = url;
217140
- a.download = 'editorbrain-' + intake.brandId + '-respuestas.json';
217327
+ a.download = 'editorbrain-' + intake.brandId + (draft?'-borrador.json':'-respuestas.json');
217141
217328
  document.body.append(a);
217142
217329
  a.click();
217143
217330
  a.remove();
217144
217331
  setTimeout(() => URL.revokeObjectURL(url), 1000);
217332
+ }
217333
+ function download() { try {
217334
+ validate();downloadIntake();dirty=false;
217145
217335
  setStatus('Respuestas descargadas. Entrega este archivo a tu agente para aplicar tus preferencias.');
217146
217336
  }
217147
217337
  catch (e) {
217148
217338
  setStatus(e.message, true);
217149
217339
  } }
217340
+ async function persistDraft(value,importing=false) {
217341
+ const body=JSON.stringify({intake:value,expectedDraft:data.submission.draftVersion??null,...(importing?{importing:true}:{})});
217342
+ if(new Blob([body]).size>128*1024)throw new Error('El borrador supera 128 KiB.');
217343
+ const response=await fetch(data.submission.draftUrl,{method:'POST',headers:{'Content-Type':'application/json','X-EditorBrain-Onboarding':data.submission.csrfToken},body,credentials:'omit',redirect:'error'});
217344
+ const result=await response.json();
217345
+ if(!response.ok||result.saved!==true||result.draft!==true||result.applied!==false||typeof result.version!=='string'||!/^[a-f0-9]{64}$/.test(result.version))throw new Error(typeof result.error==='string'?result.error:'No pudimos confirmar el borrador. Conserva una copia antes de cerrar.');
217346
+ data.submission.draftVersion=result.version;
217347
+ }
217348
+ async function saveDraft() {
217349
+ if(busy)return;
217350
+ try{
217351
+ setStatus('');setStatus('',true);
217352
+ busy=true;render();
217353
+ if(data.submission?.draftUrl){await persistDraft(cleanIntake());dirty=false;setStatus('Borrador guardado en esta sesión. Puedes cerrar y retomarlo con tu agente. No confirma categorías ni aplica preferencias.');}
217354
+ else{downloadIntake(true);dirty=false;setStatus('Borrador descargado. Devuélvelo a tu agente para validarlo y retomar la misma sesión con onboarding serve --session <sesión> --file <borrador>. No se aplicó a tu marca.');}
217355
+ }catch(e){setStatus(e.message||'No pudimos guardar el borrador.',true);}
217356
+ finally{busy=false;render();}
217357
+ }
217358
+ async function importDraft(file){
217359
+ if(!file||busy||!data.submission?.draftUrl)return;
217360
+ try{
217361
+ setStatus('');setStatus('',true);
217362
+ busy=true;render();
217363
+ if(file.size>128*1024)throw new Error('El archivo supera 128 KiB.');
217364
+ const value=JSON.parse(await file.text());
217365
+ if(!value||value.brandId!==intake.brandId)throw new Error('El borrador pertenece a otra marca. Conservamos tus respuestas actuales.');
217366
+ await persistDraft(value,true);dirty=false;location.reload();
217367
+ }catch(e){setStatus(e.message||'No pudimos importar el borrador. Conservamos tus respuestas.',true);}
217368
+ finally{busy=false;$('draft-file').value='';render();}
217369
+ }
217150
217370
  async function submit() { if (busy || !data.submission)
217151
217371
  return; try {
217152
217372
  validate();
@@ -217154,10 +217374,11 @@ var artifactScript = String.raw`
217154
217374
  busy = true;
217155
217375
  document.querySelectorAll('button').forEach(b => b.disabled = true);
217156
217376
  setStatus('Guardando tus preferencias locales…');
217157
- const response = await fetch(data.submission.actionUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-EditorBrain-Onboarding': data.submission.csrfToken }, body: JSON.stringify({ intake: cleanIntake() }), credentials: 'omit', redirect: 'error' });
217377
+ const response = await fetch(data.submission.actionUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-EditorBrain-Onboarding': data.submission.csrfToken }, body: JSON.stringify({ intake: cleanIntake(), expectedDraft: data.submission.draftVersion??null }), credentials: 'omit', redirect: 'error' });
217158
217378
  const result = await response.json();
217159
217379
  if (!response.ok || !result.saved)
217160
217380
  throw new Error(typeof result.error === 'string' ? result.error : 'No se pudo confirmar el guardado. Conserva una copia de tus respuestas.');
217381
+ dirty=false;
217161
217382
  setStatus('Preferencias guardadas. Vuelve a tu agente para aplicarlas.');
217162
217383
  }
217163
217384
  catch (e) {
@@ -217169,9 +217390,22 @@ var artifactScript = String.raw`
217169
217390
  document.querySelectorAll('button').forEach(b => b.disabled = false);
217170
217391
  render();
217171
217392
  } }
217393
+ $('theme-toggle').addEventListener('click', () => {
217394
+ const dark = document.body.dataset.theme !== 'dark';
217395
+ document.body.dataset.theme = dark ? 'dark' : 'light';
217396
+ const label = dark ? 'Cambiar a modo claro' : 'Cambiar a modo oscuro';
217397
+ $('theme-toggle').setAttribute('aria-label', label);
217398
+ $('theme-toggle').title = label;
217399
+ });
217172
217400
  $('previous').addEventListener('click', () => navigate(visibleSteps().filter(index => index < step).at(-1) ?? 0));
217173
217401
  $('next').addEventListener('click', confirmStep);
217174
217402
  $('download-top').addEventListener('click', download);
217403
+ $('save-draft').addEventListener('click', saveDraft);
217404
+ $('import-draft').hidden=!data.submission?.draftUrl;
217405
+ $('import-draft').addEventListener('click',()=>$('draft-file').click());
217406
+ $('draft-file').addEventListener('change',()=>void importDraft($('draft-file').files?.[0]));
217407
+ $('draft-help').textContent=data.submission?.draftUrl?'Guardar borrador conserva respuestas incompletas en esta sesión, sin aplicarlas a tu marca.':'Puedes descargar un borrador incompleto y devolverlo a tu agente para retomar esta misma sesión.';
217408
+ window.addEventListener('beforeunload',event=>{if(dirty){event.preventDefault();event.returnValue='';}});
217175
217409
  $('close-dialog').addEventListener('click', () => $('style-dialog').close());
217176
217410
  $('preferences').addEventListener('submit', event => event.preventDefault());
217177
217411
  document.addEventListener('visibilitychange', () => { if (document.hidden)
@@ -217180,6 +217414,7 @@ var artifactScript = String.raw`
217180
217414
  observeMotion(); });
217181
217415
  matchMedia('(prefers-reduced-motion: reduce)').addEventListener('change', observeMotion);
217182
217416
  render();
217417
+ if(data.restoredDraft)setStatus('Recuperamos tu borrador local. Las categorías pendientes siguen pendientes y tu marca todavía no ha cambiado.');
217183
217418
  })();
217184
217419
 
217185
217420
  `;
@@ -217256,6 +217491,41 @@ var failure2 = (code, message, hint = "Reopen onboarding against the current fil
217256
217491
  function starterOutputId(brandId2) {
217257
217492
  return `onboarding-${brandId2.slice(0, 48)}-${createHash21("sha256").update(brandId2).digest("hex").slice(0, 12)}`;
217258
217493
  }
217494
+ var maxDraftBytes = 128 * 1024;
217495
+ function draftContent(intake) {
217496
+ const content = stableJson(intake);
217497
+ if (Buffer.byteLength(content) > maxDraftBytes) throw failure2("INVALID_ONBOARDING_DRAFT", "The saved draft would exceed 128 KiB. Reduce notes or references before saving.");
217498
+ return content;
217499
+ }
217500
+ async function readDraft(root, path, brandId2) {
217501
+ const target = await checkedPath(root, path, false), handle = await open21(target, constants18.O_RDONLY | constants18.O_NOFOLLOW | constants18.O_NONBLOCK);
217502
+ try {
217503
+ const before = await handle.stat();
217504
+ if (!before.isFile() || before.size > maxDraftBytes) throw failure2("INVALID_ONBOARDING_DRAFT", "A draft must be a regular JSON file of at most 128 KiB.");
217505
+ const buffer = Buffer.alloc(maxDraftBytes + 1);
217506
+ let size = 0;
217507
+ while (size < buffer.length) {
217508
+ const result2 = await handle.read(buffer, size, buffer.length - size, size);
217509
+ if (!result2.bytesRead) break;
217510
+ size += result2.bytesRead;
217511
+ }
217512
+ const after = await handle.stat();
217513
+ if (size > maxDraftBytes || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw failure2("INVALID_ONBOARDING_DRAFT", "The draft is too large or changed while reading.");
217514
+ const intake = validateOnboardingIntake(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, size))));
217515
+ if (intake.brandId !== brandId2) throw failure2("ONBOARDING_BRAND_MISMATCH", "This draft belongs to another brand.");
217516
+ return intake;
217517
+ } finally {
217518
+ await handle.close();
217519
+ }
217520
+ }
217521
+ async function optionalDraft(root, path, brandId2) {
217522
+ try {
217523
+ return await readDraft(root, path, brandId2);
217524
+ } catch (error62) {
217525
+ if (error62.code === "ENOENT") return void 0;
217526
+ throw error62;
217527
+ }
217528
+ }
217259
217529
  function scaffold(brandId2, projectId) {
217260
217530
  const files = Object.fromEntries(Object.entries(createWorkspace({ brand: brandId2, project: projectId })).filter(([p]) => !p.startsWith(`.editorbrain/brands/${brandId2}/`)));
217261
217531
  const outputId = starterOutputId(brandId2), output3 = JSON.parse(files[".editorbrain/output-profiles/vertical.json"]);
@@ -217317,7 +217587,7 @@ async function createOnboarding(options) {
217317
217587
  const session = { schemaVersion: 1, kind: "editorbrain.onboarding", brandId: brandId2, projectId, intake, snapshots: saved };
217318
217588
  await atomicWrite(root, `${directory}/session.json`, stableJson(session), { document: false, overwrite: false, mode: 384 });
217319
217589
  await atomicWrite(root, `${directory}/index.html`, renderOnboardingArtifact({ intake, requiresIdentity: saved[`.editorbrain/brands/${brandId2}/brand.md`] === null }), { document: false, overwrite: false, mode: 384 });
217320
- return { schemaVersion: 1, brandId: brandId2, projectId, configuration: creativeConfiguration(intake.profile?.creativeDirection ?? void 0, intake.profile?.creativePreferencesReviewed ?? void 0), artifact: join21(root, directory, "index.html"), session: `${directory}/session.json`, answers: `${directory}/answers.json`, savedToBrain: false, next: "Show the HTML artifact, or run onboarding serve --session <session>. Static artifacts download answers: put them in this workspace and run onboarding apply --session <session> --file <answers>. Never fill choices on the user\u2019s behalf." };
217590
+ return { schemaVersion: 1, brandId: brandId2, projectId, configuration: creativeConfiguration(intake.profile?.creativeDirection ?? void 0, intake.profile?.creativePreferencesReviewed ?? void 0), artifact: join21(root, directory, "index.html"), session: `${directory}/session.json`, answers: `${directory}/answers.json`, draft: `${directory}/draft.json`, savedToBrain: false, next: "Show the HTML artifact, or run onboarding serve --session <session>. Save incomplete choices as a draft without confirming categories. Resume a downloaded draft in this same session with onboarding serve --session <session> --file <draft>. Apply only final reviewed answers with onboarding apply --session <session> --file <answers>. Never fill choices on the user\u2019s behalf." };
217321
217591
  }
217322
217592
  async function applyOnboarding(options) {
217323
217593
  const root = await ensureRoot(options.directory);
@@ -217374,7 +217644,20 @@ async function syncOnboarding(client, options) {
217374
217644
  async function serveOnboarding(options) {
217375
217645
  const root = await ensureRoot(options.directory), session = await readSession(root, options.session), seconds2 = options.timeoutSeconds ?? 1800;
217376
217646
  if (!Number.isInteger(seconds2) || seconds2 < 1 || seconds2 > 3600) throw failure2("INVALID_ARGUMENT", "Timeout must be between 1 and 3600 seconds.");
217377
- const token = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex"), prefix = `/${token}`, answers = `${dirname21(options.session)}/answers.json`;
217647
+ const token = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex"), prefix = `/${token}`, answers = `${dirname21(options.session)}/answers.json`, draft = `${dirname21(options.session)}/draft.json`;
217648
+ let previousDraft;
217649
+ if (options.file) {
217650
+ const imported = await readDraft(root, options.file, session.brandId), content = draftContent(imported);
217651
+ await withWorkspaceLock(root, async () => {
217652
+ const previous = await optionalDraft(root, draft, session.brandId);
217653
+ if (previous) {
217654
+ previousDraft = `${dirname21(options.session)}/draft-before-import-${Date.now()}-${randomBytes(3).toString("hex")}.json`;
217655
+ await atomicWrite(root, previousDraft, stableJson(previous), { document: false, overwrite: false, mode: 384 });
217656
+ }
217657
+ await atomicWrite(root, draft, content, { document: false, mode: 384 });
217658
+ }, { migrateLegacy: false });
217659
+ }
217660
+ const restoredDraft = !!await optionalDraft(root, draft, session.brandId);
217378
217661
  let origin = "", consumed = false, busy = false, server;
217379
217662
  let complete, reject;
217380
217663
  const done = new Promise((yes, no) => {
@@ -217389,10 +217672,13 @@ async function serveOnboarding(options) {
217389
217672
  try {
217390
217673
  if (req.headers.host !== new URL(origin).host) return send(403, { error: "Host no permitido." });
217391
217674
  if (req.method === "GET" && req.url === `${prefix}/`) {
217675
+ const saved = await optionalDraft(root, draft, session.brandId);
217676
+ const html = renderOnboardingArtifact({ intake: saved ?? session.intake, requiresIdentity: session.snapshots[`.editorbrain/brands/${session.brandId}/brand.md`] === null, submission: { actionUrl: `${origin}${prefix}/answers`, draftUrl: `${origin}${prefix}/draft`, draftVersion: saved ? await sha256(stableJson(saved)) : null, csrfToken: csrf }, restoredDraft: !!saved });
217392
217677
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: https://editorbrain.com; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" });
217393
- return res.end(renderOnboardingArtifact({ intake: session.intake, requiresIdentity: session.snapshots[`.editorbrain/brands/${session.brandId}/brand.md`] === null, submission: { actionUrl: `${origin}${prefix}/answers`, csrfToken: csrf } }));
217678
+ return res.end(html);
217394
217679
  }
217395
- if (req.method !== "POST" || req.url !== `${prefix}/answers`) return send(404, { error: "No encontrado." });
217680
+ const savingDraft = req.url === `${prefix}/draft`;
217681
+ if (req.method !== "POST" || !savingDraft && req.url !== `${prefix}/answers`) return send(404, { error: "No encontrado." });
217396
217682
  if (req.headers.origin !== origin || req.headers["x-editorbrain-onboarding"] !== csrf || req.headers["content-type"]?.split(";")[0] !== "application/json") return send(403, { error: "Solicitud no autorizada." });
217397
217683
  if (consumed || busy) return send(409, { error: "Esta sesi\xF3n ya recibi\xF3 respuestas." });
217398
217684
  busy = true;
@@ -217400,18 +217686,45 @@ async function serveOnboarding(options) {
217400
217686
  const chunks = [];
217401
217687
  for await (const chunk of req) {
217402
217688
  size += chunk.length;
217403
- if (size > 131072) {
217404
- send(413, { error: "Respuestas demasiado grandes." });
217689
+ if (size > maxDraftBytes) {
217690
+ send(413, { error: "Respuestas demasiado grandes: m\xE1ximo 128 KiB." });
217405
217691
  busy = false;
217406
217692
  return;
217407
217693
  }
217408
217694
  chunks.push(Buffer.from(chunk));
217409
217695
  }
217410
217696
  const payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
217411
- if (!payload || Object.keys(payload).some((k) => k !== "intake")) throw Error("Formato inv\xE1lido.");
217697
+ if (!payload || Object.keys(payload).some((k) => !(savingDraft ? ["intake", "expectedDraft", "importing"] : ["intake", "expectedDraft"]).includes(k))) throw Error("Formato inv\xE1lido.");
217412
217698
  const intake = validateOnboardingIntake(payload.intake);
217413
217699
  if (intake.brandId !== session.brandId) throw Error("La marca no coincide.");
217414
- await atomicWrite(root, answers, stableJson(intake), { document: false, overwrite: false, mode: 384 });
217700
+ if (savingDraft) {
217701
+ if (payload.expectedDraft !== null && (typeof payload.expectedDraft !== "string" || !/^[a-f0-9]{64}$/.test(payload.expectedDraft)) || payload.importing !== void 0 && typeof payload.importing !== "boolean") throw Error("Revisi\xF3n de borrador inv\xE1lida. Recarga antes de guardar.");
217702
+ const content = draftContent(intake), result2 = await withWorkspaceLock(root, async () => {
217703
+ const current2 = await optionalDraft(root, draft, session.brandId), currentVersion = current2 ? await sha256(stableJson(current2)) : null;
217704
+ if (currentVersion !== payload.expectedDraft) return { conflict: true };
217705
+ let previousDraft2;
217706
+ if (payload.importing && current2) {
217707
+ previousDraft2 = `${dirname21(options.session)}/draft-before-import-${Date.now()}-${randomBytes(3).toString("hex")}.json`;
217708
+ await atomicWrite(root, previousDraft2, stableJson(current2), { document: false, overwrite: false, mode: 384 });
217709
+ }
217710
+ await atomicWrite(root, draft, content, { document: false, mode: 384 });
217711
+ return { conflict: false, version: await sha256(content), previousDraft: previousDraft2 };
217712
+ }, { migrateLegacy: false });
217713
+ busy = false;
217714
+ if (result2.conflict) return send(409, { code: "ONBOARDING_DRAFT_CONFLICT", error: "Otra pesta\xF1a cambi\xF3 este borrador. Descarga una copia de tus respuestas y recarga para conciliar; no sobrescribimos lo guardado." });
217715
+ return send(200, { saved: true, draft: true, applied: false, path: draft, version: result2.version, ...result2.previousDraft ? { previousDraft: result2.previousDraft } : {} });
217716
+ }
217717
+ if (payload.expectedDraft !== void 0 && payload.expectedDraft !== null && (typeof payload.expectedDraft !== "string" || !/^[a-f0-9]{64}$/.test(payload.expectedDraft))) throw Error("Revisi\xF3n de borrador inv\xE1lida. Recarga antes de guardar.");
217718
+ const finalized = await withWorkspaceLock(root, async () => {
217719
+ const current2 = await optionalDraft(root, draft, session.brandId), currentVersion = current2 ? await sha256(stableJson(current2)) : null;
217720
+ if (currentVersion !== (payload.expectedDraft ?? null)) return false;
217721
+ await atomicWrite(root, answers, stableJson(intake), { document: false, overwrite: false, mode: 384 });
217722
+ return true;
217723
+ }, { migrateLegacy: false });
217724
+ if (!finalized) {
217725
+ busy = false;
217726
+ return send(409, { code: "ONBOARDING_DRAFT_CONFLICT", error: "Otra pesta\xF1a cambi\xF3 este borrador. Descarga una copia de tus respuestas y recarga para conciliar antes de finalizar; no sobrescribimos lo guardado." });
217727
+ }
217415
217728
  consumed = true;
217416
217729
  send(200, { saved: true, path: answers });
217417
217730
  complete({ schemaVersion: 1, saved: true, answers: join21(root, answers), session: options.session, applied: false, next: "Review saved choices and run onboarding apply with this session and answers file." });
@@ -217434,7 +217747,7 @@ async function serveOnboarding(options) {
217434
217747
  process.once("SIGINT", stop);
217435
217748
  process.once("SIGTERM", stop);
217436
217749
  try {
217437
- options.onReady?.({ url: `${origin}${prefix}/`, answers: join21(root, answers) });
217750
+ options.onReady?.({ url: `${origin}${prefix}/`, answers: join21(root, answers), draft: join21(root, draft), restoredDraft, ...options.file ? { importedDraft: options.file } : {}, ...previousDraft ? { previousDraft: join21(root, previousDraft) } : {} });
217438
217751
  return await done;
217439
217752
  } finally {
217440
217753
  clearTimeout(timer);
@@ -217454,7 +217767,7 @@ async function onboardingStatus(options) {
217454
217767
  }
217455
217768
 
217456
217769
  // packages/cli/src/brain.ts
217457
- var object17 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
217770
+ var object16 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
217458
217771
  var integer2 = (value, min = 0) => Number.isSafeInteger(value) && Number(value) >= min;
217459
217772
  var text13 = (value, max) => typeof value === "string" && !!value.trim() && value.length <= max && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);
217460
217773
  var hash10 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
@@ -217471,7 +217784,7 @@ function brainRevision(value) {
217471
217784
  return Number(value);
217472
217785
  }
217473
217786
  function validateInput(input2, accept = false) {
217474
- if (!object17(input2) || Object.keys(input2).some((key) => !(accept ? ["brandId", "expectedDesignRevision", "runId", "reviewed"] : ["brandId", "expectedDesignRevision"]).includes(key))) throw invalidInput("Only the brand, document revision and explicit reviewed run are accepted.");
217787
+ if (!object16(input2) || Object.keys(input2).some((key) => !(accept ? ["brandId", "expectedDesignRevision", "runId", "reviewed"] : ["brandId", "expectedDesignRevision"]).includes(key))) throw invalidInput("Only the brand, document revision and explicit reviewed run are accepted.");
217475
217788
  brandId(input2.brandId);
217476
217789
  if (!integer2(input2.expectedDesignRevision, 1)) throw invalidInput("A positive source design revision is required.");
217477
217790
  if (accept && (!hash10(input2.runId) || input2.reviewed !== true)) throw invalidInput("Accept only a specific proposal already reviewed and approved by the user; --run and --reviewed are required.");
@@ -217489,19 +217802,19 @@ function brainState(value, brand, write = false) {
217489
217802
  const invalid15 = () => {
217490
217803
  throw invalidResponse(write);
217491
217804
  };
217492
- if (!object17(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text13(value.notice, 2e3) || value.contextVersion !== void 0 && !hash10(value.contextVersion) || value.contextChanged !== void 0 && typeof value.contextChanged !== "boolean") return invalid15();
217805
+ if (!object16(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text13(value.notice, 2e3) || value.contextVersion !== void 0 && !hash10(value.contextVersion) || value.contextChanged !== void 0 && typeof value.contextChanged !== "boolean") return invalid15();
217493
217806
  let run2 = null;
217494
217807
  if (value.run !== null) {
217495
217808
  const row = value.run;
217496
- if (!object17(row) || !hash10(row.id) || !["queued", "running", "ready", "accepted", "failed"].includes(String(row.status)) || !integer2(row.sourceDesignRevision, 1) || !(row.acceptedDesignRevision === null || integer2(row.acceptedDesignRevision, 1)) || !(row.errorCode === null || typeof row.errorCode === "string" && /^[a-z][a-z0-9_]{0,119}$/.test(row.errorCode)) || !date5(row.createdAt) || !date5(row.updatedAt)) return invalid15();
217809
+ if (!object16(row) || !hash10(row.id) || !["queued", "running", "ready", "accepted", "failed"].includes(String(row.status)) || !integer2(row.sourceDesignRevision, 1) || !(row.acceptedDesignRevision === null || integer2(row.acceptedDesignRevision, 1)) || !(row.errorCode === null || typeof row.errorCode === "string" && /^[a-z][a-z0-9_]{0,119}$/.test(row.errorCode)) || !date5(row.createdAt) || !date5(row.updatedAt)) return invalid15();
217497
217810
  if (row.status === "accepted" ? row.acceptedDesignRevision !== row.sourceDesignRevision + 1 : row.acceptedDesignRevision !== null) return invalid15();
217498
217811
  let proposal = null;
217499
217812
  if (row.proposal !== null) {
217500
217813
  const proposed = row.proposal;
217501
- if (!object17(proposed) || !text13(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return invalid15();
217814
+ if (!object16(proposed) || !text13(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return invalid15();
217502
217815
  const recommendations = [];
217503
217816
  for (const item of proposed.recommendations) {
217504
- if (!object17(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text13(item.text, 500) || !text13(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) => !text13(field, 400))) return invalid15();
217817
+ if (!object16(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text13(item.text, 500) || !text13(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) => !text13(field, 400))) return invalid15();
217505
217818
  recommendations.push({ area: item.area, text: item.text, reason: item.reason, sourceFields: [...item.sourceFields] });
217506
217819
  }
217507
217820
  proposal = { summary: proposed.summary, recommendations };
@@ -217510,7 +217823,7 @@ function brainState(value, brand, write = false) {
217510
217823
  let usage = null;
217511
217824
  if (row.usage !== null) {
217512
217825
  const measured = row.usage;
217513
- if (!object17(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer2(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return invalid15();
217826
+ if (!object16(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer2(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return invalid15();
217514
217827
  usage = { inputTokens: measured.inputTokens, outputTokens: measured.outputTokens, totalTokens: measured.totalTokens, durationMs: measured.durationMs };
217515
217828
  }
217516
217829
  run2 = { id: row.id, status: row.status, proposal, usage, errorCode: row.errorCode, sourceDesignRevision: row.sourceDesignRevision, acceptedDesignRevision: row.acceptedDesignRevision, createdAt: row.createdAt, updatedAt: row.updatedAt };
@@ -217729,8 +218042,8 @@ async function loginWithDevice(options, overrides = {}) {
217729
218042
  }
217730
218043
 
217731
218044
  // packages/cli/src/index.ts
217732
- import { chmod as chmod5, lstat as lstat28, mkdir as mkdir22, open as open24 } from "node:fs/promises";
217733
- import { constants as constants21 } from "node:fs";
218045
+ import { chmod as chmod5, lstat as lstat28, mkdir as mkdir22, open as open25 } from "node:fs/promises";
218046
+ import { constants as constants22 } from "node:fs";
217734
218047
  import { homedir as homedir5 } from "node:os";
217735
218048
  import { basename as basename10, dirname as dirname27, extname as extname12, join as join26, resolve as resolve20 } from "node:path";
217736
218049
 
@@ -217778,14 +218091,14 @@ async function prepareDirectionContext(root, client, projectId) {
217778
218091
  function invalid8() {
217779
218092
  throw new CliError("AUDIO_PROFILE_INVALID", "Invalid audio check profile.", "Use explicit numeric loudness targets and bounded runtime limits.");
217780
218093
  }
217781
- function object18(value, keys4) {
218094
+ function object17(value, keys4) {
217782
218095
  if (!value || typeof value !== "object" || Array.isArray(value)) invalid8();
217783
218096
  const result2 = value;
217784
218097
  if (Object.keys(result2).some((key) => !keys4.includes(key))) invalid8();
217785
218098
  return result2;
217786
218099
  }
217787
218100
  function validateAudioCheckProfile(value) {
217788
- const input2 = object18(value, ["schemaVersion", "loudness", "limits"]);
218101
+ const input2 = object17(value, ["schemaVersion", "loudness", "limits"]);
217789
218102
  if (input2.schemaVersion !== 1) invalid8();
217790
218103
  let loudness;
217791
218104
  try {
@@ -217793,7 +218106,7 @@ function validateAudioCheckProfile(value) {
217793
218106
  } catch {
217794
218107
  invalid8();
217795
218108
  }
217796
- const limits = input2.limits === void 0 ? {} : object18(input2.limits, ["timeoutMs", "maxOutputBytes"]);
218109
+ const limits = input2.limits === void 0 ? {} : object17(input2.limits, ["timeoutMs", "maxOutputBytes"]);
217797
218110
  const timeoutMs = limits.timeoutMs === void 0 ? 6e5 : limits.timeoutMs;
217798
218111
  const maxOutputBytes = limits.maxOutputBytes === void 0 ? 4 * 1024 * 1024 : limits.maxOutputBytes;
217799
218112
  if (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e5 || typeof maxOutputBytes !== "number" || !Number.isInteger(maxOutputBytes) || maxOutputBytes < 1024 || maxOutputBytes > 16 * 1024 * 1024) invalid8();
@@ -218433,21 +218746,21 @@ import { resolve as resolve15 } from "node:path";
218433
218746
  function invalidProfile(message) {
218434
218747
  throw new CliError("RENDER_PROFILE_INVALID", message, "Use a schemaVersion: 1 render profile with explicit technical requirements.");
218435
218748
  }
218436
- function object19(value, path, keys4) {
218749
+ function object18(value, path, keys4) {
218437
218750
  if (!value || typeof value !== "object" || Array.isArray(value)) invalidProfile(`${path} must be an object.`);
218438
218751
  const result2 = value;
218439
218752
  for (const key of Object.keys(result2)) if (!keys4.includes(key)) invalidProfile(`${path} contains unsupported field ${key}.`);
218440
218753
  return result2;
218441
218754
  }
218442
218755
  function validateRenderCheckProfile(value) {
218443
- const root = object19(value, "profile", ["schemaVersion", "expected", "tolerance", "audio", "silence", "black", "peak", "limits"]);
218756
+ const root = object18(value, "profile", ["schemaVersion", "expected", "tolerance", "audio", "silence", "black", "peak", "limits"]);
218444
218757
  if (root.schemaVersion !== 1) invalidProfile("profile.schemaVersion must be 1.");
218445
- const expected = root.expected === void 0 ? {} : object19(root.expected, "expected", ["width", "height", "fps", "durationSeconds"]);
218446
- const tolerance = root.tolerance === void 0 ? {} : object19(root.tolerance, "tolerance", ["fps", "durationSeconds"]);
218447
- const silence = root.silence === void 0 ? {} : object19(root.silence, "silence", ["enabled", "minDurationSeconds", "thresholdDb"]);
218448
- const black = root.black === void 0 ? {} : object19(root.black, "black", ["enabled", "minDurationSeconds", "pixelThreshold", "pictureBlackRatio"]);
218449
- const peak = root.peak === void 0 ? {} : object19(root.peak, "peak", ["enabled", "thresholdDbFS"]);
218450
- const limits = root.limits === void 0 ? {} : object19(root.limits, "limits", ["timeoutMs", "maxOutputBytes"]);
218758
+ const expected = root.expected === void 0 ? {} : object18(root.expected, "expected", ["width", "height", "fps", "durationSeconds"]);
218759
+ const tolerance = root.tolerance === void 0 ? {} : object18(root.tolerance, "tolerance", ["fps", "durationSeconds"]);
218760
+ const silence = root.silence === void 0 ? {} : object18(root.silence, "silence", ["enabled", "minDurationSeconds", "thresholdDb"]);
218761
+ const black = root.black === void 0 ? {} : object18(root.black, "black", ["enabled", "minDurationSeconds", "pixelThreshold", "pictureBlackRatio"]);
218762
+ const peak = root.peak === void 0 ? {} : object18(root.peak, "peak", ["enabled", "thresholdDbFS"]);
218763
+ const limits = root.limits === void 0 ? {} : object18(root.limits, "limits", ["timeoutMs", "maxOutputBytes"]);
218451
218764
  const number6 = (v, name, min, max, fallback, integer3 = false) => {
218452
218765
  if (v === void 0 && fallback !== void 0) return fallback;
218453
218766
  if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max || integer3 && !Number.isInteger(v)) invalidProfile(`${name} must be ${integer3 ? "an integer" : "a finite number"} between ${min} and ${max}.`);
@@ -218694,8 +219007,8 @@ async function checkRender(options) {
218694
219007
 
218695
219008
  // packages/cli/src/motion-components.ts
218696
219009
  import { createHash as createHash23 } from "node:crypto";
218697
- import { constants as constants18 } from "node:fs";
218698
- import { lstat as lstat25, mkdir as mkdir17, open as open21, rmdir as rmdir3, unlink as unlink15 } from "node:fs/promises";
219010
+ import { constants as constants19 } from "node:fs";
219011
+ import { lstat as lstat25, mkdir as mkdir17, open as open22, rmdir as rmdir3, unlink as unlink15 } from "node:fs/promises";
218699
219012
  import { dirname as dirname23, extname as extname8, resolve as resolve16 } from "node:path";
218700
219013
 
218701
219014
  // packages/core/src/motion-editorial.ts
@@ -220183,9 +220496,9 @@ function motionDocumentBoot(config3) {
220183
220496
  }
220184
220497
  config3.items.forEach((item, index) => {
220185
220498
  const pos = layout.overview[index];
220186
- const object21 = element("div", "sticker-object", world);
220187
- stickerObjects.push(object21);
220188
- box(object21, pos.x - pos.size / 2, pos.y - pos.size / 2, pos.size, pos.size);
220499
+ const object20 = element("div", "sticker-object", world);
220500
+ stickerObjects.push(object20);
220501
+ box(object20, pos.x - pos.size / 2, pos.y - pos.size / 2, pos.size, pos.size);
220189
220502
  if (item.image) {
220190
220503
  const image2 = document.createElement("img");
220191
220504
  image2.src = item.image;
@@ -220194,7 +220507,7 @@ function motionDocumentBoot(config3) {
220194
220507
  image2.draggable = false;
220195
220508
  image2.dataset.stickerIndex = String(index);
220196
220509
  image2.style.visibility = "hidden";
220197
- object21.appendChild(image2);
220510
+ object20.appendChild(image2);
220198
220511
  images.push(image2);
220199
220512
  } else {
220200
220513
  const illustration = svgNode("svg", { viewBox: "-125 -125 250 250", class: "illustration", role: "img", "aria-label": "Illustration: " + item.label });
@@ -220202,7 +220515,7 @@ function motionDocumentBoot(config3) {
220202
220515
  illustration.appendChild(svgNode("path", { d: pathOf(contours[index]), fill: "none", stroke: "var(--fg)", "stroke-width": "1.4", "stroke-linejoin": "round" }));
220203
220516
  const glyph = svgNode("path", { d: index % 2 ? "M-24,0 L-6,18 L30,-22" : "M-28,0 H28 M0,-28 V28", fill: "none", stroke: "var(--fg)", "stroke-width": "6", "stroke-linecap": "round", "stroke-linejoin": "round" });
220204
220517
  illustration.appendChild(glyph);
220205
- object21.appendChild(illustration);
220518
+ object20.appendChild(illustration);
220206
220519
  }
220207
220520
  const overviewLabel = element("div", "overview-label measured", world, item.label);
220208
220521
  box(overviewLabel, pos.x - pos.labelWidth / 2, pos.y + pos.size / 2 + s * 0.02, pos.labelWidth, pos.labelHeight);
@@ -220277,9 +220590,9 @@ function motionDocumentBoot(config3) {
220277
220590
  const ca = cameraFor(a.index), cb = cameraFor(b.index), focus = lerp(ca.focus, cb.focus, blend);
220278
220591
  const x = lerp(ca.x, cb.x, blend), y = lerp(ca.y, cb.y, blend), z2 = lerp(ca.z, cb.z, blend);
220279
220592
  stickerPaint.clearRect(0, 0, W, H);
220280
- stickerObjects.forEach((object21, index) => {
220593
+ stickerObjects.forEach((object20, index) => {
220281
220594
  const pos = layout.overview[index];
220282
- box(object21, x + (pos.x - pos.size / 2) * z2, y + (pos.y - pos.size / 2) * z2, pos.size * z2, pos.size * z2);
220595
+ box(object20, x + (pos.x - pos.size / 2) * z2, y + (pos.y - pos.size / 2) * z2, pos.size * z2, pos.size * z2);
220283
220596
  });
220284
220597
  overviewLabels.forEach((node2, index) => {
220285
220598
  const pos = layout.overview[index];
@@ -220508,18 +220821,18 @@ ${motionSceneLayout.toString()}
220508
220821
 
220509
220822
  // packages/cli/src/motion-components.ts
220510
220823
  var fail2 = (message) => new CliError("MOTION_COMPONENT_INVALID", message, "Use a pinned component, explicit resolved token bindings, a local WOFF2/TTF font and 2\u20134 plain-text items.");
220511
- function object20(value, name, allowed) {
220824
+ function object19(value, name, allowed) {
220512
220825
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !allowed.includes(key))) throw fail2(`${name} has invalid or unsupported fields.`);
220513
220826
  }
220514
220827
  function inputDocument(value) {
220515
- object20(value, "Input", ["componentId", "componentVersion", "bindings", "fontFile", "title", "subtitle", "duration", "items", "motion"]);
220828
+ object19(value, "Input", ["componentId", "componentVersion", "bindings", "fontFile", "title", "subtitle", "duration", "items", "motion"]);
220516
220829
  if (typeof value.componentId !== "string" || value.componentVersion !== "1.0.0" || !getMotionComponent(value.componentId, value.componentVersion)) throw fail2("Unknown component or unsupported pinned componentVersion.");
220517
- object20(value.bindings, "bindings", ["background", "foreground", "accent", "fontFamily"]);
220830
+ object19(value.bindings, "bindings", ["background", "foreground", "accent", "fontFamily"]);
220518
220831
  for (const role2 of ["background", "foreground", "accent", "fontFamily"]) if (typeof value.bindings[role2] !== "string" || !/^[a-z][a-z0-9_.-]{0,79}$/.test(value.bindings[role2])) throw fail2(`bindings.${role2} must name an explicit semantic token key.`);
220519
220832
  if (typeof value.fontFile !== "string" || !value.fontFile) throw fail2("fontFile is required.");
220520
220833
  if (!Array.isArray(value.items) || value.items.length < 2 || value.items.length > 4) throw fail2("Input requires 2\u20134 items.");
220521
220834
  for (const item of value.items) {
220522
- object20(item, "item", ["label", "detail", "imageFile", "shape"]);
220835
+ object19(item, "item", ["label", "detail", "imageFile", "shape"]);
220523
220836
  if (item.imageFile !== void 0 && (typeof item.imageFile !== "string" || !item.imageFile)) throw fail2("imageFile must be an explicit local image path.");
220524
220837
  }
220525
220838
  return value;
@@ -220530,7 +220843,7 @@ function inputPath(base, value) {
220530
220843
  }
220531
220844
  async function sourceFile(path, role2, max) {
220532
220845
  await assertNoMediaSymlinks(path);
220533
- const handle = await open21(path, constants18.O_RDONLY | constants18.O_NOFOLLOW | constants18.O_NONBLOCK);
220846
+ const handle = await open22(path, constants19.O_RDONLY | constants19.O_NOFOLLOW | constants19.O_NONBLOCK);
220534
220847
  try {
220535
220848
  const before = await handle.stat();
220536
220849
  if (!before.isFile() || before.size === 0 || before.size > max) throw fail2(`${role2} must be a nonempty regular file of at most ${max} bytes.`);
@@ -220686,7 +220999,7 @@ Preparation is not a rendered video or a quality certification. Inspect text fit
220686
220999
  created.push({ path: options.outDirectory, dev: info.dev, ino: info.ino, directory: true });
220687
221000
  for (const [name, content] of Object.entries(files)) {
220688
221001
  const path = `${options.outDirectory}/${name}`;
220689
- const handle = await open21(await productionOutputPath(root, path), constants18.O_WRONLY | constants18.O_CREAT | constants18.O_EXCL | constants18.O_NOFOLLOW, 384);
221002
+ const handle = await open22(await productionOutputPath(root, path), constants19.O_WRONLY | constants19.O_CREAT | constants19.O_EXCL | constants19.O_NOFOLLOW, 384);
220690
221003
  try {
220691
221004
  const stat3 = await handle.stat();
220692
221005
  created.push({ path, dev: stat3.dev, ino: stat3.ino, directory: false });
@@ -220747,8 +221060,8 @@ import { dirname as dirname25, join as join24, resolve as resolve18 } from "node
220747
221060
  // packages/cli/src/style-rule-check.ts
220748
221061
  import { spawn as spawn6 } from "node:child_process";
220749
221062
  import { createHash as createHash24, randomUUID as randomUUID9 } from "node:crypto";
220750
- import { constants as constants19 } from "node:fs";
220751
- import { mkdir as mkdir18, lstat as lstat26, open as open22, writeFile as writeFile5 } from "node:fs/promises";
221063
+ import { constants as constants20 } from "node:fs";
221064
+ import { mkdir as mkdir18, lstat as lstat26, open as open23, writeFile as writeFile5 } from "node:fs/promises";
220752
221065
  import { dirname as dirname24, join as join23, resolve as resolve17 } from "node:path";
220753
221066
  var digest5 = (value) => createHash24("sha256").update(value).digest("hex");
220754
221067
  var HASH = /^[a-f0-9]{64}$/;
@@ -220818,7 +221131,7 @@ function recognizedLines(frame, caseSensitive = false) {
220818
221131
  }
220819
221132
  var errorCode2 = (e) => e instanceof CliError ? e.code : "STYLE_RULE_CHECK_FAILED";
220820
221133
  async function readFrameBytes(path, maxBytes) {
220821
- const handle = await open22(path, constants19.O_RDONLY | (constants19.O_NOFOLLOW ?? 0) | (constants19.O_NONBLOCK ?? 0));
221134
+ const handle = await open23(path, constants20.O_RDONLY | (constants20.O_NOFOLLOW ?? 0) | (constants20.O_NONBLOCK ?? 0));
220822
221135
  try {
220823
221136
  const before = await handle.stat();
220824
221137
  if (!before.isFile() || before.size < 1 || before.size > maxBytes) throw new CliError("STYLE_FRAME_INVALID", "Invalid bounded frame artifact.", "Repeat verification with stable local outputs.");
@@ -221794,8 +222107,8 @@ async function productionReviewCommand(client, root, command, flags) {
221794
222107
  }
221795
222108
 
221796
222109
  // packages/cli/src/production-submit.ts
221797
- import { constants as constants20 } from "node:fs";
221798
- import { open as open23, mkdir as mkdir21 } from "node:fs/promises";
222110
+ import { constants as constants21 } from "node:fs";
222111
+ import { open as open24, mkdir as mkdir21 } from "node:fs/promises";
221799
222112
  import { randomUUID as randomUUID12 } from "node:crypto";
221800
222113
  import { basename as basename9, extname as extname11, join as join25 } from "node:path";
221801
222114
 
@@ -221951,7 +222264,7 @@ async function submitProduction(client, root, flags, runtime2 = { probe: probeLo
221951
222264
  if (receipt.state === "prepared" || receipt.state === "uploading") {
221952
222265
  const previewPath = await checkedPath(root, receipt.preview.path, false), preview = await runtime2.probe(previewPath);
221953
222266
  if (preview.sha256 !== receipt.preview.sha256 || preview.bytes !== receipt.preview.bytes || preview.bytes > plan.upload.maxFileBytes) throw new CliError("SUBMISSION_PREVIEW_CHANGED", "The saved preview bytes changed.", "Preserve the submission receipt and restore its exact preview before retrying.");
221954
- const handle = await open23(previewPath, constants20.O_RDONLY | constants20.O_NOFOLLOW | constants20.O_NONBLOCK);
222267
+ const handle = await open24(previewPath, constants21.O_RDONLY | constants21.O_NOFOLLOW | constants21.O_NONBLOCK);
221955
222268
  let bytes;
221956
222269
  try {
221957
222270
  const stat3 = await handle.stat();
@@ -222021,7 +222334,7 @@ editorbrain init [--dir folder] [--brand id] [--style id] [--project id] [--topi
222021
222334
  editorbrain onboarding guide
222022
222335
  editorbrain onboarding status --brand <brand-id> [--dir folder]
222023
222336
  editorbrain onboarding create --brand ID [--project ID] [--dir folder] [--out .editorbrain-local/onboarding/new]
222024
- editorbrain onboarding serve --session path [--dir folder] [--timeout seconds] [--no-browser]
222337
+ editorbrain onboarding serve --session path [--file draft.json] [--dir folder] [--timeout seconds] [--no-browser]
222025
222338
  editorbrain onboarding apply --session path --file answers.json [--dir folder] [--dry-run]
222026
222339
  editorbrain onboarding sync --session path [--dir folder] [--dry-run]
222027
222340
  editorbrain resources guide
@@ -222586,7 +222899,7 @@ async function main() {
222586
222899
  }
222587
222900
  if (command === "onboarding") {
222588
222901
  if (args.workspace && subcommand !== "sync") throw new Error("--workspace is not supported for local onboarding. Use separate project folders.");
222589
- const allowed = new Set(subcommand === "status" ? ["brand", "dir"] : subcommand === "create" ? ["brand", "project", "dir", "out"] : subcommand === "serve" ? ["session", "dir", "timeout", "no-browser"] : subcommand === "apply" ? ["session", "file", "dir", "dry-run"] : subcommand === "sync" ? ["session", "dir", "dry-run", "url"] : []);
222902
+ const allowed = new Set(subcommand === "status" ? ["brand", "dir"] : subcommand === "create" ? ["brand", "project", "dir", "out"] : subcommand === "serve" ? ["session", "file", "dir", "timeout", "no-browser"] : subcommand === "apply" ? ["session", "file", "dir", "dry-run"] : subcommand === "sync" ? ["session", "dir", "dry-run", "url"] : []);
222590
222903
  if (!["guide", "status", "create", "serve", "apply", "sync"].includes(subcommand) || args.positional.length !== 2) throw new Error("Use onboarding guide, status, create, serve, apply or sync.");
222591
222904
  for (const flag2 of Object.keys(args.flags)) if (!allowed.has(flag2)) throw new Error(`--${flag2} is not supported here.`);
222592
222905
  if (subcommand === "guide") {
@@ -222609,7 +222922,7 @@ async function main() {
222609
222922
  const session = str2(args, "session");
222610
222923
  if (!session) throw new Error("--session is required.");
222611
222924
  if (subcommand === "serve") {
222612
- output2(await serveOnboarding({ directory, session, timeoutSeconds: str2(args, "timeout") === void 0 ? void 0 : Number(str2(args, "timeout")), onReady: (value) => {
222925
+ output2(await serveOnboarding({ directory, session, file: str2(args, "file"), timeoutSeconds: str2(args, "timeout") === void 0 ? void 0 : Number(str2(args, "timeout")), onReady: (value) => {
222613
222926
  process.stderr.write(JSON.stringify({ ...value, status: "waiting_for_choices" }) + "\n");
222614
222927
  if (!args.flags["no-browser"]) void openSystemBrowser(value.url).catch(() => process.stderr.write("Open the local URL above, or use the saved HTML artifact.\n"));
222615
222928
  } }));
@@ -223440,7 +223753,7 @@ async function main() {
223440
223753
  }
223441
223754
  if (subcommand === "upload" && argument) {
223442
223755
  const target = resolve20(str2(args, "dir") ?? process.cwd(), argument);
223443
- const handle = await open24(target, constants21.O_RDONLY | constants21.O_NOFOLLOW);
223756
+ const handle = await open25(target, constants22.O_RDONLY | constants22.O_NOFOLLOW);
223444
223757
  let bytes;
223445
223758
  try {
223446
223759
  const info = await handle.stat();
@@ -223559,7 +223872,7 @@ async function main() {
223559
223872
  if (command === "search" && subcommand === "brief") {
223560
223873
  const path = str2(args, "file");
223561
223874
  if (!path) throw new Error("Provide --file with the editorial brief JSON after inspecting the actual material.");
223562
- const handle = await open24(resolve20(path), constants21.O_RDONLY | constants21.O_NOFOLLOW);
223875
+ const handle = await open25(resolve20(path), constants22.O_RDONLY | constants22.O_NOFOLLOW);
223563
223876
  let brief;
223564
223877
  try {
223565
223878
  const stat3 = await handle.stat();
@@ -223581,7 +223894,7 @@ async function main() {
223581
223894
  const scriptPath = str2(args, "script"), videoPath = str2(args, "video");
223582
223895
  let script, assetId = str2(args, "asset");
223583
223896
  const readInput = async (path, max) => {
223584
- const handle = await open24(resolve20(path), constants21.O_RDONLY | constants21.O_NOFOLLOW);
223897
+ const handle = await open25(resolve20(path), constants22.O_RDONLY | constants22.O_NOFOLLOW);
223585
223898
  try {
223586
223899
  const stat3 = await handle.stat();
223587
223900
  if (!stat3.isFile() || stat3.size < 1 || stat3.size > max) throw new Error(`Input must be a regular file of at most ${max} bytes.`);